proj_name
stringclasses 131
values | relative_path
stringlengths 30
228
| class_name
stringlengths 1
68
| func_name
stringlengths 1
48
| masked_class
stringlengths 78
9.82k
| func_body
stringlengths 46
9.61k
| len_input
int64 29
2.01k
| len_output
int64 14
1.94k
| total
int64 55
2.05k
| relevant_context
stringlengths 0
38.4k
|
|---|---|---|---|---|---|---|---|---|---|
brianfrankcooper_YCSB
|
YCSB/core/src/main/java/site/ycsb/NumericByteIterator.java
|
NumericByteIterator
|
getDouble
|
class NumericByteIterator extends ByteIterator {
private final byte[] payload;
private final boolean floatingPoint;
private int off;
public NumericByteIterator(final long value) {
floatingPoint = false;
payload = Utils.longToBytes(value);
off = 0;
}
public NumericByteIterator(final double value) {
floatingPoint = true;
payload = Utils.doubleToBytes(value);
off = 0;
}
@Override
public boolean hasNext() {
return off < payload.length;
}
@Override
public byte nextByte() {
return payload[off++];
}
@Override
public long bytesLeft() {
return payload.length - off;
}
@Override
public void reset() {
off = 0;
}
public long getLong() {
if (floatingPoint) {
throw new IllegalStateException("Byte iterator is of the type double");
}
return Utils.bytesToLong(payload);
}
public double getDouble() {<FILL_FUNCTION_BODY>}
public boolean isFloatingPoint() {
return floatingPoint;
}
}
|
if (!floatingPoint) {
throw new IllegalStateException("Byte iterator is of the type long");
}
return Utils.bytesToDouble(payload);
| 318
| 45
| 363
|
<methods>public non-sealed void <init>() ,public abstract long bytesLeft() ,public abstract boolean hasNext() ,public java.lang.Byte next() ,public int nextBuf(byte[], int) ,public abstract byte nextByte() ,public void remove() ,public void reset() ,public byte[] toArray() ,public java.lang.String toString() <variables>
|
brianfrankcooper_YCSB
|
YCSB/core/src/main/java/site/ycsb/RandomByteIterator.java
|
RandomByteIterator
|
nextBuf
|
class RandomByteIterator extends ByteIterator {
private final long len;
private long off;
private int bufOff;
private final byte[] buf;
@Override
public boolean hasNext() {
return (off + bufOff) < len;
}
private void fillBytesImpl(byte[] buffer, int base) {
int bytes = ThreadLocalRandom.current().nextInt();
switch (buffer.length - base) {
default:
buffer[base + 5] = (byte) (((bytes >> 25) & 95) + ' ');
case 5:
buffer[base + 4] = (byte) (((bytes >> 20) & 63) + ' ');
case 4:
buffer[base + 3] = (byte) (((bytes >> 15) & 31) + ' ');
case 3:
buffer[base + 2] = (byte) (((bytes >> 10) & 95) + ' ');
case 2:
buffer[base + 1] = (byte) (((bytes >> 5) & 63) + ' ');
case 1:
buffer[base + 0] = (byte) (((bytes) & 31) + ' ');
case 0:
break;
}
}
private void fillBytes() {
if (bufOff == buf.length) {
fillBytesImpl(buf, 0);
bufOff = 0;
off += buf.length;
}
}
public RandomByteIterator(long len) {
this.len = len;
this.buf = new byte[6];
this.bufOff = buf.length;
fillBytes();
this.off = 0;
}
public byte nextByte() {
fillBytes();
bufOff++;
return buf[bufOff - 1];
}
@Override
public int nextBuf(byte[] buffer, int bufOffset) {<FILL_FUNCTION_BODY>}
@Override
public long bytesLeft() {
return len - off - bufOff;
}
@Override
public void reset() {
off = 0;
}
/** Consumes remaining contents of this object, and returns them as a byte array. */
public byte[] toArray() {
long left = bytesLeft();
if (left != (int) left) {
throw new ArrayIndexOutOfBoundsException("Too much data to fit in one array!");
}
byte[] ret = new byte[(int) left];
int bufOffset = 0;
while (bufOffset < ret.length) {
bufOffset = nextBuf(ret, bufOffset);
}
return ret;
}
}
|
int ret;
if (len - off < buffer.length - bufOffset) {
ret = (int) (len - off);
} else {
ret = buffer.length - bufOffset;
}
int i;
for (i = 0; i < ret; i += 6) {
fillBytesImpl(buffer, i + bufOffset);
}
off += ret;
return ret + bufOffset;
| 688
| 107
| 795
|
<methods>public non-sealed void <init>() ,public abstract long bytesLeft() ,public abstract boolean hasNext() ,public java.lang.Byte next() ,public int nextBuf(byte[], int) ,public abstract byte nextByte() ,public void remove() ,public void reset() ,public byte[] toArray() ,public java.lang.String toString() <variables>
|
brianfrankcooper_YCSB
|
YCSB/core/src/main/java/site/ycsb/Status.java
|
Status
|
toString
|
class Status {
private final String name;
private final String description;
/**
* @param name A short name for the status.
* @param description A description of the status.
*/
public Status(String name, String description) {
super();
this.name = name;
this.description = description;
}
public String getName() {
return name;
}
public String getDescription() {
return description;
}
@Override
public String toString() {<FILL_FUNCTION_BODY>}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((description == null) ? 0 : description.hashCode());
result = prime * result + ((name == null) ? 0 : name.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
Status other = (Status) obj;
if (description == null) {
if (other.description != null) {
return false;
}
} else if (!description.equals(other.description)) {
return false;
}
if (name == null) {
if (other.name != null) {
return false;
}
} else if (!name.equals(other.name)) {
return false;
}
return true;
}
/**
* Is {@code this} a passing state for the operation: {@link Status#OK} or {@link Status#BATCHED_OK}.
* @return true if the operation is successful, false otherwise
*/
public boolean isOk() {
return this == OK || this == BATCHED_OK;
}
public static final Status OK = new Status("OK", "The operation completed successfully.");
public static final Status ERROR = new Status("ERROR", "The operation failed.");
public static final Status NOT_FOUND = new Status("NOT_FOUND", "The requested record was not found.");
public static final Status NOT_IMPLEMENTED = new Status("NOT_IMPLEMENTED", "The operation is not " +
"implemented for the current binding.");
public static final Status UNEXPECTED_STATE = new Status("UNEXPECTED_STATE", "The operation reported" +
" success, but the result was not as expected.");
public static final Status BAD_REQUEST = new Status("BAD_REQUEST", "The request was not valid.");
public static final Status FORBIDDEN = new Status("FORBIDDEN", "The operation is forbidden.");
public static final Status SERVICE_UNAVAILABLE = new Status("SERVICE_UNAVAILABLE", "Dependant " +
"service for the current binding is not available.");
public static final Status BATCHED_OK = new Status("BATCHED_OK", "The operation has been batched by " +
"the binding to be executed later.");
}
|
return "Status [name=" + name + ", description=" + description + "]";
| 785
| 25
| 810
|
<no_super_class>
|
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;
}
| 829
| 32
| 861
|
<methods>public non-sealed void <init>() ,public abstract long bytesLeft() ,public abstract boolean hasNext() ,public java.lang.Byte next() ,public int nextBuf(byte[], int) ,public abstract byte nextByte() ,public void remove() ,public void reset() ,public byte[] toArray() ,public java.lang.String toString() <variables>
|
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.
}
}
}
| 172
| 240
| 412
|
<methods>public void <init>() ,public void <init>(java.lang.Runnable) ,public void <init>(java.lang.String) ,public void <init>(java.lang.ThreadGroup, java.lang.Runnable) ,public void <init>(java.lang.ThreadGroup, java.lang.String) ,public void <init>(java.lang.Runnable, java.lang.String) ,public void <init>(java.lang.ThreadGroup, java.lang.Runnable, java.lang.String) ,public void <init>(java.lang.ThreadGroup, java.lang.Runnable, java.lang.String, long) ,public void <init>(java.lang.ThreadGroup, java.lang.Runnable, java.lang.String, long, boolean) ,public static int activeCount() ,public final void checkAccess() ,public int countStackFrames() ,public static native java.lang.Thread currentThread() ,public static void dumpStack() ,public static int enumerate(java.lang.Thread[]) ,public static Map<java.lang.Thread,java.lang.StackTraceElement[]> getAllStackTraces() ,public java.lang.ClassLoader getContextClassLoader() ,public static java.lang.Thread.UncaughtExceptionHandler getDefaultUncaughtExceptionHandler() ,public long getId() ,public final java.lang.String getName() ,public final int getPriority() ,public java.lang.StackTraceElement[] getStackTrace() ,public java.lang.Thread.State getState() ,public final java.lang.ThreadGroup getThreadGroup() ,public java.lang.Thread.UncaughtExceptionHandler getUncaughtExceptionHandler() ,public static native boolean holdsLock(java.lang.Object) ,public void interrupt() ,public static boolean interrupted() ,public final boolean isAlive() ,public final boolean isDaemon() ,public boolean isInterrupted() ,public final void join() throws java.lang.InterruptedException,public final synchronized void join(long) throws java.lang.InterruptedException,public final synchronized void join(long, int) throws java.lang.InterruptedException,public static void onSpinWait() ,public final void resume() ,public void run() ,public void setContextClassLoader(java.lang.ClassLoader) ,public final void setDaemon(boolean) ,public static void setDefaultUncaughtExceptionHandler(java.lang.Thread.UncaughtExceptionHandler) ,public final synchronized void setName(java.lang.String) ,public final void setPriority(int) ,public void setUncaughtExceptionHandler(java.lang.Thread.UncaughtExceptionHandler) ,public static native void sleep(long) throws java.lang.InterruptedException,public static void sleep(long, int) throws java.lang.InterruptedException,public synchronized void start() ,public final void stop() ,public final void suspend() ,public java.lang.String toString() ,public static native void yield() <variables>private static final java.lang.StackTraceElement[] EMPTY_STACK_TRACE,public static final int MAX_PRIORITY,public static final int MIN_PRIORITY,public static final int NORM_PRIORITY,private volatile sun.nio.ch.Interruptible blocker,private final java.lang.Object blockerLock,private java.lang.ClassLoader contextClassLoader,private boolean daemon,private static volatile java.lang.Thread.UncaughtExceptionHandler defaultUncaughtExceptionHandler,private volatile long eetop,private java.lang.ThreadGroup group,java.lang.ThreadLocal.ThreadLocalMap inheritableThreadLocals,private java.security.AccessControlContext inheritedAccessControlContext,private volatile boolean interrupted,private volatile java.lang.String name,volatile java.lang.Object parkBlocker,private int priority,private final long stackSize,private boolean stillborn,private java.lang.Runnable target,private static int threadInitNumber,int threadLocalRandomProbe,int threadLocalRandomSecondarySeed,long threadLocalRandomSeed,java.lang.ThreadLocal.ThreadLocalMap threadLocals,private static long threadSeqNumber,private volatile int threadStatus,private final long tid,private volatile java.lang.Thread.UncaughtExceptionHandler uncaughtExceptionHandler
|
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();
}
}
| 305
| 238
| 543
|
<methods>public void <init>(long) ,public java.lang.Long lastValue() ,public double mean() ,public java.lang.Long nextValue() <variables>private final non-sealed java.util.concurrent.atomic.AtomicLong counter
|
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.");
| 139
| 120
| 259
|
<methods>public non-sealed void <init>() ,public final java.lang.String lastString() ,public abstract java.lang.String lastValue() ,public final java.lang.String nextString() ,public abstract java.lang.String nextValue() <variables>
|
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");
| 475
| 101
| 576
|
<methods>public non-sealed void <init>() ,public java.lang.Number lastValue() ,public abstract double mean() <variables>private java.lang.Number lastVal
|
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);
}
| 275
| 42
| 317
|
<methods>public non-sealed void <init>() ,public final java.lang.String lastString() ,public abstract java.lang.String lastValue() ,public final java.lang.String nextString() ,public abstract java.lang.String nextValue() <variables>
|
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();
| 194
| 24
| 218
|
<no_super_class>
|
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);
| 544
| 76
| 620
|
<methods>public non-sealed void <init>() ,public java.lang.Number lastValue() ,public abstract double mean() <variables>private java.lang.Number lastVal
|
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;
| 699
| 124
| 823
|
<methods>public non-sealed void <init>() ,public java.lang.Number lastValue() ,public abstract double mean() <variables>private java.lang.Number 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);
| 733
| 105
| 838
|
<methods>public void <init>() ,public void <init>(long, java.util.concurrent.TimeUnit) ,public void <init>(long, java.util.concurrent.TimeUnit, long) ,public long currentValue() ,public long getOffset(long) ,public void initalizeTimestamp(long) ,public java.lang.Long lastValue() ,public java.lang.Long nextValue() <variables>protected long currentTimestamp,protected long interval,protected long lastTimestamp,protected long startTimestamp,protected java.util.concurrent.TimeUnit timeUnits
|
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());
}
| 976
| 152
| 1,128
|
<methods>public non-sealed void <init>() ,public java.lang.Number lastValue() ,public abstract double mean() <variables>private java.lang.Number lastVal
|
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;
| 297
| 35
| 332
|
<methods>public non-sealed void <init>() ,public java.lang.Number lastValue() ,public abstract double mean() <variables>private java.lang.Number lastVal
|
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;
| 275
| 27
| 302
|
<methods>public non-sealed void <init>() ,public final java.lang.String lastString() ,public abstract java.lang.String lastValue() ,public final java.lang.String nextString() ,public abstract java.lang.String nextValue() <variables>
|
brianfrankcooper_YCSB
|
YCSB/core/src/main/java/site/ycsb/generator/UniformLongGenerator.java
|
UniformLongGenerator
|
nextValue
|
class UniformLongGenerator extends NumberGenerator {
private final long lb, ub, interval;
/**
* Creates a generator that will return longs uniformly randomly from the
* interval [lb,ub] inclusive (that is, lb and ub are possible values)
* (lb and ub are possible values).
*
* @param lb the lower bound (inclusive) of generated values
* @param ub the upper bound (inclusive) of generated values
*/
public UniformLongGenerator(long lb, long ub) {
this.lb = lb;
this.ub = ub;
interval = this.ub - this.lb + 1;
}
@Override
public Long nextValue() {<FILL_FUNCTION_BODY>}
@Override
public double mean() {
return ((lb + (long) ub)) / 2.0;
}
}
|
long ret = Math.abs(ThreadLocalRandom.current().nextLong()) % interval + lb;
setLastValue(ret);
return ret;
| 248
| 46
| 294
|
<methods>public non-sealed void <init>() ,public java.lang.Number lastValue() ,public abstract double mean() <variables>private java.lang.Number lastVal
|
brianfrankcooper_YCSB
|
YCSB/core/src/main/java/site/ycsb/generator/UnixEpochTimestampGenerator.java
|
UnixEpochTimestampGenerator
|
initalizeTimestamp
|
class UnixEpochTimestampGenerator extends Generator<Long> {
/** The base timestamp used as a starting reference. */
protected long startTimestamp;
/** The current timestamp that will be incremented. */
protected long currentTimestamp;
/** The last used timestamp. Should always be one interval behind current. */
protected long lastTimestamp;
/** The interval to increment by. Multiplied by {@link #timeUnits}. */
protected long interval;
/** The units of time the interval represents. */
protected TimeUnit timeUnits;
/**
* Default ctor with the current system time and a 60 second interval.
*/
public UnixEpochTimestampGenerator() {
this(60, TimeUnit.SECONDS);
}
/**
* Ctor that uses the current system time as current.
* @param interval The interval for incrementing the timestamp.
* @param timeUnits The units of time the increment represents.
*/
public UnixEpochTimestampGenerator(final long interval, final TimeUnit timeUnits) {
this.interval = interval;
this.timeUnits = timeUnits;
// move the first timestamp by 1 interval so that the first call to nextValue
// returns this timestamp
initalizeTimestamp(-1);
currentTimestamp -= getOffset(1);
lastTimestamp = currentTimestamp;
}
/**
* Ctor for supplying a starting timestamp.
* @param interval The interval for incrementing the timestamp.
* @param timeUnits The units of time the increment represents.
* @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()}
* or seconds and any interval above, {@code System.currentTimeMillis() / 1000}
*/
public UnixEpochTimestampGenerator(final long interval, final TimeUnit timeUnits,
final long startTimestamp) {
this.interval = interval;
this.timeUnits = timeUnits;
// move the first timestamp by 1 interval so that the first call to nextValue
// returns this timestamp
currentTimestamp = startTimestamp - getOffset(1);
this.startTimestamp = currentTimestamp;
lastTimestamp = currentTimestamp - getOffset(1);
}
/**
* Sets the starting timestamp to the current system time plus the interval offset.
* E.g. to set the time an hour in the past, supply a value of {@code -60}.
* @param intervalOffset The interval to increment or decrement by.
*/
public void initalizeTimestamp(final long intervalOffset) {<FILL_FUNCTION_BODY>}
@Override
public Long nextValue() {
lastTimestamp = currentTimestamp;
currentTimestamp += getOffset(1);
return currentTimestamp;
}
/**
* Returns the proper increment offset to use given the interval and timeunits.
* @param intervalOffset The amount of offset to multiply by.
* @return An offset value to adjust the timestamp by.
*/
public long getOffset(final long intervalOffset) {
switch (timeUnits) {
case NANOSECONDS:
case MICROSECONDS:
case MILLISECONDS:
case SECONDS:
return intervalOffset * interval;
case MINUTES:
return intervalOffset * interval * (long) 60;
case HOURS:
return intervalOffset * interval * (long) (60 * 60);
case DAYS:
return intervalOffset * interval * (long) (60 * 60 * 24);
default:
throw new IllegalArgumentException("Unhandled time unit type: " + timeUnits);
}
}
@Override
public Long lastValue() {
return lastTimestamp;
}
/** @return The current timestamp as set by the last call to {@link #nextValue()} */
public long currentValue() {
return currentTimestamp;
}
}
|
switch (timeUnits) {
case NANOSECONDS:
currentTimestamp = System.nanoTime() + getOffset(intervalOffset);
break;
case MICROSECONDS:
currentTimestamp = (System.nanoTime() / 1000) + getOffset(intervalOffset);
break;
case MILLISECONDS:
currentTimestamp = System.currentTimeMillis() + getOffset(intervalOffset);
break;
case SECONDS:
currentTimestamp = (System.currentTimeMillis() / 1000) +
getOffset(intervalOffset);
break;
case MINUTES:
currentTimestamp = (System.currentTimeMillis() / 1000) +
getOffset(intervalOffset);
break;
case HOURS:
currentTimestamp = (System.currentTimeMillis() / 1000) +
getOffset(intervalOffset);
break;
case DAYS:
currentTimestamp = (System.currentTimeMillis() / 1000) +
getOffset(intervalOffset);
break;
default:
throw new IllegalArgumentException("Unhandled time unit type: " + timeUnits);
}
startTimestamp = currentTimestamp;
| 1,054
| 311
| 1,365
|
<methods>public non-sealed void <init>() ,public final java.lang.String lastString() ,public abstract java.lang.Long lastValue() ,public final java.lang.String nextString() ,public abstract java.lang.Long nextValue() <variables>
|
brianfrankcooper_YCSB
|
YCSB/core/src/main/java/site/ycsb/measurements/Measurements.java
|
StartTimeHolder
|
getOpMeasurement
|
class StartTimeHolder {
protected long time;
long startTime() {
if (time == 0) {
return System.nanoTime();
} else {
return time;
}
}
}
private final ThreadLocal<StartTimeHolder> tlIntendedStartTime = new ThreadLocal<Measurements.StartTimeHolder>() {
protected StartTimeHolder initialValue() {
return new StartTimeHolder();
}
};
public void setIntendedStartTimeNs(long time) {
if (measurementInterval == 0) {
return;
}
tlIntendedStartTime.get().time = time;
}
public long getIntendedStartTimeNs() {
if (measurementInterval == 0) {
return 0L;
}
return tlIntendedStartTime.get().startTime();
}
/**
* Report a single value of a single metric. E.g. for read latency, operation="READ" and latency is the measured
* value.
*/
public void measure(String operation, int latency) {
if (measurementInterval == 1) {
return;
}
try {
OneMeasurement m = getOpMeasurement(operation);
m.measure(latency);
} catch (java.lang.ArrayIndexOutOfBoundsException e) {
// This seems like a terribly hacky way to cover up for a bug in the measurement code
System.out.println("ERROR: java.lang.ArrayIndexOutOfBoundsException - ignoring and continuing");
e.printStackTrace();
e.printStackTrace(System.out);
}
}
/**
* Report a single value of a single metric. E.g. for read latency, operation="READ" and latency is the measured
* value.
*/
public void measureIntended(String operation, int latency) {
if (measurementInterval == 0) {
return;
}
try {
OneMeasurement m = getOpIntendedMeasurement(operation);
m.measure(latency);
} catch (java.lang.ArrayIndexOutOfBoundsException e) {
// This seems like a terribly hacky way to cover up for a bug in the measurement code
System.out.println("ERROR: java.lang.ArrayIndexOutOfBoundsException - ignoring and continuing");
e.printStackTrace();
e.printStackTrace(System.out);
}
}
private OneMeasurement getOpMeasurement(String operation) {<FILL_FUNCTION_BODY>
|
OneMeasurement m = opToMesurementMap.get(operation);
if (m == null) {
m = constructOneMeasurement(operation);
OneMeasurement oldM = opToMesurementMap.putIfAbsent(operation, m);
if (oldM != null) {
m = oldM;
}
}
return m;
| 634
| 96
| 730
|
<no_super_class>
|
brianfrankcooper_YCSB
|
YCSB/core/src/main/java/site/ycsb/measurements/OneMeasurement.java
|
OneMeasurement
|
reportStatus
|
class OneMeasurement {
private final String name;
private final ConcurrentHashMap<Status, AtomicInteger> returncodes;
public String getName() {
return name;
}
/**
* @param name measurement name
*/
public OneMeasurement(String name) {
this.name = name;
this.returncodes = new ConcurrentHashMap<>();
}
public abstract void measure(int latency);
public abstract String getSummary();
/**
* No need for synchronization, using CHM to deal with that.
*/
public void reportStatus(Status status) {<FILL_FUNCTION_BODY>}
/**
* Export the current measurements to a suitable format.
*
* @param exporter Exporter representing the type of format to write to.
* @throws IOException Thrown if the export failed.
*/
public abstract void exportMeasurements(MeasurementsExporter exporter) throws IOException;
protected final void exportStatusCounts(MeasurementsExporter exporter) throws IOException {
for (Map.Entry<Status, AtomicInteger> entry : returncodes.entrySet()) {
exporter.write(getName(), "Return=" + entry.getKey().getName(), entry.getValue().get());
}
}
}
|
AtomicInteger counter = returncodes.get(status);
if (counter == null) {
counter = new AtomicInteger();
AtomicInteger other = returncodes.putIfAbsent(status, counter);
if (other != null) {
counter = other;
}
}
counter.incrementAndGet();
| 322
| 89
| 411
|
<no_super_class>
|
brianfrankcooper_YCSB
|
YCSB/core/src/main/java/site/ycsb/measurements/OneMeasurementHistogram.java
|
OneMeasurementHistogram
|
measure
|
class OneMeasurementHistogram extends OneMeasurement {
public static final String BUCKETS = "histogram.buckets";
public static final String BUCKETS_DEFAULT = "1000";
public static final String VERBOSE_PROPERTY = "measurement.histogram.verbose";
/**
* Specify the range of latencies to track in the histogram.
*/
private final int buckets;
/**
* Groups operations in discrete blocks of 1ms width.
*/
private long[] histogram;
/**
* Counts all operations outside the histogram's range.
*/
private long histogramoverflow;
/**
* The total number of reported operations.
*/
private long operations;
/**
* The sum of each latency measurement over all operations.
* Calculated in ms.
*/
private long totallatency;
/**
* The sum of each latency measurement squared over all operations.
* Used to calculate variance of latency.
* Calculated in ms.
*/
private double totalsquaredlatency;
/**
* Whether or not to emit the histogram buckets.
*/
private final boolean verbose;
//keep a windowed version of these stats for printing status
private long windowoperations;
private long windowtotallatency;
private int min;
private int max;
public OneMeasurementHistogram(String name, Properties props) {
super(name);
buckets = Integer.parseInt(props.getProperty(BUCKETS, BUCKETS_DEFAULT));
verbose = Boolean.valueOf(props.getProperty(VERBOSE_PROPERTY, String.valueOf(false)));
histogram = new long[buckets];
histogramoverflow = 0;
operations = 0;
totallatency = 0;
totalsquaredlatency = 0;
windowoperations = 0;
windowtotallatency = 0;
min = -1;
max = -1;
}
/* (non-Javadoc)
* @see site.ycsb.OneMeasurement#measure(int)
*/
public synchronized void measure(int latency) {<FILL_FUNCTION_BODY>}
@Override
public void exportMeasurements(MeasurementsExporter exporter) throws IOException {
double mean = totallatency / ((double) operations);
double variance = totalsquaredlatency / ((double) operations) - (mean * mean);
exporter.write(getName(), "Operations", operations);
exporter.write(getName(), "AverageLatency(us)", mean);
exporter.write(getName(), "LatencyVariance(us)", variance);
exporter.write(getName(), "MinLatency(us)", min);
exporter.write(getName(), "MaxLatency(us)", max);
long opcounter=0;
boolean done95th = false;
for (int i = 0; i < buckets; i++) {
opcounter += histogram[i];
if ((!done95th) && (((double) opcounter) / ((double) operations) >= 0.95)) {
exporter.write(getName(), "95thPercentileLatency(us)", i * 1000);
done95th = true;
}
if (((double) opcounter) / ((double) operations) >= 0.99) {
exporter.write(getName(), "99thPercentileLatency(us)", i * 1000);
break;
}
}
exportStatusCounts(exporter);
if (verbose) {
for (int i = 0; i < buckets; i++) {
exporter.write(getName(), Integer.toString(i), histogram[i]);
}
exporter.write(getName(), ">" + buckets, histogramoverflow);
}
}
@Override
public String getSummary() {
if (windowoperations == 0) {
return "";
}
DecimalFormat d = new DecimalFormat("#.##");
double report = ((double) windowtotallatency) / ((double) windowoperations);
windowtotallatency = 0;
windowoperations = 0;
return "[" + getName() + " AverageLatency(us)=" + d.format(report) + "]";
}
}
|
//latency reported in us and collected in bucket by ms.
if (latency / 1000 >= buckets) {
histogramoverflow++;
} else {
histogram[latency / 1000]++;
}
operations++;
totallatency += latency;
totalsquaredlatency += ((double) latency) * ((double) latency);
windowoperations++;
windowtotallatency += latency;
if ((min < 0) || (latency < min)) {
min = latency;
}
if ((max < 0) || (latency > max)) {
max = latency;
}
| 1,116
| 169
| 1,285
|
<methods>public void <init>(java.lang.String) ,public abstract void exportMeasurements(site.ycsb.measurements.exporter.MeasurementsExporter) throws java.io.IOException,public java.lang.String getName() ,public abstract java.lang.String getSummary() ,public abstract void measure(int) ,public void reportStatus(site.ycsb.Status) <variables>private final non-sealed java.lang.String name,private final non-sealed ConcurrentHashMap<site.ycsb.Status,java.util.concurrent.atomic.AtomicInteger> returncodes
|
brianfrankcooper_YCSB
|
YCSB/core/src/main/java/site/ycsb/measurements/OneMeasurementRaw.java
|
RawDataPointComparator
|
exportMeasurements
|
class RawDataPointComparator implements Comparator<RawDataPoint> {
@Override
public int compare(RawDataPoint p1, RawDataPoint p2) {
if (p1.value() < p2.value()) {
return -1;
} else if (p1.value() == p2.value()) {
return 0;
} else {
return 1;
}
}
}
/**
* Optionally, user can configure an output file to save the raw data points.
* Default is none, raw results will be written to stdout.
*
*/
public static final String OUTPUT_FILE_PATH = "measurement.raw.output_file";
public static final String OUTPUT_FILE_PATH_DEFAULT = "";
/**
* Optionally, user can request to not output summary stats. This is useful
* if the user chains the raw measurement type behind the HdrHistogram type
* which already outputs summary stats. But even in that case, the user may
* still want this class to compute summary stats for them, especially if
* they want accurate computation of percentiles (because percentils computed
* by histogram classes are still approximations).
*/
public static final String NO_SUMMARY_STATS = "measurement.raw.no_summary";
public static final String NO_SUMMARY_STATS_DEFAULT = "false";
private final PrintStream outputStream;
private boolean noSummaryStats = false;
private LinkedList<RawDataPoint> measurements;
private long totalLatency = 0;
// A window of stats to print summary for at the next getSummary() call.
// It's supposed to be a one line summary, so we will just print count and
// average.
private int windowOperations = 0;
private long windowTotalLatency = 0;
public OneMeasurementRaw(String name, Properties props) {
super(name);
String outputFilePath = props.getProperty(OUTPUT_FILE_PATH, OUTPUT_FILE_PATH_DEFAULT);
if (!outputFilePath.isEmpty()) {
System.out.println("Raw data measurement: will output to result file: " +
outputFilePath);
try {
outputStream = new PrintStream(
new FileOutputStream(outputFilePath, true),
true);
} catch (FileNotFoundException e) {
throw new RuntimeException("Failed to open raw data output file", e);
}
} else {
System.out.println("Raw data measurement: will output to stdout.");
outputStream = System.out;
}
noSummaryStats = Boolean.parseBoolean(props.getProperty(NO_SUMMARY_STATS,
NO_SUMMARY_STATS_DEFAULT));
measurements = new LinkedList<>();
}
@Override
public synchronized void measure(int latency) {
totalLatency += latency;
windowTotalLatency += latency;
windowOperations++;
measurements.add(new RawDataPoint(latency));
}
@Override
public void exportMeasurements(MeasurementsExporter exporter)
throws IOException {<FILL_FUNCTION_BODY>
|
// Output raw data points first then print out a summary of percentiles to
// stdout.
outputStream.println(getName() +
" latency raw data: op, timestamp(ms), latency(us)");
for (RawDataPoint point : measurements) {
outputStream.println(
String.format("%s,%d,%d", getName(), point.timeStamp(),
point.value()));
}
if (outputStream != System.out) {
outputStream.close();
}
int totalOps = measurements.size();
exporter.write(getName(), "Total Operations", totalOps);
if (totalOps > 0 && !noSummaryStats) {
exporter.write(getName(),
"Below is a summary of latency in microseconds:", -1);
exporter.write(getName(), "Average",
(double) totalLatency / (double) totalOps);
Collections.sort(measurements, new RawDataPointComparator());
exporter.write(getName(), "Min", measurements.get(0).value());
exporter.write(
getName(), "Max", measurements.get(totalOps - 1).value());
exporter.write(
getName(), "p1", measurements.get((int) (totalOps * 0.01)).value());
exporter.write(
getName(), "p5", measurements.get((int) (totalOps * 0.05)).value());
exporter.write(
getName(), "p50", measurements.get((int) (totalOps * 0.5)).value());
exporter.write(
getName(), "p90", measurements.get((int) (totalOps * 0.9)).value());
exporter.write(
getName(), "p95", measurements.get((int) (totalOps * 0.95)).value());
exporter.write(
getName(), "p99", measurements.get((int) (totalOps * 0.99)).value());
exporter.write(getName(), "p99.9",
measurements.get((int) (totalOps * 0.999)).value());
exporter.write(getName(), "p99.99",
measurements.get((int) (totalOps * 0.9999)).value());
}
exportStatusCounts(exporter);
| 784
| 602
| 1,386
|
<methods>public void <init>(java.lang.String) ,public abstract void exportMeasurements(site.ycsb.measurements.exporter.MeasurementsExporter) throws java.io.IOException,public java.lang.String getName() ,public abstract java.lang.String getSummary() ,public abstract void measure(int) ,public void reportStatus(site.ycsb.Status) <variables>private final non-sealed java.lang.String name,private final non-sealed ConcurrentHashMap<site.ycsb.Status,java.util.concurrent.atomic.AtomicInteger> returncodes
|
brianfrankcooper_YCSB
|
YCSB/core/src/main/java/site/ycsb/measurements/OneMeasurementTimeSeries.java
|
OneMeasurementTimeSeries
|
getSummary
|
class OneMeasurementTimeSeries extends OneMeasurement {
/**
* Granularity for time series; measurements will be averaged in chunks of this granularity. Units are milliseconds.
*/
public static final String GRANULARITY = "timeseries.granularity";
public static final String GRANULARITY_DEFAULT = "1000";
private final int granularity;
private final Vector<SeriesUnit> measurements;
private long start = -1;
private long currentunit = -1;
private long count = 0;
private long sum = 0;
private long operations = 0;
private long totallatency = 0;
//keep a windowed version of these stats for printing status
private int windowoperations = 0;
private long windowtotallatency = 0;
private int min = -1;
private int max = -1;
public OneMeasurementTimeSeries(String name, Properties props) {
super(name);
granularity = Integer.parseInt(props.getProperty(GRANULARITY, GRANULARITY_DEFAULT));
measurements = new Vector<>();
}
private synchronized void checkEndOfUnit(boolean forceend) {
long now = System.currentTimeMillis();
if (start < 0) {
currentunit = 0;
start = now;
}
long unit = ((now - start) / granularity) * granularity;
if ((unit > currentunit) || (forceend)) {
double avg = ((double) sum) / ((double) count);
measurements.add(new SeriesUnit(currentunit, avg));
currentunit = unit;
count = 0;
sum = 0;
}
}
@Override
public void measure(int latency) {
checkEndOfUnit(false);
count++;
sum += latency;
totallatency += latency;
operations++;
windowoperations++;
windowtotallatency += latency;
if (latency > max) {
max = latency;
}
if ((latency < min) || (min < 0)) {
min = latency;
}
}
@Override
public void exportMeasurements(MeasurementsExporter exporter) throws IOException {
checkEndOfUnit(true);
exporter.write(getName(), "Operations", operations);
exporter.write(getName(), "AverageLatency(us)", (((double) totallatency) / ((double) operations)));
exporter.write(getName(), "MinLatency(us)", min);
exporter.write(getName(), "MaxLatency(us)", max);
// TODO: 95th and 99th percentile latency
exportStatusCounts(exporter);
for (SeriesUnit unit : measurements) {
exporter.write(getName(), Long.toString(unit.time), unit.average);
}
}
@Override
public String getSummary() {<FILL_FUNCTION_BODY>}
}
|
if (windowoperations == 0) {
return "";
}
DecimalFormat d = new DecimalFormat("#.##");
double report = ((double) windowtotallatency) / ((double) windowoperations);
windowtotallatency = 0;
windowoperations = 0;
return "[" + getName() + " AverageLatency(us)=" + d.format(report) + "]";
| 766
| 107
| 873
|
<methods>public void <init>(java.lang.String) ,public abstract void exportMeasurements(site.ycsb.measurements.exporter.MeasurementsExporter) throws java.io.IOException,public java.lang.String getName() ,public abstract java.lang.String getSummary() ,public abstract void measure(int) ,public void reportStatus(site.ycsb.Status) <variables>private final non-sealed java.lang.String name,private final non-sealed ConcurrentHashMap<site.ycsb.Status,java.util.concurrent.atomic.AtomicInteger> returncodes
|
brianfrankcooper_YCSB
|
YCSB/core/src/main/java/site/ycsb/measurements/exporter/TextMeasurementsExporter.java
|
TextMeasurementsExporter
|
write
|
class TextMeasurementsExporter implements MeasurementsExporter {
private final BufferedWriter bw;
public TextMeasurementsExporter(OutputStream os) {
this.bw = new BufferedWriter(new OutputStreamWriter(os));
}
public void write(String metric, String measurement, int i) throws IOException {<FILL_FUNCTION_BODY>}
public void write(String metric, String measurement, long i) throws IOException {
bw.write("[" + metric + "], " + measurement + ", " + i);
bw.newLine();
}
public void write(String metric, String measurement, double d) throws IOException {
bw.write("[" + metric + "], " + measurement + ", " + d);
bw.newLine();
}
public void close() throws IOException {
this.bw.close();
}
}
|
bw.write("[" + metric + "], " + measurement + ", " + i);
bw.newLine();
| 219
| 33
| 252
|
<no_super_class>
|
brianfrankcooper_YCSB
|
YCSB/core/src/main/java/site/ycsb/workloads/ConstantOccupancyWorkload.java
|
ConstantOccupancyWorkload
|
init
|
class ConstantOccupancyWorkload extends CoreWorkload {
private long disksize;
private long storageages;
private double occupancy;
private long objectCount;
public static final String STORAGE_AGE_PROPERTY = "storageages";
public static final long STORAGE_AGE_PROPERTY_DEFAULT = 10;
public static final String DISK_SIZE_PROPERTY = "disksize";
public static final long DISK_SIZE_PROPERTY_DEFAULT = 100 * 1000 * 1000;
public static final String OCCUPANCY_PROPERTY = "occupancy";
public static final double OCCUPANCY_PROPERTY_DEFAULT = 0.9;
@Override
public void init(Properties p) throws WorkloadException {<FILL_FUNCTION_BODY>}
}
|
disksize = Long.parseLong(p.getProperty(DISK_SIZE_PROPERTY, String.valueOf(DISK_SIZE_PROPERTY_DEFAULT)));
storageages = Long.parseLong(p.getProperty(STORAGE_AGE_PROPERTY, String.valueOf(STORAGE_AGE_PROPERTY_DEFAULT)));
occupancy = Double.parseDouble(p.getProperty(OCCUPANCY_PROPERTY, String.valueOf(OCCUPANCY_PROPERTY_DEFAULT)));
if (p.getProperty(Client.RECORD_COUNT_PROPERTY) != null ||
p.getProperty(Client.INSERT_COUNT_PROPERTY) != null ||
p.getProperty(Client.OPERATION_COUNT_PROPERTY) != null) {
System.err.println("Warning: record, insert or operation count was set prior to initting " +
"ConstantOccupancyWorkload. Overriding old values.");
}
NumberGenerator g = CoreWorkload.getFieldLengthGenerator(p);
double fieldsize = g.mean();
int fieldcount = Integer.parseInt(p.getProperty(FIELD_COUNT_PROPERTY, FIELD_COUNT_PROPERTY_DEFAULT));
objectCount = (long) (occupancy * (disksize / (fieldsize * fieldcount)));
if (objectCount == 0) {
throw new IllegalStateException("Object count was zero. Perhaps disksize is too low?");
}
p.setProperty(Client.RECORD_COUNT_PROPERTY, String.valueOf(objectCount));
p.setProperty(Client.OPERATION_COUNT_PROPERTY, String.valueOf(storageages * objectCount));
p.setProperty(Client.INSERT_COUNT_PROPERTY, String.valueOf(objectCount));
super.init(p);
| 217
| 457
| 674
|
<methods>public non-sealed void <init>() ,public static java.lang.String buildKeyName(long, int, boolean) ,public boolean doInsert(site.ycsb.DB, java.lang.Object) ,public boolean doTransaction(site.ycsb.DB, java.lang.Object) ,public void doTransactionInsert(site.ycsb.DB) ,public void doTransactionRead(site.ycsb.DB) ,public void doTransactionReadModifyWrite(site.ycsb.DB) ,public void doTransactionScan(site.ycsb.DB) ,public void doTransactionUpdate(site.ycsb.DB) ,public void init(java.util.Properties) throws site.ycsb.WorkloadException<variables>public static final java.lang.String DATA_INTEGRITY_PROPERTY,public static final java.lang.String DATA_INTEGRITY_PROPERTY_DEFAULT,public static final java.lang.String FIELD_COUNT_PROPERTY,public static final java.lang.String FIELD_COUNT_PROPERTY_DEFAULT,public static final java.lang.String FIELD_LENGTH_DISTRIBUTION_PROPERTY,public static final java.lang.String FIELD_LENGTH_DISTRIBUTION_PROPERTY_DEFAULT,public static final java.lang.String FIELD_LENGTH_HISTOGRAM_FILE_PROPERTY,public static final java.lang.String FIELD_LENGTH_HISTOGRAM_FILE_PROPERTY_DEFAULT,public static final java.lang.String FIELD_LENGTH_PROPERTY,public static final java.lang.String FIELD_LENGTH_PROPERTY_DEFAULT,public static final java.lang.String FIELD_NAME_PREFIX,public static final java.lang.String FIELD_NAME_PREFIX_DEFAULT,public static final java.lang.String HOTSPOT_DATA_FRACTION,public static final java.lang.String HOTSPOT_DATA_FRACTION_DEFAULT,public static final java.lang.String HOTSPOT_OPN_FRACTION,public static final java.lang.String HOTSPOT_OPN_FRACTION_DEFAULT,public static final java.lang.String INSERTION_RETRY_INTERVAL,public static final java.lang.String INSERTION_RETRY_INTERVAL_DEFAULT,public static final java.lang.String INSERTION_RETRY_LIMIT,public static final java.lang.String INSERTION_RETRY_LIMIT_DEFAULT,public static final java.lang.String INSERT_ORDER_PROPERTY,public static final java.lang.String INSERT_ORDER_PROPERTY_DEFAULT,public static final java.lang.String INSERT_PROPORTION_PROPERTY,public static final java.lang.String INSERT_PROPORTION_PROPERTY_DEFAULT,public static final java.lang.String MAX_SCAN_LENGTH_PROPERTY,public static final java.lang.String MAX_SCAN_LENGTH_PROPERTY_DEFAULT,public static final java.lang.String MIN_FIELD_LENGTH_PROPERTY,public static final java.lang.String MIN_FIELD_LENGTH_PROPERTY_DEFAULT,public static final java.lang.String MIN_SCAN_LENGTH_PROPERTY,public static final java.lang.String MIN_SCAN_LENGTH_PROPERTY_DEFAULT,public static final java.lang.String READMODIFYWRITE_PROPORTION_PROPERTY,public static final java.lang.String READMODIFYWRITE_PROPORTION_PROPERTY_DEFAULT,public static final java.lang.String READ_ALL_FIELDS_BY_NAME_PROPERTY,public static final java.lang.String READ_ALL_FIELDS_BY_NAME_PROPERTY_DEFAULT,public static final java.lang.String READ_ALL_FIELDS_PROPERTY,public static final java.lang.String READ_ALL_FIELDS_PROPERTY_DEFAULT,public static final java.lang.String READ_PROPORTION_PROPERTY,public static final java.lang.String READ_PROPORTION_PROPERTY_DEFAULT,public static final java.lang.String REQUEST_DISTRIBUTION_PROPERTY,public static final java.lang.String REQUEST_DISTRIBUTION_PROPERTY_DEFAULT,public static final java.lang.String SCAN_LENGTH_DISTRIBUTION_PROPERTY,public static final java.lang.String SCAN_LENGTH_DISTRIBUTION_PROPERTY_DEFAULT,public static final java.lang.String SCAN_PROPORTION_PROPERTY,public static final java.lang.String SCAN_PROPORTION_PROPERTY_DEFAULT,public static final java.lang.String TABLENAME_PROPERTY,public static final java.lang.String TABLENAME_PROPERTY_DEFAULT,public static final java.lang.String UPDATE_PROPORTION_PROPERTY,public static final java.lang.String UPDATE_PROPORTION_PROPERTY_DEFAULT,public static final java.lang.String WRITE_ALL_FIELDS_PROPERTY,public static final java.lang.String WRITE_ALL_FIELDS_PROPERTY_DEFAULT,public static final java.lang.String ZERO_PADDING_PROPERTY,public static final java.lang.String ZERO_PADDING_PROPERTY_DEFAULT,private boolean dataintegrity,protected site.ycsb.generator.NumberGenerator fieldchooser,protected long fieldcount,protected site.ycsb.generator.NumberGenerator fieldlengthgenerator,private List<java.lang.String> fieldnames,protected int insertionRetryInterval,protected int insertionRetryLimit,protected site.ycsb.generator.NumberGenerator keychooser,protected site.ycsb.generator.NumberGenerator keysequence,private site.ycsb.measurements.Measurements measurements,protected site.ycsb.generator.DiscreteGenerator operationchooser,protected boolean orderedinserts,protected boolean readallfields,protected boolean readallfieldsbyname,protected long recordcount,protected site.ycsb.generator.NumberGenerator scanlength,protected java.lang.String table,protected site.ycsb.generator.AcknowledgedCounterGenerator transactioninsertkeysequence,protected boolean writeallfields,protected int zeropadding
|
brianfrankcooper_YCSB
|
YCSB/crail/src/main/java/site/ycsb/db/crail/CrailClient.java
|
CrailClient
|
insert
|
class CrailClient extends DB {
private static final Logger LOG = LoggerFactory.getLogger(CrailClient.class);
private CrailStore client;
private long startTime;
private long endTime;
private String usertable;
private boolean enumerateKeys;
@Override
public void init() throws DBException {
super.init();
try {
CrailConfiguration crailConf = new CrailConfiguration();
this.client = CrailStore.newInstance(crailConf);
usertable = getProperties().getProperty("table", "usertable");
enumerateKeys = Boolean.parseBoolean(getProperties().getProperty("crail.enumeratekeys", "false"));
if (client.lookup(usertable).get() == null) {
client.create(usertable, CrailNodeType.TABLE, CrailStorageClass.DEFAULT,
CrailLocationClass.DEFAULT, true).get().syncDir();
}
this.startTime = System.nanoTime();
} catch(Exception e){
throw new DBException(e);
}
}
@Override
public void cleanup() throws DBException {
try {
this.endTime = System.nanoTime();
long runTime = (endTime - startTime) / 1000000;
client.close();
} catch(Exception e){
throw new DBException(e);
}
}
@Override
public Status read(String table, String key, Set<String> fields, Map<String, ByteIterator> result) {
try {
String path = table + "/" + key;
CrailKeyValue file = client.lookup(path).get().asKeyValue();
CrailBufferedInputStream stream = file.getBufferedInputStream(1024);
while(stream.available() < Integer.BYTES){
assert true;
}
int fieldKeyLength = stream.readInt();
while(stream.available() < fieldKeyLength){
assert true;
}
byte[] fieldKey = new byte[fieldKeyLength];
int res = stream.read(fieldKey);
if (res != fieldKey.length){
stream.close();
return Status.ERROR;
}
while(stream.available() < Integer.BYTES){
assert true;
}
int fieldValueLength = stream.readInt();
while(stream.available() < fieldValueLength){
assert true;
}
byte[] fieldValue = new byte[fieldValueLength];
res = stream.read(fieldValue);
if (res != fieldValue.length){
stream.close();
return Status.ERROR;
}
result.put(new String(fieldKey), new ByteArrayByteIterator(fieldValue));
stream.close();
return Status.OK;
} catch(Exception e){
LOG.error("Error during read, table " + table + ", key " + key + ", exception " + e.getMessage());
return new Status("read error", "reading exception");
}
}
@Override
public Status scan(String table, String startKey, int recordCount, Set<String> fields,
Vector<HashMap<String, ByteIterator>> result) {
return Status.NOT_IMPLEMENTED;
}
@Override
public Status update(String table, String key, Map<String, ByteIterator> values) {
return insert(table, key, values);
}
@Override
public Status insert(String table, String key, Map<String, ByteIterator> values) {<FILL_FUNCTION_BODY>}
@Override
public Status delete(String table, String key) {
try {
String path = table + "/" + key;
client.delete(path, false).get().syncDir();
} catch(Exception e){
LOG.error("Error during delete, table " + table + ", key " + key + ", exception " + e.getMessage());
return Status.ERROR;
}
return Status.OK;
}
}
|
try {
String path = table + "/" + key;
CrailKeyValue file = client.create(path, CrailNodeType.KEYVALUE, CrailStorageClass.DEFAULT,
CrailLocationClass.DEFAULT, enumerateKeys).get().asKeyValue();
CrailBufferedOutputStream stream = file.getBufferedOutputStream(1024);
for (Entry<String, ByteIterator> entry : values.entrySet()){
byte[] fieldKey = entry.getKey().getBytes();
int fieldKeyLength = fieldKey.length;
byte[] fieldValue = entry.getValue().toArray();
int fieldValueLength = fieldValue.length;
stream.writeInt(fieldKeyLength);
stream.write(fieldKey);
stream.writeInt(fieldValueLength);
stream.write(fieldValue);
}
file.syncDir();
stream.close();
} catch(Exception e){
LOG.error("Error during insert, table " + table + ", key " + key + ", exception " + e.getMessage());
return Status.ERROR;
}
return Status.OK;
| 1,004
| 271
| 1,275
|
<methods>public non-sealed void <init>() ,public void cleanup() throws site.ycsb.DBException,public abstract site.ycsb.Status delete(java.lang.String, java.lang.String) ,public java.util.Properties getProperties() ,public void init() throws site.ycsb.DBException,public abstract site.ycsb.Status insert(java.lang.String, java.lang.String, Map<java.lang.String,site.ycsb.ByteIterator>) ,public abstract site.ycsb.Status read(java.lang.String, java.lang.String, Set<java.lang.String>, Map<java.lang.String,site.ycsb.ByteIterator>) ,public abstract site.ycsb.Status scan(java.lang.String, java.lang.String, int, Set<java.lang.String>, Vector<HashMap<java.lang.String,site.ycsb.ByteIterator>>) ,public void setProperties(java.util.Properties) ,public abstract site.ycsb.Status update(java.lang.String, java.lang.String, Map<java.lang.String,site.ycsb.ByteIterator>) <variables>private java.util.Properties properties
|
brianfrankcooper_YCSB
|
YCSB/elasticsearch5/src/main/java/site/ycsb/db/elasticsearch5/Elasticsearch5.java
|
Elasticsearch5
|
parseIntegerProperty
|
class Elasticsearch5 {
private Elasticsearch5() {
}
static final String KEY = "key";
static int parseIntegerProperty(final Properties properties, final String key, final int defaultValue) {<FILL_FUNCTION_BODY>}
}
|
final String value = properties.getProperty(key);
return value == null ? defaultValue : Integer.parseInt(value);
| 70
| 33
| 103
|
<no_super_class>
|
brianfrankcooper_YCSB
|
YCSB/geode/src/main/java/site/ycsb/db/GeodeClient.java
|
GeodeClient
|
getRegion
|
class GeodeClient extends DB {
/**
* property name of the port where Geode server is listening for connections.
*/
private static final String SERVERPORT_PROPERTY_NAME = "geode.serverport";
/**
* property name of the host where Geode server is running.
*/
private static final String SERVERHOST_PROPERTY_NAME = "geode.serverhost";
/**
* default value of {@link #SERVERHOST_PROPERTY_NAME}.
*/
private static final String SERVERHOST_PROPERTY_DEFAULT = "localhost";
/**
* property name to specify a Geode locator. This property can be used in both
* client server and p2p topology
*/
private static final String LOCATOR_PROPERTY_NAME = "geode.locator";
/**
* property name to specify Geode topology.
*/
private static final String TOPOLOGY_PROPERTY_NAME = "geode.topology";
/**
* value of {@value #TOPOLOGY_PROPERTY_NAME} when peer to peer topology should be used.
* (client-server topology is default)
*/
private static final String TOPOLOGY_P2P_VALUE = "p2p";
/**
* Pattern to split up a locator string in the form host[port].
*/
private static final Pattern LOCATOR_PATTERN = Pattern.compile("(.+)\\[(\\d+)\\]");;
private GemFireCache cache;
/**
* true if ycsb client runs as a client to a Geode cache server.
*/
private boolean isClient;
@Override
public void init() throws DBException {
Properties props = getProperties();
// hostName where Geode cacheServer is running
String serverHost = null;
// port of Geode cacheServer
int serverPort = 0;
String locatorStr = null;
if (props != null && !props.isEmpty()) {
String serverPortStr = props.getProperty(SERVERPORT_PROPERTY_NAME);
if (serverPortStr != null) {
serverPort = Integer.parseInt(serverPortStr);
}
serverHost = props.getProperty(SERVERHOST_PROPERTY_NAME, SERVERHOST_PROPERTY_DEFAULT);
locatorStr = props.getProperty(LOCATOR_PROPERTY_NAME);
String topology = props.getProperty(TOPOLOGY_PROPERTY_NAME);
if (topology != null && topology.equals(TOPOLOGY_P2P_VALUE)) {
CacheFactory cf = new CacheFactory();
if (locatorStr != null) {
cf.set("locators", locatorStr);
}
cache = cf.create();
isClient = false;
return;
}
}
isClient = true;
ClientCacheFactory ccf = new ClientCacheFactory();
ccf.setPdxReadSerialized(true);
if (serverPort != 0) {
ccf.addPoolServer(serverHost, serverPort);
} else {
InetSocketAddress locatorAddress = getLocatorAddress(locatorStr);
ccf.addPoolLocator(locatorAddress.getHostName(), locatorAddress.getPort());
}
cache = ccf.create();
}
static InetSocketAddress getLocatorAddress(String locatorStr) {
Matcher matcher = LOCATOR_PATTERN.matcher(locatorStr);
if(!matcher.matches()) {
throw new IllegalStateException("Unable to parse locator: " + locatorStr);
}
return new InetSocketAddress(matcher.group(1), Integer.parseInt(matcher.group(2)));
}
@Override
public Status read(String table, String key, Set<String> fields,
Map<String, ByteIterator> result) {
Region<String, PdxInstance> r = getRegion(table);
PdxInstance val = r.get(key);
if (val != null) {
if (fields == null) {
for (String fieldName : val.getFieldNames()) {
result.put(fieldName, new ByteArrayByteIterator((byte[]) val.getField(fieldName)));
}
} else {
for (String field : fields) {
result.put(field, new ByteArrayByteIterator((byte[]) val.getField(field)));
}
}
return Status.OK;
}
return Status.ERROR;
}
@Override
public Status scan(String table, String startkey, int recordcount,
Set<String> fields, Vector<HashMap<String, ByteIterator>> result) {
// Geode does not support scan
return Status.ERROR;
}
@Override
public Status update(String table, String key, Map<String, ByteIterator> values) {
getRegion(table).put(key, convertToBytearrayMap(values));
return Status.OK;
}
@Override
public Status insert(String table, String key, Map<String, ByteIterator> values) {
getRegion(table).put(key, convertToBytearrayMap(values));
return Status.OK;
}
@Override
public Status delete(String table, String key) {
getRegion(table).destroy(key);
return Status.OK;
}
private PdxInstance convertToBytearrayMap(Map<String, ByteIterator> values) {
PdxInstanceFactory pdxInstanceFactory = cache.createPdxInstanceFactory(JSONFormatter.JSON_CLASSNAME);
for (Map.Entry<String, ByteIterator> entry : values.entrySet()) {
pdxInstanceFactory.writeByteArray(entry.getKey(), entry.getValue().toArray());
}
return pdxInstanceFactory.create();
}
private Region<String, PdxInstance> getRegion(String table) {<FILL_FUNCTION_BODY>}
}
|
Region<String, PdxInstance> r = cache.getRegion(table);
if (r == null) {
try {
if (isClient) {
ClientRegionFactory<String, PdxInstance> crf =
((ClientCache) cache).createClientRegionFactory(ClientRegionShortcut.PROXY);
r = crf.create(table);
} else {
RegionFactory<String, PdxInstance> rf = ((Cache) cache).createRegionFactory(RegionShortcut.PARTITION);
r = rf.create(table);
}
} catch (RegionExistsException e) {
// another thread created the region
r = cache.getRegion(table);
}
}
return r;
| 1,502
| 180
| 1,682
|
<methods>public non-sealed void <init>() ,public void cleanup() throws site.ycsb.DBException,public abstract site.ycsb.Status delete(java.lang.String, java.lang.String) ,public java.util.Properties getProperties() ,public void init() throws site.ycsb.DBException,public abstract site.ycsb.Status insert(java.lang.String, java.lang.String, Map<java.lang.String,site.ycsb.ByteIterator>) ,public abstract site.ycsb.Status read(java.lang.String, java.lang.String, Set<java.lang.String>, Map<java.lang.String,site.ycsb.ByteIterator>) ,public abstract site.ycsb.Status scan(java.lang.String, java.lang.String, int, Set<java.lang.String>, Vector<HashMap<java.lang.String,site.ycsb.ByteIterator>>) ,public void setProperties(java.util.Properties) ,public abstract site.ycsb.Status update(java.lang.String, java.lang.String, Map<java.lang.String,site.ycsb.ByteIterator>) <variables>private java.util.Properties properties
|
brianfrankcooper_YCSB
|
YCSB/griddb/src/main/java/site/ycsb/db/griddb/GridDBClient.java
|
RowComparator
|
update
|
class RowComparator implements Comparator<Row> {
public int compare(Row row1, Row row2) throws NullPointerException {
int result = 0;
try {
Object val1 = row1.getValue(0);
Object val2 = row2.getValue(0);
result = ((String)val1).compareTo((String)val2);
} catch (GSException e) {
LOGGER.severe("There is a exception: " + e.getMessage());
throw new NullPointerException();
}
return result;
}
}
public void init() throws DBException {
LOGGER.info("GridDBClient");
final Properties props = getProperties();
notificationAddress = props.getProperty("notificationAddress");
notificationPort = props.getProperty("notificationPort");
notificationMember = props.getProperty("notificationMember");
clusterName = props.getProperty("clusterName");
userName = props.getProperty("userName");
password = props.getProperty("password");
containerPrefix = props.getProperty("table", "usertable") + "@";
String fieldcount = props.getProperty("fieldcount");
String fieldlength = props.getProperty("fieldlength");
LOGGER.info("notificationAddress=" + notificationAddress + " notificationPort=" + notificationPort +
" notificationMember=" + notificationMember);
LOGGER.info("clusterName=" + clusterName + " userName=" + userName);
LOGGER.info("fieldcount=" + fieldcount + " fieldlength=" + fieldlength);
final Properties gridstoreProp = new Properties();
if (clusterName == null || userName == null || password == null) {
LOGGER.severe("[ERROR] clusterName or userName or password argument not specified");
throw new DBException();
}
if (fieldcount == null || fieldlength == null) {
LOGGER.severe("[ERROR] fieldcount or fieldlength argument not specified");
throw new DBException();
} else {
if (!fieldcount.equals(String.valueOf(FIELD_NUM)) || !fieldlength.equals("100")) {
LOGGER.severe("[ERROR] Invalid argment: fieldcount or fieldlength");
throw new DBException();
}
}
if (notificationAddress != null) {
if (notificationPort == null) {
LOGGER.severe("[ERROR] notificationPort argument not specified");
throw new DBException();
}
//(A)multicast method
gridstoreProp.setProperty("notificationAddress", notificationAddress);
gridstoreProp.setProperty("notificationPort", notificationPort);
} else if (notificationMember != null) {
//(B)fixed list method
gridstoreProp.setProperty("notificationMember", notificationMember);
} else {
LOGGER.severe("[ERROR] notificationAddress and notificationMember argument not specified");
throw new DBException();
}
gridstoreProp.setProperty("clusterName", clusterName);
gridstoreProp.setProperty("user", userName);
gridstoreProp.setProperty("password", password);
gridstoreProp.setProperty("containerCacheSize", String.valueOf(DEFAULT_CACHE_CONTAINER_NUM));
List<ColumnInfo> columnInfoList = new ArrayList<ColumnInfo>();
ColumnInfo keyInfo = new ColumnInfo("key", SCHEMA_TYPE);
columnInfoList.add(keyInfo);
for (int i = 0; i < FIELD_NUM; i++) {
String columnName = String.format(VALUE_COLUMN_NAME_PREFIX + "%d", i);
ColumnInfo info = new ColumnInfo(columnName, SCHEMA_TYPE);
columnInfoList.add(info);
}
containerInfo = new ContainerInfo(null, ContainerType.COLLECTION, columnInfoList, true);
try {
GridStoreFactory.getInstance().setProperties(gridstoreProp);
store = GridStoreFactory.getInstance().getGridStore(gridstoreProp);
PartitionController controller = store.getPartitionController();
numContainer = controller.getPartitionCount();
for(int k = 0; k < numContainer; k++) {
String name = containerPrefix + k;
store.putContainer(name, containerInfo, false);
}
} catch (GSException e) {
LOGGER.severe("Exception: " + e.getMessage());
throw new DBException();
}
LOGGER.info("numContainer=" + numContainer + " containerCasheSize=" +
String.valueOf(DEFAULT_CACHE_CONTAINER_NUM));
}
public void cleanup() throws DBException {
try {
store.close();
} catch (GSException e) {
LOGGER.severe("Exception when close." + e.getMessage());
throw new DBException();
}
}
public Status read(String table, String key, Set<String> fields, Map<String, ByteIterator> result) {
try {
Object rowKey = makeRowKey(key);
String containerKey = makeContainerKey(key);
final Container<Object, Row> container = store.getContainer(containerKey);
if(container == null) {
LOGGER.severe("[ERROR]getCollection " + containerKey + " in read()");
return Status.ERROR;
}
Row targetRow = container.get(rowKey);
if (targetRow == null) {
LOGGER.severe("[ERROR]get(rowKey) in read()");
return Status.ERROR;
}
for (int i = 1; i < containerInfo.getColumnCount(); i++) {
result.put(containerInfo.getColumnInfo(i).getName(),
new ByteArrayByteIterator(targetRow.getValue(i).toString().getBytes()));
}
return Status.OK;
} catch (GSException e) {
LOGGER.severe("Exception: " + e.getMessage());
return Status.ERROR;
}
}
public Status scan(String table, String startkey, int recordcount, Set<String> fields,
Vector<HashMap<String, ByteIterator>> result) {
LOGGER.severe("[ERROR]scan() not supported");
return Status.ERROR;
}
public Status update(String table, String key, Map<String, ByteIterator> values) {<FILL_FUNCTION_BODY>
|
try {
Object rowKey = makeRowKey(key);
String containerKey = makeContainerKey(key);
final Container<Object, Row> container = store.getContainer(containerKey);
if(container == null) {
LOGGER.severe("[ERROR]getCollection " + containerKey + " in update()");
return Status.ERROR;
}
Row targetRow = container.get(rowKey);
if (targetRow == null) {
LOGGER.severe("[ERROR]get(rowKey) in update()");
return Status.ERROR;
}
int setCount = 0;
for (int i = 1; i < containerInfo.getColumnCount() && setCount < values.size(); i++) {
containerInfo.getColumnInfo(i).getName();
ByteIterator byteIterator = values.get(containerInfo.getColumnInfo(i).getName());
if (byteIterator != null) {
Object value = makeValue(byteIterator);
targetRow.setValue(i, value);
setCount++;
}
}
if (setCount != values.size()) {
LOGGER.severe("Error setCount = " + setCount);
return Status.ERROR;
}
container.put(targetRow);
return Status.OK;
} catch (GSException e) {
LOGGER.severe("Exception: " + e.getMessage());
return Status.ERROR;
}
| 1,592
| 362
| 1,954
|
<methods>public non-sealed void <init>() ,public void cleanup() throws site.ycsb.DBException,public abstract site.ycsb.Status delete(java.lang.String, java.lang.String) ,public java.util.Properties getProperties() ,public void init() throws site.ycsb.DBException,public abstract site.ycsb.Status insert(java.lang.String, java.lang.String, Map<java.lang.String,site.ycsb.ByteIterator>) ,public abstract site.ycsb.Status read(java.lang.String, java.lang.String, Set<java.lang.String>, Map<java.lang.String,site.ycsb.ByteIterator>) ,public abstract site.ycsb.Status scan(java.lang.String, java.lang.String, int, Set<java.lang.String>, Vector<HashMap<java.lang.String,site.ycsb.ByteIterator>>) ,public void setProperties(java.util.Properties) ,public abstract site.ycsb.Status update(java.lang.String, java.lang.String, Map<java.lang.String,site.ycsb.ByteIterator>) <variables>private java.util.Properties properties
|
brianfrankcooper_YCSB
|
YCSB/ignite/src/main/java/site/ycsb/db/ignite/IgniteAbstractClient.java
|
IgniteAbstractClient
|
init
|
class IgniteAbstractClient extends DB {
/** */
protected static Logger log = LogManager.getLogger(IgniteAbstractClient.class);
protected static final String DEFAULT_CACHE_NAME = "usertable";
protected static final String HOSTS_PROPERTY = "hosts";
protected static final String PORTS_PROPERTY = "ports";
protected static final String CLIENT_NODE_NAME = "YCSB client node";
protected static final String PORTS_DEFAULTS = "47500..47509";
/**
* Count the number of times initialized to teardown on the last
* {@link #cleanup()}.
*/
protected static final AtomicInteger INIT_COUNT = new AtomicInteger(0);
/** Ignite cluster. */
protected static Ignite cluster = null;
/** Ignite cache to store key-values. */
protected static IgniteCache<String, BinaryObject> cache = null;
/** Debug flag. */
protected static boolean debug = false;
protected static TcpDiscoveryIpFinder ipFinder = new TcpDiscoveryVmIpFinder(true);
/**
* 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>}
/**
* Cleanup any state for this DB. Called once per DB instance; there is one DB
* instance per client thread.
*/
@Override
public void cleanup() throws DBException {
synchronized (INIT_COUNT) {
final int curInitCount = INIT_COUNT.decrementAndGet();
if (curInitCount <= 0) {
cluster.close();
cluster = null;
}
if (curInitCount < 0) {
// This should never happen.
throw new DBException(
String.format("initCount is negative: %d", curInitCount));
}
}
}
@Override
public Status scan(String table, String startkey, int recordcount,
Set<String> fields, Vector<HashMap<String, ByteIterator>> result) {
return Status.NOT_IMPLEMENTED;
}
}
|
// Keep track of number of calls to init (for later cleanup)
INIT_COUNT.incrementAndGet();
// Synchronized so that we only have a single
// cluster/session instance for all the threads.
synchronized (INIT_COUNT) {
// Check if the cluster has already been initialized
if (cluster != null) {
return;
}
try {
debug = Boolean.parseBoolean(getProperties().getProperty("debug", "false"));
IgniteConfiguration igcfg = new IgniteConfiguration();
igcfg.setIgniteInstanceName(CLIENT_NODE_NAME);
String host = getProperties().getProperty(HOSTS_PROPERTY);
if (host == null) {
throw new DBException(String.format(
"Required property \"%s\" missing for Ignite Cluster",
HOSTS_PROPERTY));
}
String ports = getProperties().getProperty(PORTS_PROPERTY, PORTS_DEFAULTS);
if (ports == null) {
throw new DBException(String.format(
"Required property \"%s\" missing for Ignite Cluster",
PORTS_PROPERTY));
}
System.setProperty("IGNITE_QUIET", "false");
TcpDiscoverySpi disco = new TcpDiscoverySpi();
Collection<String> addrs = new LinkedHashSet<>();
addrs.add(host + ":" + ports);
((TcpDiscoveryVmIpFinder) ipFinder).setAddresses(addrs);
disco.setIpFinder(ipFinder);
igcfg.setDiscoverySpi(disco);
igcfg.setNetworkTimeout(2000);
igcfg.setClientMode(true);
Log4J2Logger logger = new Log4J2Logger(this.getClass().getClassLoader().getResource("log4j2.xml"));
igcfg.setGridLogger(logger);
log.info("Start Ignite client node.");
cluster = Ignition.start(igcfg);
log.info("Activate Ignite cluster.");
cluster.active(true);
cache = cluster.cache(DEFAULT_CACHE_NAME).withKeepBinary();
if(cache == null) {
throw new DBException(new IgniteCheckedException("Failed to find cache " + DEFAULT_CACHE_NAME));
}
} catch (Exception e) {
throw new DBException(e);
}
} // synchronized
| 572
| 635
| 1,207
|
<methods>public non-sealed void <init>() ,public void cleanup() throws site.ycsb.DBException,public abstract site.ycsb.Status delete(java.lang.String, java.lang.String) ,public java.util.Properties getProperties() ,public void init() throws site.ycsb.DBException,public abstract site.ycsb.Status insert(java.lang.String, java.lang.String, Map<java.lang.String,site.ycsb.ByteIterator>) ,public abstract site.ycsb.Status read(java.lang.String, java.lang.String, Set<java.lang.String>, Map<java.lang.String,site.ycsb.ByteIterator>) ,public abstract site.ycsb.Status scan(java.lang.String, java.lang.String, int, Set<java.lang.String>, Vector<HashMap<java.lang.String,site.ycsb.ByteIterator>>) ,public void setProperties(java.util.Properties) ,public abstract site.ycsb.Status update(java.lang.String, java.lang.String, Map<java.lang.String,site.ycsb.ByteIterator>) <variables>private java.util.Properties properties
|
brianfrankcooper_YCSB
|
YCSB/ignite/src/main/java/site/ycsb/db/ignite/IgniteClient.java
|
IgniteClient
|
insert
|
class IgniteClient extends IgniteAbstractClient {
/** */
private static Logger log = LogManager.getLogger(IgniteClient.class);
/** Cached binary type. */
private BinaryType binType = null;
/** Cached binary type's fields. */
private final ConcurrentHashMap<String, BinaryField> fieldsCache = new ConcurrentHashMap<>();
/**
* Read a record from the database. Each field/value pair from the result will
* be stored in a HashMap.
*
* @param table The name of the table
* @param key The record key of the record to read.
* @param fields The list of fields to read, or null for all of them
* @param result A HashMap of field/value pairs for the result
* @return Zero on success, a non-zero error code on error
*/
@Override
public Status read(String table, String key, Set<String> fields,
Map<String, ByteIterator> result) {
try {
BinaryObject po = cache.get(key);
if (po == null) {
return Status.NOT_FOUND;
}
if (binType == null) {
binType = po.type();
}
for (String s : F.isEmpty(fields) ? binType.fieldNames() : fields) {
BinaryField bfld = fieldsCache.get(s);
if (bfld == null) {
bfld = binType.field(s);
fieldsCache.put(s, bfld);
}
String val = bfld.value(po);
if (val != null) {
result.put(s, new StringByteIterator(val));
}
if (debug) {
log.info("table:{" + table + "}, key:{" + key + "}" + ", fields:{" + fields + "}");
log.info("fields in po{" + binType.fieldNames() + "}");
log.info("result {" + result + "}");
}
}
return Status.OK;
} catch (Exception e) {
log.error(String.format("Error reading key: %s", key), e);
return Status.ERROR;
}
}
/**
* Update a record in the database. Any field/value pairs in the specified
* values HashMap will be written into the record with the specified record
* key, overwriting any existing values with the same field name.
*
* @param table The name of the table
* @param key The record key of the record to write.
* @param values A HashMap of field/value pairs to update in the record
* @return Zero on success, a non-zero error code on error
*/
@Override
public Status update(String table, String key,
Map<String, ByteIterator> values) {
try {
cache.invoke(key, new Updater(values));
return Status.OK;
} catch (Exception e) {
log.error(String.format("Error updating key: %s", key), e);
return Status.ERROR;
}
}
/**
* Insert a record in the database. Any field/value pairs in the specified
* values HashMap will be written into the record with the specified record
* key.
*
* @param table The name of the table
* @param key The record key of the record to insert.
* @param values A HashMap of field/value pairs to insert in the record
* @return Zero on success, a non-zero error code on error
*/
@Override
public Status insert(String table, String key,
Map<String, ByteIterator> values) {<FILL_FUNCTION_BODY>}
/**
* Delete a record from the database.
*
* @param table The name of the table
* @param key The record key of the record to delete.
* @return Zero on success, a non-zero error code on error
*/
@Override
public Status delete(String table, String key) {
try {
cache.remove(key);
return Status.OK;
} catch (Exception e) {
log.error(String.format("Error deleting key: %s ", key), e);
}
return Status.ERROR;
}
/**
* Entry processor to update values.
*/
public static class Updater implements CacheEntryProcessor<String, BinaryObject, Object> {
private String[] flds;
private String[] vals;
/**
* @param values Updated fields.
*/
Updater(Map<String, ByteIterator> values) {
flds = new String[values.size()];
vals = new String[values.size()];
int idx = 0;
for (Map.Entry<String, ByteIterator> e : values.entrySet()) {
flds[idx] = e.getKey();
vals[idx] = e.getValue().toString();
++idx;
}
}
/**
* {@inheritDoc}
*/
@Override
public Object process(MutableEntry<String, BinaryObject> mutableEntry, Object... objects)
throws EntryProcessorException {
BinaryObjectBuilder bob = mutableEntry.getValue().toBuilder();
for (int i = 0; i < flds.length; ++i) {
bob.setField(flds[i], vals[i]);
}
mutableEntry.setValue(bob.build());
return null;
}
}
}
|
try {
BinaryObjectBuilder bob = cluster.binary().builder("CustomType");
for (Map.Entry<String, ByteIterator> entry : values.entrySet()) {
bob.setField(entry.getKey(), entry.getValue().toString());
if (debug) {
log.info(entry.getKey() + ":" + entry.getValue());
}
}
BinaryObject bo = bob.build();
if (table.equals(DEFAULT_CACHE_NAME)) {
cache.put(key, bo);
} else {
throw new UnsupportedOperationException("Unexpected table name: " + table);
}
return Status.OK;
} catch (Exception e) {
log.error(String.format("Error inserting key: %s", key), e);
return Status.ERROR;
}
| 1,421
| 217
| 1,638
|
<methods>public non-sealed void <init>() ,public void cleanup() throws site.ycsb.DBException,public void init() throws site.ycsb.DBException,public site.ycsb.Status scan(java.lang.String, java.lang.String, int, Set<java.lang.String>, Vector<HashMap<java.lang.String,site.ycsb.ByteIterator>>) <variables>protected static final java.lang.String CLIENT_NODE_NAME,protected static final java.lang.String DEFAULT_CACHE_NAME,protected static final java.lang.String HOSTS_PROPERTY,protected static final java.util.concurrent.atomic.AtomicInteger INIT_COUNT,protected static final java.lang.String PORTS_DEFAULTS,protected static final java.lang.String PORTS_PROPERTY,protected static IgniteCache<java.lang.String,BinaryObject> cache,protected static Ignite cluster,protected static boolean debug,protected static TcpDiscoveryIpFinder ipFinder,protected static Logger log
|
brianfrankcooper_YCSB
|
YCSB/infinispan/src/main/java/site/ycsb/db/InfinispanClient.java
|
InfinispanClient
|
insert
|
class InfinispanClient extends DB {
private static final Log LOGGER = LogFactory.getLog(InfinispanClient.class);
// An optimisation for clustered mode
private final boolean clustered;
private EmbeddedCacheManager infinispanManager;
public InfinispanClient() {
clustered = Boolean.getBoolean("infinispan.clustered");
}
public void init() throws DBException {
try {
infinispanManager = new DefaultCacheManager("infinispan-config.xml");
} catch (IOException e) {
throw new DBException(e);
}
}
public void cleanup() {
infinispanManager.stop();
infinispanManager = null;
}
public Status read(String table, String key, Set<String> fields, Map<String, ByteIterator> result) {
try {
Map<String, String> row;
if (clustered) {
row = AtomicMapLookup.getAtomicMap(infinispanManager.getCache(table), key, false);
} else {
Cache<String, Map<String, String>> cache = infinispanManager.getCache(table);
row = cache.get(key);
}
if (row != null) {
result.clear();
if (fields == null || fields.isEmpty()) {
StringByteIterator.putAllAsByteIterators(result, row);
} else {
for (String field : fields) {
result.put(field, new StringByteIterator(row.get(field)));
}
}
}
return Status.OK;
} catch (Exception e) {
LOGGER.error(e);
return Status.ERROR;
}
}
public Status scan(String table, String startkey, int recordcount,
Set<String> fields, Vector<HashMap<String, ByteIterator>> result) {
LOGGER.warn("Infinispan does not support scan semantics");
return Status.OK;
}
public Status update(String table, String key, Map<String, ByteIterator> values) {
try {
if (clustered) {
AtomicMap<String, String> row = AtomicMapLookup.getAtomicMap(infinispanManager.getCache(table), key);
StringByteIterator.putAllAsStrings(row, values);
} else {
Cache<String, Map<String, String>> cache = infinispanManager.getCache(table);
Map<String, String> row = cache.get(key);
if (row == null) {
row = StringByteIterator.getStringMap(values);
cache.put(key, row);
} else {
StringByteIterator.putAllAsStrings(row, values);
}
}
return Status.OK;
} catch (Exception e) {
LOGGER.error(e);
return Status.ERROR;
}
}
public Status insert(String table, String key, Map<String, ByteIterator> values) {<FILL_FUNCTION_BODY>}
public Status delete(String table, String key) {
try {
if (clustered) {
AtomicMapLookup.removeAtomicMap(infinispanManager.getCache(table), key);
} else {
infinispanManager.getCache(table).remove(key);
}
return Status.OK;
} catch (Exception e) {
LOGGER.error(e);
return Status.ERROR;
}
}
}
|
try {
if (clustered) {
AtomicMap<String, String> row = AtomicMapLookup.getAtomicMap(infinispanManager.getCache(table), key);
row.clear();
StringByteIterator.putAllAsStrings(row, values);
} else {
infinispanManager.getCache(table).put(key, values);
}
return Status.OK;
} catch (Exception e) {
LOGGER.error(e);
return Status.ERROR;
}
| 890
| 136
| 1,026
|
<methods>public non-sealed void <init>() ,public void cleanup() throws site.ycsb.DBException,public abstract site.ycsb.Status delete(java.lang.String, java.lang.String) ,public java.util.Properties getProperties() ,public void init() throws site.ycsb.DBException,public abstract site.ycsb.Status insert(java.lang.String, java.lang.String, Map<java.lang.String,site.ycsb.ByteIterator>) ,public abstract site.ycsb.Status read(java.lang.String, java.lang.String, Set<java.lang.String>, Map<java.lang.String,site.ycsb.ByteIterator>) ,public abstract site.ycsb.Status scan(java.lang.String, java.lang.String, int, Set<java.lang.String>, Vector<HashMap<java.lang.String,site.ycsb.ByteIterator>>) ,public void setProperties(java.util.Properties) ,public abstract site.ycsb.Status update(java.lang.String, java.lang.String, Map<java.lang.String,site.ycsb.ByteIterator>) <variables>private java.util.Properties properties
|
brianfrankcooper_YCSB
|
YCSB/infinispan/src/main/java/site/ycsb/db/InfinispanRemoteClient.java
|
InfinispanRemoteClient
|
read
|
class InfinispanRemoteClient extends DB {
private static final Log LOGGER = LogFactory.getLog(InfinispanRemoteClient.class);
private RemoteCacheManager remoteIspnManager;
private String cacheName = null;
@Override
public void init() throws DBException {
remoteIspnManager = RemoteCacheManagerHolder.getInstance(getProperties());
cacheName = getProperties().getProperty("cache");
}
@Override
public void cleanup() {
remoteIspnManager.stop();
remoteIspnManager = null;
}
@Override
public Status insert(String table, String recordKey, Map<String, ByteIterator> values) {
String compositKey = createKey(table, recordKey);
Map<String, String> stringValues = new HashMap<>();
StringByteIterator.putAllAsStrings(stringValues, values);
try {
cache().put(compositKey, stringValues);
return Status.OK;
} catch (Exception e) {
LOGGER.error(e);
return Status.ERROR;
}
}
@Override
public Status read(String table, String recordKey, Set<String> fields, Map<String, ByteIterator> result) {<FILL_FUNCTION_BODY>}
@Override
public Status scan(String table, String startkey, int recordcount, Set<String> fields,
Vector<HashMap<String, ByteIterator>> result) {
LOGGER.warn("Infinispan does not support scan semantics");
return Status.NOT_IMPLEMENTED;
}
@Override
public Status update(String table, String recordKey, Map<String, ByteIterator> values) {
String compositKey = createKey(table, recordKey);
try {
Map<String, String> stringValues = new HashMap<>();
StringByteIterator.putAllAsStrings(stringValues, values);
cache().put(compositKey, stringValues);
return Status.OK;
} catch (Exception e) {
LOGGER.error(e);
return Status.ERROR;
}
}
@Override
public Status delete(String table, String recordKey) {
String compositKey = createKey(table, recordKey);
try {
cache().remove(compositKey);
return Status.OK;
} catch (Exception e) {
LOGGER.error(e);
return Status.ERROR;
}
}
private RemoteCache<String, Map<String, String>> cache() {
if (this.cacheName != null) {
return remoteIspnManager.getCache(cacheName);
} else {
return remoteIspnManager.getCache();
}
}
private String createKey(String table, String recordKey) {
return table + "-" + recordKey;
}
}
|
String compositKey = createKey(table, recordKey);
try {
Map<String, String> values = cache().get(compositKey);
if (values == null || values.isEmpty()) {
return Status.NOT_FOUND;
}
if (fields == null) { //get all field/value pairs
StringByteIterator.putAllAsByteIterators(result, values);
} else {
for (String field : fields) {
String value = values.get(field);
if (value != null) {
result.put(field, new StringByteIterator(value));
}
}
}
return Status.OK;
} catch (Exception e) {
LOGGER.error(e);
return Status.ERROR;
}
| 716
| 198
| 914
|
<methods>public non-sealed void <init>() ,public void cleanup() throws site.ycsb.DBException,public abstract site.ycsb.Status delete(java.lang.String, java.lang.String) ,public java.util.Properties getProperties() ,public void init() throws site.ycsb.DBException,public abstract site.ycsb.Status insert(java.lang.String, java.lang.String, Map<java.lang.String,site.ycsb.ByteIterator>) ,public abstract site.ycsb.Status read(java.lang.String, java.lang.String, Set<java.lang.String>, Map<java.lang.String,site.ycsb.ByteIterator>) ,public abstract site.ycsb.Status scan(java.lang.String, java.lang.String, int, Set<java.lang.String>, Vector<HashMap<java.lang.String,site.ycsb.ByteIterator>>) ,public void setProperties(java.util.Properties) ,public abstract site.ycsb.Status update(java.lang.String, java.lang.String, Map<java.lang.String,site.ycsb.ByteIterator>) <variables>private java.util.Properties properties
|
brianfrankcooper_YCSB
|
YCSB/infinispan/src/main/java/site/ycsb/db/RemoteCacheManagerHolder.java
|
RemoteCacheManagerHolder
|
getInstance
|
class RemoteCacheManagerHolder {
private static volatile RemoteCacheManager cacheManager = null;
private RemoteCacheManagerHolder() {
}
static RemoteCacheManager getInstance(Properties props) {<FILL_FUNCTION_BODY>}
}
|
RemoteCacheManager result = cacheManager;
if (result == null) {
synchronized (RemoteCacheManagerHolder.class) {
result = cacheManager;
if (result == null) {
result = new RemoteCacheManager(props);
cacheManager = new RemoteCacheManager(props);
}
}
}
return result;
| 62
| 88
| 150
|
<no_super_class>
|
brianfrankcooper_YCSB
|
YCSB/jdbc/src/main/java/site/ycsb/db/JdbcDBCli.java
|
JdbcDBCli
|
executeCommand
|
class JdbcDBCli {
private static void usageMessage() {
System.out.println("JdbcCli. Options:");
System.out.println(" -p key=value properties defined.");
System.out.println(" -P location of the properties file to load.");
System.out.println(" -c SQL command to execute.");
}
private static void executeCommand(Properties props, String sql) throws SQLException {<FILL_FUNCTION_BODY>}
/**
* @param args
*/
public static void main(String[] args) {
if (args.length == 0) {
usageMessage();
System.exit(0);
}
Properties props = new Properties();
Properties fileprops = new Properties();
String sql = null;
// parse arguments
int argindex = 0;
while (args[argindex].startsWith("-")) {
if (args[argindex].compareTo("-P") == 0) {
argindex++;
if (argindex >= args.length) {
usageMessage();
System.exit(0);
}
String propfile = args[argindex];
argindex++;
Properties myfileprops = new Properties();
try {
myfileprops.load(new FileInputStream(propfile));
} catch (IOException e) {
System.out.println(e.getMessage());
System.exit(0);
}
// Issue #5 - remove call to stringPropertyNames to make compilable
// under Java 1.5
for (Enumeration<?> e = myfileprops.propertyNames(); e.hasMoreElements();) {
String prop = (String) e.nextElement();
fileprops.setProperty(prop, myfileprops.getProperty(prop));
}
} else if (args[argindex].compareTo("-p") == 0) {
argindex++;
if (argindex >= args.length) {
usageMessage();
System.exit(0);
}
int eq = args[argindex].indexOf('=');
if (eq < 0) {
usageMessage();
System.exit(0);
}
String name = args[argindex].substring(0, eq);
String value = args[argindex].substring(eq + 1);
props.put(name, value);
argindex++;
} else if (args[argindex].compareTo("-c") == 0) {
argindex++;
if (argindex >= args.length) {
usageMessage();
System.exit(0);
}
sql = args[argindex++];
} else {
System.out.println("Unknown option " + args[argindex]);
usageMessage();
System.exit(0);
}
if (argindex >= args.length) {
break;
}
}
if (argindex != args.length) {
usageMessage();
System.exit(0);
}
// overwrite file properties with properties from the command line
// Issue #5 - remove call to stringPropertyNames to make compilable under
// Java 1.5
for (Enumeration<?> e = props.propertyNames(); e.hasMoreElements();) {
String prop = (String) e.nextElement();
fileprops.setProperty(prop, props.getProperty(prop));
}
if (sql == null) {
System.err.println("Missing command.");
usageMessage();
System.exit(1);
}
try {
executeCommand(fileprops, sql);
} catch (SQLException e) {
System.err.println("Error in executing command. " + e);
System.exit(1);
}
}
/**
* Hidden constructor.
*/
private JdbcDBCli() {
super();
}
}
|
String driver = props.getProperty(JdbcDBClient.DRIVER_CLASS);
String username = props.getProperty(JdbcDBClient.CONNECTION_USER);
String password = props.getProperty(JdbcDBClient.CONNECTION_PASSWD, "");
String url = props.getProperty(JdbcDBClient.CONNECTION_URL);
if (driver == null || username == null || url == null) {
throw new SQLException("Missing connection information.");
}
Connection conn = null;
try {
Class.forName(driver);
conn = DriverManager.getConnection(url, username, password);
Statement stmt = conn.createStatement();
stmt.execute(sql);
System.out.println("Command \"" + sql + "\" successfully executed.");
} catch (ClassNotFoundException e) {
throw new SQLException("JDBC Driver class not found.");
} finally {
if (conn != null) {
System.out.println("Closing database connection.");
conn.close();
}
}
| 985
| 267
| 1,252
|
<no_super_class>
|
brianfrankcooper_YCSB
|
YCSB/jdbc/src/main/java/site/ycsb/db/JdbcDBClient.java
|
OrderedFieldInfo
|
init
|
class OrderedFieldInfo {
private String fieldKeys;
private List<String> fieldValues;
OrderedFieldInfo(String fieldKeys, List<String> fieldValues) {
this.fieldKeys = fieldKeys;
this.fieldValues = fieldValues;
}
String getFieldKeys() {
return fieldKeys;
}
List<String> getFieldValues() {
return fieldValues;
}
}
/**
* For the given key, returns what shard contains data for this key.
*
* @param key Data key to do operation on
* @return Shard index
*/
private int getShardIndexByKey(String key) {
int ret = Math.abs(key.hashCode()) % conns.size();
return ret;
}
/**
* For the given key, returns Connection object that holds connection to the
* shard that contains this key.
*
* @param key Data key to get information for
* @return Connection object
*/
private Connection getShardConnectionByKey(String key) {
return conns.get(getShardIndexByKey(key));
}
private void cleanupAllConnections() throws SQLException {
for (Connection conn : conns) {
if (!autoCommit) {
conn.commit();
}
conn.close();
}
}
/** Returns parsed int value from the properties if set, otherwise returns -1. */
private static int getIntProperty(Properties props, String key) throws DBException {
String valueStr = props.getProperty(key);
if (valueStr != null) {
try {
return Integer.parseInt(valueStr);
} catch (NumberFormatException nfe) {
System.err.println("Invalid " + key + " specified: " + valueStr);
throw new DBException(nfe);
}
}
return -1;
}
/** Returns parsed boolean value from the properties if set, otherwise returns defaultVal. */
private static boolean getBoolProperty(Properties props, String key, boolean defaultVal) {
String valueStr = props.getProperty(key);
if (valueStr != null) {
return Boolean.parseBoolean(valueStr);
}
return defaultVal;
}
@Override
public void init() throws DBException {<FILL_FUNCTION_BODY>
|
if (initialized) {
System.err.println("Client connection already initialized.");
return;
}
props = getProperties();
String urls = props.getProperty(CONNECTION_URL, DEFAULT_PROP);
String user = props.getProperty(CONNECTION_USER, DEFAULT_PROP);
String passwd = props.getProperty(CONNECTION_PASSWD, DEFAULT_PROP);
String driver = props.getProperty(DRIVER_CLASS);
this.jdbcFetchSize = getIntProperty(props, JDBC_FETCH_SIZE);
this.batchSize = getIntProperty(props, DB_BATCH_SIZE);
this.autoCommit = getBoolProperty(props, JDBC_AUTO_COMMIT, true);
this.batchUpdates = getBoolProperty(props, JDBC_BATCH_UPDATES, false);
try {
// The SQL Syntax for Scan depends on the DB engine
// - SQL:2008 standard: FETCH FIRST n ROWS after the ORDER BY
// - SQL Server before 2012: TOP n after the SELECT
// - others (MySQL,MariaDB, PostgreSQL before 8.4)
// TODO: check product name and version rather than driver name
if (driver != null) {
if (driver.contains("sqlserver")) {
sqlserverScans = true;
sqlansiScans = false;
}
if (driver.contains("oracle")) {
sqlserverScans = false;
sqlansiScans = true;
}
if (driver.contains("postgres")) {
sqlserverScans = false;
sqlansiScans = true;
}
Class.forName(driver);
}
int shardCount = 0;
conns = new ArrayList<Connection>(3);
// for a longer explanation see the README.md
// semicolons aren't present in JDBC urls, so we use them to delimit
// multiple JDBC connections to shard across.
final String[] urlArr = urls.split(";");
for (String url : urlArr) {
System.out.println("Adding shard node URL: " + url);
Connection conn = DriverManager.getConnection(url, user, passwd);
// Since there is no explicit commit method in the DB interface, all
// operations should auto commit, except when explicitly told not to
// (this is necessary in cases such as for PostgreSQL when running a
// scan workload with fetchSize)
conn.setAutoCommit(autoCommit);
shardCount++;
conns.add(conn);
}
System.out.println("Using shards: " + shardCount + ", batchSize:" + batchSize + ", fetchSize: " + jdbcFetchSize);
cachedStatements = new ConcurrentHashMap<StatementType, PreparedStatement>();
this.dbFlavor = DBFlavor.fromJdbcUrl(urlArr[0]);
} catch (ClassNotFoundException e) {
System.err.println("Error in initializing the JDBS driver: " + e);
throw new DBException(e);
} catch (SQLException e) {
System.err.println("Error in database operation: " + e);
throw new DBException(e);
} catch (NumberFormatException e) {
System.err.println("Invalid value for fieldcount property. " + e);
throw new DBException(e);
}
initialized = true;
| 595
| 873
| 1,468
|
<methods>public non-sealed void <init>() ,public void cleanup() throws site.ycsb.DBException,public abstract site.ycsb.Status delete(java.lang.String, java.lang.String) ,public java.util.Properties getProperties() ,public void init() throws site.ycsb.DBException,public abstract site.ycsb.Status insert(java.lang.String, java.lang.String, Map<java.lang.String,site.ycsb.ByteIterator>) ,public abstract site.ycsb.Status read(java.lang.String, java.lang.String, Set<java.lang.String>, Map<java.lang.String,site.ycsb.ByteIterator>) ,public abstract site.ycsb.Status scan(java.lang.String, java.lang.String, int, Set<java.lang.String>, Vector<HashMap<java.lang.String,site.ycsb.ByteIterator>>) ,public void setProperties(java.util.Properties) ,public abstract site.ycsb.Status update(java.lang.String, java.lang.String, Map<java.lang.String,site.ycsb.ByteIterator>) <variables>private java.util.Properties properties
|
brianfrankcooper_YCSB
|
YCSB/jdbc/src/main/java/site/ycsb/db/JdbcDBCreateTable.java
|
JdbcDBCreateTable
|
main
|
class JdbcDBCreateTable {
private static void usageMessage() {
System.out.println("Create Table Client. Options:");
System.out.println(" -p key=value properties defined.");
System.out.println(" -P location of the properties file to load.");
System.out.println(" -n name of the table.");
System.out.println(" -f number of fields (default 10).");
}
private static void createTable(Properties props, String tablename) throws SQLException {
String driver = props.getProperty(JdbcDBClient.DRIVER_CLASS);
String username = props.getProperty(JdbcDBClient.CONNECTION_USER);
String password = props.getProperty(JdbcDBClient.CONNECTION_PASSWD, "");
String url = props.getProperty(JdbcDBClient.CONNECTION_URL);
int fieldcount = Integer.parseInt(props.getProperty(JdbcDBClient.FIELD_COUNT_PROPERTY,
JdbcDBClient.FIELD_COUNT_PROPERTY_DEFAULT));
if (driver == null || username == null || url == null) {
throw new SQLException("Missing connection information.");
}
Connection conn = null;
try {
Class.forName(driver);
conn = DriverManager.getConnection(url, username, password);
Statement stmt = conn.createStatement();
StringBuilder sql = new StringBuilder("DROP TABLE IF EXISTS ");
sql.append(tablename);
sql.append(";");
stmt.execute(sql.toString());
sql = new StringBuilder("CREATE TABLE ");
sql.append(tablename);
sql.append(" (YCSB_KEY VARCHAR PRIMARY KEY");
for (int idx = 0; idx < fieldcount; idx++) {
sql.append(", FIELD");
sql.append(idx);
sql.append(" TEXT");
}
sql.append(");");
stmt.execute(sql.toString());
System.out.println("Table " + tablename + " created..");
} catch (ClassNotFoundException e) {
throw new SQLException("JDBC Driver class not found.");
} finally {
if (conn != null) {
System.out.println("Closing database connection.");
conn.close();
}
}
}
/**
* @param args
*/
public static void main(String[] args) {<FILL_FUNCTION_BODY>}
/**
* Hidden constructor.
*/
private JdbcDBCreateTable() {
super();
}
}
|
if (args.length == 0) {
usageMessage();
System.exit(0);
}
String tablename = null;
int fieldcount = -1;
Properties props = new Properties();
Properties fileprops = new Properties();
// parse arguments
int argindex = 0;
while (args[argindex].startsWith("-")) {
if (args[argindex].compareTo("-P") == 0) {
argindex++;
if (argindex >= args.length) {
usageMessage();
System.exit(0);
}
String propfile = args[argindex];
argindex++;
Properties myfileprops = new Properties();
try {
myfileprops.load(new FileInputStream(propfile));
} catch (IOException e) {
System.out.println(e.getMessage());
System.exit(0);
}
// Issue #5 - remove call to stringPropertyNames to make compilable
// under Java 1.5
for (Enumeration<?> e = myfileprops.propertyNames(); e.hasMoreElements();) {
String prop = (String) e.nextElement();
fileprops.setProperty(prop, myfileprops.getProperty(prop));
}
} else if (args[argindex].compareTo("-p") == 0) {
argindex++;
if (argindex >= args.length) {
usageMessage();
System.exit(0);
}
int eq = args[argindex].indexOf('=');
if (eq < 0) {
usageMessage();
System.exit(0);
}
String name = args[argindex].substring(0, eq);
String value = args[argindex].substring(eq + 1);
props.put(name, value);
argindex++;
} else if (args[argindex].compareTo("-n") == 0) {
argindex++;
if (argindex >= args.length) {
usageMessage();
System.exit(0);
}
tablename = args[argindex++];
} else if (args[argindex].compareTo("-f") == 0) {
argindex++;
if (argindex >= args.length) {
usageMessage();
System.exit(0);
}
try {
fieldcount = Integer.parseInt(args[argindex++]);
} catch (NumberFormatException e) {
System.err.println("Invalid number for field count");
usageMessage();
System.exit(1);
}
} else {
System.out.println("Unknown option " + args[argindex]);
usageMessage();
System.exit(0);
}
if (argindex >= args.length) {
break;
}
}
if (argindex != args.length) {
usageMessage();
System.exit(0);
}
// overwrite file properties with properties from the command line
// Issue #5 - remove call to stringPropertyNames to make compilable under
// Java 1.5
for (Enumeration<?> e = props.propertyNames(); e.hasMoreElements();) {
String prop = (String) e.nextElement();
fileprops.setProperty(prop, props.getProperty(prop));
}
props = fileprops;
if (tablename == null) {
System.err.println("table name missing.");
usageMessage();
System.exit(1);
}
if (fieldcount > 0) {
props.setProperty(JdbcDBClient.FIELD_COUNT_PROPERTY, String.valueOf(fieldcount));
}
try {
createTable(props, tablename);
} catch (SQLException e) {
System.err.println("Error in creating table. " + e);
System.exit(1);
}
| 664
| 987
| 1,651
|
<no_super_class>
|
brianfrankcooper_YCSB
|
YCSB/jdbc/src/main/java/site/ycsb/db/StatementType.java
|
StatementType
|
equals
|
class StatementType {
enum Type {
INSERT(1), DELETE(2), READ(3), UPDATE(4), SCAN(5);
private final int internalType;
private Type(int type) {
internalType = type;
}
int getHashCode() {
final int prime = 31;
int result = 1;
result = prime * result + internalType;
return result;
}
}
private Type type;
private int shardIndex;
private int numFields;
private String tableName;
private String fieldString;
public StatementType(Type type, String tableName, int numFields, String fieldString, int shardIndex) {
this.type = type;
this.tableName = tableName;
this.numFields = numFields;
this.fieldString = fieldString;
this.shardIndex = shardIndex;
}
public String getTableName() {
return tableName;
}
public String getFieldString() {
return fieldString;
}
public int getNumFields() {
return numFields;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + numFields + 100 * shardIndex;
result = prime * result + ((tableName == null) ? 0 : tableName.hashCode());
result = prime * result + ((type == null) ? 0 : type.getHashCode());
return result;
}
@Override
public boolean equals(Object obj) {<FILL_FUNCTION_BODY>}
}
|
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
StatementType other = (StatementType) obj;
if (numFields != other.numFields) {
return false;
}
if (shardIndex != other.shardIndex) {
return false;
}
if (tableName == null) {
if (other.tableName != null) {
return false;
}
} else if (!tableName.equals(other.tableName)) {
return false;
}
if (type != other.type) {
return false;
}
if (!fieldString.equals(other.fieldString)) {
return false;
}
return true;
| 419
| 223
| 642
|
<no_super_class>
|
brianfrankcooper_YCSB
|
YCSB/jdbc/src/main/java/site/ycsb/db/flavors/DBFlavor.java
|
DBFlavor
|
fromJdbcUrl
|
class DBFlavor {
enum DBName {
DEFAULT,
PHOENIX
}
private final DBName dbName;
public DBFlavor(DBName dbName) {
this.dbName = dbName;
}
public static DBFlavor fromJdbcUrl(String url) {<FILL_FUNCTION_BODY>}
/**
* Create and return a SQL statement for inserting data.
*/
public abstract String createInsertStatement(StatementType insertType, String key);
/**
* Create and return a SQL statement for reading data.
*/
public abstract String createReadStatement(StatementType readType, String key);
/**
* Create and return a SQL statement for deleting data.
*/
public abstract String createDeleteStatement(StatementType deleteType, String key);
/**
* Create and return a SQL statement for updating data.
*/
public abstract String createUpdateStatement(StatementType updateType, String key);
/**
* Create and return a SQL statement for scanning data.
*/
public abstract String createScanStatement(StatementType scanType, String key,
boolean sqlserverScans, boolean sqlansiScans);
}
|
if (url.startsWith("jdbc:phoenix")) {
return new PhoenixDBFlavor();
}
return new DefaultDBFlavor();
| 295
| 42
| 337
|
<no_super_class>
|
brianfrankcooper_YCSB
|
YCSB/jdbc/src/main/java/site/ycsb/db/flavors/DefaultDBFlavor.java
|
DefaultDBFlavor
|
createUpdateStatement
|
class DefaultDBFlavor extends DBFlavor {
public DefaultDBFlavor() {
super(DBName.DEFAULT);
}
public DefaultDBFlavor(DBName dbName) {
super(dbName);
}
@Override
public String createInsertStatement(StatementType insertType, String key) {
StringBuilder insert = new StringBuilder("INSERT INTO ");
insert.append(insertType.getTableName());
insert.append(" (" + JdbcDBClient.PRIMARY_KEY + "," + insertType.getFieldString() + ")");
insert.append(" VALUES(?");
for (int i = 0; i < insertType.getNumFields(); i++) {
insert.append(",?");
}
insert.append(")");
return insert.toString();
}
@Override
public String createReadStatement(StatementType readType, String key) {
StringBuilder read = new StringBuilder("SELECT * FROM ");
read.append(readType.getTableName());
read.append(" WHERE ");
read.append(JdbcDBClient.PRIMARY_KEY);
read.append(" = ");
read.append("?");
return read.toString();
}
@Override
public String createDeleteStatement(StatementType deleteType, String key) {
StringBuilder delete = new StringBuilder("DELETE FROM ");
delete.append(deleteType.getTableName());
delete.append(" WHERE ");
delete.append(JdbcDBClient.PRIMARY_KEY);
delete.append(" = ?");
return delete.toString();
}
@Override
public String createUpdateStatement(StatementType updateType, String key) {<FILL_FUNCTION_BODY>}
@Override
public String createScanStatement(StatementType scanType, String key, boolean sqlserverScans, boolean sqlansiScans) {
StringBuilder select;
if (sqlserverScans) {
select = new StringBuilder("SELECT TOP (?) * FROM ");
} else {
select = new StringBuilder("SELECT * FROM ");
}
select.append(scanType.getTableName());
select.append(" WHERE ");
select.append(JdbcDBClient.PRIMARY_KEY);
select.append(" >= ?");
select.append(" ORDER BY ");
select.append(JdbcDBClient.PRIMARY_KEY);
if (!sqlserverScans) {
if (sqlansiScans) {
select.append(" FETCH FIRST ? ROWS ONLY");
} else {
select.append(" LIMIT ?");
}
}
return select.toString();
}
}
|
String[] fieldKeys = updateType.getFieldString().split(",");
StringBuilder update = new StringBuilder("UPDATE ");
update.append(updateType.getTableName());
update.append(" SET ");
for (int i = 0; i < fieldKeys.length; i++) {
update.append(fieldKeys[i]);
update.append("=?");
if (i < fieldKeys.length - 1) {
update.append(", ");
}
}
update.append(" WHERE ");
update.append(JdbcDBClient.PRIMARY_KEY);
update.append(" = ?");
return update.toString();
| 652
| 164
| 816
|
<methods>public void <init>(site.ycsb.db.flavors.DBFlavor.DBName) ,public abstract java.lang.String createDeleteStatement(site.ycsb.db.StatementType, java.lang.String) ,public abstract java.lang.String createInsertStatement(site.ycsb.db.StatementType, java.lang.String) ,public abstract java.lang.String createReadStatement(site.ycsb.db.StatementType, java.lang.String) ,public abstract java.lang.String createScanStatement(site.ycsb.db.StatementType, java.lang.String, boolean, boolean) ,public abstract java.lang.String createUpdateStatement(site.ycsb.db.StatementType, java.lang.String) ,public static site.ycsb.db.flavors.DBFlavor fromJdbcUrl(java.lang.String) <variables>private final non-sealed site.ycsb.db.flavors.DBFlavor.DBName dbName
|
brianfrankcooper_YCSB
|
YCSB/jdbc/src/main/java/site/ycsb/db/flavors/PhoenixDBFlavor.java
|
PhoenixDBFlavor
|
createUpdateStatement
|
class PhoenixDBFlavor extends DefaultDBFlavor {
public PhoenixDBFlavor() {
super(DBName.PHOENIX);
}
@Override
public String createInsertStatement(StatementType insertType, String key) {
// Phoenix uses UPSERT syntax
StringBuilder insert = new StringBuilder("UPSERT INTO ");
insert.append(insertType.getTableName());
insert.append(" (" + JdbcDBClient.PRIMARY_KEY + "," + insertType.getFieldString() + ")");
insert.append(" VALUES(?");
for (int i = 0; i < insertType.getNumFields(); i++) {
insert.append(",?");
}
insert.append(")");
return insert.toString();
}
@Override
public String createUpdateStatement(StatementType updateType, String key) {<FILL_FUNCTION_BODY>}
}
|
// Phoenix doesn't have UPDATE semantics, just re-use UPSERT VALUES on the specific columns
String[] fieldKeys = updateType.getFieldString().split(",");
StringBuilder update = new StringBuilder("UPSERT INTO ");
update.append(updateType.getTableName());
update.append(" (");
// Each column to update
for (int i = 0; i < fieldKeys.length; i++) {
update.append(fieldKeys[i]).append(",");
}
// And then set the primary key column
update.append(JdbcDBClient.PRIMARY_KEY).append(") VALUES(");
// Add an unbound param for each column to update
for (int i = 0; i < fieldKeys.length; i++) {
update.append("?, ");
}
// Then the primary key column's value
update.append("?)");
return update.toString();
| 224
| 229
| 453
|
<methods>public void <init>() ,public void <init>(site.ycsb.db.flavors.DBFlavor.DBName) ,public java.lang.String createDeleteStatement(site.ycsb.db.StatementType, java.lang.String) ,public java.lang.String createInsertStatement(site.ycsb.db.StatementType, java.lang.String) ,public java.lang.String createReadStatement(site.ycsb.db.StatementType, java.lang.String) ,public java.lang.String createScanStatement(site.ycsb.db.StatementType, java.lang.String, boolean, boolean) ,public java.lang.String createUpdateStatement(site.ycsb.db.StatementType, java.lang.String) <variables>
|
brianfrankcooper_YCSB
|
YCSB/maprjsondb/src/main/java/site/ycsb/db/mapr/MapRJSONDBClient.java
|
MapRJSONDBClient
|
scan
|
class MapRJSONDBClient extends site.ycsb.DB {
private Connection connection = null;
private DocumentStore documentStore = null;
private Driver driver = null;
@Override
public void init() {
connection = DriverManager.getConnection("ojai:mapr:");
driver = connection.getDriver();
}
@Override
public void cleanup() {
documentStore.close();
connection.close();
}
@Override
public Status read(String table, String key, Set<String> fields,
Map<String, ByteIterator> result) {
try {
DocumentStore docStore = getTable(table);
Document doc = docStore.findById(key, getFieldPaths(fields));
buildRowResult(doc, result);
return Status.OK;
} catch (Exception e) {
return Status.ERROR;
}
}
@Override
public Status scan(String table, String startkey, int recordcount,
Set<String> fields, Vector<HashMap<String, ByteIterator>> result) {<FILL_FUNCTION_BODY>}
@Override
public Status update(String table, String key,
Map<String, ByteIterator> values) {
try {
DocumentStore docStore = getTable(table);
docStore.update(key, newMutation(values));
return Status.OK;
} catch (Exception e) {
return Status.ERROR;
}
}
@Override
public Status insert(String table, String key,
Map<String, ByteIterator> values) {
try {
DocumentStore docStore = getTable(table);
docStore.insertOrReplace(key, newDocument(values));
return Status.OK;
} catch (Exception e) {
return Status.ERROR;
}
}
@Override
public Status delete(String table, String key) {
try {
DocumentStore docStore = getTable(table);
docStore.delete(key);
return Status.OK;
} catch (Exception e) {
return Status.ERROR;
}
}
/**
* Get the OJAI DocumentStore instance for a given table.
*
* @param tableName
* @return
*/
private DocumentStore getTable(String tableName) {
if (documentStore == null) {
documentStore = connection.getStore(tableName);
}
return documentStore;
}
/**
* Construct a Document object from the map of OJAI values.
*
* @param values
* @return
*/
private Document newDocument(Map<String, ByteIterator> values) {
Document document = driver.newDocument();
for (Map.Entry<String, ByteIterator> entry : values.entrySet()) {
document.set(entry.getKey(), entry.getValue().toArray());
}
return document;
}
/**
* Build a DocumentMutation object for the values specified.
* @param values
* @return
*/
private DocumentMutation newMutation(Map<String, ByteIterator> values) {
DocumentMutation mutation = driver.newMutation();
for (Map.Entry<String, ByteIterator> entry : values.entrySet()) {
mutation.setOrReplace(entry.getKey(),
ByteBuffer.wrap(entry.getValue().toArray()));
}
return mutation;
}
/**
* Get field path array from the set.
*
* @param fields
* @return
*/
private String[] getFieldPaths(Set<String> fields) {
if (fields != null) {
return fields.toArray(new String[fields.size()]);
}
return new String[0];
}
/**
* Build result the map from the Document passed.
*
* @param document
* @return
*/
private HashMap<String, ByteIterator> buildRowResult(Document document) {
return buildRowResult(document, null);
}
/**
* Build result the map from the Document passed.
*
* @param document
* @param result
* @return
*/
private HashMap<String, ByteIterator> buildRowResult(Document document,
Map<String, ByteIterator> result) {
if (document != null) {
if (result == null) {
result = new HashMap<String, ByteIterator>();
}
for (Map.Entry<String, Value> kv : document) {
result.put(kv.getKey(), new ValueByteIterator(kv.getValue()));
}
}
return (HashMap<String, ByteIterator>)result;
}
}
|
try {
DocumentStore docStore = getTable(table);
QueryCondition condition = driver.newCondition()
.is(DocumentConstants.ID_FIELD, Op.GREATER_OR_EQUAL, startkey)
.build();
Query query = driver.newQuery()
.select(getFieldPaths(fields))
.where(condition)
.build();
try (DocumentStream stream =
docStore.findQuery(query)) {
int numResults = 0;
for (Document record : stream) {
result.add(buildRowResult(record));
numResults++;
if (numResults >= recordcount) {
break;
}
}
}
return Status.OK;
} catch (Exception e) {
e.printStackTrace();
return Status.ERROR;
}
| 1,191
| 212
| 1,403
|
<methods>public non-sealed void <init>() ,public void cleanup() throws site.ycsb.DBException,public abstract site.ycsb.Status delete(java.lang.String, java.lang.String) ,public java.util.Properties getProperties() ,public void init() throws site.ycsb.DBException,public abstract site.ycsb.Status insert(java.lang.String, java.lang.String, Map<java.lang.String,site.ycsb.ByteIterator>) ,public abstract site.ycsb.Status read(java.lang.String, java.lang.String, Set<java.lang.String>, Map<java.lang.String,site.ycsb.ByteIterator>) ,public abstract site.ycsb.Status scan(java.lang.String, java.lang.String, int, Set<java.lang.String>, Vector<HashMap<java.lang.String,site.ycsb.ByteIterator>>) ,public void setProperties(java.util.Properties) ,public abstract site.ycsb.Status update(java.lang.String, java.lang.String, Map<java.lang.String,site.ycsb.ByteIterator>) <variables>private java.util.Properties properties
|
brianfrankcooper_YCSB
|
YCSB/mongodb/src/main/java/site/ycsb/db/OptionsSupport.java
|
OptionsSupport
|
updateUrl
|
class OptionsSupport {
/** Value for an unavailable property. */
private static final String UNAVAILABLE = "n/a";
/**
* Updates the URL with the appropriate attributes if legacy properties are
* set and the URL does not have the property already set.
*
* @param url
* The URL to update.
* @param props
* The legacy properties.
* @return The updated URL.
*/
public static String updateUrl(String url, Properties props) {<FILL_FUNCTION_BODY>}
/**
* Adds an option to the url if it does not already contain the option.
*
* @param url
* The URL to append the options to.
* @param name
* The name of the option.
* @param value
* The value for the option.
* @return The updated URL.
*/
private static String addUrlOption(String url, String name, String value) {
String fullName = name + "=";
if (!url.contains(fullName)) {
if (url.contains("?")) {
return url + "&" + fullName + value;
}
return url + "?" + fullName + value;
}
return url;
}
/**
* Hidden Constructor.
*/
private OptionsSupport() {
// Nothing.
}
}
|
String result = url;
// max connections.
final String maxConnections =
props.getProperty("mongodb.maxconnections", UNAVAILABLE).toLowerCase();
if (!UNAVAILABLE.equals(maxConnections)) {
result = addUrlOption(result, "maxPoolSize", maxConnections);
}
// Blocked thread multiplier.
final String threadsAllowedToBlockForConnectionMultiplier =
props
.getProperty(
"mongodb.threadsAllowedToBlockForConnectionMultiplier",
UNAVAILABLE).toLowerCase();
if (!UNAVAILABLE.equals(threadsAllowedToBlockForConnectionMultiplier)) {
result =
addUrlOption(result, "waitQueueMultiple",
threadsAllowedToBlockForConnectionMultiplier);
}
// write concern
String writeConcernType =
props.getProperty("mongodb.writeConcern", UNAVAILABLE).toLowerCase();
if (!UNAVAILABLE.equals(writeConcernType)) {
if ("errors_ignored".equals(writeConcernType)) {
result = addUrlOption(result, "w", "0");
} else if ("unacknowledged".equals(writeConcernType)) {
result = addUrlOption(result, "w", "0");
} else if ("acknowledged".equals(writeConcernType)) {
result = addUrlOption(result, "w", "1");
} else if ("journaled".equals(writeConcernType)) {
result = addUrlOption(result, "journal", "true"); // this is the
// documented option
// name
result = addUrlOption(result, "j", "true"); // but keep this until
// MongoDB Java driver
// supports "journal" option
} else if ("replica_acknowledged".equals(writeConcernType)) {
result = addUrlOption(result, "w", "2");
} else if ("majority".equals(writeConcernType)) {
result = addUrlOption(result, "w", "majority");
} else {
System.err.println("WARNING: Invalid writeConcern: '"
+ writeConcernType + "' will be ignored. "
+ "Must be one of [ unacknowledged | acknowledged | "
+ "journaled | replica_acknowledged | majority ]");
}
}
// read preference
String readPreferenceType =
props.getProperty("mongodb.readPreference", UNAVAILABLE).toLowerCase();
if (!UNAVAILABLE.equals(readPreferenceType)) {
if ("primary".equals(readPreferenceType)) {
result = addUrlOption(result, "readPreference", "primary");
} else if ("primary_preferred".equals(readPreferenceType)) {
result = addUrlOption(result, "readPreference", "primaryPreferred");
} else if ("secondary".equals(readPreferenceType)) {
result = addUrlOption(result, "readPreference", "secondary");
} else if ("secondary_preferred".equals(readPreferenceType)) {
result = addUrlOption(result, "readPreference", "secondaryPreferred");
} else if ("nearest".equals(readPreferenceType)) {
result = addUrlOption(result, "readPreference", "nearest");
} else {
System.err.println("WARNING: Invalid readPreference: '"
+ readPreferenceType + "' will be ignored. "
+ "Must be one of [ primary | primary_preferred | "
+ "secondary | secondary_preferred | nearest ]");
}
}
return result;
| 353
| 931
| 1,284
|
<no_super_class>
|
brianfrankcooper_YCSB
|
YCSB/nosqldb/src/main/java/site/ycsb/db/NoSqlDbClient.java
|
NoSqlDbClient
|
init
|
class NoSqlDbClient extends DB {
private KVStore store;
private int getPropertyInt(Properties properties, String key,
int defaultValue) throws DBException {
String p = properties.getProperty(key);
int i = defaultValue;
if (p != null) {
try {
i = Integer.parseInt(p);
} catch (NumberFormatException e) {
throw new DBException("Illegal number format in " + key + " property");
}
}
return i;
}
@Override
public void init() throws DBException {<FILL_FUNCTION_BODY>}
@Override
public void cleanup() throws DBException {
store.close();
}
/**
* Create a key object. We map "table" and (YCSB's) "key" to a major component
* of the oracle.kv.Key, and "field" to a minor component.
*
* @return An oracle.kv.Key object.
*/
private static Key createKey(String table, String key, String field) {
List<String> majorPath = new ArrayList<String>();
majorPath.add(table);
majorPath.add(key);
if (field == null) {
return Key.createKey(majorPath);
}
return Key.createKey(majorPath, field);
}
private static Key createKey(String table, String key) {
return createKey(table, key, null);
}
private static String getFieldFromKey(Key key) {
return key.getMinorPath().get(0);
}
@Override
public Status read(String table, String key, Set<String> fields, Map<String, ByteIterator> result) {
Key kvKey = createKey(table, key);
SortedMap<Key, ValueVersion> kvResult;
try {
kvResult = store.multiGet(kvKey, null, null);
} catch (FaultException e) {
System.err.println(e);
return Status.ERROR;
}
for (Map.Entry<Key, ValueVersion> entry : kvResult.entrySet()) {
/* If fields is null, read all fields */
String field = getFieldFromKey(entry.getKey());
if (fields != null && !fields.contains(field)) {
continue;
}
result.put(field,
new ByteArrayByteIterator(entry.getValue().getValue().getValue()));
}
return Status.OK;
}
@Override
public Status scan(String table, String startkey, int recordcount,
Set<String> fields, Vector<HashMap<String, ByteIterator>> result) {
System.err.println("Oracle NoSQL Database does not support Scan semantics");
return Status.ERROR;
}
@Override
public Status update(String table, String key, Map<String, ByteIterator> values) {
for (Map.Entry<String, ByteIterator> entry : values.entrySet()) {
Key kvKey = createKey(table, key, entry.getKey());
Value kvValue = Value.createValue(entry.getValue().toArray());
try {
store.put(kvKey, kvValue);
} catch (FaultException e) {
System.err.println(e);
return Status.ERROR;
}
}
return Status.OK;
}
@Override
public Status insert(String table, String key, Map<String, ByteIterator> values) {
return update(table, key, values);
}
@Override
public Status delete(String table, String key) {
Key kvKey = createKey(table, key);
try {
store.multiDelete(kvKey, null, null);
} catch (FaultException e) {
System.err.println(e);
return Status.ERROR;
}
return Status.OK;
}
}
|
Properties properties = getProperties();
/* Mandatory properties */
String storeName = properties.getProperty("storeName", "kvstore");
String[] helperHosts =
properties.getProperty("helperHost", "localhost:5000").split(",");
KVStoreConfig config = new KVStoreConfig(storeName, helperHosts);
/* Optional properties */
String p;
p = properties.getProperty("consistency");
if (p != null) {
if (p.equalsIgnoreCase("ABSOLUTE")) {
config.setConsistency(Consistency.ABSOLUTE);
} else if (p.equalsIgnoreCase("NONE_REQUIRED")) {
config.setConsistency(Consistency.NONE_REQUIRED);
} else {
throw new DBException("Illegal value in consistency property");
}
}
p = properties.getProperty("durability");
if (p != null) {
if (p.equalsIgnoreCase("COMMIT_NO_SYNC")) {
config.setDurability(Durability.COMMIT_NO_SYNC);
} else if (p.equalsIgnoreCase("COMMIT_SYNC")) {
config.setDurability(Durability.COMMIT_SYNC);
} else if (p.equalsIgnoreCase("COMMIT_WRITE_NO_SYNC")) {
config.setDurability(Durability.COMMIT_WRITE_NO_SYNC);
} else {
throw new DBException("Illegal value in durability property");
}
}
int maxActiveRequests =
getPropertyInt(properties, "requestLimit.maxActiveRequests",
RequestLimitConfig.DEFAULT_MAX_ACTIVE_REQUESTS);
int requestThresholdPercent =
getPropertyInt(properties, "requestLimit.requestThresholdPercent",
RequestLimitConfig.DEFAULT_REQUEST_THRESHOLD_PERCENT);
int nodeLimitPercent =
getPropertyInt(properties, "requestLimit.nodeLimitPercent",
RequestLimitConfig.DEFAULT_NODE_LIMIT_PERCENT);
RequestLimitConfig requestLimitConfig;
/*
* It is said that the constructor could throw NodeRequestLimitException in
* Javadoc, the exception is not provided
*/
// try {
requestLimitConfig = new RequestLimitConfig(maxActiveRequests,
requestThresholdPercent, nodeLimitPercent);
// } catch (NodeRequestLimitException e) {
// throw new DBException(e);
// }
config.setRequestLimit(requestLimitConfig);
p = properties.getProperty("requestTimeout");
if (p != null) {
long timeout = 1;
try {
timeout = Long.parseLong(p);
} catch (NumberFormatException e) {
throw new DBException(
"Illegal number format in requestTimeout property");
}
try {
// TODO Support other TimeUnit
config.setRequestTimeout(timeout, TimeUnit.SECONDS);
} catch (IllegalArgumentException e) {
throw new DBException(e);
}
}
try {
store = KVStoreFactory.getStore(config);
} catch (FaultException e) {
throw new DBException(e);
}
| 1,000
| 821
| 1,821
|
<methods>public non-sealed void <init>() ,public void cleanup() throws site.ycsb.DBException,public abstract site.ycsb.Status delete(java.lang.String, java.lang.String) ,public java.util.Properties getProperties() ,public void init() throws site.ycsb.DBException,public abstract site.ycsb.Status insert(java.lang.String, java.lang.String, Map<java.lang.String,site.ycsb.ByteIterator>) ,public abstract site.ycsb.Status read(java.lang.String, java.lang.String, Set<java.lang.String>, Map<java.lang.String,site.ycsb.ByteIterator>) ,public abstract site.ycsb.Status scan(java.lang.String, java.lang.String, int, Set<java.lang.String>, Vector<HashMap<java.lang.String,site.ycsb.ByteIterator>>) ,public void setProperties(java.util.Properties) ,public abstract site.ycsb.Status update(java.lang.String, java.lang.String, Map<java.lang.String,site.ycsb.ByteIterator>) <variables>private java.util.Properties properties
|
brianfrankcooper_YCSB
|
YCSB/postgrenosql/src/main/java/site/ycsb/postgrenosql/StatementType.java
|
StatementType
|
hashCode
|
class StatementType {
enum Type {
INSERT(1), DELETE(2), READ(3), UPDATE(4), SCAN(5);
private final int internalType;
Type(int type) {
internalType = type;
}
int getHashCode() {
final int prime = 31;
int result = 1;
result = prime * result + internalType;
return result;
}
}
private Type type;
private String tableName;
private Set<String> fields;
public StatementType(Type type, String tableName, Set<String> fields) {
this.type = type;
this.tableName = tableName;
this.fields = fields;
}
public String getTableName() {
return tableName;
}
public Set<String> getFields() {
return fields;
}
@Override
public int hashCode() {<FILL_FUNCTION_BODY>}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
StatementType other = (StatementType) obj;
if (type != other.type) {
return false;
}
if (tableName == null) {
if (other.tableName != null) {
return false;
}
} else if (!tableName.equals(other.tableName)) {
return false;
}
if (fields == null) {
if (other.fields != null) {
return false;
}
}else if (!fields.equals(other.fields)) {
return false;
}
return true;
}
}
|
final int prime = 31;
int result = 1;
result = prime * result + ((type == null) ? 0 : type.getHashCode());
result = prime * result + ((tableName == null) ? 0 : tableName.hashCode());
result = prime * result + ((fields == null) ? 0 : fields.hashCode());
return result;
| 476
| 93
| 569
|
<no_super_class>
|
brianfrankcooper_YCSB
|
YCSB/rados/src/main/java/site/ycsb/db/RadosClient.java
|
RadosClient
|
read
|
class RadosClient extends DB {
private Rados rados;
private IoCTX ioctx;
public static final String CONFIG_FILE_PROPERTY = "rados.configfile";
public static final String CONFIG_FILE_DEFAULT = "/etc/ceph/ceph.conf";
public static final String ID_PROPERTY = "rados.id";
public static final String ID_DEFAULT = "admin";
public static final String POOL_PROPERTY = "rados.pool";
public static final String POOL_DEFAULT = "data";
private boolean isInited = false;
public void init() throws DBException {
Properties props = getProperties();
String configfile = props.getProperty(CONFIG_FILE_PROPERTY);
if (configfile == null) {
configfile = CONFIG_FILE_DEFAULT;
}
String id = props.getProperty(ID_PROPERTY);
if (id == null) {
id = ID_DEFAULT;
}
String pool = props.getProperty(POOL_PROPERTY);
if (pool == null) {
pool = POOL_DEFAULT;
}
// try {
// } catch (UnsatisfiedLinkError e) {
// throw new DBException("RADOS library is not loaded.");
// }
rados = new Rados(id);
try {
rados.confReadFile(new File(configfile));
rados.connect();
ioctx = rados.ioCtxCreate(pool);
} catch (RadosException e) {
throw new DBException(e.getMessage() + ": " + e.getReturnValue());
}
isInited = true;
}
public void cleanup() throws DBException {
if (isInited) {
rados.shutDown();
rados.ioCtxDestroy(ioctx);
isInited = false;
}
}
@Override
public Status read(String table, String key, Set<String> fields, Map<String, ByteIterator> result) {<FILL_FUNCTION_BODY>}
@Override
public Status insert(String table, String key, Map<String, ByteIterator> values) {
JSONObject json = new JSONObject();
for (final Entry<String, ByteIterator> e : values.entrySet()) {
json.put(e.getKey(), e.getValue().toString());
}
try {
ioctx.write(key, json.toString());
} catch (RadosException e) {
return new Status("ERROR-" + e.getReturnValue(), e.getMessage());
}
return Status.OK;
}
@Override
public Status delete(String table, String key) {
try {
ioctx.remove(key);
} catch (RadosException e) {
return new Status("ERROR-" + e.getReturnValue(), e.getMessage());
}
return Status.OK;
}
@Override
public Status update(String table, String key, Map<String, ByteIterator> values) {
Status rtn = delete(table, key);
if (rtn.equals(Status.OK)) {
return insert(table, key, values);
}
return rtn;
}
@Override
public Status scan(String table, String startkey, int recordcount, Set<String> fields,
Vector<HashMap<String, ByteIterator>> result) {
return Status.NOT_IMPLEMENTED;
}
}
|
byte[] buffer;
try {
RadosObjectInfo info = ioctx.stat(key);
buffer = new byte[(int)info.getSize()];
ReadOp rop = ioctx.readOpCreate();
ReadResult readResult = rop.queueRead(0, info.getSize());
// TODO: more size than byte length possible;
// rop.operate(key, Rados.OPERATION_NOFLAG); // for rados-java 0.3.0
rop.operate(key, 0);
// readResult.raiseExceptionOnError("Error ReadOP(%d)", readResult.getRVal()); // for rados-java 0.3.0
if (readResult.getRVal() < 0) {
throw new RadosException("Error ReadOP", readResult.getRVal());
}
if (info.getSize() != readResult.getBytesRead()) {
return new Status("ERROR", "Error the object size read");
}
readResult.getBuffer().get(buffer);
} catch (RadosException e) {
return new Status("ERROR-" + e.getReturnValue(), e.getMessage());
}
JSONObject json = new JSONObject(new String(buffer, java.nio.charset.StandardCharsets.UTF_8));
Set<String> fieldsToReturn = (fields == null ? json.keySet() : fields);
for (String name : fieldsToReturn) {
result.put(name, new StringByteIterator(json.getString(name)));
}
return result.isEmpty() ? Status.ERROR : Status.OK;
| 884
| 402
| 1,286
|
<methods>public non-sealed void <init>() ,public void cleanup() throws site.ycsb.DBException,public abstract site.ycsb.Status delete(java.lang.String, java.lang.String) ,public java.util.Properties getProperties() ,public void init() throws site.ycsb.DBException,public abstract site.ycsb.Status insert(java.lang.String, java.lang.String, Map<java.lang.String,site.ycsb.ByteIterator>) ,public abstract site.ycsb.Status read(java.lang.String, java.lang.String, Set<java.lang.String>, Map<java.lang.String,site.ycsb.ByteIterator>) ,public abstract site.ycsb.Status scan(java.lang.String, java.lang.String, int, Set<java.lang.String>, Vector<HashMap<java.lang.String,site.ycsb.ByteIterator>>) ,public void setProperties(java.util.Properties) ,public abstract site.ycsb.Status update(java.lang.String, java.lang.String, Map<java.lang.String,site.ycsb.ByteIterator>) <variables>private java.util.Properties properties
|
brianfrankcooper_YCSB
|
YCSB/redis/src/main/java/site/ycsb/db/RedisClient.java
|
RedisClient
|
insert
|
class RedisClient extends DB {
private JedisCommands jedis;
public static final String HOST_PROPERTY = "redis.host";
public static final String PORT_PROPERTY = "redis.port";
public static final String PASSWORD_PROPERTY = "redis.password";
public static final String CLUSTER_PROPERTY = "redis.cluster";
public static final String TIMEOUT_PROPERTY = "redis.timeout";
public static final String INDEX_KEY = "_indices";
public void init() throws DBException {
Properties props = getProperties();
int port;
String portString = props.getProperty(PORT_PROPERTY);
if (portString != null) {
port = Integer.parseInt(portString);
} else {
port = Protocol.DEFAULT_PORT;
}
String host = props.getProperty(HOST_PROPERTY);
boolean clusterEnabled = Boolean.parseBoolean(props.getProperty(CLUSTER_PROPERTY));
if (clusterEnabled) {
Set<HostAndPort> jedisClusterNodes = new HashSet<>();
jedisClusterNodes.add(new HostAndPort(host, port));
jedis = new JedisCluster(jedisClusterNodes);
} else {
String redisTimeout = props.getProperty(TIMEOUT_PROPERTY);
if (redisTimeout != null){
jedis = new Jedis(host, port, Integer.parseInt(redisTimeout));
} else {
jedis = new Jedis(host, port);
}
((Jedis) jedis).connect();
}
String password = props.getProperty(PASSWORD_PROPERTY);
if (password != null) {
((BasicCommands) jedis).auth(password);
}
}
public void cleanup() throws DBException {
try {
((Closeable) jedis).close();
} catch (IOException e) {
throw new DBException("Closing connection failed.");
}
}
/*
* Calculate a hash for a key to store it in an index. The actual return value
* of this function is not interesting -- it primarily needs to be fast and
* scattered along the whole space of doubles. In a real world scenario one
* would probably use the ASCII values of the keys.
*/
private double hash(String key) {
return key.hashCode();
}
// XXX jedis.select(int index) to switch to `table`
@Override
public Status read(String table, String key, Set<String> fields,
Map<String, ByteIterator> result) {
if (fields == null) {
StringByteIterator.putAllAsByteIterators(result, jedis.hgetAll(key));
} else {
String[] fieldArray =
(String[]) fields.toArray(new String[fields.size()]);
List<String> values = jedis.hmget(key, fieldArray);
Iterator<String> fieldIterator = fields.iterator();
Iterator<String> valueIterator = values.iterator();
while (fieldIterator.hasNext() && valueIterator.hasNext()) {
result.put(fieldIterator.next(),
new StringByteIterator(valueIterator.next()));
}
assert !fieldIterator.hasNext() && !valueIterator.hasNext();
}
return result.isEmpty() ? Status.ERROR : Status.OK;
}
@Override
public Status insert(String table, String key,
Map<String, ByteIterator> values) {<FILL_FUNCTION_BODY>}
@Override
public Status delete(String table, String key) {
return jedis.del(key) == 0 && jedis.zrem(INDEX_KEY, key) == 0 ? Status.ERROR
: Status.OK;
}
@Override
public Status update(String table, String key,
Map<String, ByteIterator> values) {
return jedis.hmset(key, StringByteIterator.getStringMap(values))
.equals("OK") ? Status.OK : Status.ERROR;
}
@Override
public Status scan(String table, String startkey, int recordcount,
Set<String> fields, Vector<HashMap<String, ByteIterator>> result) {
Set<String> keys = jedis.zrangeByScore(INDEX_KEY, hash(startkey),
Double.POSITIVE_INFINITY, 0, recordcount);
HashMap<String, ByteIterator> values;
for (String key : keys) {
values = new HashMap<String, ByteIterator>();
read(table, key, fields, values);
result.add(values);
}
return Status.OK;
}
}
|
if (jedis.hmset(key, StringByteIterator.getStringMap(values))
.equals("OK")) {
jedis.zadd(INDEX_KEY, hash(key), key);
return Status.OK;
}
return Status.ERROR;
| 1,214
| 70
| 1,284
|
<methods>public non-sealed void <init>() ,public void cleanup() throws site.ycsb.DBException,public abstract site.ycsb.Status delete(java.lang.String, java.lang.String) ,public java.util.Properties getProperties() ,public void init() throws site.ycsb.DBException,public abstract site.ycsb.Status insert(java.lang.String, java.lang.String, Map<java.lang.String,site.ycsb.ByteIterator>) ,public abstract site.ycsb.Status read(java.lang.String, java.lang.String, Set<java.lang.String>, Map<java.lang.String,site.ycsb.ByteIterator>) ,public abstract site.ycsb.Status scan(java.lang.String, java.lang.String, int, Set<java.lang.String>, Vector<HashMap<java.lang.String,site.ycsb.ByteIterator>>) ,public void setProperties(java.util.Properties) ,public abstract site.ycsb.Status update(java.lang.String, java.lang.String, Map<java.lang.String,site.ycsb.ByteIterator>) <variables>private java.util.Properties properties
|
brianfrankcooper_YCSB
|
YCSB/riak/src/main/java/site/ycsb/db/riak/RiakUtils.java
|
RiakUtils
|
createResultHashMap
|
class RiakUtils {
private RiakUtils() {
super();
}
private static byte[] toBytes(final int anInteger) {
byte[] aResult = new byte[4];
aResult[0] = (byte) (anInteger >> 24);
aResult[1] = (byte) (anInteger >> 16);
aResult[2] = (byte) (anInteger >> 8);
aResult[3] = (byte) (anInteger /* >> 0 */);
return aResult;
}
private static int fromBytes(final byte[] aByteArray) {
checkArgument(aByteArray.length == 4);
return (aByteArray[0] << 24) | (aByteArray[1] & 0xFF) << 16 | (aByteArray[2] & 0xFF) << 8 | (aByteArray[3] & 0xFF);
}
private static void close(final OutputStream anOutputStream) {
try {
anOutputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
private static void close(final InputStream anInputStream) {
try {
anInputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* Serializes a Map, transforming the contained list of (String, ByteIterator) couples into a byte array.
*
* @param aTable A Map to serialize.
* @return A byte array containng the serialized table.
*/
static byte[] serializeTable(Map<String, ByteIterator> aTable) {
final ByteArrayOutputStream anOutputStream = new ByteArrayOutputStream();
final Set<Map.Entry<String, ByteIterator>> theEntries = aTable.entrySet();
try {
for (final Map.Entry<String, ByteIterator> anEntry : theEntries) {
final byte[] aColumnName = anEntry.getKey().getBytes();
anOutputStream.write(toBytes(aColumnName.length));
anOutputStream.write(aColumnName);
final byte[] aColumnValue = anEntry.getValue().toArray();
anOutputStream.write(toBytes(aColumnValue.length));
anOutputStream.write(aColumnValue);
}
return anOutputStream.toByteArray();
} catch (IOException e) {
throw new IllegalStateException(e);
} finally {
close(anOutputStream);
}
}
/**
* Deserializes an input byte array, transforming it into a list of (String, ByteIterator) pairs (i.e. a Map).
*
* @param aValue A byte array containing the table to deserialize.
* @param theResult A Map containing the deserialized table.
*/
private static void deserializeTable(final byte[] aValue, final Map<String, ByteIterator> theResult) {
final ByteArrayInputStream anInputStream = new ByteArrayInputStream(aValue);
byte[] aSizeBuffer = new byte[4];
try {
while (anInputStream.available() > 0) {
anInputStream.read(aSizeBuffer);
final int aColumnNameLength = fromBytes(aSizeBuffer);
final byte[] aColumnNameBuffer = new byte[aColumnNameLength];
anInputStream.read(aColumnNameBuffer);
anInputStream.read(aSizeBuffer);
final int aColumnValueLength = fromBytes(aSizeBuffer);
final byte[] aColumnValue = new byte[aColumnValueLength];
anInputStream.read(aColumnValue);
theResult.put(new String(aColumnNameBuffer), new ByteArrayByteIterator(aColumnValue));
}
} catch (Exception e) {
throw new IllegalStateException(e);
} finally {
close(anInputStream);
}
}
/**
* Obtains a Long number from a key string. This will be the key used by Riak for all the transactions.
*
* @param key The key to convert from String to Long.
* @return A Long number parsed from the key String.
*/
static Long getKeyAsLong(String key) {
String keyString = key.replaceFirst("[a-zA-Z]*", "");
return Long.parseLong(keyString);
}
/**
* Function that retrieves all the fields searched within a read or scan operation and puts them in the result
* HashMap.
*
* @param fields The list of fields to read, or null for all of them.
* @param response A Vector of HashMaps, where each HashMap is a set field/value pairs for one record.
* @param resultHashMap The HashMap to return as result.
*/
static void createResultHashMap(Set<String> fields, FetchValue.Response response,
HashMap<String, ByteIterator>resultHashMap) {<FILL_FUNCTION_BODY>}
}
|
// If everything went fine, then a result must be given. Such an object is a hash table containing the (field,
// value) pairs based on the requested fields. Note that in a read operation, ONLY ONE OBJECT IS RETRIEVED!
// The following line retrieves the previously serialized table which was store with an insert transaction.
byte[] responseFieldsAndValues = response.getValues().get(0).getValue().getValue();
// Deserialize the stored response table.
HashMap<String, ByteIterator> deserializedTable = new HashMap<>();
deserializeTable(responseFieldsAndValues, deserializedTable);
// If only specific fields are requested, then only these should be put in the result object!
if (fields != null) {
// Populate the HashMap to provide as result.
for (Object field : fields.toArray()) {
// Comparison between a requested field and the ones retrieved. If they're equal (i.e. the get() operation
// DOES NOT return a null value), then proceed to store the pair in the resultHashMap.
ByteIterator value = deserializedTable.get(field);
if (value != null) {
resultHashMap.put((String) field, value);
}
}
} else {
// If, instead, no field is specified, then all those retrieved must be provided as result.
for (String field : deserializedTable.keySet()) {
resultHashMap.put(field, deserializedTable.get(field));
}
}
| 1,233
| 382
| 1,615
|
<no_super_class>
|
brianfrankcooper_YCSB
|
YCSB/tarantool/src/main/java/site/ycsb/db/TarantoolClient.java
|
TarantoolClient
|
tupleConvertFilter
|
class TarantoolClient extends DB {
private static final Logger LOGGER = Logger.getLogger(TarantoolClient.class.getName());
private static final String HOST_PROPERTY = "tarantool.host";
private static final String PORT_PROPERTY = "tarantool.port";
private static final String SPACE_PROPERTY = "tarantool.space";
private static final String DEFAULT_HOST = "localhost";
private static final String DEFAULT_PORT = "3301";
private static final String DEFAULT_SPACE = "1024";
private TarantoolConnection16 connection;
private int spaceNo;
public void init() throws DBException {
Properties props = getProperties();
int port = Integer.parseInt(props.getProperty(PORT_PROPERTY, DEFAULT_PORT));
String host = props.getProperty(HOST_PROPERTY, DEFAULT_HOST);
spaceNo = Integer.parseInt(props.getProperty(SPACE_PROPERTY, DEFAULT_SPACE));
try {
this.connection = new TarantoolConnection16Impl(host, port);
} catch (Exception exc) {
throw new DBException("Can't initialize Tarantool connection", exc);
}
}
public void cleanup() throws DBException {
this.connection.close();
}
@Override
public Status insert(String table, String key, Map<String, ByteIterator> values) {
return replace(key, values, "Can't insert element");
}
private HashMap<String, ByteIterator> tupleConvertFilter(List<String> input, Set<String> fields) {<FILL_FUNCTION_BODY>}
@Override
public Status read(String table, String key, Set<String> fields, Map<String, ByteIterator> result) {
try {
List<String> response = this.connection.select(this.spaceNo, 0, Arrays.asList(key), 0, 1, 0);
result = tupleConvertFilter(response, fields);
return Status.OK;
} catch (TarantoolException exc) {
LOGGER.log(Level.SEVERE, "Can't select element", exc);
return Status.ERROR;
} catch (NullPointerException exc) {
return Status.ERROR;
}
}
@Override
public Status scan(String table, String startkey,
int recordcount, Set<String> fields,
Vector<HashMap<String, ByteIterator>> result) {
List<List<String>> response;
try {
response = this.connection.select(this.spaceNo, 0, Arrays.asList(startkey), 0, recordcount, 6);
} catch (TarantoolException exc) {
LOGGER.log(Level.SEVERE, "Can't select range elements", exc);
return Status.ERROR;
} catch (NullPointerException exc) {
return Status.ERROR;
}
for (List<String> i : response) {
HashMap<String, ByteIterator> temp = tupleConvertFilter(i, fields);
if (!temp.isEmpty()) {
result.add((HashMap<String, ByteIterator>) temp.clone());
}
}
return Status.OK;
}
@Override
public Status delete(String table, String key) {
try {
this.connection.delete(this.spaceNo, Collections.singletonList(key));
} catch (TarantoolException exc) {
LOGGER.log(Level.SEVERE, "Can't delete element", exc);
return Status.ERROR;
} catch (NullPointerException e) {
return Status.ERROR;
}
return Status.OK;
}
@Override
public Status update(String table, String key, Map<String, ByteIterator> values) {
return replace(key, values, "Can't replace element");
}
private Status replace(String key, Map<String, ByteIterator> values, String exceptionDescription) {
int j = 0;
String[] tuple = new String[1 + 2 * values.size()];
tuple[0] = key;
for (Map.Entry<String, ByteIterator> i : values.entrySet()) {
tuple[j + 1] = i.getKey();
tuple[j + 2] = i.getValue().toString();
j += 2;
}
try {
this.connection.replace(this.spaceNo, tuple);
} catch (TarantoolException exc) {
LOGGER.log(Level.SEVERE, exceptionDescription, exc);
return Status.ERROR;
}
return Status.OK;
}
}
|
HashMap<String, ByteIterator> result = new HashMap<>();
if (input == null) {
return result;
}
for (int i = 1; i < input.toArray().length; i += 2) {
if (fields == null || fields.contains(input.get(i))) {
result.put(input.get(i), new StringByteIterator(input.get(i + 1)));
}
}
return result;
| 1,168
| 115
| 1,283
|
<methods>public non-sealed void <init>() ,public void cleanup() throws site.ycsb.DBException,public abstract site.ycsb.Status delete(java.lang.String, java.lang.String) ,public java.util.Properties getProperties() ,public void init() throws site.ycsb.DBException,public abstract site.ycsb.Status insert(java.lang.String, java.lang.String, Map<java.lang.String,site.ycsb.ByteIterator>) ,public abstract site.ycsb.Status read(java.lang.String, java.lang.String, Set<java.lang.String>, Map<java.lang.String,site.ycsb.ByteIterator>) ,public abstract site.ycsb.Status scan(java.lang.String, java.lang.String, int, Set<java.lang.String>, Vector<HashMap<java.lang.String,site.ycsb.ByteIterator>>) ,public void setProperties(java.util.Properties) ,public abstract site.ycsb.Status update(java.lang.String, java.lang.String, Map<java.lang.String,site.ycsb.ByteIterator>) <variables>private java.util.Properties properties
|
brianfrankcooper_YCSB
|
YCSB/voltdb/src/main/java/site/ycsb/db/voltdb/ConnectionHelper.java
|
ConnectionHelper
|
connectToOneServerWithRetry
|
class ConnectionHelper {
/**
* Default port for VoltDB.
*/
private static final int VOLTDB_DEFAULT_PORT = 21212;
/**
* hidden constructor.
*/
private ConnectionHelper() {
}
/**
* Creates a factory used to connect to a VoltDB instance. (Note that if a
* corresponding connection exists, all parameters other than 'servers' are
* ignored)
*
* @param servers The comma separated list of VoltDB servers in
* hostname[:port] format that the instance will use.
* @param user The username for the connection
* @param password The password for the specified user
* @param ratelimit A limit on the number of transactions per second for the
* VoltDB instance
* @return The existing factory if a corresponding connection has already been
* created; the newly created one otherwise.
* @throws IOException Throws if a connection is already open with a
* different server string.
* @throws InterruptedException
*/
public static Client createConnection(String servers, String user, String password,
int ratelimit) throws IOException, InterruptedException {
ClientConfig config = new ClientConfig(user, password);
config.setMaxTransactionsPerSecond(ratelimit);
Client client = ClientFactory.createClient(config);
// Note that in VoltDB there is a distinction between creating an instance of a client
// and actually connecting to the DB...
connect(client, servers);
return client;
}
/**
* Connect to a single server with retry. Limited exponential backoff. No
* timeout. This will run until the process is killed if it's not able to
* connect.
*
* @param server hostname:port or just hostname (hostname can be ip).
*/
private static void connectToOneServerWithRetry(final Client client, String server) {<FILL_FUNCTION_BODY>}
/**
* See if DB servers are present on the network.
*
* @return true or false
*/
public static boolean checkDBServers(String servernames) {
String[] serverNamesArray = servernames.split(",");
boolean dbThere = false;
Socket socket = null;
try {
// Connect
socket = new Socket(serverNamesArray[0], VOLTDB_DEFAULT_PORT);
dbThere = true;
} catch (IOException connectFailed) {
dbThere = false;
} finally {
if (socket != null) {
try {
socket.close();
} catch (IOException ignore) {
// Ignore.
}
}
socket = null;
}
return dbThere;
}
/**
* Connect to a set of servers in parallel. Each will retry until connection.
* This call will block until all have connected.
*
* @param servers A comma separated list of servers using the hostname:port
* syntax (where :port is optional).
* @throws InterruptedException if anything bad happens with the threads.
*/
private static void connect(final Client client, String servers) throws InterruptedException {
Logger logger = LoggerFactory.getLogger(ConnectionHelper.class);
logger.info("Connecting to VoltDB...");
String[] serverArray = servers.split(",");
final CountDownLatch connections = new CountDownLatch(serverArray.length);
// use a new thread to connect to each server
for (final String server : serverArray) {
new Thread(new Runnable() {
@Override
public void run() {
connectToOneServerWithRetry(client, server);
connections.countDown();
}
}).start();
}
// block until all have connected
connections.await();
}
}
|
Logger logger = LoggerFactory.getLogger(ConnectionHelper.class);
int sleep = 1000;
while (true) {
try {
client.createConnection(server);
break;
} catch (Exception e) {
logger.error("Connection failed - retrying in %d second(s).\n", sleep / 1000);
try {
Thread.sleep(sleep);
} catch (java.lang.InterruptedException e2) {
logger.error(e2.getMessage());
}
if (sleep < 8000) {
sleep += sleep;
}
}
}
logger.info("Connected to VoltDB node at:" + server);
| 981
| 186
| 1,167
|
<no_super_class>
|
brianfrankcooper_YCSB
|
YCSB/voltdb/src/main/java/site/ycsb/db/voltdb/YCSBSchemaBuilder.java
|
YCSBSchemaBuilder
|
loadClassesAndDDLIfNeeded
|
class YCSBSchemaBuilder {
private static final String PROCEDURE_GET_WAS_NOT_FOUND = "Procedure Get was not found";
private static final Charset UTF8 = Charset.forName("UTF-8");
private final String createTableDDL = "CREATE TABLE Store (keyspace VARBINARY(128) NOT NULL\n"
+ ", key VARCHAR(128) NOT NULL, value VARBINARY(2056) NOT NULL\n"
+ ", PRIMARY KEY (key, keyspace));";
private final String partitionTableDDL = "PARTITION TABLE Store ON COLUMN key;\n";
private final String createGetDDL = "CREATE PROCEDURE Get PARTITION ON TABLE Store COLUMN key PARAMETER 1\n"
+ "AS SELECT value FROM Store WHERE keyspace = ? AND key = ?;";
private final String createPutDDL = "CREATE PROCEDURE PARTITION ON TABLE Store COLUMN key PARAMETER 1\n"
+ "FROM CLASS site.ycsb.db.voltdb.procs.Put;";
private final String createScanDDL = "CREATE PROCEDURE PARTITION ON TABLE Store COLUMN key \n"
+ "FROM CLASS site.ycsb.db.voltdb.procs.Scan;";
private final String createScanAllDDL = "CREATE PROCEDURE \n" + "FROM CLASS site.ycsb.db.voltdb.procs.ScanAll;";
private final String[] ddlStatements = {createTableDDL, partitionTableDDL };
private final String[] procStatements = {createGetDDL, createPutDDL, createScanDDL, createScanAllDDL };
private final String[] jarFiles = {"Put.class", "Scan.class", "ScanAll.class", "ByteWrapper.class" };
private final String jarFileName = "ycsb-procs.jar";
private Logger logger = LoggerFactory.getLogger(YCSBSchemaBuilder.class);
/**
* Utility class to build the YCSB schema.
*
* @author srmadscience / VoltDB
*
*/
YCSBSchemaBuilder() {
super();
}
/**
* See if we think YCSB Schema already exists...
*
* @return true if the 'Get' procedure exists and takes one string as a
* parameter.
*/
public boolean schemaExists(Client voltClient) {
final String testString = "Test";
boolean schemaExists = false;
try {
ClientResponse response = voltClient.callProcedure("Get", testString.getBytes(UTF8), testString);
if (response.getStatus() == ClientResponse.SUCCESS) {
// YCSB Database exists...
schemaExists = true;
} else {
// If we'd connected to a copy of VoltDB without the schema and tried to call Get
// we'd have got a ProcCallException
logger.error("Error while calling schemaExists(): " + response.getStatusString());
schemaExists = false;
}
} catch (ProcCallException pce) {
schemaExists = false;
// Sanity check: Make sure we've got the *right* ProcCallException...
if (!pce.getMessage().equals(PROCEDURE_GET_WAS_NOT_FOUND)) {
logger.error("Got unexpected Exception while calling schemaExists()", pce);
}
} catch (Exception e) {
logger.error("Error while creating classes.", e);
schemaExists = false;
}
return schemaExists;
}
/**
* Load classes and DDL required by YCSB.
*
* @throws Exception
*/
public synchronized void loadClassesAndDDLIfNeeded(Client voltClient) throws Exception {<FILL_FUNCTION_BODY>}
/**
* Add an entry to our JAR file.
*
* @param fileName
* @param source
* @param target
* @throws IOException
*/
private void add(String fileName, InputStream source, JarOutputStream target) throws IOException {
BufferedInputStream in = null;
try {
JarEntry entry = new JarEntry(fileName.replace("\\", "/"));
entry.setTime(System.currentTimeMillis());
target.putNextEntry(entry);
in = new BufferedInputStream(source);
byte[] buffer = new byte[1024];
while (true) {
int count = in.read(buffer);
if (count == -1) {
break;
}
target.write(buffer, 0, count);
}
target.closeEntry();
} finally {
if (in != null) {
in.close();
}
}
}
}
|
if (schemaExists(voltClient)) {
return;
}
File tempDir = Files.createTempDirectory("voltdbYCSB").toFile();
if (!tempDir.canWrite()) {
throw new Exception("Temp Directory (from Files.createTempDirectory()) '"
+ tempDir.getAbsolutePath() + "' is not writable");
}
ClientResponse cr;
for (int i = 0; i < ddlStatements.length; i++) {
try {
cr = voltClient.callProcedure("@AdHoc", ddlStatements[i]);
if (cr.getStatus() != ClientResponse.SUCCESS) {
throw new Exception("Attempt to execute '" + ddlStatements[i] + "' failed:" + cr.getStatusString());
}
logger.info(ddlStatements[i]);
} catch (Exception e) {
if (e.getMessage().indexOf("object name already exists") > -1) {
// Someone else has done this...
return;
}
throw (e);
}
}
logger.info("Creating JAR file in " + tempDir + File.separator + jarFileName);
Manifest manifest = new Manifest();
manifest.getMainAttributes().put(Attributes.Name.MANIFEST_VERSION, "1.0");
JarOutputStream newJarFile = new JarOutputStream(new FileOutputStream(tempDir + File.separator + jarFileName),
manifest);
for (int i = 0; i < jarFiles.length; i++) {
InputStream is = getClass().getResourceAsStream("/site/ycsb/db/voltdb/procs/" + jarFiles[i]);
add("site/ycsb/db/voltdb/procs/" + jarFiles[i], is, newJarFile);
}
newJarFile.close();
File file = new File(tempDir + File.separator + jarFileName);
byte[] jarFileContents = new byte[(int) file.length()];
FileInputStream fis = new FileInputStream(file);
fis.read(jarFileContents);
fis.close();
logger.info("Calling @UpdateClasses to load JAR file containing procedures");
cr = voltClient.callProcedure("@UpdateClasses", jarFileContents, null);
if (cr.getStatus() != ClientResponse.SUCCESS) {
throw new Exception("Attempt to execute UpdateClasses failed:" + cr.getStatusString());
}
for (int i = 0; i < procStatements.length; i++) {
logger.info(procStatements[i]);
cr = voltClient.callProcedure("@AdHoc", procStatements[i]);
if (cr.getStatus() != ClientResponse.SUCCESS) {
throw new Exception("Attempt to execute '" + procStatements[i] + "' failed:" + cr.getStatusString());
}
}
| 1,233
| 739
| 1,972
|
<no_super_class>
|
brianfrankcooper_YCSB
|
YCSB/voltdb/src/main/java/site/ycsb/db/voltdb/procs/ByteWrapper.java
|
ByteWrapper
|
equals
|
class ByteWrapper {
private byte[] marr;
private int moff;
private int mlen;
ByteWrapper(byte[] arr, int off, int len) {
marr = arr;
moff = off;
mlen = len;
}
@Override
public boolean equals(Object obj) {<FILL_FUNCTION_BODY>}
@Override
public int hashCode() {
if (this.marr == null) {
return 0;
}
int res = 1;
for (int i = 0; i < mlen; i++) {
res = 31 * res + marr[moff + i];
}
return res;
}
}
|
if (this == obj) {
return true;
}
if (!(obj instanceof ByteWrapper)) {
return false;
}
ByteWrapper that = (ByteWrapper) obj;
if (this.mlen != that.mlen) {
return false;
}
for (int i = 0; i < this.mlen; i++) {
if (this.marr[this.moff + i] != that.marr[that.moff + i]) {
return false;
}
}
return true;
| 185
| 142
| 327
|
<no_super_class>
|
brianfrankcooper_YCSB
|
YCSB/voltdb/src/main/java/site/ycsb/db/voltdb/procs/Put.java
|
Put
|
merge
|
class Put extends VoltProcedure {
private final SQLStmt selectStmt = new SQLStmt("SELECT value FROM Store WHERE keyspace = ? AND key = ?");
private final SQLStmt insertStmt = new SQLStmt("INSERT INTO Store VALUES (?, ?, ?)");
private final SQLStmt updateStmt = new SQLStmt("UPDATE Store SET value = ? WHERE keyspace = ? AND key = ?");
public long run(byte[] keyspace, String key, byte[] data) {
voltQueueSQL(selectStmt, keyspace, key);
VoltTable res = voltExecuteSQL()[0];
if (res.advanceRow()) {
voltQueueSQL(updateStmt, merge(res.getVarbinary(0), data), keyspace, key);
} else {
voltQueueSQL(insertStmt, keyspace, key, data);
}
voltExecuteSQL(true);
return 0L;
}
private byte[] merge(byte[] dest, byte[] src) {<FILL_FUNCTION_BODY>}
}
|
HashSet<ByteWrapper> mergeSet = new HashSet<ByteWrapper>();
ByteBuffer buf = ByteBuffer.wrap(src);
int nSrc = buf.getInt();
for (int i = 0; i < nSrc; i++) {
int len = buf.getInt();
int off = buf.position();
mergeSet.add(new ByteWrapper(src, off, len));
buf.position(off + len);
len = buf.getInt();
buf.position(buf.position() + len);
}
byte[] merged = new byte[src.length + dest.length];
ByteBuffer out = ByteBuffer.wrap(merged);
buf = ByteBuffer.wrap(dest);
int nDest = buf.getInt();
int nFields = nSrc + nDest;
out.putInt(nFields);
int blockStart = 4;
int blockEnd = 4;
for (int i = 0; i < nDest; i++) {
int len = buf.getInt();
int off = buf.position();
boolean flushBlock = mergeSet.contains(new ByteWrapper(dest, off, len));
buf.position(off + len);
len = buf.getInt();
buf.position(buf.position() + len);
if (flushBlock) {
if (blockStart < blockEnd) {
out.put(dest, blockStart, blockEnd - blockStart);
}
nFields--;
blockStart = buf.position();
}
blockEnd = buf.position();
}
if (blockStart < blockEnd) {
out.put(dest, blockStart, blockEnd - blockStart);
}
out.put(src, 4, src.length - 4);
int length = out.position();
if (nFields != nSrc + nDest) {
out.position(0);
out.putInt(nFields);
}
byte[] res = new byte[length];
System.arraycopy(merged, 0, res, 0, length);
return res;
| 261
| 524
| 785
|
<no_super_class>
|
brianfrankcooper_YCSB
|
YCSB/voltdb/src/main/java/site/ycsb/db/voltdb/procs/Scan.java
|
Scan
|
run
|
class Scan extends VoltProcedure {
private final SQLStmt getBddStmt = new SQLStmt(
"SELECT value, key FROM Store WHERE keyspace = ? AND key >= ? ORDER BY key, keyspace LIMIT ?");
private final SQLStmt getUnbddStmt = new SQLStmt(
"SELECT value, key FROM Store WHERE keyspace = ? ORDER BY key, keyspace LIMIT ?");
public VoltTable[] run(String partKey, byte[] keyspace, byte[] rangeMin, int count) throws Exception {<FILL_FUNCTION_BODY>}
}
|
if (rangeMin != null) {
voltQueueSQL(getBddStmt, keyspace, new String(rangeMin, "UTF-8"), count);
} else {
voltQueueSQL(getUnbddStmt, keyspace, count);
}
return voltExecuteSQL(true);
| 143
| 77
| 220
|
<no_super_class>
|
brianfrankcooper_YCSB
|
YCSB/voltdb/src/main/java/site/ycsb/db/voltdb/procs/ScanAll.java
|
ScanAll
|
run
|
class ScanAll extends VoltProcedure {
private final SQLStmt getBddStmt = new SQLStmt(
"SELECT value, key FROM Store WHERE keyspace = ? AND key >= ? ORDER BY key, keyspace LIMIT ?");
private final SQLStmt getUnbddStmt = new SQLStmt(
"SELECT value, key FROM Store WHERE keyspace = ? ORDER BY key, keyspace LIMIT ?");
public VoltTable[] run(byte[] keyspace, byte[] rangeMin, int count) throws Exception {<FILL_FUNCTION_BODY>}
}
|
if (rangeMin != null) {
voltQueueSQL(getBddStmt, keyspace, new String(rangeMin, "UTF-8"), count);
} else {
voltQueueSQL(getUnbddStmt, keyspace, count);
}
return voltExecuteSQL(true);
| 142
| 77
| 219
|
<no_super_class>
|
brianfrankcooper_YCSB
|
YCSB/voltdb/src/main/java/site/ycsb/db/voltdb/sortedvolttable/VoltDBTableSortedMergeWrangler.java
|
VoltDBTableSortedMergeWrangler
|
getSortedTable
|
class VoltDBTableSortedMergeWrangler {
private ClientResponseWithPartitionKey[] theTables = null;
@SuppressWarnings("rawtypes")
private Comparable whatWeSelectedLastTime = null;
public VoltDBTableSortedMergeWrangler(ClientResponseWithPartitionKey[] response) {
super();
this.theTables = response;
}
/**
* Takes 'theTables' and merges them based on column 'columnId'. We assume that
* column 'columnId' in each element of 'theTables' is correctly sorted within
* itself.
*
* @param columnid
* @param limit How many rows we want
* @return A new VoltTable.
* @throws NeedsToBeComparableException - if column columnId doesn't implement Comparable.
* @throws IncomingVoltTablesNeedToBeSortedException - incoming data isn't already sorted.
* @throws ClientResponseIsBadException - The procedure worked but is complaining.
*/
public VoltTable getSortedTable(int columnid, int limit)
throws NeedsToBeComparableException, IncomingVoltTablesNeedToBeSortedException, ClientResponseIsBadException {<FILL_FUNCTION_BODY>}
/**
* This routine looks at column 'columnId' in an array of VoltTable and
* identifies which one is lowest. Note that as we call 'advanceRow' elsewhere
* this will change.
*
* @param columnid
* @return the VoltTable with the lowest value for column 'columnId'. or -1 if
* we've exhausted all the VoltTables.
* @throws NeedsToBeComparableException
* @throws IncomingVoltTablesNeedToBeSortedException
*/
@SuppressWarnings({ "rawtypes", "unchecked" })
private int getLowestId(int columnid) throws NeedsToBeComparableException, IncomingVoltTablesNeedToBeSortedException {
int lowestId = -1;
Comparable lowestObservedValue = null;
for (int i = 0; i < theTables.length; i++) {
VoltTable currentTable = theTables[i].response.getResults()[0];
int activeRowIndex = currentTable.getActiveRowIndex();
int rowCount = currentTable.getRowCount();
if (activeRowIndex > -1 && activeRowIndex < rowCount) {
if (lowestObservedValue == null) {
lowestId = i;
lowestObservedValue = getComparable(currentTable, columnid);
} else {
Comparable newObservedValue = getComparable(currentTable, columnid);
if (newObservedValue.compareTo(lowestObservedValue) <= 0) {
lowestId = i;
lowestObservedValue = getComparable(currentTable, columnid);
}
}
}
}
// If we found something make sure that the data in columnid was sorted
// properly when it was retrieved.
if (lowestId > -1) {
Comparable latestItemWeSelected = getComparable(theTables[lowestId].response.getResults()[0], columnid);
if (whatWeSelectedLastTime != null && latestItemWeSelected.compareTo(whatWeSelectedLastTime) < 0) {
throw new IncomingVoltTablesNeedToBeSortedException(
"Latest Item '" + latestItemWeSelected + "' is before last item '" + whatWeSelectedLastTime + "'");
}
whatWeSelectedLastTime = latestItemWeSelected;
}
return lowestId;
}
/**
* Get the value we're working with as a Comparable.
*
* @param theTable
* @param columnId
* @return a Comparable.
* @throws NeedsToBeComparableException
*/
@SuppressWarnings("rawtypes")
private Comparable getComparable(VoltTable theTable, int columnId) throws NeedsToBeComparableException {
Comparable c = null;
VoltType vt = theTable.getColumnType(columnId);
Object theValue = theTable.get(columnId, vt);
if (theValue instanceof Comparable) {
c = (Comparable) theValue;
} else {
throw new NeedsToBeComparableException(
theValue + ": Only Comparables are supported by VoltDBTableSortedMergeWrangler");
}
return c;
}
/**
* Do a comparison of byte arrays. Not used right now, but will be when we added
* support for VARBINARY.
*
* @param left
* @param right
* @return whether 'left' is <, >, or = 'right'
*/
private int compare(byte[] left, byte[] right) {
for (int i = 0, j = 0; i < left.length && j < right.length; i++, j++) {
int a = (left[i] & 0xff);
int b = (right[j] & 0xff);
if (a != b) {
return a - b;
}
}
return left.length - right.length;
}
}
|
whatWeSelectedLastTime = null;
// Create an empty output table
VoltTable outputTable = new VoltTable(theTables[0].response.getResults()[0].getTableSchema());
// make sure our input tables are usable, and ready to be read from the
// start
for (int i = 0; i < theTables.length; i++) {
VoltTable currentTable = theTables[i].response.getResults()[0];
if (theTables[i].response.getStatus() != ClientResponse.SUCCESS) {
throw new ClientResponseIsBadException(i + " " + theTables[i].response.getStatusString());
}
currentTable.resetRowPosition();
currentTable.advanceRow();
}
// Find table with lowest value for columnId, which is supposed to be
// the sort key.
int lowestId = getLowestId(columnid);
// Loop until we run out of data or get 'limit' rows.
while (lowestId > -1 && outputTable.getRowCount() < limit) {
// having identified the lowest Table pull that row, add it to
// the output table, and then call 'advanceRow' so we can do this
// again...
VoltTable lowestTable = theTables[lowestId].response.getResults()[0];
outputTable.add(lowestTable.cloneRow());
lowestTable.advanceRow();
// Find table with lowest value for columnId
lowestId = getLowestId(columnid);
}
return outputTable;
| 1,362
| 402
| 1,764
|
<no_super_class>
|
brianfrankcooper_YCSB
|
YCSB/zookeeper/src/main/java/site/ycsb/db/zookeeper/ZKClient.java
|
ZKClient
|
insert
|
class ZKClient extends DB {
private ZooKeeper zk;
private Watcher watcher;
private static final String CONNECT_STRING = "zookeeper.connectString";
private static final String DEFAULT_CONNECT_STRING = "127.0.0.1:2181";
private static final String SESSION_TIMEOUT_PROPERTY = "zookeeper.sessionTimeout";
private static final long DEFAULT_SESSION_TIMEOUT = TimeUnit.SECONDS.toMillis(30L);
private static final String WATCH_FLAG = "zookeeper.watchFlag";
private static final Charset UTF_8 = Charset.forName("UTF-8");
private static final Logger LOG = LoggerFactory.getLogger(ZKClient.class);
public void init() throws DBException {
Properties props = getProperties();
String connectString = props.getProperty(CONNECT_STRING);
if (connectString == null || connectString.length() == 0) {
connectString = DEFAULT_CONNECT_STRING;
}
if(Boolean.parseBoolean(props.getProperty(WATCH_FLAG))) {
watcher = new SimpleWatcher();
} else {
watcher = null;
}
long sessionTimeout;
String sessionTimeoutString = props.getProperty(SESSION_TIMEOUT_PROPERTY);
if (sessionTimeoutString != null) {
sessionTimeout = Integer.parseInt(sessionTimeoutString);
} else {
sessionTimeout = DEFAULT_SESSION_TIMEOUT;
}
try {
zk = new ZooKeeper(connectString, (int) sessionTimeout, new SimpleWatcher());
} catch (IOException e) {
throw new DBException("Creating connection failed.");
}
}
public void cleanup() throws DBException {
try {
zk.close();
} catch (InterruptedException e) {
throw new DBException("Closing connection failed.");
}
}
@Override
public Status read(String table, String key, Set<String> fields,
Map<String, ByteIterator> result) {
String path = getPath(key);
try {
byte[] data = zk.getData(path, watcher, null);
if (data == null || data.length == 0) {
return Status.NOT_FOUND;
}
deserializeValues(data, fields, result);
return Status.OK;
} catch (KeeperException | InterruptedException e) {
LOG.error("Error when reading a path:{},tableName:{}", path, table, e);
return Status.ERROR;
}
}
@Override
public Status insert(String table, String key,
Map<String, ByteIterator> values) {<FILL_FUNCTION_BODY>}
@Override
public Status delete(String table, String key) {
String path = getPath(key);
try {
zk.delete(path, -1);
return Status.OK;
} catch (InterruptedException | KeeperException e) {
LOG.error("Error when deleting a path:{},tableName:{}", path, table, e);
return Status.ERROR;
}
}
@Override
public Status update(String table, String key,
Map<String, ByteIterator> values) {
String path = getPath(key);
try {
// we have to do a read operation here before setData to meet the YCSB's update semantics:
// update a single record in the database, adding or replacing the specified fields.
byte[] data = zk.getData(path, watcher, null);
if (data == null || data.length == 0) {
return Status.NOT_FOUND;
}
final Map<String, ByteIterator> result = new HashMap<>();
deserializeValues(data, null, result);
result.putAll(values);
// update
zk.setData(path, getJsonStrFromByteMap(result).getBytes(UTF_8), -1);
return Status.OK;
} catch (KeeperException | InterruptedException e) {
LOG.error("Error when updating a path:{},tableName:{}", path, table, e);
return Status.ERROR;
}
}
@Override
public Status scan(String table, String startkey, int recordcount,
Set<String> fields, Vector<HashMap<String, ByteIterator>> result) {
return Status.NOT_IMPLEMENTED;
}
private String getPath(String key) {
return key.startsWith("/") ? key : "/" + key;
}
/**
* converting the key:values map to JSON Strings.
*/
private static String getJsonStrFromByteMap(Map<String, ByteIterator> map) {
Map<String, String> stringMap = StringByteIterator.getStringMap(map);
return JSONValue.toJSONString(stringMap);
}
private Map<String, ByteIterator> deserializeValues(final byte[] data, final Set<String> fields,
final Map<String, ByteIterator> result) {
JSONObject jsonObject = (JSONObject)JSONValue.parse(new String(data, UTF_8));
Iterator<String> iterator = jsonObject.keySet().iterator();
while(iterator.hasNext()) {
String field = iterator.next();
String value = jsonObject.get(field).toString();
if(fields == null || fields.contains(field)) {
result.put(field, new StringByteIterator(value));
}
}
return result;
}
private static class SimpleWatcher implements Watcher {
public void process(WatchedEvent e) {
if (e.getType() == Event.EventType.None) {
return;
}
if (e.getState() == Event.KeeperState.SyncConnected) {
//do nothing
}
}
}
}
|
String path = getPath(key);
String data = getJsonStrFromByteMap(values);
try {
zk.create(path, data.getBytes(UTF_8), ZooDefs.Ids.OPEN_ACL_UNSAFE,
CreateMode.PERSISTENT);
return Status.OK;
} catch (KeeperException.NodeExistsException e1) {
return Status.OK;
} catch (KeeperException | InterruptedException e2) {
LOG.error("Error when inserting a path:{},tableName:{}", path, table, e2);
return Status.ERROR;
}
| 1,508
| 161
| 1,669
|
<methods>public non-sealed void <init>() ,public void cleanup() throws site.ycsb.DBException,public abstract site.ycsb.Status delete(java.lang.String, java.lang.String) ,public java.util.Properties getProperties() ,public void init() throws site.ycsb.DBException,public abstract site.ycsb.Status insert(java.lang.String, java.lang.String, Map<java.lang.String,site.ycsb.ByteIterator>) ,public abstract site.ycsb.Status read(java.lang.String, java.lang.String, Set<java.lang.String>, Map<java.lang.String,site.ycsb.ByteIterator>) ,public abstract site.ycsb.Status scan(java.lang.String, java.lang.String, int, Set<java.lang.String>, Vector<HashMap<java.lang.String,site.ycsb.ByteIterator>>) ,public void setProperties(java.util.Properties) ,public abstract site.ycsb.Status update(java.lang.String, java.lang.String, Map<java.lang.String,site.ycsb.ByteIterator>) <variables>private java.util.Properties properties
|
infinilabs_analysis-pinyin
|
analysis-pinyin/elasticsearch/src/main/java/com/infinilabs/elasticsearch/analysis/AnalysisPinyinPlugin.java
|
AnalysisPinyinPlugin
|
getTokenizers
|
class AnalysisPinyinPlugin extends Plugin implements AnalysisPlugin {
@Override
public Map<String, AnalysisModule.AnalysisProvider<TokenizerFactory>> getTokenizers() {<FILL_FUNCTION_BODY>}
@Override
public Map<String, AnalysisModule.AnalysisProvider<org.elasticsearch.index.analysis.TokenFilterFactory>> getTokenFilters() {
Map<String, AnalysisModule.AnalysisProvider<org.elasticsearch.index.analysis.TokenFilterFactory>> extra = new HashMap<>();
extra.put("pinyin", PinyinTokenFilterFactory::new);
return extra;
}
@Override
public Map<String, AnalysisModule.AnalysisProvider<AnalyzerProvider<? extends Analyzer>>> getAnalyzers() {
return Collections.singletonMap("pinyin", PinyinAnalyzerProvider::new);
}
}
|
Map<String, AnalysisModule.AnalysisProvider<TokenizerFactory>> extra = new HashMap<>();
extra.put("pinyin", PinyinTokenizerFactory::new);
extra.put("pinyin_first_letter", PinyinAbbreviationsTokenizerFactory::new);
return extra;
| 210
| 76
| 286
|
<no_super_class>
|
infinilabs_analysis-pinyin
|
analysis-pinyin/elasticsearch/src/main/java/com/infinilabs/elasticsearch/analysis/PinyinAbbreviationsTokenizerFactory.java
|
PinyinAbbreviationsTokenizerFactory
|
create
|
class PinyinAbbreviationsTokenizerFactory extends AbstractTokenizerFactory {
public PinyinAbbreviationsTokenizerFactory(IndexSettings indexSettings, Environment env, String name, Settings settings) {
super(indexSettings, settings, name);
}
@Override
public Tokenizer create() {<FILL_FUNCTION_BODY>}
}
|
PinyinConfig config=new ESPinyinConfig();
config.keepFirstLetter=true;
config.keepFullPinyin=false;
config.keepNoneChinese=false;
config.keepNoneChineseTogether=true;
config.noneChinesePinyinTokenize=false;
config.keepOriginal=false;
config.lowercase=true;
config.trimWhitespace=true;
config.keepNoneChineseInFirstLetter=true;
return new PinyinTokenizer(config);
| 96
| 148
| 244
|
<no_super_class>
|
infinilabs_analysis-pinyin
|
analysis-pinyin/opensearch/src/main/java/com/infinilabs/opensearch/analysis/AnalysisPinyinPlugin.java
|
AnalysisPinyinPlugin
|
getTokenizers
|
class AnalysisPinyinPlugin extends Plugin implements AnalysisPlugin {
@Override
public Map<String, AnalysisModule.AnalysisProvider<TokenizerFactory>> getTokenizers() {<FILL_FUNCTION_BODY>}
@Override
public Map<String, AnalysisModule.AnalysisProvider<org.opensearch.index.analysis.TokenFilterFactory>> getTokenFilters() {
Map<String, AnalysisModule.AnalysisProvider<org.opensearch.index.analysis.TokenFilterFactory>> extra = new HashMap<>();
extra.put("pinyin", PinyinTokenFilterFactory::new);
return extra;
}
@Override
public Map<String, AnalysisModule.AnalysisProvider<AnalyzerProvider<? extends Analyzer>>> getAnalyzers() {
return Collections.singletonMap("pinyin", PinyinAnalyzerProvider::new);
}
}
|
Map<String, AnalysisModule.AnalysisProvider<TokenizerFactory>> extra = new HashMap<>();
extra.put("pinyin", PinyinTokenizerFactory::new);
extra.put("pinyin_first_letter", PinyinAbbreviationsTokenizerFactory::new);
return extra;
| 212
| 76
| 288
|
<no_super_class>
|
infinilabs_analysis-pinyin
|
analysis-pinyin/opensearch/src/main/java/com/infinilabs/opensearch/analysis/PinyinAbbreviationsTokenizerFactory.java
|
PinyinAbbreviationsTokenizerFactory
|
create
|
class PinyinAbbreviationsTokenizerFactory extends AbstractTokenizerFactory {
public PinyinAbbreviationsTokenizerFactory(IndexSettings indexSettings, Environment env, String name, Settings settings) {
super(indexSettings, settings, name);
}
@Override
public Tokenizer create() {<FILL_FUNCTION_BODY>}
}
|
PinyinConfig config=new ESPinyinConfig();
config.keepFirstLetter=true;
config.keepFullPinyin=false;
config.keepNoneChinese=false;
config.keepNoneChineseTogether=true;
config.noneChinesePinyinTokenize=false;
config.keepOriginal=false;
config.lowercase=true;
config.trimWhitespace=true;
config.keepNoneChineseInFirstLetter=true;
return new PinyinTokenizer(config);
| 88
| 136
| 224
|
<no_super_class>
|
infinilabs_analysis-pinyin
|
analysis-pinyin/pinyin-core/src/main/java/com/infinilabs/pinyin/analysis/ChineseUtil.java
|
ChineseUtil
|
segmentChinese
|
class ChineseUtil {
/**
* 汉字始
*/
public static char CJK_UNIFIED_IDEOGRAPHS_START = '\u4E00';
/**
* 汉字止
*/
public static char CJK_UNIFIED_IDEOGRAPHS_END = '\u9FA5';
public static List<String> segmentChinese(String str){<FILL_FUNCTION_BODY>}
}
|
if (StringUtil.isBlank(str)) {
return Collections.emptyList();
}
List<String> lists = str.length()<=32767?new ArrayList<>(str.length()):new LinkedList<>();
for (int i=0;i<str.length();i++){
char c = str.charAt(i);
if(c>=CJK_UNIFIED_IDEOGRAPHS_START&&c<=CJK_UNIFIED_IDEOGRAPHS_END){
lists.add(String.valueOf(c));
}
else{
lists.add(null);
}
}
return lists;
| 116
| 175
| 291
|
<no_super_class>
|
infinilabs_analysis-pinyin
|
analysis-pinyin/pinyin-core/src/main/java/com/infinilabs/pinyin/analysis/PinyinAlphabetTokenizer.java
|
PinyinAlphabetTokenizer
|
segPinyinStr
|
class PinyinAlphabetTokenizer {
private static final int PINYIN_MAX_LENGTH = 6;
public static List<String> walk(String text) {
return segPinyinStr(text);
}
private static List<String> segPinyinStr(String content) {<FILL_FUNCTION_BODY>}
private static List<String> splitByNoletter(String pinyinStr) {
List<String> pinyinStrList = new ArrayList<>();
StringBuffer sb = new StringBuffer();
boolean lastWord = true;
for (char c : pinyinStr.toCharArray()) {
if ((c > 96 && c < 123) || (c > 64 && c < 91)) {
if (!lastWord){
pinyinStrList.add(sb.toString());
sb.setLength(0);
}
sb.append(c);
lastWord = true;
} else {
if (lastWord & sb.length()>0) {
pinyinStrList.add(sb.toString());
sb.setLength(0);
}
sb.append(c);
lastWord = false;
}
}
if (sb.length() > 0) {
pinyinStrList.add(sb.toString());
}
return pinyinStrList;
}
private static List<String> positiveMaxMatch(String pinyinText, int maxLength) {
List<String> pinyinList = new ArrayList<>();
StringBuffer noMatchBuffer = new StringBuffer();
for (int start = 0; start < pinyinText.length(); ) {
int end = start + maxLength;
if (end > pinyinText.length()) {
end = pinyinText.length();
}
if (start == end) {
break;
}
String sixStr = pinyinText.substring(start, end);
boolean match = false;
for (int j = 0; j < sixStr.length(); j++) {
String guess = sixStr.substring(0, sixStr.length() - j);
if (PinyinAlphabetDict.getInstance().match(guess)) {
pinyinList.add(guess);
start += guess.length();
match = true;
break;
}
}
if (!match) { //没命中,向后移动一位
noMatchBuffer.append(sixStr.substring(0, 1));
start++;
}else { // 命中,加上之前没命中的,并清空
if (noMatchBuffer.length() > 0) {
pinyinList.add(noMatchBuffer.toString());
noMatchBuffer.setLength(0);
}
}
}
if (noMatchBuffer.length() > 0) {
pinyinList.add(noMatchBuffer.toString());
noMatchBuffer.setLength(0);
}
return pinyinList;
}
private static List<String> reverseMaxMatch(String pinyinText, int maxLength) {
List<String> pinyinList = new ArrayList<>();
StringBuffer noMatchBuffer = new StringBuffer();
for (int end = pinyinText.length(); end >= 0; ) {
int start = end - maxLength;
if (start < 0) {
start = 0;
}
if (start == end) {
break;
}
boolean match = false;
String sixStr = pinyinText.substring(start, end);
for (int j = 0; j < sixStr.length(); j++) {
String guess = sixStr.substring(j);
if (PinyinAlphabetDict.getInstance().match(guess)) {
pinyinList.add(guess);
end -= guess.length();
match = true;
break;
}
}
if (!match) { //一个也没命中
noMatchBuffer.append(sixStr.substring(sixStr.length() - 1));
end--;
} else {
if (noMatchBuffer.length() > 0) {
pinyinList.add(noMatchBuffer.toString());
noMatchBuffer.setLength(0);
}
}
}
if (noMatchBuffer.length() > 0) {
pinyinList.add(noMatchBuffer.toString());
noMatchBuffer.setLength(0);
}
// reverse 保持切词顺序
Collections.reverse(pinyinList);
return pinyinList;
}
}
|
String pinyinStr = content;
pinyinStr = pinyinStr.toLowerCase();
// 按非letter切分
List<String> pinyinStrList = splitByNoletter(pinyinStr);
List<String> pinyinList = new ArrayList<>();
for (String pinyinText : pinyinStrList) {
if (pinyinText.length() == 1) {
pinyinList.add(pinyinText);
} else {
List<String> forward = positiveMaxMatch(pinyinText, PINYIN_MAX_LENGTH);
if (forward.size() == 1) { // 前向只切出1个的话,没有必要再做逆向分词
pinyinList.addAll(forward);
} else {
// 分别正向、逆向最大匹配,选出最短的作为最优结果
List<String> backward = reverseMaxMatch(pinyinText, PINYIN_MAX_LENGTH);
if (forward.size() <= backward.size()) {
pinyinList.addAll(forward);
} else {
pinyinList.addAll(backward);
}
}
}
}
return pinyinList;
| 1,163
| 315
| 1,478
|
<no_super_class>
|
infinilabs_analysis-pinyin
|
analysis-pinyin/pinyin-core/src/main/java/org/nlpcn/commons/lang/pinyin/Pinyin.java
|
Pinyin
|
list2StringSkipNull
|
class Pinyin {
/**
* 拼音返回
*
* @param str
* @return [chang, jiang, cheng, zhang]
*/
public static List<String> pinyin(String str) {
return PinyinUtil.INSTANCE.convert(str, PinyinFormat.TONELESS_PINYIN_FORMAT);
}
/**
* 取得每个字的首字符
*
* @param str
* @return [c, j, c, z]
*/
public static List<String> firstChar(String str) {
return PinyinUtil.INSTANCE.convert(str, PinyinFormat.ABBR_PINYIN_FORMAT);
}
/**
* 取得每个字的帶音標
*
* @param str
* @return [cháng, jiāng, chéng, zhăng]
*/
public static List<String> unicodePinyin(String str) {
return PinyinUtil.INSTANCE.convert(str, PinyinFormat.UNICODE_PINYIN_FORMAT);
}
/**
* 要音標的拼音
*
* @param str
* @return [chang2, jiang1, cheng2, zhang3]
*/
public static List<String> tonePinyin(String str) {
return PinyinUtil.INSTANCE.convert(str, PinyinFormat.DEFAULT_PINYIN_FORMAT);
}
/**
* list 转换为字符串
*
* @param list
* @param spearator
* @return
*/
public static String list2String(List<String> list, String spearator) {
StringBuilder sb = new StringBuilder();
boolean flag = true;
for (String string : list) {
if (string == null) {
string = "NULL";
}
if (flag) {
sb.append(string);
flag = false;
} else {
sb.append(spearator);
sb.append(string);
}
}
return sb.toString();
}
/**
* list 转换为字符串 默认空格
*
* @param list
* @return
*/
public static String list2String(List<String> list) {
return list2String(list, " ");
}
/**
* 动态增加到拼音词典中
*
* @param word
* 大长今
* @param pinyins
* ['da4', 'chang2' ,'jing1']
*/
public static void insertPinyin(String word, String[] pinyins) {
PinyinUtil.INSTANCE.insertPinyin(word, pinyins);
}
/**
* list 转换为字符串 默认空格,忽略null
*
* @param list
* @return
*/
public static String list2StringSkipNull(List<String> list) {
return list2StringSkipNull(list, " ");
}
/**
* list 转换为字符串
*
* @param list
* @param spearator
* @return
*/
public static String list2StringSkipNull(List<String> list, String spearator) {<FILL_FUNCTION_BODY>}
}
|
StringBuilder sb = new StringBuilder();
boolean flag = true;
for (String string : list) {
if (string == null) {
continue;
}
if (flag) {
sb.append(string);
flag = false;
} else {
sb.append(spearator);
sb.append(string);
}
}
return sb.toString();
| 875
| 111
| 986
|
<no_super_class>
|
infinilabs_analysis-pinyin
|
analysis-pinyin/pinyin-core/src/main/java/org/nlpcn/commons/lang/pinyin/PinyinFormatter.java
|
PinyinFormatter
|
convertToneNumber2ToneMark
|
class PinyinFormatter {
public static String formatPinyin(String pinyinStr, PinyinFormat format) {
if (ToneType.WITH_ABBR == format.getToneType()) {
pinyinStr = abbr(pinyinStr);
} else {
if ((ToneType.WITH_TONE_MARK == format.getToneType())
&& ((YuCharType.WITH_V == format.getYuCharType()) || (YuCharType.WITH_U_AND_COLON == format
.getYuCharType()))) {
// ToneType.WITH_TONE_MARK force YuCharType.WITH_U_UNICODE
format.setYuCharType(YuCharType.WITH_U_UNICODE);
// throw new BadPinyinFormatException(
// "tone marks cannot be added to v or u:");
}
switch (format.getToneType()) {
case WITHOUT_TONE:
pinyinStr = pinyinStr.replaceAll("[1-5]", "");
break;
case WITH_TONE_MARK:
pinyinStr = pinyinStr.replaceAll("u:", "v");
pinyinStr = convertToneNumber2ToneMark(pinyinStr);
break;
default:
break;
}
switch (format.getYuCharType()) {
case WITH_V:
pinyinStr = pinyinStr.replaceAll("u:", "v");
break;
case WITH_U_UNICODE:
pinyinStr = pinyinStr.replaceAll("u:", "ü");
break;
default:
break;
}
}
switch (format.getCaseType()) {
case UPPERCASE:
pinyinStr = pinyinStr.toUpperCase();
break;
case CAPITALIZE:
pinyinStr = capitalize(pinyinStr);
break;
default:
break;
}
return pinyinStr;
}
public static String abbr(String str) {
if (str == null || str.length() == 0) {
return str;
}
return str.substring(0, 1);
}
public static String capitalize(String str) {
int strLen;
if (str == null || (strLen = str.length()) == 0) {
return str;
}
return new StringBuilder(strLen)
.append(Character.toTitleCase(str.charAt(0)))
.append(str.substring(1)).toString();
}
/**
* Convert tone numbers to tone marks using Unicode <br/>
* <br/>
*
* <b>Algorithm for determining location of tone mark</b><br/>
*
* A simple algorithm for determining the vowel on which the tone mark
* appears is as follows:<br/>
*
* <ol>
* <li>First, look for an "a" or an "e". If either vowel appears, it takes
* the tone mark. There are no possible pinyin syllables that contain both
* an "a" and an "e".
*
* <li>If there is no "a" or "e", look for an "ou". If "ou" appears, then
* the "o" takes the tone mark.
*
* <li>If none of the above cases hold, then the last vowel in the syllable
* takes the tone mark.
*
* </ol>
*
* @param pinyinStr
* the ascii represention with tone numbers
* @return the unicode represention with tone marks
*/
private static String convertToneNumber2ToneMark(final String pinyinStr) {<FILL_FUNCTION_BODY>}
}
|
String lowerCasePinyinStr = pinyinStr.toLowerCase();
if (lowerCasePinyinStr.matches("[a-z]*[1-5]?")) {
final char defautlCharValue = '$';
final int defautlIndexValue = -1;
char unmarkedVowel = defautlCharValue;
int indexOfUnmarkedVowel = defautlIndexValue;
final char charA = 'a';
final char charE = 'e';
final String ouStr = "ou";
final String allUnmarkedVowelStr = "aeiouv";
final String allMarkedVowelStr = "āáăàaēéĕèeīíĭìiōóŏòoūúŭùuǖǘǚǜü";
if (lowerCasePinyinStr.matches("[a-z]*[1-5]")) {
int tuneNumber = Character.getNumericValue(lowerCasePinyinStr
.charAt(lowerCasePinyinStr.length() - 1));
int indexOfA = lowerCasePinyinStr.indexOf(charA);
int indexOfE = lowerCasePinyinStr.indexOf(charE);
int ouIndex = lowerCasePinyinStr.indexOf(ouStr);
if (-1 != indexOfA) {
indexOfUnmarkedVowel = indexOfA;
unmarkedVowel = charA;
} else if (-1 != indexOfE) {
indexOfUnmarkedVowel = indexOfE;
unmarkedVowel = charE;
} else if (-1 != ouIndex) {
indexOfUnmarkedVowel = ouIndex;
unmarkedVowel = ouStr.charAt(0);
} else {
for (int i = lowerCasePinyinStr.length() - 1; i >= 0; i--) {
if (String.valueOf(lowerCasePinyinStr.charAt(i))
.matches("[" + allUnmarkedVowelStr + "]")) {
indexOfUnmarkedVowel = i;
unmarkedVowel = lowerCasePinyinStr.charAt(i);
break;
}
}
}
if ((defautlCharValue != unmarkedVowel)
&& (defautlIndexValue != indexOfUnmarkedVowel)) {
int rowIndex = allUnmarkedVowelStr.indexOf(unmarkedVowel);
int columnIndex = tuneNumber - 1;
int vowelLocation = rowIndex * 5 + columnIndex;
char markedVowel = allMarkedVowelStr.charAt(vowelLocation);
StringBuffer resultBuffer = new StringBuffer();
resultBuffer.append(lowerCasePinyinStr.substring(0,
indexOfUnmarkedVowel).replaceAll("v", "ü"));
resultBuffer.append(markedVowel);
resultBuffer.append(lowerCasePinyinStr.substring(
indexOfUnmarkedVowel + 1,
lowerCasePinyinStr.length() - 1).replaceAll("v",
"ü"));
return resultBuffer.toString();
} else
// error happens in the procedure of locating vowel
{
return lowerCasePinyinStr;
}
} else
// input string has no any tune number
{
// only replace v with ü (umlat) character
return lowerCasePinyinStr.replaceAll("v", "ü");
}
} else
// bad format
{
return lowerCasePinyinStr;
}
| 1,013
| 960
| 1,973
|
<no_super_class>
|
infinilabs_analysis-pinyin
|
analysis-pinyin/pinyin-core/src/main/java/org/nlpcn/commons/lang/pinyin/PinyinWord.java
|
PinyinWord
|
toString
|
class PinyinWord {
public String py;
public int tone;
PinyinWord(String pinyinStr) {
this.py = pinyinStr.substring(0, pinyinStr.length() - 1);
char c = pinyinStr.charAt(pinyinStr.length() - 1);
if (c >= '0' && c <= '9') {
this.tone = Integer.parseInt(String.valueOf(c));
} else {
this.py = pinyinStr;
}
}
public PinyinWord(char c) {
this.py = String.valueOf(c);
}
public String toString() {<FILL_FUNCTION_BODY>}
public static void main(String[] args) {
System.out.println(new PinyinWord("bei3"));
;
}
}
|
if (tone > 0)
return this.py + tone;
else
return this.py;
| 225
| 30
| 255
|
<no_super_class>
|
infinilabs_analysis-pinyin
|
analysis-pinyin/pinyin-core/src/main/java/org/nlpcn/commons/lang/tire/GetWord.java
|
GetWord
|
getParam
|
class GetWord extends SmartGetWord<String[]> {
public GetWord(Forest forest, char[] chars) {
super(forest, chars);
}
public GetWord(Forest forest, String content) {
super(forest, content);
}
public String getParam(int i) {<FILL_FUNCTION_BODY>}
public String[] getParams() {
return this.getParam();
}
}
|
final String[] param = this.getParam();
if (param == null || i >= param.length) {
return null;
} else {
return param[i];
}
| 113
| 51
| 164
|
<methods>public void <init>(SmartForest<java.lang.String[]>, java.lang.String) ,public void <init>(SmartForest<java.lang.String[]>, char[]) ,public java.lang.String getAllWords() ,public java.lang.String getFrontWords() ,public java.lang.String[] getParam() ,public boolean isE(char) ,public boolean isNum(char) ,public void reset(java.lang.String) <variables>private static final java.lang.String EMPTYSTRING,private SmartForest<java.lang.String[]> branch,private char[] chars,private SmartForest<java.lang.String[]> forest,int i,boolean isBack,public int offe,private java.lang.String[] param,int root,byte status,private java.lang.String str,private java.lang.Integer tempJLen,private int tempOffe
|
infinilabs_analysis-pinyin
|
analysis-pinyin/pinyin-core/src/main/java/org/nlpcn/commons/lang/tire/domain/Value.java
|
Value
|
toString
|
class Value {
private static final String TAB = "\t";
private String keyword;
private String[] paramers = new String[0];
public Value(String keyword, String... paramers) {
this.keyword = keyword;
if (paramers != null) {
this.paramers = paramers;
}
}
public Value(String temp) {
String[] strs = temp.split(TAB);
this.keyword = strs[0];
if (strs.length > 1) {
this.paramers = Arrays.copyOfRange(strs, 1, strs.length);
}
}
public String getKeyword() {
return keyword;
}
public void setKeyword(String keyword) {
this.keyword = keyword;
}
public String[] getParamers() {
return paramers;
}
public void setParamers(String[] paramers) {
this.paramers = paramers;
}
@Override
public String toString() {<FILL_FUNCTION_BODY>}
}
|
StringBuilder sb = new StringBuilder();
sb.append(keyword);
for (int i = 0; i < paramers.length; i++) {
sb.append(TAB);
sb.append(paramers[i]);
}
return sb.toString();
| 264
| 74
| 338
|
<no_super_class>
|
infinilabs_analysis-pinyin
|
analysis-pinyin/pinyin-core/src/main/java/org/nlpcn/commons/lang/tire/library/Library.java
|
Library
|
insertWord
|
class Library {
public static Forest makeForest(String path) throws Exception {
return makeForest(new FileInputStream(path));
}
public static Forest makeForest(String path, String encoding) throws Exception {
return makeForest(new FileInputStream(path), encoding);
}
public static Forest makeForest(InputStream inputStream) throws Exception {
return makeForest(IOUtil.getReader(inputStream, "UTF-8"));
}
public static Forest makeForest(InputStream inputStream, String encoding) throws Exception {
return makeForest(IOUtil.getReader(inputStream, encoding));
}
public static Forest makeForest(BufferedReader br) throws Exception {
return makeLibrary(br, new Forest());
}
/**
* 传入value数组.构造树
*
* @param values
* @return
*/
public static Forest makeForest(List<Value> values) {
Forest forest = new Forest();
for (Value value : values) {
insertWord(forest, value.toString());
}
return forest;
}
/**
* 词典树的构造方法
*
* @param br
* @param forest
* @return
* @throws Exception
*/
private static Forest makeLibrary(BufferedReader br, Forest forest) throws Exception {
if (br == null)
return forest;
try {
String temp = null;
while ((temp = br.readLine()) != null) {
insertWord(forest, temp);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
br.close();
}
return forest;
}
public static void insertWord(Forest forest, Value value) {
insertWord(forest, value.getKeyword(), value.getParamers());
}
/**
* 插入一个词
*
* @param forest
* @param temp
*/
public static void insertWord(Forest forest, String temp) {
String[] param = temp.split("\t");
temp = param[0];
String[] resultParams = new String[param.length - 1];
for (int j = 1; j < param.length; j++) {
resultParams[j - 1] = param[j];
}
insertWord(forest, temp, resultParams);
}
private static void insertWord(Forest forest, String temp, String... param) {<FILL_FUNCTION_BODY>}
/**
* 删除一个词
*
* @param forest
* @param word
*/
public static void removeWord(Forest forest, String word) {
SmartForest<String[]> branch = forest;
char[] chars = word.toCharArray();
for (int i = 0; i < chars.length; i++) {
if (branch == null)
return;
if (chars.length == i + 1) {
branch.add(new Forest(chars[i], -1, null));
}
branch = branch.getBranch(chars[i]);
}
}
}
|
SmartForest<String[]> branch = forest;
char[] chars = temp.toCharArray();
for (int i = 0; i < chars.length; i++) {
if (chars.length == i + 1) {
branch.add(new Forest(chars[i], 3, param));
} else {
branch.add(new Forest(chars[i], 1, null));
}
branch = branch.getBranch(chars[i]);
}
| 905
| 144
| 1,049
|
<no_super_class>
|
infinilabs_analysis-pinyin
|
analysis-pinyin/pinyin-core/src/main/java/org/nlpcn/commons/lang/util/AnsjArrays.java
|
AnsjArrays
|
main
|
class AnsjArrays {
private static final int INSERTIONSORT_THRESHOLD = 7;
/**
* 二分法查找.摘抄了jdk的东西..只不过把他的自动装箱功能给去掉了
*
* @param branches
* branches
* @param c
* char
* @return idx
*/
public static <T extends SmartForest<T>> int binarySearch(T[] branches, char c) {
int high = branches.length - 1;
if (branches.length < 1) {
return high;
}
int low = 0;
while (low <= high) {
int mid = (low + high) >>> 1;
int cmp = branches[mid].compareTo(c);
if (cmp < 0)
low = mid + 1;
else if (cmp > 0)
high = mid - 1;
else
return mid; // key found
}
return -(low + 1); // key not found.
}
public static void main(String[] args) {<FILL_FUNCTION_BODY>}
public static void sort(SmartForest[] a) {
SmartForest[] aux = a.clone();
mergeSort(aux, a, 0, a.length, 0);
}
public static void sort(SmartForest[] a, int fromIndex, int toIndex) {
rangeCheck(a.length, fromIndex, toIndex);
SmartForest[] aux = copyOfRange(a, fromIndex, toIndex);
mergeSort(aux, a, fromIndex, toIndex, -fromIndex);
}
private static void rangeCheck(int arrayLen, int fromIndex, int toIndex) {
if (fromIndex > toIndex)
throw new IllegalArgumentException("fromIndex(" + fromIndex + ") > toIndex(" + toIndex + ")");
if (fromIndex < 0)
throw new ArrayIndexOutOfBoundsException(fromIndex);
if (toIndex > arrayLen)
throw new ArrayIndexOutOfBoundsException(toIndex);
}
private static void mergeSort(SmartForest[] src, SmartForest[] dest, int low, int high, int off) {
int length = high - low;
// Insertion sort on smallest arrays
if (length < INSERTIONSORT_THRESHOLD) {
for (int i = low; i < high; i++)
for (int j = i; j > low && (dest[j - 1]).compareTo(dest[j].getC()) > 0; j--)
swap(dest, j, j - 1);
return;
}
// Recursively sort halves of dest into src
int destLow = low;
int destHigh = high;
low += off;
high += off;
int mid = (low + high) >>> 1;
mergeSort(dest, src, low, mid, -off);
mergeSort(dest, src, mid, high, -off);
// If list is already sorted, just copy from src to dest. This is an
// optimization that results in faster sorts for nearly ordered lists.
if (src[mid - 1].compareTo(src[mid].getC()) <= 0) {
System.arraycopy(src, low, dest, destLow, length);
return;
}
// Merge sorted halves (now in src) into dest
for (int i = destLow, p = low, q = mid; i < destHigh; i++) {
if (q >= high || p < mid && src[p].compareTo(src[q].getC()) <= 0)
dest[i] = src[p++];
else
dest[i] = src[q++];
}
}
/**
* Swaps x[a] with x[b].
*/
private static void swap(SmartForest[] x, int a, int b) {
SmartForest t = x[a];
x[a] = x[b];
x[b] = t;
}
@SuppressWarnings("unchecked")
public static <T> T[] copyOfRange(T[] original, int from, int to) {
return copyOfRange(original, from, to, (Class<T[]>) original.getClass());
}
public static <T, U> T[] copyOfRange(U[] original, int from, int to, Class<? extends T[]> newType) {
int newLength = to - from;
if (newLength < 0)
throw new IllegalArgumentException(from + " > " + to);
@SuppressWarnings("unchecked")
T[] copy = ((Object) newType == (Object) Object[].class) ? (T[]) new Object[newLength] : (T[]) Array.newInstance(newType.getComponentType(), newLength);
System.arraycopy(original, from, copy, 0, Math.min(original.length - from, newLength));
return copy;
}
}
|
int[] chars = { 1, 2, 3, 4, 5, 6, 8, 7 };
chars = Arrays.copyOf(chars, 100);
System.out.println(chars.length);
for (int i = 0; i < chars.length; i++) {
System.out.println(chars[i]);
}
| 1,383
| 115
| 1,498
|
<no_super_class>
|
infinilabs_analysis-pinyin
|
analysis-pinyin/pinyin-core/src/main/java/org/nlpcn/commons/lang/util/CollectionUtil.java
|
CollectionUtil
|
as
|
class CollectionUtil {
/**
* map 按照value排序
*
* @return
*/
public static <K, V> List<Map.Entry<K, V>> sortMapByValue(Map<K, V> map, final int sort) {
List<Map.Entry<K, V>> orderList = new ArrayList<Map.Entry<K, V>>(map.entrySet());
Collections.sort(orderList, new Comparator<Map.Entry<K, V>>() {
@Override
@SuppressWarnings("unchecked")
public int compare(Map.Entry<K, V> o1, Map.Entry<K, V> o2) {
return (((Comparable<V>) o2.getValue()).compareTo(o1.getValue())) * sort;
}
});
return orderList;
}
public static <K, V> Map<K, V> as(K k1, V v1) {<FILL_FUNCTION_BODY>}
}
|
Map<K,V> result = new HashMap<K, V>() ;
result.put(k1, v1) ;
return result ;
| 276
| 47
| 323
|
<no_super_class>
|
infinilabs_analysis-pinyin
|
analysis-pinyin/pinyin-core/src/main/java/org/nlpcn/commons/lang/util/FileFinder.java
|
FileFinder
|
find
|
class FileFinder {
private static final Log LOG = LogFactory.getLog();
/**
* 系统路径分隔符
*/
private static final String SEPARATOR = System.getProperty("path.separator");
private static final String[] PATHS_PROPERTIES = new String[] { "java.class.path", "java.library.path" };
public static List<File> fileDir = new ArrayList<File>();
static {
fileDir.add(new File("").getAbsoluteFile());
}
/**
* 输入一个文件名或者文件的最后路径寻找文件 default deep Integer.max
*
* @param
* @return
*/
public static File find(String lastPath) {
return find(lastPath, Integer.MAX_VALUE);
}
/**
* 输入一个文件名或者文件的最后路径寻找文件
*
* @param
* @return
*/
public static File find(String lastPath, int deep) {<FILL_FUNCTION_BODY>}
/**
* 根据一个文件深度查找
*
* @param file
* @param lastPath
* @param deep integer.max
* @return
*/
public static File findByFile(File file, String lastPath) {
return findByFile(file, lastPath, Integer.MAX_VALUE);
}
/**
* 根据一个文件深度查找
*
* @param file
* @param lastPath
* @param deep
* @return
*/
public static File findByFile(File file, String lastPath, int deep) {
if (deep == 0 || !file.exists() || !file.canRead()) {
return null;
}
if (file.getAbsolutePath().endsWith(lastPath)) {
return file;
}
if (file.isDirectory()) {
File[] listFiles = file.listFiles();
if (listFiles != null && listFiles.length > 0) {
for (File file2 : listFiles) {
File temp = findByFile(file2, lastPath, deep - 1);
if (temp != null) {
return temp;
}
}
}
}
return null;
}
}
|
// 先深度查找
for (File file : fileDir) {
if (file.exists() && file.canRead()) {
file = findByFile(file, lastPath, deep);
if (file != null) {
return file;
}
}
}
// 再从基本几个目录中查找
for (String pathProperties : PATHS_PROPERTIES) {
String[] propertyPath = System.getProperty(pathProperties).split(SEPARATOR);
for (String path : propertyPath) {
File file = new File(path);
try {
if (file.canRead() && file.exists()) {
file = findByFile(file, lastPath, deep);
if (file != null) {
return file;
}
}
} catch (AccessControlException e) {
LOG.info(path + " not access to visit");
}
}
}
return null;
| 644
| 276
| 920
|
<no_super_class>
|
infinilabs_analysis-pinyin
|
analysis-pinyin/pinyin-core/src/main/java/org/nlpcn/commons/lang/util/FileIterator.java
|
FileIterator
|
hasNext
|
class FileIterator implements Iterator<String>, Closeable {
String temp = null;
private BufferedReader br = null;
protected FileIterator(String path, String charEncoding) throws UnsupportedEncodingException, FileNotFoundException {
br = IOUtil.getReader(path, charEncoding);
}
protected FileIterator(InputStream is, String charEncoding) throws UnsupportedEncodingException, FileNotFoundException {
br = IOUtil.getReader(is, charEncoding);
}
@Override
public boolean hasNext() {<FILL_FUNCTION_BODY>}
public String readLine() {
try {
if (temp == null) {
temp = br.readLine();
}
return temp;
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return null;
} finally {
temp = null;
}
}
@Override
public void close() {
if (br != null)
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
public String next() {
return readLine();
}
@Override
public void remove() {
throw new RuntimeException("file iteartor can not remove ");
}
}
|
if (temp == null) {
try {
temp = br.readLine();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if (temp == null) {
return false;
} else {
return true;
}
} else {
return true;
}
| 377
| 113
| 490
|
<no_super_class>
|
infinilabs_analysis-pinyin
|
analysis-pinyin/pinyin-core/src/main/java/org/nlpcn/commons/lang/util/MD5.java
|
MD5
|
code
|
class MD5 {
/**
* MD5加密类
* @param str 要加密的字符串
* @return 加密后的字符串
*/
public static String code(String str){<FILL_FUNCTION_BODY>}
}
|
try {
MessageDigest md = MessageDigest.getInstance("MD5");
md.update(str.getBytes());
byte[]byteDigest = md.digest();
int i;
StringBuffer buf = new StringBuffer("");
for (int offset = 0; offset < byteDigest.length; offset++) {
i = byteDigest[offset];
if (i < 0)
i += 256;
if (i < 16)
buf.append("0");
buf.append(Integer.toHexString(i));
}
//32位加密
return buf.toString();
// 16位的加密
//return buf.toString().substring(8, 24);
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
return null;
}
| 68
| 227
| 295
|
<no_super_class>
|
infinilabs_analysis-pinyin
|
analysis-pinyin/pinyin-core/src/main/java/org/nlpcn/commons/lang/util/MapCount.java
|
MapCount
|
getDic
|
class MapCount<T> implements Serializable {
private static final long serialVersionUID = 1L;
private HashMap<T, Double> hm = null;
public MapCount() {
hm = new HashMap<T, Double>();
}
public MapCount(HashMap<T, Double> hm) {
this.hm = hm;
}
public MapCount(int initialCapacity) {
hm = new HashMap<T, Double>(initialCapacity);
}
/**
* 增加一个元素
*
* @param t
* @param n
*/
public void add(T t, double n) {
Double value = null;
if ((value = hm.get(t)) != null) {
hm.put(t, value + n);
} else {
hm.put(t, Double.valueOf(n));
}
}
/**
* 兼容旧的api
*
* @param t
* @param n
*/
public void add(T t, int n) {
add(t, (double) n);
}
/**
* 计数增加.默认为1
*
* @param t
*/
public void add(T t) {
this.add(t, 1);
}
/**
* map的大小
*
* @return
*/
public int size() {
return hm.size();
}
/**
* 删除一个元素
*
* @param t
*/
public void remove(T t) {
hm.remove(t);
}
/**
* 得道内部的map
*
* @return
*/
public HashMap<T, Double> get() {
return this.hm;
}
/**
* 将map序列化为词典格式
*
* @return
*/
public String getDic() {<FILL_FUNCTION_BODY>}
/**
* 批量增加
*
* @param hs
*/
public void addAll(Collection<T> collection) {
for (T t : collection) {
this.add(t);
}
}
/**
* 批量增加
*
* @param hs
*/
public void addAll(Collection<T> collection, double weight) {
for (T t : collection) {
this.add(t, weight);
}
}
/**
* 批量增加
*
* @param hs
*/
public void addAll(Map<T, Double> map) {
for (Entry<T, Double> e : map.entrySet()) {
this.add(e.getKey(), e.getValue());
}
}
}
|
Iterator<Entry<T, Double>> iterator = this.hm.entrySet().iterator();
StringBuilder sb = new StringBuilder();
Entry<T, Double> next = null;
while (iterator.hasNext()) {
next = iterator.next();
sb.append(next.getKey());
sb.append("\t");
sb.append(next.getValue());
sb.append("\n");
}
return sb.toString();
| 718
| 122
| 840
|
<no_super_class>
|
infinilabs_analysis-pinyin
|
analysis-pinyin/pinyin-core/src/main/java/org/nlpcn/commons/lang/util/MapFactory.java
|
MapFactory
|
treeMap
|
class MapFactory<K, V> {
private Map<K, V> map = null;
private MapFactory() {
}
public static <K, V> MapFactory<K, V> hashMap() {
MapFactory<K, V> mf = new MapFactory<K, V>();
mf.map = new HashMap<K, V>();
return mf;
}
public static <K, V> MapFactory<K, V> treeMap() {<FILL_FUNCTION_BODY>}
public MapFactory<K, V> a(K k, V v) {
map.put(k, v);
return this;
}
public Map<K, V> toMap() {
return map;
}
}
|
MapFactory<K, V> mf = new MapFactory<K, V>();
mf.map = new TreeMap<K, V>();
return mf;
| 212
| 51
| 263
|
<no_super_class>
|
infinilabs_analysis-pinyin
|
analysis-pinyin/pinyin-core/src/main/java/org/nlpcn/commons/lang/util/MurmurHash.java
|
MurmurHash
|
hash64
|
class MurmurHash {
// all methods static; private constructor.
private MurmurHash() {}
/**
* Generates 32 bit hash from byte array of the given length and
* seed.
*
* @param data byte array to hash
* @param length length of the array to hash
* @param seed initial seed value
* @return 32 bit hash of the given array
*/
public static int hash32(final byte[] data, int length, int seed) {
// 'm' and 'r' are mixing constants generated offline.
// They're not really 'magic', they just happen to work well.
final int m = 0x5bd1e995;
final int r = 24;
// Initialize the hash to a random value
int h = seed^length;
int length4 = length/4;
for (int i=0; i<length4; i++) {
final int i4 = i*4;
int k = (data[i4+0]&0xff) +((data[i4+1]&0xff)<<8)
+((data[i4+2]&0xff)<<16) +((data[i4+3]&0xff)<<24);
k *= m;
k ^= k >>> r;
k *= m;
h *= m;
h ^= k;
}
// Handle the last few bytes of the input array
switch (length%4) {
case 3: h ^= (data[(length&~3) +2]&0xff) << 16;
case 2: h ^= (data[(length&~3) +1]&0xff) << 8;
case 1: h ^= (data[length&~3]&0xff);
h *= m;
}
h ^= h >>> 13;
h *= m;
h ^= h >>> 15;
return h;
}
/**
* Generates 32 bit hash from byte array with default seed value.
*
* @param data byte array to hash
* @param length length of the array to hash
* @return 32 bit hash of the given array
*/
public static int hash32(final byte[] data, int length) {
return hash32(data, length, 0x9747b28c);
}
/**
* Generates 32 bit hash from a string.
*
* @param text string to hash
* @return 32 bit hash of the given string
*/
public static int hash32(final String text) {
final byte[] bytes = text.getBytes();
return hash32(bytes, bytes.length);
}
/**
* Generates 32 bit hash from a substring.
*
* @param text string to hash
* @param from starting index
* @param length length of the substring to hash
* @return 32 bit hash of the given string
*/
public static int hash32(final String text, int from, int length) {
return hash32(text.substring( from, from+length));
}
/**
* Generates 64 bit hash from byte array of the given length and seed.
*
* @param data byte array to hash
* @param length length of the array to hash
* @param seed initial seed value
* @return 64 bit hash of the given array
*/
public static long hash64(final byte[] data, int length, int seed) {<FILL_FUNCTION_BODY>}
/**
* Generates 64 bit hash from byte array with default seed value.
*
* @param data byte array to hash
* @param length length of the array to hash
* @return 64 bit hash of the given string
*/
public static long hash64(final byte[] data, int length) {
return hash64(data, length, 0xe17a1465);
}
/**
* Generates 64 bit hash from a string.
*
* @param text string to hash
* @return 64 bit hash of the given string
*/
public static long hash64(final String text) {
final byte[] bytes = text.getBytes();
return hash64(bytes, bytes.length);
}
/**
* Generates 64 bit hash from a substring.
*
* @param text string to hash
* @param from starting index
* @param length length of the substring to hash
* @return 64 bit hash of the given array
*/
public static long hash64(final String text, int from, int length) {
return hash64(text.substring( from, from+length));
}
}
|
final long m = 0xc6a4a7935bd1e995L;
final int r = 47;
long h = (seed&0xffffffffl)^(length*m);
int length8 = length/8;
for (int i=0; i<length8; i++) {
final int i8 = i*8;
long k = ((long)data[i8+0]&0xff) +(((long)data[i8+1]&0xff)<<8)
+(((long)data[i8+2]&0xff)<<16) +(((long)data[i8+3]&0xff)<<24)
+(((long)data[i8+4]&0xff)<<32) +(((long)data[i8+5]&0xff)<<40)
+(((long)data[i8+6]&0xff)<<48) +(((long)data[i8+7]&0xff)<<56);
k *= m;
k ^= k >>> r;
k *= m;
h ^= k;
h *= m;
}
switch (length%8) {
case 7: h ^= (long)(data[(length&~7)+6]&0xff) << 48;
case 6: h ^= (long)(data[(length&~7)+5]&0xff) << 40;
case 5: h ^= (long)(data[(length&~7)+4]&0xff) << 32;
case 4: h ^= (long)(data[(length&~7)+3]&0xff) << 24;
case 3: h ^= (long)(data[(length&~7)+2]&0xff) << 16;
case 2: h ^= (long)(data[(length&~7)+1]&0xff) << 8;
case 1: h ^= (long)(data[length&~7]&0xff);
h *= m;
};
h ^= h >>> r;
h *= m;
h ^= h >>> r;
return h;
| 1,259
| 582
| 1,841
|
<no_super_class>
|
infinilabs_analysis-pinyin
|
analysis-pinyin/pinyin-core/src/main/java/org/nlpcn/commons/lang/util/WordWeight.java
|
WordWeight
|
exportChiSquare
|
class WordWeight {
private MapCount<String> mc = new MapCount<String>(); // 词频统计
private HashMap<String, MapCount<String>> x2mat = new HashMap<String, MapCount<String>>();
private MapCount<String> x2mc = new MapCount<String>();
private Integer maxCount;
private Integer recyclingCount;
private double allFreq;
public WordWeight() {
};
/**
* 新的个数 = maxCount - recyclingCount; recyclingCount< maxCount
*
* @param maxCount
* 最大值,当超过这个值后进行回收
* @param recyclingCount
* 回收个数
*/
public WordWeight(Integer maxCount, Integer recyclingCount) {
this.maxCount = maxCount;
this.recyclingCount = recyclingCount;
}
public void add(String word) {
add(word, 1);
}
public void add(String word, double weight) {
allFreq += weight;
mc.add(word, weight);
if (maxCount != null && recyclingCount != null && mc.get().size() >= maxCount) {
recycling();
}
}
public void add(String word, String target) {
add(word, target, 1);
}
public void add(String word, String target, double weight) {
if (x2mat.containsKey(target)) {
x2mat.get(target).add(word, weight);
} else {
x2mat.put(target, new MapCount<String>());
x2mat.get(target).add(word, weight);
}
x2mc.add(target, 1);
add(word, weight);
}
/**
* 导出词频统计结果
*
* @return
*/
public Map<String, Double> export() {
Map<String, Double> result = new HashMap<String, Double>();
result.putAll(mc.get());
return result;
}
/**
* 导出IDF统计结果
*
* @return
*/
public Map<String, Double> exportIDF() {
Map<String, Double> result = new HashMap<String, Double>();
for (Entry<String, Double> entry : mc.get().entrySet()) {
result.put(entry.getKey(), Math.log(allFreq / entry.getValue()));
}
return result;
}
public HashMap<String, MapCount<String>> exportChiSquare() {<FILL_FUNCTION_BODY>}
/**
* 回收
*/
private void recycling() {
List<Entry<String, Double>> list = CollectionUtil.sortMapByValue(mc.get(), -1);
Set<String> targetSet = x2mat.keySet();
String word;
for (int i = 0; i < recyclingCount; i++) {
word = list.get(i).getKey();
allFreq -= mc.get().remove(word); // 从全局中移除数字
for (String target : targetSet) {
Double r2 = x2mat.get(target).get().remove(word);
if (r2 != null) {
x2mc.add(target, -r2);
}
}
}
}
}
|
HashMap<String, MapCount<String>> x2final = new HashMap<String, MapCount<String>>();
double sum = allFreq;
Double a, b, c, d;
for (Entry<String, MapCount<String>> iter1 : x2mat.entrySet()) {
String target = iter1.getKey();
for (Entry<String, Double> iter2 : iter1.getValue().get().entrySet()) {
String name = iter2.getKey();
a = iter2.getValue();
b = x2mc.get().get(target) - a;
c = mc.get().get(name) - a;
d = sum - b - c + a;
Double x2stat = Math.pow(a * d - b * c, 2) / (a + c) / (b + d);
if (x2final.get(target) != null) {
x2final.get(target).add(name, x2stat);
} else {
x2final.put(target, new MapCount<String>());
x2final.get(target).add(name, x2stat);
}
}
}
return x2final;
| 880
| 316
| 1,196
|
<no_super_class>
|
infinilabs_analysis-pinyin
|
analysis-pinyin/pinyin-core/src/main/java/org/nlpcn/commons/lang/util/logging/Log4j2Impl.java
|
Log4j2Impl
|
resetStat
|
class Log4j2Impl implements Log {
private Logger log;
private int errorCount;
private int warnCount;
private int infoCount;
private int debugCount;
/**
* @since 0.2.21
* @param log
*/
public Log4j2Impl(Logger log){
this.log = log;
}
public Log4j2Impl(String loggerName){
log = LogManager.getLogger(loggerName);
}
public Logger getLog() {
return log;
}
public boolean isDebugEnabled() {
return log.isDebugEnabled();
}
public void error(String s, Throwable e) {
errorCount++;
log.error(s, e);
}
public void error(String s) {
errorCount++;
log.error(s);
}
public void debug(String s) {
debugCount++;
log.debug(s);
}
public void debug(String s, Throwable e) {
debugCount++;
log.debug(s, e);
}
public void warn(String s) {
log.warn(s);
warnCount++;
}
public void warn(String s, Throwable e) {
log.warn(s, e);
warnCount++;
}
public int getWarnCount() {
return warnCount;
}
public int getErrorCount() {
return errorCount;
}
public void resetStat() {<FILL_FUNCTION_BODY>}
public int getDebugCount() {
return debugCount;
}
public boolean isInfoEnabled() {
return log.isInfoEnabled();
}
public void info(String msg) {
infoCount++;
log.info(msg);
}
public boolean isWarnEnabled() {
return log.isEnabled(Level.WARN);
}
public int getInfoCount() {
return infoCount;
}
public String toString() {
return log.toString();
}
}
|
errorCount = 0;
warnCount = 0;
infoCount = 0;
debugCount = 0;
| 555
| 31
| 586
|
<no_super_class>
|
infinilabs_analysis-pinyin
|
analysis-pinyin/pinyin-core/src/main/java/org/nlpcn/commons/lang/util/logging/Log4jImpl.java
|
Log4jImpl
|
resetStat
|
class Log4jImpl implements Log {
private static final String callerFQCN = Log4jImpl.class.getName();
private Logger log;
private int errorCount;
private int warnCount;
private int infoCount;
private int debugCount;
/**
* @since 0.2.21
* @param log
*/
public Log4jImpl(Logger log){
this.log = log;
}
public Log4jImpl(String loggerName){
log = Logger.getLogger(loggerName);
}
public Logger getLog() {
return log;
}
public boolean isDebugEnabled() {
return log.isDebugEnabled();
}
public void error(String s, Throwable e) {
errorCount++;
log.log(callerFQCN, Level.ERROR, s, e);
}
public void error(String s) {
errorCount++;
log.log(callerFQCN, Level.ERROR, s, null);
}
public void debug(String s) {
debugCount++;
log.log(callerFQCN, Level.DEBUG, s, null);
}
public void debug(String s, Throwable e) {
debugCount++;
log.log(callerFQCN, Level.DEBUG, s, e);
}
public void warn(String s) {
log.log(callerFQCN, Level.WARN, s, null);
warnCount++;
}
public void warn(String s, Throwable e) {
log.log(callerFQCN, Level.WARN, s, e);
warnCount++;
}
public int getWarnCount() {
return warnCount;
}
public int getErrorCount() {
return errorCount;
}
public void resetStat() {<FILL_FUNCTION_BODY>}
public int getDebugCount() {
return debugCount;
}
public boolean isInfoEnabled() {
return log.isInfoEnabled();
}
public void info(String msg) {
infoCount++;
log.log(callerFQCN, Level.INFO, msg, null);
}
public boolean isWarnEnabled() {
return log.isEnabledFor(Level.WARN);
}
public int getInfoCount() {
return infoCount;
}
public String toString() {
return log.toString();
}
}
|
errorCount = 0;
warnCount = 0;
infoCount = 0;
debugCount = 0;
| 656
| 31
| 687
|
<no_super_class>
|
infinilabs_analysis-pinyin
|
analysis-pinyin/pinyin-core/src/main/java/org/nlpcn/commons/lang/util/logging/LogFactory.java
|
LogFactory
|
selectLog4JLogging
|
class LogFactory {
private static Constructor logConstructor;
static {
String logType = System.getProperty("druid.logType");
if (logType != null) {
if (logType.equalsIgnoreCase("slf4j")) {
tryImplementation("org.slf4j.Logger", "org.nlpcn.commons.lang.util.logging.SLF4JImpl");
} else if (logType.equalsIgnoreCase("log4j")) {
tryImplementation("org.apache.log4j.Logger", "org.nlpcn.commons.lang.util.logging.Log4jImpl");
} else if (logType.equalsIgnoreCase("log4j2")) {
tryImplementation("org.apache.logging.log4j.Logger", "org.nlpcn.commons.lang.util.logging.Log4j2Impl");
} else if (logType.equalsIgnoreCase("commonsLog")) {
tryImplementation("org.apache.commons.logging.LogFactory", "org.nlpcn.commons.lang.util.logging.JakartaCommonsLoggingImpl");
} else if (logType.equalsIgnoreCase("jdkLog")) {
tryImplementation("java.util.logging.Logger", "org.nlpcn.commons.lang.util.logging.Jdk14LoggingImpl");
}
}
// 优先选择log4j,而非Apache Common Logging. 因为后者无法设置真实Log调用者的信息
tryImplementation("org.apache.log4j.Logger", "org.nlpcn.commons.lang.util.logging.Log4jImpl");
tryImplementation("org.apache.logging.log4j.Logger", "org.nlpcn.commons.lang.util.logging.Log4j2Impl");
tryImplementation("org.slf4j.Logger", "org.nlpcn.commons.lang.util.logging.SLF4JImpl");
tryImplementation("org.apache.commons.logging.LogFactory", "org.nlpcn.commons.lang.util.logging.JakartaCommonsLoggingImpl");
tryImplementation("java.util.logging.Logger", "org.nlpcn.commons.lang.util.logging.Jdk14LoggingImpl");
if (logConstructor == null) {
try {
logConstructor = NoLoggingImpl.class.getConstructor(String.class);
} catch (Exception e) {
throw new IllegalStateException(e.getMessage(), e);
}
}
}
@SuppressWarnings("unchecked")
private static void tryImplementation(String testClassName, String implClassName) {
if (logConstructor != null) {
return;
}
try {
Resources.classForName(testClassName);
Class implClass = Resources.classForName(implClassName);
logConstructor = implClass.getConstructor(new Class[] { String.class });
Class<?> declareClass = logConstructor.getDeclaringClass();
if (!Log.class.isAssignableFrom(declareClass)) {
logConstructor = null;
}
try {
if (null != logConstructor) {
logConstructor.newInstance(LogFactory.class.getName());
}
} catch (Throwable t) {
logConstructor = null;
}
} catch (Throwable t) {
// skip
}
}
public static Log getLog(Class clazz) {
return getLog(clazz.getName());
}
public static Log getLog(String loggerName) {
try {
return (Log) logConstructor.newInstance(loggerName);
} catch (Throwable t) {
throw new RuntimeException("Error creating logger for logger '" + loggerName + "'. Cause: " + t, t);
}
}
/**
* 获取log默认当前类,不支持android
* @return
*/
public static Log getLog() {
StackTraceElement[] sts = Thread.currentThread().getStackTrace();
return getLog(sts[2].getClassName());
}
@SuppressWarnings("unchecked")
public static synchronized void selectLog4JLogging() {<FILL_FUNCTION_BODY>}
@SuppressWarnings("unchecked")
public static synchronized void selectJavaLogging() {
try {
Resources.classForName("java.util.logging.Logger");
Class implClass = Resources.classForName("org.nlpcn.commons.lang.util.logging.Jdk14LoggingImpl");
logConstructor = implClass.getConstructor(new Class[] { String.class });
} catch (Throwable t) {
//ignore
}
}
}
|
try {
Resources.classForName("org.apache.log4j.Logger");
Class implClass = Resources.classForName("org.nlpcn.commons.lang.util.logging.Log4jImpl");
logConstructor = implClass.getConstructor(new Class[] { String.class });
} catch (Throwable t) {
//ignore
}
| 1,194
| 96
| 1,290
|
<no_super_class>
|
infinilabs_analysis-pinyin
|
analysis-pinyin/pinyin-core/src/main/java/org/nlpcn/commons/lang/util/logging/NoLoggingImpl.java
|
NoLoggingImpl
|
error
|
class NoLoggingImpl implements Log {
private String loggerName;
public NoLoggingImpl(String loggerName){
this.loggerName = loggerName;
}
public String getLoggerName() {
return this.loggerName;
}
public boolean isDebugEnabled() {
return false;
}
public void error(String s, Throwable e) {
error(s);
if (e != null) {
e.printStackTrace();
}
}
public void error(String s) {<FILL_FUNCTION_BODY>}
public void debug(String s) {
System.out.println(s);
}
public void debug(String s, Throwable e) {
System.out.println(s+e!=null?e.getMessage():"");
}
public void warn(String s) {
System.out.println(s);
}
@Override
public void warn(String s, Throwable e) {
System.out.println(s+","+e!=null?e.getMessage():"");
}
@Override
public boolean isInfoEnabled() {
return false;
}
@Override
public void info(String s) {
System.out.println(s);
}
@Override
public boolean isWarnEnabled() {
return false;
}
}
|
if (s != null) {
System.err.println(loggerName + " : " + s);
}
| 367
| 33
| 400
|
<no_super_class>
|
infinilabs_analysis-pinyin
|
analysis-pinyin/pinyin-core/src/main/java/org/nlpcn/commons/lang/util/logging/Resources.java
|
Resources
|
classForName
|
class Resources extends Object {
private static ClassLoader defaultClassLoader;
private Resources(){
}
/**
* Returns the default classloader (may be null).
*
* @return The default classloader
*/
public static ClassLoader getDefaultClassLoader() {
return defaultClassLoader;
}
/**
* Sets the default classloader
*
* @param defaultClassLoader - the new default ClassLoader
*/
public static void setDefaultClassLoader(ClassLoader defaultClassLoader) {
Resources.defaultClassLoader = defaultClassLoader;
}
/**
* Loads a class
*
* @param className - the class to load
* @return The loaded class
* @throws ClassNotFoundException If the class cannot be found (duh!)
*/
public static Class<?> classForName(String className) throws ClassNotFoundException {<FILL_FUNCTION_BODY>}
private static ClassLoader getClassLoader() {
if (defaultClassLoader != null) {
return defaultClassLoader;
} else {
return Thread.currentThread().getContextClassLoader();
}
}
}
|
Class<?> clazz = null;
try {
clazz = getClassLoader().loadClass(className);
} catch (Exception e) {
// Ignore. Failsafe below.
}
if (clazz == null) {
clazz = Class.forName(className);
}
return clazz;
| 333
| 97
| 430
|
<no_super_class>
|
infinilabs_analysis-pinyin
|
analysis-pinyin/pinyin-core/src/main/java/org/nlpcn/commons/lang/util/tuples/KeyValue.java
|
KeyValue
|
fromIterable
|
class KeyValue<A,B>
extends Tuple
implements IValueKey<A>,
IValueValue<B> {
private static final long serialVersionUID = 3460957157833872509L;
private static final int SIZE = 2;
private final A key;
private final B value;
public static <A,B> KeyValue<A,B> with(final A key, final B value) {
return new KeyValue<A,B>(key,value);
}
/**
* <p>
* Create tuple from array. Array has to have exactly two elements.
* </p>
*
* @param <X> the array component type
* @param array the array to be converted to a tuple
* @return the tuple
*/
public static <X> KeyValue<X,X> fromArray(final X[] array) {
if (array == null) {
throw new IllegalArgumentException("Array cannot be null");
}
if (array.length != 2) {
throw new IllegalArgumentException("Array must have exactly 2 elements in order to create a KeyValue. Size is " + array.length);
}
return new KeyValue<X,X>(array[0],array[1]);
}
public static <X> KeyValue<X,X> fromCollection(final Collection<X> collection) {
return fromIterable(collection);
}
public static <X> KeyValue<X,X> fromIterable(final Iterable<X> iterable) {
return fromIterable(iterable, 0, true);
}
public static <X> KeyValue<X,X> fromIterable(final Iterable<X> iterable, int index) {
return fromIterable(iterable, index, false);
}
private static <X> KeyValue<X,X> fromIterable(final Iterable<X> iterable, int index, final boolean exactSize) {<FILL_FUNCTION_BODY>}
public KeyValue(
final A key,
final B value) {
super(key, value);
this.key = key;
this.value = value;
}
public A getKey() {
return this.key;
}
public B getValue() {
return this.value;
}
@Override
public int getSize() {
return SIZE;
}
public <X> KeyValue<X,B> setKey(final X key) {
return new KeyValue<X,B>(key, this.value);
}
public <Y> KeyValue<A,Y> setValue(final Y value) {
return new KeyValue<A,Y>(this.key, value);
}
}
|
if (iterable == null) {
throw new IllegalArgumentException("Iterable cannot be null");
}
boolean tooFewElements = false;
X element0 = null;
X element1 = null;
final Iterator<X> iter = iterable.iterator();
int i = 0;
while (i < index) {
if (iter.hasNext()) {
iter.next();
} else {
tooFewElements = true;
}
i++;
}
if (iter.hasNext()) {
element0 = iter.next();
} else {
tooFewElements = true;
}
if (iter.hasNext()) {
element1 = iter.next();
} else {
tooFewElements = true;
}
if (tooFewElements && exactSize) {
throw new IllegalArgumentException("Not enough elements for creating a KeyValue (2 needed)");
}
if (iter.hasNext() && exactSize) {
throw new IllegalArgumentException("Iterable must have exactly 2 available elements in order to create a KeyValue.");
}
return new KeyValue<X,X>(element0, element1);
| 850
| 361
| 1,211
|
<methods>public int compareTo(org.nlpcn.commons.lang.util.tuples.Tuple) ,public final boolean contains(java.lang.Object) ,public final boolean containsAll(Collection<?>) ,public final transient boolean containsAll(java.lang.Object[]) ,public final boolean equals(java.lang.Object) ,public abstract int getSize() ,public final java.lang.Object getValue(int) ,public final int hashCode() ,public final int indexOf(java.lang.Object) ,public final Iterator<java.lang.Object> iterator() ,public final int lastIndexOf(java.lang.Object) ,public final java.lang.Object[] toArray() ,public final List<java.lang.Object> toList() ,public final java.lang.String toString() <variables>private static final long serialVersionUID,private final non-sealed java.lang.Object[] valueArray,private final non-sealed List<java.lang.Object> valueList
|
infinilabs_analysis-pinyin
|
analysis-pinyin/pinyin-core/src/main/java/org/nlpcn/commons/lang/util/tuples/LabelValue.java
|
LabelValue
|
fromIterable
|
class LabelValue<A,B>
extends Tuple
implements IValueLabel<A>,
IValueValue<B> {
private static final long serialVersionUID = 5055574980300695706L;
private static final int SIZE = 2;
private final A label;
private final B value;
public static <A,B> LabelValue<A,B> with(final A label, final B value) {
return new LabelValue<A,B>(label,value);
}
/**
* <p>
* Create tuple from array. Array has to have exactly two elements.
* </p>
*
* @param <X> the array component type
* @param array the array to be converted to a tuple
* @return the tuple
*/
public static <X> LabelValue<X,X> fromArray(final X[] array) {
if (array == null) {
throw new IllegalArgumentException("Array cannot be null");
}
if (array.length != 2) {
throw new IllegalArgumentException("Array must have exactly 2 elements in order to create a LabelValue. Size is " + array.length);
}
return new LabelValue<X,X>(array[0],array[1]);
}
public static <X> LabelValue<X,X> fromCollection(final Collection<X> collection) {
return fromIterable(collection);
}
public static <X> LabelValue<X,X> fromIterable(final Iterable<X> iterable) {
return fromIterable(iterable, 0, true);
}
public static <X> LabelValue<X,X> fromIterable(final Iterable<X> iterable, int index) {
return fromIterable(iterable, index, false);
}
private static <X> LabelValue<X,X> fromIterable(final Iterable<X> iterable, int index, final boolean exactSize) {<FILL_FUNCTION_BODY>}
public LabelValue(
final A label,
final B value) {
super(label, value);
this.label = label;
this.value = value;
}
public A getLabel() {
return this.label;
}
public B getValue() {
return this.value;
}
@Override
public int getSize() {
return SIZE;
}
public <X> LabelValue<X,B> setLabel(final X label) {
return new LabelValue<X,B>(label, this.value);
}
public <Y> LabelValue<A,Y> setValue(final Y value) {
return new LabelValue<A,Y>(this.label, value);
}
}
|
if (iterable == null) {
throw new IllegalArgumentException("Iterable cannot be null");
}
boolean tooFewElements = false;
X element0 = null;
X element1 = null;
final Iterator<X> iter = iterable.iterator();
int i = 0;
while (i < index) {
if (iter.hasNext()) {
iter.next();
} else {
tooFewElements = true;
}
i++;
}
if (iter.hasNext()) {
element0 = iter.next();
} else {
tooFewElements = true;
}
if (iter.hasNext()) {
element1 = iter.next();
} else {
tooFewElements = true;
}
if (tooFewElements && exactSize) {
throw new IllegalArgumentException("Not enough elements for creating a LabelValue (2 needed)");
}
if (iter.hasNext() && exactSize) {
throw new IllegalArgumentException("Iterable must have exactly 2 available elements in order to create a LabelValue.");
}
return new LabelValue<X,X>(element0, element1);
| 854
| 361
| 1,215
|
<methods>public int compareTo(org.nlpcn.commons.lang.util.tuples.Tuple) ,public final boolean contains(java.lang.Object) ,public final boolean containsAll(Collection<?>) ,public final transient boolean containsAll(java.lang.Object[]) ,public final boolean equals(java.lang.Object) ,public abstract int getSize() ,public final java.lang.Object getValue(int) ,public final int hashCode() ,public final int indexOf(java.lang.Object) ,public final Iterator<java.lang.Object> iterator() ,public final int lastIndexOf(java.lang.Object) ,public final java.lang.Object[] toArray() ,public final List<java.lang.Object> toList() ,public final java.lang.String toString() <variables>private static final long serialVersionUID,private final non-sealed java.lang.Object[] valueArray,private final non-sealed List<java.lang.Object> valueList
|
infinilabs_analysis-pinyin
|
analysis-pinyin/pinyin-core/src/main/java/org/nlpcn/commons/lang/util/tuples/Tuple.java
|
Tuple
|
indexOf
|
class Tuple implements Iterable<Object>, Serializable, Comparable<Tuple> {
private static final long serialVersionUID = 5431085632328343101L;
private final Object[] valueArray;
private final List<Object> valueList;
/**
*
* @deprecated Will be removed in 1.4. The "size" parameter is of no use at
* this level, so use the simpler Tuple(values) constructor instead.
*/
@Deprecated
protected Tuple(@SuppressWarnings("unused") final int size, final Object... values) {
super();
this.valueArray = values;
this.valueList = Arrays.asList(values);
}
protected Tuple(final Object... values) {
super();
this.valueArray = values;
this.valueList = Arrays.asList(values);
}
/**
* <p>
* Return the size of the tuple.
* </p>
*
* @return the size of the tuple.
*/
public abstract int getSize();
/**
* <p>
* Get the value at a specific position in the tuple. This method
* has to return object, so using it you will lose the type-safety you
* get with the <tt>getValueX()</tt> methods.
* </p>
*
* @param pos the position of the value to be retrieved.
* @return the value
*/
public final Object getValue(final int pos) {
if (pos >= getSize()) {
throw new IllegalArgumentException(
"Cannot retrieve position " + pos + " in " + this.getClass().getSimpleName() +
". Positions for this class start with 0 and end with " + (getSize() - 1));
}
return this.valueArray[pos];
}
public final Iterator<Object> iterator() {
return this.valueList.iterator();
}
@Override
public final String toString() {
return this.valueList.toString();
}
public final boolean contains(final Object value) {
for (final Object val : this.valueList) {
if (val == null) {
if (value == null) {
return true;
}
} else {
if (val.equals(value)) {
return true;
}
}
}
return false;
}
public final boolean containsAll(final Collection<?> collection) {
for (final Object value : collection) {
if (!contains(value)) {
return false;
}
}
return true;
}
public final boolean containsAll(final Object... values) {
if (values == null) {
throw new IllegalArgumentException("Values array cannot be null");
}
for (final Object value : values) {
if (!contains(value)) {
return false;
}
}
return true;
}
public final int indexOf(final Object value) {<FILL_FUNCTION_BODY>}
public final int lastIndexOf(final Object value) {
for (int i = getSize() - 1; i >= 0; i--) {
final Object val = this.valueList.get(i);
if (val == null) {
if (value == null) {
return i;
}
} else {
if (val.equals(value)) {
return i;
}
}
}
return -1;
}
public final List<Object> toList() {
return Collections.unmodifiableList(new ArrayList<Object>(this.valueList));
}
public final Object[] toArray() {
return this.valueArray.clone();
}
@Override
public final int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result
+ ((this.valueList == null) ? 0 : this.valueList.hashCode());
return result;
}
@Override
public final boolean equals(final Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final Tuple other = (Tuple) obj;
return this.valueList.equals(other.valueList);
}
@SuppressWarnings({ "rawtypes", "unchecked" })
public int compareTo(final Tuple o) {
final int tLen = this.valueArray.length;
final Object[] oValues = o.valueArray;
final int oLen = oValues.length;
for (int i = 0; i < tLen && i < oLen; i++) {
final Comparable tElement = (Comparable)this.valueArray[i];
final Comparable oElement = (Comparable)oValues[i];
final int comparison = tElement.compareTo(oElement);
if (comparison != 0) {
return comparison;
}
}
return (Integer.valueOf(tLen)).compareTo(Integer.valueOf(oLen));
}
}
|
int i = 0;
for (final Object val : this.valueList) {
if (val == null) {
if (value == null) {
return i;
}
} else {
if (val.equals(value)) {
return i;
}
}
i++;
}
return -1;
| 1,621
| 106
| 1,727
|
<no_super_class>
|
assertj_assertj
|
assertj/assertj-core/src/main/java/org/assertj/core/api/AbstractAtomicFieldUpdaterAssert.java
|
AbstractAtomicFieldUpdaterAssert
|
hasValue
|
class AbstractAtomicFieldUpdaterAssert<SELF extends AbstractAtomicFieldUpdaterAssert<SELF, VALUE, ATOMIC, OBJECT>, VALUE, ATOMIC, OBJECT>
extends AbstractObjectAssert<SELF, ATOMIC> {
private final boolean expectedNullAllowed;
protected AbstractAtomicFieldUpdaterAssert(ATOMIC actual, Class<?> selfType, boolean expectedNullAllowed) {
super(actual, selfType);
this.expectedNullAllowed = expectedNullAllowed;
}
public SELF hasValue(VALUE expectedValue, final OBJECT obj) {<FILL_FUNCTION_BODY>}
protected abstract VALUE getActualValue(OBJECT obj);
protected void validate(VALUE expectedValue) {
isNotNull();
if (!expectedNullAllowed) {
checkNotNull(expectedValue);
}
}
private void checkNotNull(VALUE expectedValue) {
checkArgument(expectedValue != null, "The expected value should not be <null>.");
}
}
|
validate(expectedValue);
VALUE actualValue = getActualValue(obj);
if (!objects.getComparisonStrategy().areEqual(actualValue, expectedValue)) {
throwAssertionError(shouldHaveValue(actual, actualValue, expectedValue, obj));
}
return myself;
| 266
| 72
| 338
|
<methods>public void <init>(ATOMIC, Class<?>) ,public SELF as(org.assertj.core.description.Description) ,public transient SELF as(java.lang.String, java.lang.Object[]) ,public SELF doesNotReturn(T, Function<ATOMIC,T>) ,public transient AbstractListAssert<?,List<?>,java.lang.Object,ObjectAssert<java.lang.Object>> extracting(java.lang.String[]) ,public AbstractObjectAssert<?,?> extracting(java.lang.String) ,public ASSERT extracting(java.lang.String, InstanceOfAssertFactory<?,ASSERT>) ,public final transient AbstractListAssert<?,List<?>,java.lang.Object,ObjectAssert<java.lang.Object>> extracting(Function<? super ATOMIC,?>[]) ,public AbstractObjectAssert<?,T> extracting(Function<? super ATOMIC,T>) ,public ASSERT extracting(Function<? super ATOMIC,T>, InstanceOfAssertFactory<?,ASSERT>) ,public SELF hasAllNullFieldsOrProperties() ,public transient SELF hasAllNullFieldsOrPropertiesExcept(java.lang.String[]) ,public SELF hasFieldOrProperty(java.lang.String) ,public SELF hasFieldOrPropertyWithValue(java.lang.String, java.lang.Object) ,public SELF hasNoNullFieldsOrProperties() ,public transient SELF hasNoNullFieldsOrPropertiesExcept(java.lang.String[]) ,public transient SELF hasOnlyFields(java.lang.String[]) ,public SELF isEqualToComparingFieldByField(java.lang.Object) ,public SELF isEqualToComparingFieldByFieldRecursively(java.lang.Object) ,public transient SELF isEqualToComparingOnlyGivenFields(java.lang.Object, java.lang.String[]) ,public transient SELF isEqualToIgnoringGivenFields(java.lang.Object, java.lang.String[]) ,public SELF isEqualToIgnoringNullFields(java.lang.Object) ,public SELF returns(T, Function<ATOMIC,T>) ,public transient SELF usingComparatorForFields(Comparator<T>, java.lang.String[]) ,public SELF usingComparatorForType(Comparator<? super T>, Class<T>) ,public org.assertj.core.api.RecursiveAssertionAssert usingRecursiveAssertion() ,public org.assertj.core.api.RecursiveAssertionAssert usingRecursiveAssertion(org.assertj.core.api.recursive.assertion.RecursiveAssertionConfiguration) ,public RecursiveComparisonAssert<?> usingRecursiveComparison() ,public RecursiveComparisonAssert<?> usingRecursiveComparison(org.assertj.core.api.recursive.comparison.RecursiveComparisonConfiguration) <variables>private Map<java.lang.String,Comparator<?>> comparatorsByPropertyOrField,private org.assertj.core.internal.TypeComparators comparatorsByType
|
assertj_assertj
|
assertj/assertj-core/src/main/java/org/assertj/core/api/AbstractAtomicReferenceAssert.java
|
AbstractAtomicReferenceAssert
|
hasReference
|
class AbstractAtomicReferenceAssert<SELF extends AbstractAtomicReferenceAssert<SELF, VALUE, ATOMIC>, VALUE, ATOMIC>
extends AbstractObjectAssert<SELF, ATOMIC> {
protected AbstractAtomicReferenceAssert(ATOMIC actual, Class<?> selfType) {
super(actual, selfType);
}
public SELF hasReference(VALUE expectedReference) {<FILL_FUNCTION_BODY>}
protected abstract VALUE getReference();
}
|
isNotNull();
if (!this.objects.getComparisonStrategy().areEqual(getReference(), expectedReference)) {
throwAssertionError(shouldHaveReference(actual, getReference(), expectedReference));
}
return myself;
| 128
| 57
| 185
|
<methods>public void <init>(ATOMIC, Class<?>) ,public SELF as(org.assertj.core.description.Description) ,public transient SELF as(java.lang.String, java.lang.Object[]) ,public SELF doesNotReturn(T, Function<ATOMIC,T>) ,public transient AbstractListAssert<?,List<?>,java.lang.Object,ObjectAssert<java.lang.Object>> extracting(java.lang.String[]) ,public AbstractObjectAssert<?,?> extracting(java.lang.String) ,public ASSERT extracting(java.lang.String, InstanceOfAssertFactory<?,ASSERT>) ,public final transient AbstractListAssert<?,List<?>,java.lang.Object,ObjectAssert<java.lang.Object>> extracting(Function<? super ATOMIC,?>[]) ,public AbstractObjectAssert<?,T> extracting(Function<? super ATOMIC,T>) ,public ASSERT extracting(Function<? super ATOMIC,T>, InstanceOfAssertFactory<?,ASSERT>) ,public SELF hasAllNullFieldsOrProperties() ,public transient SELF hasAllNullFieldsOrPropertiesExcept(java.lang.String[]) ,public SELF hasFieldOrProperty(java.lang.String) ,public SELF hasFieldOrPropertyWithValue(java.lang.String, java.lang.Object) ,public SELF hasNoNullFieldsOrProperties() ,public transient SELF hasNoNullFieldsOrPropertiesExcept(java.lang.String[]) ,public transient SELF hasOnlyFields(java.lang.String[]) ,public SELF isEqualToComparingFieldByField(java.lang.Object) ,public SELF isEqualToComparingFieldByFieldRecursively(java.lang.Object) ,public transient SELF isEqualToComparingOnlyGivenFields(java.lang.Object, java.lang.String[]) ,public transient SELF isEqualToIgnoringGivenFields(java.lang.Object, java.lang.String[]) ,public SELF isEqualToIgnoringNullFields(java.lang.Object) ,public SELF returns(T, Function<ATOMIC,T>) ,public transient SELF usingComparatorForFields(Comparator<T>, java.lang.String[]) ,public SELF usingComparatorForType(Comparator<? super T>, Class<T>) ,public org.assertj.core.api.RecursiveAssertionAssert usingRecursiveAssertion() ,public org.assertj.core.api.RecursiveAssertionAssert usingRecursiveAssertion(org.assertj.core.api.recursive.assertion.RecursiveAssertionConfiguration) ,public RecursiveComparisonAssert<?> usingRecursiveComparison() ,public RecursiveComparisonAssert<?> usingRecursiveComparison(org.assertj.core.api.recursive.comparison.RecursiveComparisonConfiguration) <variables>private Map<java.lang.String,Comparator<?>> comparatorsByPropertyOrField,private org.assertj.core.internal.TypeComparators comparatorsByType
|
assertj_assertj
|
assertj/assertj-core/src/main/java/org/assertj/core/api/AbstractBooleanAssert.java
|
AbstractBooleanAssert
|
isFalse
|
class AbstractBooleanAssert<SELF extends AbstractBooleanAssert<SELF>> extends AbstractAssert<SELF, Boolean> {
@VisibleForTesting
Booleans booleans = Booleans.instance();
protected AbstractBooleanAssert(Boolean actual, Class<?> selfType) {
super(actual, selfType);
}
/**
* Verifies that the actual value is {@code true}.
* <p>
* Example:
* <pre><code class='java'> // assertions will pass
* assertThat(true).isTrue();
* assertThat(Boolean.TRUE).isTrue();
*
* // assertions will fail
* assertThat(false).isTrue();
* assertThat(Boolean.FALSE).isTrue();</code></pre>
*
* @return {@code this} assertion object.
* @throws AssertionError if the actual value is {@code null}.
* @throws AssertionError if the actual value is not {@code true}.
*/
public SELF isTrue() {
objects.assertNotNull(info, actual);
if (actual) return myself;
throw Failures.instance().failure(info, shouldBeTrue(actual), actual, true);
}
/**
* Verifies that the actual value is {@code false}.
* <p>
* Example:
* <pre><code class='java'> // assertions will pass
* assertThat(false).isFalse();
* assertThat(Boolean.FALSE).isFalse();
*
* // assertions will fail
* assertThat(true).isFalse();
* assertThat(Boolean.TRUE).isFalse();</code></pre>
*
* @return {@code this} assertion object.
* @throws AssertionError if the actual value is {@code null}.
* @throws AssertionError if the actual value is not {@code false}.
*/
public SELF isFalse() {<FILL_FUNCTION_BODY>}
/**
* Verifies that the actual value is equal to the given one.
* <p>
* Example:
* <pre><code class='java'> // assertions will pass
* assertThat(true).isEqualTo(true);
* assertThat(Boolean.FALSE).isEqualTo(false);
*
* // assertions will fail
* assertThat(true).isEqualTo(false);
* assertThat(Boolean.TRUE).isEqualTo(false);</code></pre>
*
* @param expected the given value to compare the actual value to.
* @return {@code this} assertion object.
* @throws AssertionError if the actual value is {@code null}.
* @throws AssertionError if the actual value is not equal to the given one.
*/
public SELF isEqualTo(boolean expected) {
booleans.assertEqual(info, actual, expected);
return myself;
}
/**
* Verifies that the actual value is not equal to the given one.
* <p>
* Example:
* <pre><code class='java'> // assertions will pass
* assertThat(true).isNotEqualTo(false);
* assertThat(Boolean.FALSE).isNotEqualTo(true);
*
* // assertions will fail
* assertThat(true).isNotEqualTo(true);
* assertThat(Boolean.FALSE).isNotEqualTo(false);</code></pre>
*
* @param other the given value to compare the actual value to.
* @return {@code this} assertion object.
* @throws AssertionError if the actual value is {@code null}.
* @throws AssertionError if the actual value is equal to the given one.
*/
public SELF isNotEqualTo(boolean other) {
booleans.assertNotEqual(info, actual, other);
return myself;
}
/**
* Do not use this method.
*
* @deprecated Custom Comparator is not supported for Boolean comparison.
* @throws UnsupportedOperationException if this method is called.
*/
@Override
@Deprecated
public final SELF usingComparator(Comparator<? super Boolean> customComparator) {
return usingComparator(customComparator, null);
}
/**
* Do not use this method.
*
* @deprecated Custom Comparator is not supported for Boolean comparison.
* @throws UnsupportedOperationException if this method is called.
*/
@Override
@Deprecated
public final SELF usingComparator(Comparator<? super Boolean> customComparator, String customComparatorDescription) {
throw new UnsupportedOperationException("custom Comparator is not supported for Boolean comparison");
}
}
|
objects.assertNotNull(info, actual);
if (actual == false) return myself;
throw Failures.instance().failure(info, shouldBeFalse(actual), actual, false);
| 1,173
| 49
| 1,222
|
<methods>public ASSERT asInstanceOf(InstanceOfAssertFactory<?,ASSERT>) ,public AbstractListAssert<?,List<?>,java.lang.Object,ObjectAssert<java.lang.Object>> asList() ,public AbstractStringAssert<?> asString() ,public SELF describedAs(org.assertj.core.description.Description) ,public java.lang.String descriptionText() ,public SELF doesNotHave(Condition<? super java.lang.Boolean>) ,public SELF doesNotHaveSameClassAs(java.lang.Object) ,public SELF doesNotHaveSameHashCodeAs(java.lang.Object) ,public SELF doesNotHaveToString(java.lang.String) ,public transient SELF doesNotHaveToString(java.lang.String, java.lang.Object[]) ,public boolean equals(java.lang.Object) ,public org.assertj.core.api.WritableAssertionInfo getWritableAssertionInfo() ,public SELF has(Condition<? super java.lang.Boolean>) ,public SELF hasSameClassAs(java.lang.Object) ,public SELF hasSameHashCodeAs(java.lang.Object) ,public SELF hasToString(java.lang.String) ,public transient SELF hasToString(java.lang.String, java.lang.Object[]) ,public int hashCode() ,public SELF is(Condition<? super java.lang.Boolean>) ,public SELF isEqualTo(java.lang.Object) ,public SELF isExactlyInstanceOf(Class<?>) ,public transient SELF isIn(java.lang.Object[]) ,public SELF isIn(Iterable<?>) ,public SELF isInstanceOf(Class<?>) ,public transient SELF isInstanceOfAny(Class<?>[]) ,public SELF isInstanceOfSatisfying(Class<T>, Consumer<T>) ,public SELF isNot(Condition<? super java.lang.Boolean>) ,public SELF isNotEqualTo(java.lang.Object) ,public SELF isNotExactlyInstanceOf(Class<?>) ,public transient SELF isNotIn(java.lang.Object[]) ,public SELF isNotIn(Iterable<?>) ,public SELF isNotInstanceOf(Class<?>) ,public transient SELF isNotInstanceOfAny(Class<?>[]) ,public SELF isNotNull() ,public transient SELF isNotOfAnyClassIn(Class<?>[]) ,public SELF isNotSameAs(java.lang.Object) ,public void isNull() ,public transient SELF isOfAnyClassIn(Class<?>[]) ,public SELF isSameAs(java.lang.Object) ,public SELF matches(Predicate<? super java.lang.Boolean>) ,public SELF matches(Predicate<? super java.lang.Boolean>, java.lang.String) ,public transient SELF overridingErrorMessage(java.lang.String, java.lang.Object[]) ,public SELF overridingErrorMessage(Supplier<java.lang.String>) ,public SELF satisfies(Condition<? super java.lang.Boolean>) ,public final transient SELF satisfies(Consumer<? super java.lang.Boolean>[]) ,public final transient SELF satisfies(ThrowingConsumer<? super java.lang.Boolean>[]) ,public final transient SELF satisfiesAnyOf(Consumer<? super java.lang.Boolean>[]) ,public final transient SELF satisfiesAnyOf(ThrowingConsumer<? super java.lang.Boolean>[]) ,public static void setCustomRepresentation(org.assertj.core.presentation.Representation) ,public static void setDescriptionConsumer(Consumer<org.assertj.core.description.Description>) ,public static void setPrintAssertionsDescription(boolean) ,public SELF usingComparator(Comparator<? super java.lang.Boolean>) ,public SELF usingComparator(Comparator<? super java.lang.Boolean>, java.lang.String) ,public SELF usingDefaultComparator() ,public transient SELF withFailMessage(java.lang.String, java.lang.Object[]) ,public SELF withFailMessage(Supplier<java.lang.String>) ,public SELF withRepresentation(org.assertj.core.presentation.Representation) ,public SELF withThreadDumpOnError() <variables>private static final java.lang.String ORG_ASSERTJ,protected final non-sealed java.lang.Boolean actual,org.assertj.core.error.AssertionErrorCreator assertionErrorCreator,org.assertj.core.internal.Conditions conditions,static org.assertj.core.presentation.Representation customRepresentation,private static Consumer<org.assertj.core.description.Description> descriptionConsumer,public org.assertj.core.api.WritableAssertionInfo info,protected final non-sealed SELF myself,protected org.assertj.core.internal.Objects objects,static boolean printAssertionsDescription,public static boolean throwUnsupportedExceptionOnEquals
|
assertj_assertj
|
assertj/assertj-core/src/main/java/org/assertj/core/api/AbstractCollectionAssert.java
|
AbstractCollectionAssert
|
assertIsUnmodifiable
|
class AbstractCollectionAssert<SELF extends AbstractCollectionAssert<SELF, ACTUAL, ELEMENT, ELEMENT_ASSERT>,
ACTUAL extends Collection<? extends ELEMENT>,
ELEMENT,
ELEMENT_ASSERT extends AbstractAssert<ELEMENT_ASSERT, ELEMENT>>
extends AbstractIterableAssert<SELF, ACTUAL, ELEMENT, ELEMENT_ASSERT> {
//@format:on
protected AbstractCollectionAssert(ACTUAL actual, Class<?> selfType) {
super(actual, selfType);
}
/**
* Verifies that the actual collection is unmodifiable, i.e., throws an {@link UnsupportedOperationException} with
* any attempt to modify the collection.
* <p>
* Example:
* <pre><code class='java'> // assertions will pass
* assertThat(Collections.unmodifiableCollection(new ArrayList<>())).isUnmodifiable();
* assertThat(Collections.unmodifiableList(new ArrayList<>())).isUnmodifiable();
* assertThat(Collections.unmodifiableSet(new HashSet<>())).isUnmodifiable();
*
* // assertions will fail
* assertThat(new ArrayList<>()).isUnmodifiable();
* assertThat(new HashSet<>()).isUnmodifiable();</code></pre>
*
* @return {@code this} assertion object.
* @throws AssertionError if the actual collection is modifiable.
* @see Collections#unmodifiableCollection(Collection)
* @see Collections#unmodifiableList(List)
* @see Collections#unmodifiableSet(Set)
*/
@Beta
public SELF isUnmodifiable() {
isNotNull();
assertIsUnmodifiable();
return myself;
}
@SuppressWarnings("unchecked")
private void assertIsUnmodifiable() {<FILL_FUNCTION_BODY>}
private void expectUnsupportedOperationException(Runnable runnable, String method) {
try {
runnable.run();
throwAssertionError(shouldBeUnmodifiable(method));
} catch (UnsupportedOperationException e) {
// happy path
} catch (RuntimeException e) {
throwAssertionError(shouldBeUnmodifiable(method, e));
}
}
private <E extends ELEMENT> Collection<E> emptyCollection() {
return Collections.emptyList();
}
}
|
switch (actual.getClass().getName()) {
case "java.util.Collections$EmptyList":
case "java.util.Collections$EmptyNavigableSet":
case "java.util.Collections$EmptySet":
case "java.util.Collections$EmptySortedSet":
case "java.util.Collections$SingletonList":
case "java.util.Collections$SingletonSet":
// immutable by contract, although not all methods throw UnsupportedOperationException
return;
}
expectUnsupportedOperationException(() -> actual.add(null), "Collection.add(null)");
expectUnsupportedOperationException(() -> actual.addAll(emptyCollection()), "Collection.addAll(emptyCollection())");
expectUnsupportedOperationException(() -> actual.clear(), "Collection.clear()");
expectUnsupportedOperationException(() -> actual.iterator().remove(), "Collection.iterator().remove()");
expectUnsupportedOperationException(() -> actual.remove(null), "Collection.remove(null)");
expectUnsupportedOperationException(() -> actual.removeAll(emptyCollection()), "Collection.removeAll(emptyCollection())");
expectUnsupportedOperationException(() -> actual.removeIf(element -> true), "Collection.removeIf(element -> true)");
expectUnsupportedOperationException(() -> actual.retainAll(emptyCollection()), "Collection.retainAll(emptyCollection())");
if (actual instanceof List) {
List<ELEMENT> list = (List<ELEMENT>) actual;
expectUnsupportedOperationException(() -> list.add(0, null), "List.add(0, null)");
expectUnsupportedOperationException(() -> list.addAll(0, emptyCollection()), "List.addAll(0, emptyCollection())");
expectUnsupportedOperationException(() -> list.listIterator().add(null), "List.listIterator().add(null)");
expectUnsupportedOperationException(() -> list.listIterator().remove(), "List.listIterator().remove()");
expectUnsupportedOperationException(() -> list.listIterator().set(null), "List.listIterator().set(null)");
expectUnsupportedOperationException(() -> list.remove(0), "List.remove(0)");
expectUnsupportedOperationException(() -> list.replaceAll(identity()), "List.replaceAll(identity())");
expectUnsupportedOperationException(() -> list.set(0, null), "List.set(0, null)");
expectUnsupportedOperationException(() -> list.sort((o1, o2) -> 0), "List.sort((o1, o2) -> 0)");
}
if (actual instanceof NavigableSet) {
NavigableSet<ELEMENT> set = (NavigableSet<ELEMENT>) actual;
expectUnsupportedOperationException(() -> set.descendingIterator().remove(), "NavigableSet.descendingIterator().remove()");
expectUnsupportedOperationException(() -> set.pollFirst(), "NavigableSet.pollFirst()");
expectUnsupportedOperationException(() -> set.pollLast(), "NavigableSet.pollLast()");
}
| 629
| 755
| 1,384
|
<methods>public SELF allMatch(Predicate<? super ELEMENT>) ,public SELF allMatch(Predicate<? super ELEMENT>, java.lang.String) ,public SELF allSatisfy(Consumer<? super ELEMENT>) ,public SELF allSatisfy(ThrowingConsumer<? super ELEMENT>) ,public SELF anyMatch(Predicate<? super ELEMENT>) ,public SELF anySatisfy(Consumer<? super ELEMENT>) ,public SELF anySatisfy(ThrowingConsumer<? super ELEMENT>) ,public SELF are(Condition<? super ELEMENT>) ,public SELF areAtLeast(int, Condition<? super ELEMENT>) ,public SELF areAtLeastOne(Condition<? super ELEMENT>) ,public SELF areAtMost(int, Condition<? super ELEMENT>) ,public SELF areExactly(int, Condition<? super ELEMENT>) ,public SELF areNot(Condition<? super ELEMENT>) ,public transient SELF as(java.lang.String, java.lang.Object[]) ,public SELF as(org.assertj.core.description.Description) ,public final transient SELF contains(ELEMENT[]) ,public SELF containsAll(Iterable<? extends ELEMENT>) ,public SELF containsAnyElementsOf(Iterable<? extends ELEMENT>) ,public final transient SELF containsAnyOf(ELEMENT[]) ,public final transient SELF containsExactly(ELEMENT[]) ,public SELF containsExactlyElementsOf(Iterable<? extends ELEMENT>) ,public final transient SELF containsExactlyInAnyOrder(ELEMENT[]) ,public SELF containsExactlyInAnyOrderElementsOf(Iterable<? extends ELEMENT>) ,public SELF containsNull() ,public final transient SELF containsOnly(ELEMENT[]) ,public SELF containsOnlyElementsOf(Iterable<? extends ELEMENT>) ,public SELF containsOnlyNulls() ,public final transient SELF containsOnlyOnce(ELEMENT[]) ,public SELF containsOnlyOnceElementsOf(Iterable<? extends ELEMENT>) ,public final transient SELF containsSequence(ELEMENT[]) ,public SELF containsSequence(Iterable<? extends ELEMENT>) ,public final transient SELF containsSubsequence(ELEMENT[]) ,public SELF containsSubsequence(Iterable<? extends ELEMENT>) ,public SELF describedAs(org.assertj.core.description.Description) ,public transient SELF describedAs(java.lang.String, java.lang.Object[]) ,public SELF doNotHave(Condition<? super ELEMENT>) ,public final transient SELF doesNotContain(ELEMENT[]) ,public SELF doesNotContainAnyElementsOf(Iterable<? extends ELEMENT>) ,public SELF doesNotContainNull() ,public final transient SELF doesNotContainSequence(ELEMENT[]) ,public SELF doesNotContainSequence(Iterable<? extends ELEMENT>) ,public final transient SELF doesNotContainSubsequence(ELEMENT[]) ,public SELF doesNotContainSubsequence(Iterable<? extends ELEMENT>) ,public SELF doesNotHave(Condition<? super ACTUAL>) ,public transient SELF doesNotHaveAnyElementsOfTypes(Class<?>[]) ,public SELF doesNotHaveDuplicates() ,public SELF doesNotHaveSameClassAs(java.lang.Object) ,public ELEMENT_ASSERT element(int) ,public ASSERT element(int, InstanceOfAssertFactory<?,ASSERT>) ,public transient SELF elements(int[]) ,public final transient SELF endsWith(ELEMENT, ELEMENT[]) ,public SELF endsWith(ELEMENT[]) ,public AbstractListAssert<?,List<? extends java.lang.Object>,java.lang.Object,ObjectAssert<java.lang.Object>> extracting(java.lang.String) ,public AbstractListAssert<?,List<? extends P>,P,ObjectAssert<P>> extracting(java.lang.String, Class<P>) ,public transient AbstractListAssert<?,List<? extends org.assertj.core.groups.Tuple>,org.assertj.core.groups.Tuple,ObjectAssert<org.assertj.core.groups.Tuple>> extracting(java.lang.String[]) ,public AbstractListAssert<?,List<? extends V>,V,ObjectAssert<V>> extracting(Function<? super ELEMENT,V>) ,public AbstractListAssert<?,List<? extends V>,V,ObjectAssert<V>> extracting(ThrowingExtractor<? super ELEMENT,V,EXCEPTION>) ,public final transient AbstractListAssert<?,List<? extends org.assertj.core.groups.Tuple>,org.assertj.core.groups.Tuple,ObjectAssert<org.assertj.core.groups.Tuple>> extracting(Function<? super ELEMENT,?>[]) ,public AbstractListAssert<?,List<? extends java.lang.Object>,java.lang.Object,ObjectAssert<java.lang.Object>> extractingResultOf(java.lang.String) ,public AbstractListAssert<?,List<? extends P>,P,ObjectAssert<P>> extractingResultOf(java.lang.String, Class<P>) ,public SELF filteredOn(java.lang.String, java.lang.Object) ,public SELF filteredOn(java.lang.String, FilterOperator<?>) ,public SELF filteredOn(Condition<? super ELEMENT>) ,public SELF filteredOn(Function<? super ELEMENT,T>, T) ,public SELF filteredOn(Predicate<? super ELEMENT>) ,public SELF filteredOnAssertions(Consumer<? super ELEMENT>) ,public SELF filteredOnAssertions(ThrowingConsumer<? super ELEMENT>) ,public SELF filteredOnNull(java.lang.String) ,public ELEMENT_ASSERT first() ,public ASSERT first(InstanceOfAssertFactory<?,ASSERT>) ,public AbstractListAssert<?,List<? extends V>,V,ObjectAssert<V>> flatExtracting(Function<? super ELEMENT,? extends Collection<V>>) ,public AbstractListAssert<?,List<? extends V>,V,ObjectAssert<V>> flatExtracting(ThrowingExtractor<? super ELEMENT,? extends Collection<V>,EXCEPTION>) ,public final transient AbstractListAssert<?,List<? extends java.lang.Object>,java.lang.Object,ObjectAssert<java.lang.Object>> flatExtracting(Function<? super ELEMENT,?>[]) ,public final transient AbstractListAssert<?,List<? extends java.lang.Object>,java.lang.Object,ObjectAssert<java.lang.Object>> flatExtracting(ThrowingExtractor<? super ELEMENT,?,EXCEPTION>[]) ,public AbstractListAssert<?,List<? extends java.lang.Object>,java.lang.Object,ObjectAssert<java.lang.Object>> flatExtracting(java.lang.String) ,public transient AbstractListAssert<?,List<? extends java.lang.Object>,java.lang.Object,ObjectAssert<java.lang.Object>> flatExtracting(java.lang.String[]) ,public AbstractListAssert<?,List<? extends V>,V,ObjectAssert<V>> flatMap(Function<? super ELEMENT,? extends Collection<V>>) ,public AbstractListAssert<?,List<? extends V>,V,ObjectAssert<V>> flatMap(ThrowingExtractor<? super ELEMENT,? extends Collection<V>,EXCEPTION>) ,public final transient AbstractListAssert<?,List<? extends java.lang.Object>,java.lang.Object,ObjectAssert<java.lang.Object>> flatMap(Function<? super ELEMENT,?>[]) ,public final transient AbstractListAssert<?,List<? extends java.lang.Object>,java.lang.Object,ObjectAssert<java.lang.Object>> flatMap(ThrowingExtractor<? super ELEMENT,?,EXCEPTION>[]) ,public SELF has(Condition<? super ACTUAL>) ,public SELF hasAtLeastOneElementOfType(Class<?>) ,public transient SELF hasExactlyElementsOfTypes(Class<?>[]) ,public SELF hasOnlyElementsOfType(Class<?>) ,public transient SELF hasOnlyElementsOfTypes(Class<?>[]) ,public SELF hasOnlyOneElementSatisfying(Consumer<? super ELEMENT>) ,public SELF hasSameClassAs(java.lang.Object) ,public SELF hasSameElementsAs(Iterable<? extends ELEMENT>) ,public SELF hasSameSizeAs(java.lang.Object) ,public SELF hasSameSizeAs(Iterable<?>) ,public SELF hasSize(int) ,public SELF hasSizeBetween(int, int) ,public SELF hasSizeGreaterThan(int) ,public SELF hasSizeGreaterThanOrEqualTo(int) ,public SELF hasSizeLessThan(int) ,public SELF hasSizeLessThanOrEqualTo(int) ,public SELF hasToString(java.lang.String) ,public SELF have(Condition<? super ELEMENT>) ,public SELF haveAtLeast(int, Condition<? super ELEMENT>) ,public SELF haveAtLeastOne(Condition<? super ELEMENT>) ,public SELF haveAtMost(int, Condition<? super ELEMENT>) ,public SELF haveExactly(int, Condition<? super ELEMENT>) ,public SELF inBinary() ,public SELF inHexadecimal() ,public SELF is(Condition<? super ACTUAL>) ,public void isEmpty() ,public SELF isEqualTo(java.lang.Object) ,public SELF isExactlyInstanceOf(Class<?>) ,public SELF isIn(Iterable<?>) ,public transient SELF isIn(java.lang.Object[]) ,public SELF isInstanceOf(Class<?>) ,public transient SELF isInstanceOfAny(Class<?>[]) ,public SELF isNot(Condition<? super ACTUAL>) ,public SELF isNotEmpty() ,public SELF isNotEqualTo(java.lang.Object) ,public SELF isNotExactlyInstanceOf(Class<?>) ,public SELF isNotIn(Iterable<?>) ,public transient SELF isNotIn(java.lang.Object[]) ,public SELF isNotInstanceOf(Class<?>) ,public transient SELF isNotInstanceOfAny(Class<?>[]) ,public SELF isNotNull() ,public transient SELF isNotOfAnyClassIn(Class<?>[]) ,public SELF isNotSameAs(java.lang.Object) ,public void isNullOrEmpty() ,public transient SELF isOfAnyClassIn(Class<?>[]) ,public SELF isSameAs(java.lang.Object) ,public SELF isSubsetOf(Iterable<? extends ELEMENT>) ,public final transient SELF isSubsetOf(ELEMENT[]) ,public ELEMENT_ASSERT last() ,public ASSERT last(InstanceOfAssertFactory<?,ASSERT>) ,public AbstractListAssert<?,List<? extends V>,V,ObjectAssert<V>> map(Function<? super ELEMENT,V>) ,public AbstractListAssert<?,List<? extends V>,V,ObjectAssert<V>> map(ThrowingExtractor<? super ELEMENT,V,EXCEPTION>) ,public final transient AbstractListAssert<?,List<? extends org.assertj.core.groups.Tuple>,org.assertj.core.groups.Tuple,ObjectAssert<org.assertj.core.groups.Tuple>> map(Function<? super ELEMENT,?>[]) ,public SELF noneMatch(Predicate<? super ELEMENT>) ,public SELF noneSatisfy(Consumer<? super ELEMENT>) ,public SELF noneSatisfy(ThrowingConsumer<? super ELEMENT>) ,public transient SELF overridingErrorMessage(java.lang.String, java.lang.Object[]) ,public final transient SELF satisfiesExactly(Consumer<? super ELEMENT>[]) ,public final transient SELF satisfiesExactly(ThrowingConsumer<? super ELEMENT>[]) ,public final transient SELF satisfiesExactlyInAnyOrder(Consumer<? super ELEMENT>[]) ,public final transient SELF satisfiesExactlyInAnyOrder(ThrowingConsumer<? super ELEMENT>[]) ,public SELF satisfiesOnlyOnce(Consumer<? super ELEMENT>) ,public SELF satisfiesOnlyOnce(ThrowingConsumer<? super ELEMENT>) ,public ELEMENT_ASSERT singleElement() ,public ASSERT singleElement(InstanceOfAssertFactory<?,ASSERT>) ,public AbstractIterableSizeAssert<SELF,ACTUAL,ELEMENT,ELEMENT_ASSERT> size() ,public final transient SELF startsWith(ELEMENT[]) ,public SELF usingComparator(Comparator<? super ACTUAL>) ,public SELF usingComparator(Comparator<? super ACTUAL>, java.lang.String) ,public transient SELF usingComparatorForElementFieldsWithNames(Comparator<T>, java.lang.String[]) ,public SELF usingComparatorForElementFieldsWithType(Comparator<T>, Class<T>) ,public SELF usingComparatorForType(Comparator<T>, Class<T>) ,public SELF usingDefaultComparator() ,public SELF usingDefaultElementComparator() ,public SELF usingElementComparator(Comparator<? super ELEMENT>) ,public transient SELF usingElementComparatorIgnoringFields(java.lang.String[]) ,public transient SELF usingElementComparatorOnFields(java.lang.String[]) ,public SELF usingFieldByFieldElementComparator() ,public org.assertj.core.api.RecursiveAssertionAssert usingRecursiveAssertion() ,public org.assertj.core.api.RecursiveAssertionAssert usingRecursiveAssertion(org.assertj.core.api.recursive.assertion.RecursiveAssertionConfiguration) ,public RecursiveComparisonAssert<?> usingRecursiveComparison() ,public RecursiveComparisonAssert<?> usingRecursiveComparison(org.assertj.core.api.recursive.comparison.RecursiveComparisonConfiguration) ,public SELF usingRecursiveFieldByFieldElementComparator() ,public SELF usingRecursiveFieldByFieldElementComparator(org.assertj.core.api.recursive.comparison.RecursiveComparisonConfiguration) ,public transient SELF usingRecursiveFieldByFieldElementComparatorIgnoringFields(java.lang.String[]) ,public transient SELF usingRecursiveFieldByFieldElementComparatorOnFields(java.lang.String[]) ,public transient SELF withFailMessage(java.lang.String, java.lang.Object[]) ,public SELF withThreadDumpOnError() ,public SELF zipSatisfy(Iterable<OTHER_ELEMENT>, BiConsumer<? super ELEMENT,OTHER_ELEMENT>) <variables>private static final java.lang.String ASSERT,private org.assertj.core.internal.TypeComparators comparatorsByType,private Map<java.lang.String,Comparator<?>> comparatorsForElementPropertyOrFieldNames,private org.assertj.core.internal.TypeComparators comparatorsForElementPropertyOrFieldTypes,protected org.assertj.core.internal.Iterables iterables
|
assertj_assertj
|
assertj/assertj-core/src/main/java/org/assertj/core/api/AbstractComparableAssert.java
|
AbstractComparableAssert
|
usingComparator
|
class AbstractComparableAssert<SELF extends AbstractComparableAssert<SELF, ACTUAL>, ACTUAL extends Comparable<? super ACTUAL>>
extends AbstractObjectAssert<SELF, ACTUAL> implements ComparableAssert<SELF, ACTUAL> {
@VisibleForTesting
Comparables comparables = new Comparables();
protected AbstractComparableAssert(ACTUAL actual, Class<?> selfType) {
super(actual, selfType);
}
/** {@inheritDoc} */
@Override
public SELF isEqualByComparingTo(ACTUAL other) {
comparables.assertEqualByComparison(info, actual, other);
return myself;
}
/** {@inheritDoc} */
@Override
public SELF isNotEqualByComparingTo(ACTUAL other) {
comparables.assertNotEqualByComparison(info, actual, other);
return myself;
}
/** {@inheritDoc} */
@Override
public SELF isLessThan(ACTUAL other) {
comparables.assertLessThan(info, actual, other);
return myself;
}
/** {@inheritDoc} */
@Override
public SELF isLessThanOrEqualTo(ACTUAL other) {
comparables.assertLessThanOrEqualTo(info, actual, other);
return myself;
}
/** {@inheritDoc} */
@Override
public SELF isGreaterThan(ACTUAL other) {
comparables.assertGreaterThan(info, actual, other);
return myself;
}
/** {@inheritDoc} */
@Override
public SELF isGreaterThanOrEqualTo(ACTUAL other) {
comparables.assertGreaterThanOrEqualTo(info, actual, other);
return myself;
}
/** {@inheritDoc} */
@Override
public SELF isBetween(ACTUAL startInclusive, ACTUAL endInclusive) {
comparables.assertIsBetween(info, actual, startInclusive, endInclusive, true, true);
return myself;
}
/** {@inheritDoc} */
@Override
public SELF isStrictlyBetween(ACTUAL startExclusive, ACTUAL endExclusive) {
comparables.assertIsBetween(info, actual, startExclusive, endExclusive, false, false);
return myself;
}
@Override
@CheckReturnValue
public SELF usingComparator(Comparator<? super ACTUAL> customComparator) {
return usingComparator(customComparator, null);
}
@Override
@CheckReturnValue
public SELF usingComparator(Comparator<? super ACTUAL> customComparator, String customComparatorDescription) {<FILL_FUNCTION_BODY>}
@Override
@CheckReturnValue
public SELF usingDefaultComparator() {
this.comparables = new Comparables();
return super.usingDefaultComparator();
}
@Override
@CheckReturnValue
public SELF inHexadecimal() {
return super.inHexadecimal();
}
@Override
@CheckReturnValue
public SELF inBinary() {
return super.inBinary();
}
}
|
this.comparables = new Comparables(new ComparatorBasedComparisonStrategy(customComparator, customComparatorDescription));
return super.usingComparator(customComparator, customComparatorDescription);
| 861
| 56
| 917
|
<methods>public void <init>(ACTUAL, Class<?>) ,public SELF as(org.assertj.core.description.Description) ,public transient SELF as(java.lang.String, java.lang.Object[]) ,public SELF doesNotReturn(T, Function<ACTUAL,T>) ,public transient AbstractListAssert<?,List<?>,java.lang.Object,ObjectAssert<java.lang.Object>> extracting(java.lang.String[]) ,public AbstractObjectAssert<?,?> extracting(java.lang.String) ,public ASSERT extracting(java.lang.String, InstanceOfAssertFactory<?,ASSERT>) ,public final transient AbstractListAssert<?,List<?>,java.lang.Object,ObjectAssert<java.lang.Object>> extracting(Function<? super ACTUAL,?>[]) ,public AbstractObjectAssert<?,T> extracting(Function<? super ACTUAL,T>) ,public ASSERT extracting(Function<? super ACTUAL,T>, InstanceOfAssertFactory<?,ASSERT>) ,public SELF hasAllNullFieldsOrProperties() ,public transient SELF hasAllNullFieldsOrPropertiesExcept(java.lang.String[]) ,public SELF hasFieldOrProperty(java.lang.String) ,public SELF hasFieldOrPropertyWithValue(java.lang.String, java.lang.Object) ,public SELF hasNoNullFieldsOrProperties() ,public transient SELF hasNoNullFieldsOrPropertiesExcept(java.lang.String[]) ,public transient SELF hasOnlyFields(java.lang.String[]) ,public SELF isEqualToComparingFieldByField(java.lang.Object) ,public SELF isEqualToComparingFieldByFieldRecursively(java.lang.Object) ,public transient SELF isEqualToComparingOnlyGivenFields(java.lang.Object, java.lang.String[]) ,public transient SELF isEqualToIgnoringGivenFields(java.lang.Object, java.lang.String[]) ,public SELF isEqualToIgnoringNullFields(java.lang.Object) ,public SELF returns(T, Function<ACTUAL,T>) ,public transient SELF usingComparatorForFields(Comparator<T>, java.lang.String[]) ,public SELF usingComparatorForType(Comparator<? super T>, Class<T>) ,public org.assertj.core.api.RecursiveAssertionAssert usingRecursiveAssertion() ,public org.assertj.core.api.RecursiveAssertionAssert usingRecursiveAssertion(org.assertj.core.api.recursive.assertion.RecursiveAssertionConfiguration) ,public RecursiveComparisonAssert<?> usingRecursiveComparison() ,public RecursiveComparisonAssert<?> usingRecursiveComparison(org.assertj.core.api.recursive.comparison.RecursiveComparisonConfiguration) <variables>private Map<java.lang.String,Comparator<?>> comparatorsByPropertyOrField,private org.assertj.core.internal.TypeComparators comparatorsByType
|
assertj_assertj
|
assertj/assertj-core/src/main/java/org/assertj/core/api/AbstractLongAdderAssert.java
|
AbstractLongAdderAssert
|
doesNotHaveValue
|
class AbstractLongAdderAssert<SELF extends AbstractLongAdderAssert<SELF>> extends AbstractAssert<SELF, LongAdder>
implements NumberAssert<SELF, Long>, ComparableAssert<SELF, Long> {
@VisibleForTesting
Longs longs = Longs.instance();
protected AbstractLongAdderAssert(LongAdder longAdder, Class<?> selfType) {
super(longAdder, selfType);
}
/**
* Verifies that the actual sum has the given value.
* <p>
* Example:
* <pre><code class='java'> // assertion will pass
* LongAdder actual = new LongAdder();
* actual.add(42);
* assertThat(actual).hasValue(42);
*
* // assertion will fail
* assertThat(actual).hasValue(0);</code></pre>
*
* @param expected the expected value.
* @return {@code this} assertion object.
* @throws AssertionError if the actual adder is {@code null}.
*/
public SELF hasValue(long expected) {
isNotNull();
long actualValue = actual.sum();
if (!objects.getComparisonStrategy().areEqual(actualValue, expected)) {
throwAssertionError(shouldHaveValue(actual, expected));
}
return myself;
}
/**
* Verifies that the actual sum has not the given value.
* <p>
* Example:
* <pre><code class='java'> // assertion will pass
* LongAdder actual = new LongAdder();
* actual.add(42);
* assertThat(actual).doesNotHaveValue(0);
*
* // assertion will fail
* assertThat(actual).doesNotHaveValue(42);</code></pre>
*
* @param unexpected the unexpected value.
* @return {@code this} assertion object.
* @throws AssertionError if the actual adder is {@code null}.
* @throws AssertionError if the actual sum is not the given value.
*/
public SELF doesNotHaveValue(long unexpected) {<FILL_FUNCTION_BODY>}
@Override
@CheckReturnValue
public SELF usingComparator(Comparator<? super LongAdder> customComparator) {
return usingComparator(customComparator, null);
}
@Override
@CheckReturnValue
public SELF usingComparator(Comparator<? super LongAdder> customComparator, String customComparatorDescription) {
longs = new Longs(new ComparatorBasedComparisonStrategy(customComparator, customComparatorDescription));
return super.usingComparator(customComparator, customComparatorDescription);
}
@Override
@CheckReturnValue
public SELF usingDefaultComparator() {
longs = Longs.instance();
return super.usingDefaultComparator();
}
@Override
public SELF isZero() {
longs.assertIsZero(info, actual.longValue());
return myself;
}
@Override
public SELF isNotZero() {
longs.assertIsNotZero(info, actual.longValue());
return myself;
}
@Override
public SELF isOne() {
longs.assertIsOne(info, actual.longValue());
return myself;
}
@Override
public SELF isPositive() {
longs.assertIsPositive(info, actual.longValue());
return myself;
}
@Override
public SELF isNegative() {
longs.assertIsNegative(info, actual.longValue());
return myself;
}
@Override
public SELF isNotNegative() {
longs.assertIsNotNegative(info, actual.longValue());
return myself;
}
@Override
public SELF isNotPositive() {
longs.assertIsNotPositive(info, actual.longValue());
return myself;
}
@Override
public SELF isEqualByComparingTo(Long other) {
longs.assertEqualByComparison(info, actual.longValue(), other);
return myself;
}
@Override
public SELF isNotEqualByComparingTo(Long other) {
longs.assertNotEqualByComparison(info, actual.longValue(), other);
return myself;
}
@Override
public SELF isLessThan(Long other) {
longs.assertLessThan(info, actual.longValue(), other);
return myself;
}
@Override
public SELF isLessThanOrEqualTo(Long other) {
longs.assertLessThanOrEqualTo(info, actual.longValue(), other);
return myself;
}
@Override
public SELF isGreaterThan(Long other) {
longs.assertGreaterThan(info, actual.longValue(), other);
return myself;
}
@Override
public SELF isGreaterThanOrEqualTo(Long other) {
longs.assertGreaterThanOrEqualTo(info, actual.longValue(), other);
return myself;
}
@Override
public SELF isBetween(Long start, Long end) {
longs.assertIsBetween(info, actual.longValue(), start, end);
return myself;
}
@Override
public SELF isStrictlyBetween(Long start, Long end) {
longs.assertIsStrictlyBetween(info, actual.longValue(), start, end);
return myself;
}
@Override
public SELF isCloseTo(Long expected, Offset<Long> offset) {
longs.assertIsCloseTo(info, actual.longValue(), expected, offset);
return myself;
}
@Override
public SELF isNotCloseTo(Long expected, Offset<Long> offset) {
longs.assertIsNotCloseTo(info, actual.longValue(), expected, offset);
return myself;
}
@Override
public SELF isCloseTo(Long expected, Percentage percentage) {
longs.assertIsCloseToPercentage(info, actual.longValue(), expected, percentage);
return myself;
}
@Override
public SELF isNotCloseTo(Long expected, Percentage percentage) {
longs.assertIsNotCloseToPercentage(info, actual.longValue(), expected, percentage);
return myself;
}
}
|
isNotNull();
long actualValue = actual.sum();
if (objects.getComparisonStrategy().areEqual(actualValue, unexpected)) {
throwAssertionError(shouldNotContainValue(actual, unexpected));
}
return myself;
| 1,687
| 62
| 1,749
|
<methods>public ASSERT asInstanceOf(InstanceOfAssertFactory<?,ASSERT>) ,public AbstractListAssert<?,List<?>,java.lang.Object,ObjectAssert<java.lang.Object>> asList() ,public AbstractStringAssert<?> asString() ,public SELF describedAs(org.assertj.core.description.Description) ,public java.lang.String descriptionText() ,public SELF doesNotHave(Condition<? super java.util.concurrent.atomic.LongAdder>) ,public SELF doesNotHaveSameClassAs(java.lang.Object) ,public SELF doesNotHaveSameHashCodeAs(java.lang.Object) ,public SELF doesNotHaveToString(java.lang.String) ,public transient SELF doesNotHaveToString(java.lang.String, java.lang.Object[]) ,public boolean equals(java.lang.Object) ,public org.assertj.core.api.WritableAssertionInfo getWritableAssertionInfo() ,public SELF has(Condition<? super java.util.concurrent.atomic.LongAdder>) ,public SELF hasSameClassAs(java.lang.Object) ,public SELF hasSameHashCodeAs(java.lang.Object) ,public SELF hasToString(java.lang.String) ,public transient SELF hasToString(java.lang.String, java.lang.Object[]) ,public int hashCode() ,public SELF is(Condition<? super java.util.concurrent.atomic.LongAdder>) ,public SELF isEqualTo(java.lang.Object) ,public SELF isExactlyInstanceOf(Class<?>) ,public transient SELF isIn(java.lang.Object[]) ,public SELF isIn(Iterable<?>) ,public SELF isInstanceOf(Class<?>) ,public transient SELF isInstanceOfAny(Class<?>[]) ,public SELF isInstanceOfSatisfying(Class<T>, Consumer<T>) ,public SELF isNot(Condition<? super java.util.concurrent.atomic.LongAdder>) ,public SELF isNotEqualTo(java.lang.Object) ,public SELF isNotExactlyInstanceOf(Class<?>) ,public transient SELF isNotIn(java.lang.Object[]) ,public SELF isNotIn(Iterable<?>) ,public SELF isNotInstanceOf(Class<?>) ,public transient SELF isNotInstanceOfAny(Class<?>[]) ,public SELF isNotNull() ,public transient SELF isNotOfAnyClassIn(Class<?>[]) ,public SELF isNotSameAs(java.lang.Object) ,public void isNull() ,public transient SELF isOfAnyClassIn(Class<?>[]) ,public SELF isSameAs(java.lang.Object) ,public SELF matches(Predicate<? super java.util.concurrent.atomic.LongAdder>) ,public SELF matches(Predicate<? super java.util.concurrent.atomic.LongAdder>, java.lang.String) ,public transient SELF overridingErrorMessage(java.lang.String, java.lang.Object[]) ,public SELF overridingErrorMessage(Supplier<java.lang.String>) ,public SELF satisfies(Condition<? super java.util.concurrent.atomic.LongAdder>) ,public final transient SELF satisfies(Consumer<? super java.util.concurrent.atomic.LongAdder>[]) ,public final transient SELF satisfies(ThrowingConsumer<? super java.util.concurrent.atomic.LongAdder>[]) ,public final transient SELF satisfiesAnyOf(Consumer<? super java.util.concurrent.atomic.LongAdder>[]) ,public final transient SELF satisfiesAnyOf(ThrowingConsumer<? super java.util.concurrent.atomic.LongAdder>[]) ,public static void setCustomRepresentation(org.assertj.core.presentation.Representation) ,public static void setDescriptionConsumer(Consumer<org.assertj.core.description.Description>) ,public static void setPrintAssertionsDescription(boolean) ,public SELF usingComparator(Comparator<? super java.util.concurrent.atomic.LongAdder>) ,public SELF usingComparator(Comparator<? super java.util.concurrent.atomic.LongAdder>, java.lang.String) ,public SELF usingDefaultComparator() ,public transient SELF withFailMessage(java.lang.String, java.lang.Object[]) ,public SELF withFailMessage(Supplier<java.lang.String>) ,public SELF withRepresentation(org.assertj.core.presentation.Representation) ,public SELF withThreadDumpOnError() <variables>private static final java.lang.String ORG_ASSERTJ,protected final non-sealed java.util.concurrent.atomic.LongAdder actual,org.assertj.core.error.AssertionErrorCreator assertionErrorCreator,org.assertj.core.internal.Conditions conditions,static org.assertj.core.presentation.Representation customRepresentation,private static Consumer<org.assertj.core.description.Description> descriptionConsumer,public org.assertj.core.api.WritableAssertionInfo info,protected final non-sealed SELF myself,protected org.assertj.core.internal.Objects objects,static boolean printAssertionsDescription,public static boolean throwUnsupportedExceptionOnEquals
|
assertj_assertj
|
assertj/assertj-core/src/main/java/org/assertj/core/api/AbstractMatcherAssert.java
|
AbstractMatcherAssert
|
matches
|
class AbstractMatcherAssert<SELF extends AbstractMatcherAssert<SELF>> extends AbstractAssert<SELF, Matcher> {
protected AbstractMatcherAssert(Matcher actual, Class<?> selfType) {
super(actual, selfType);
}
/**
* Verifies that the Matcher matches.
* <p>
* Example:
* <pre><code class='java'> // Assertion succeeds:
* Pattern pattern = Pattern.compile("a*");
* Matcher matcher = pattern.matcher("aaa");
* assertThat(matcher).matches();
*
* // Assertion fails:
* Pattern pattern = Pattern.compile("a*");
* Matcher matcher = pattern.matcher("abc");
* assertThat(matcher).matches();</code></pre>
*
* @return this assertion object.
* @throws AssertionError if actual does not match.
* @throws AssertionError if actual is null.
* @since 3.23.0
*/
public SELF matches() {<FILL_FUNCTION_BODY>}
}
|
isNotNull();
if (!actual.matches()) {
throw Failures.instance().failure(info, shouldMatch(actual));
}
return myself;
| 289
| 45
| 334
|
<methods>public ASSERT asInstanceOf(InstanceOfAssertFactory<?,ASSERT>) ,public AbstractListAssert<?,List<?>,java.lang.Object,ObjectAssert<java.lang.Object>> asList() ,public AbstractStringAssert<?> asString() ,public SELF describedAs(org.assertj.core.description.Description) ,public java.lang.String descriptionText() ,public SELF doesNotHave(Condition<? super java.util.regex.Matcher>) ,public SELF doesNotHaveSameClassAs(java.lang.Object) ,public SELF doesNotHaveSameHashCodeAs(java.lang.Object) ,public SELF doesNotHaveToString(java.lang.String) ,public transient SELF doesNotHaveToString(java.lang.String, java.lang.Object[]) ,public boolean equals(java.lang.Object) ,public org.assertj.core.api.WritableAssertionInfo getWritableAssertionInfo() ,public SELF has(Condition<? super java.util.regex.Matcher>) ,public SELF hasSameClassAs(java.lang.Object) ,public SELF hasSameHashCodeAs(java.lang.Object) ,public SELF hasToString(java.lang.String) ,public transient SELF hasToString(java.lang.String, java.lang.Object[]) ,public int hashCode() ,public SELF is(Condition<? super java.util.regex.Matcher>) ,public SELF isEqualTo(java.lang.Object) ,public SELF isExactlyInstanceOf(Class<?>) ,public transient SELF isIn(java.lang.Object[]) ,public SELF isIn(Iterable<?>) ,public SELF isInstanceOf(Class<?>) ,public transient SELF isInstanceOfAny(Class<?>[]) ,public SELF isInstanceOfSatisfying(Class<T>, Consumer<T>) ,public SELF isNot(Condition<? super java.util.regex.Matcher>) ,public SELF isNotEqualTo(java.lang.Object) ,public SELF isNotExactlyInstanceOf(Class<?>) ,public transient SELF isNotIn(java.lang.Object[]) ,public SELF isNotIn(Iterable<?>) ,public SELF isNotInstanceOf(Class<?>) ,public transient SELF isNotInstanceOfAny(Class<?>[]) ,public SELF isNotNull() ,public transient SELF isNotOfAnyClassIn(Class<?>[]) ,public SELF isNotSameAs(java.lang.Object) ,public void isNull() ,public transient SELF isOfAnyClassIn(Class<?>[]) ,public SELF isSameAs(java.lang.Object) ,public SELF matches(Predicate<? super java.util.regex.Matcher>) ,public SELF matches(Predicate<? super java.util.regex.Matcher>, java.lang.String) ,public transient SELF overridingErrorMessage(java.lang.String, java.lang.Object[]) ,public SELF overridingErrorMessage(Supplier<java.lang.String>) ,public SELF satisfies(Condition<? super java.util.regex.Matcher>) ,public final transient SELF satisfies(Consumer<? super java.util.regex.Matcher>[]) ,public final transient SELF satisfies(ThrowingConsumer<? super java.util.regex.Matcher>[]) ,public final transient SELF satisfiesAnyOf(Consumer<? super java.util.regex.Matcher>[]) ,public final transient SELF satisfiesAnyOf(ThrowingConsumer<? super java.util.regex.Matcher>[]) ,public static void setCustomRepresentation(org.assertj.core.presentation.Representation) ,public static void setDescriptionConsumer(Consumer<org.assertj.core.description.Description>) ,public static void setPrintAssertionsDescription(boolean) ,public SELF usingComparator(Comparator<? super java.util.regex.Matcher>) ,public SELF usingComparator(Comparator<? super java.util.regex.Matcher>, java.lang.String) ,public SELF usingDefaultComparator() ,public transient SELF withFailMessage(java.lang.String, java.lang.Object[]) ,public SELF withFailMessage(Supplier<java.lang.String>) ,public SELF withRepresentation(org.assertj.core.presentation.Representation) ,public SELF withThreadDumpOnError() <variables>private static final java.lang.String ORG_ASSERTJ,protected final non-sealed java.util.regex.Matcher actual,org.assertj.core.error.AssertionErrorCreator assertionErrorCreator,org.assertj.core.internal.Conditions conditions,static org.assertj.core.presentation.Representation customRepresentation,private static Consumer<org.assertj.core.description.Description> descriptionConsumer,public org.assertj.core.api.WritableAssertionInfo info,protected final non-sealed SELF myself,protected org.assertj.core.internal.Objects objects,static boolean printAssertionsDescription,public static boolean throwUnsupportedExceptionOnEquals
|
assertj_assertj
|
assertj/assertj-core/src/main/java/org/assertj/core/api/AbstractOptionalIntAssert.java
|
AbstractOptionalIntAssert
|
hasValue
|
class AbstractOptionalIntAssert<SELF extends AbstractOptionalIntAssert<SELF>> extends
AbstractAssert<SELF, OptionalInt> {
@VisibleForTesting
Integers integers = Integers.instance();
protected AbstractOptionalIntAssert(OptionalInt actual, Class<?> selfType) {
super(actual, selfType);
}
/**
* Verifies that there is a value present in the actual {@link java.util.OptionalInt}.
* <p>
* Assertion will pass :
* <pre><code class='java'> assertThat(OptionalInt.of(10)).isPresent();</code></pre>
* <p>
* Assertion will fail :
* <pre><code class='java'> assertThat(OptionalInt.empty()).isPresent();</code></pre>
*
* @return this assertion object.
* @throws AssertionError if actual value is empty.
* @throws AssertionError if actual is null.
*/
public SELF isPresent() {
isNotNull();
if (!actual.isPresent()) throwAssertionError(shouldBePresent(actual));
return myself;
}
/**
* Verifies that the actual {@link java.util.OptionalInt} is empty (alias of {@link #isEmpty()}).
* <p>
* Assertion will pass :
* <pre><code class='java'> assertThat(OptionalInt.empty()).isNotPresent();</code></pre>
*
* Assertion will fail :
* <pre><code class='java'> assertThat(OptionalInt.of(10)).isNotPresent();</code></pre>
*
* @return this assertion object.
*/
public SELF isNotPresent() {
return isEmpty();
}
/**
* Verifies that the actual {@link java.util.OptionalInt} is empty.
* <p>
* Assertion will pass :
* <pre><code class='java'> assertThat(OptionalInt.empty()).isEmpty();</code></pre>
* <p>
* Assertion will fail :
* <pre><code class='java'> assertThat(OptionalInt.of(10)).isEmpty();</code></pre>
*
* @return this assertion object.
* @throws AssertionError if actual value is present.
* @throws AssertionError if actual is null.
*/
public SELF isEmpty() {
isNotNull();
if (actual.isPresent()) throwAssertionError(shouldBeEmpty(actual));
return myself;
}
/**
* Verifies that there is a value present in the actual {@link java.util.OptionalInt}, it's an alias of {@link #isPresent()}.
* <p>
* Assertion will pass :
* <pre><code class='java'> assertThat(OptionalInt.of(10)).isNotEmpty();</code></pre>
* <p>
* Assertion will fail :
* <pre><code class='java'> assertThat(OptionalInt.empty()).isNotEmpty();</code></pre>
*
* @return this assertion object.
* @throws AssertionError if actual value is empty.
* @throws AssertionError if actual is null.
*/
public SELF isNotEmpty() {
return isPresent();
}
/**
* Verifies that the actual {@link java.util.OptionalInt} has the value in argument.
* <p>
* Assertion will pass :
* <pre><code class='java'> assertThat(OptionalInt.of(8)).hasValue(8);
* assertThat(OptionalInt.of(8)).hasValue(Integer.valueOf(8));</code></pre>
* <p>
* Assertion will fail :
* <pre><code class='java'> assertThat(OptionalInt.empty()).hasValue(8);
* assertThat(OptionalInt.of(7)).hasValue(8);</code></pre>
*
* @param expectedValue the expected value inside the {@link java.util.OptionalInt}.
* @return this assertion object.
* @throws AssertionError if actual value is empty.
* @throws AssertionError if actual is null.
* @throws AssertionError if actual has not the value as expected.
*/
public SELF hasValue(int expectedValue) {<FILL_FUNCTION_BODY>}
}
|
isNotNull();
if (!actual.isPresent()) throwAssertionError(shouldContain(expectedValue));
if (expectedValue != actual.getAsInt())
throw Failures.instance().failure(info, shouldContain(actual, expectedValue), actual.getAsInt(), expectedValue);
return myself;
| 1,108
| 80
| 1,188
|
<methods>public ASSERT asInstanceOf(InstanceOfAssertFactory<?,ASSERT>) ,public AbstractListAssert<?,List<?>,java.lang.Object,ObjectAssert<java.lang.Object>> asList() ,public AbstractStringAssert<?> asString() ,public SELF describedAs(org.assertj.core.description.Description) ,public java.lang.String descriptionText() ,public SELF doesNotHave(Condition<? super java.util.OptionalInt>) ,public SELF doesNotHaveSameClassAs(java.lang.Object) ,public SELF doesNotHaveSameHashCodeAs(java.lang.Object) ,public SELF doesNotHaveToString(java.lang.String) ,public transient SELF doesNotHaveToString(java.lang.String, java.lang.Object[]) ,public boolean equals(java.lang.Object) ,public org.assertj.core.api.WritableAssertionInfo getWritableAssertionInfo() ,public SELF has(Condition<? super java.util.OptionalInt>) ,public SELF hasSameClassAs(java.lang.Object) ,public SELF hasSameHashCodeAs(java.lang.Object) ,public SELF hasToString(java.lang.String) ,public transient SELF hasToString(java.lang.String, java.lang.Object[]) ,public int hashCode() ,public SELF is(Condition<? super java.util.OptionalInt>) ,public SELF isEqualTo(java.lang.Object) ,public SELF isExactlyInstanceOf(Class<?>) ,public transient SELF isIn(java.lang.Object[]) ,public SELF isIn(Iterable<?>) ,public SELF isInstanceOf(Class<?>) ,public transient SELF isInstanceOfAny(Class<?>[]) ,public SELF isInstanceOfSatisfying(Class<T>, Consumer<T>) ,public SELF isNot(Condition<? super java.util.OptionalInt>) ,public SELF isNotEqualTo(java.lang.Object) ,public SELF isNotExactlyInstanceOf(Class<?>) ,public transient SELF isNotIn(java.lang.Object[]) ,public SELF isNotIn(Iterable<?>) ,public SELF isNotInstanceOf(Class<?>) ,public transient SELF isNotInstanceOfAny(Class<?>[]) ,public SELF isNotNull() ,public transient SELF isNotOfAnyClassIn(Class<?>[]) ,public SELF isNotSameAs(java.lang.Object) ,public void isNull() ,public transient SELF isOfAnyClassIn(Class<?>[]) ,public SELF isSameAs(java.lang.Object) ,public SELF matches(Predicate<? super java.util.OptionalInt>) ,public SELF matches(Predicate<? super java.util.OptionalInt>, java.lang.String) ,public transient SELF overridingErrorMessage(java.lang.String, java.lang.Object[]) ,public SELF overridingErrorMessage(Supplier<java.lang.String>) ,public SELF satisfies(Condition<? super java.util.OptionalInt>) ,public final transient SELF satisfies(Consumer<? super java.util.OptionalInt>[]) ,public final transient SELF satisfies(ThrowingConsumer<? super java.util.OptionalInt>[]) ,public final transient SELF satisfiesAnyOf(Consumer<? super java.util.OptionalInt>[]) ,public final transient SELF satisfiesAnyOf(ThrowingConsumer<? super java.util.OptionalInt>[]) ,public static void setCustomRepresentation(org.assertj.core.presentation.Representation) ,public static void setDescriptionConsumer(Consumer<org.assertj.core.description.Description>) ,public static void setPrintAssertionsDescription(boolean) ,public SELF usingComparator(Comparator<? super java.util.OptionalInt>) ,public SELF usingComparator(Comparator<? super java.util.OptionalInt>, java.lang.String) ,public SELF usingDefaultComparator() ,public transient SELF withFailMessage(java.lang.String, java.lang.Object[]) ,public SELF withFailMessage(Supplier<java.lang.String>) ,public SELF withRepresentation(org.assertj.core.presentation.Representation) ,public SELF withThreadDumpOnError() <variables>private static final java.lang.String ORG_ASSERTJ,protected final non-sealed java.util.OptionalInt actual,org.assertj.core.error.AssertionErrorCreator assertionErrorCreator,org.assertj.core.internal.Conditions conditions,static org.assertj.core.presentation.Representation customRepresentation,private static Consumer<org.assertj.core.description.Description> descriptionConsumer,public org.assertj.core.api.WritableAssertionInfo info,protected final non-sealed SELF myself,protected org.assertj.core.internal.Objects objects,static boolean printAssertionsDescription,public static boolean throwUnsupportedExceptionOnEquals
|
assertj_assertj
|
assertj/assertj-core/src/main/java/org/assertj/core/api/AbstractOptionalLongAssert.java
|
AbstractOptionalLongAssert
|
hasValue
|
class AbstractOptionalLongAssert<SELF extends AbstractOptionalLongAssert<SELF>> extends
AbstractAssert<SELF, OptionalLong> {
protected AbstractOptionalLongAssert(OptionalLong actual, Class<?> selfType) {
super(actual, selfType);
}
/**
* Verifies that there is a value present in the actual {@link java.util.OptionalLong}.
* <p>
* Assertion will pass :
* <pre><code class='java'> assertThat(OptionalLong.of(10)).isPresent();</code></pre>
* <p>
* Assertion will fail :
* <pre><code class='java'> assertThat(OptionalLong.empty()).isPresent();</code></pre>
*
* @return this assertion object.
* @throws AssertionError if actual value is empty.
* @throws AssertionError if actual is null.
*/
public SELF isPresent() {
isNotNull();
if (!actual.isPresent()) throwAssertionError(shouldBePresent(actual));
return myself;
}
/**
* Verifies that the actual {@link java.util.OptionalLong} is empty (alias of {@link #isEmpty()}).
* <p>
* Assertion will pass :
* <pre><code class='java'> assertThat(OptionalLong.empty()).isNotPresent();</code></pre>
*
* Assertion will fail :
* <pre><code class='java'> assertThat(OptionalLong.of(10)).isNotPresent();</code></pre>
*
* @return this assertion object.
*/
public SELF isNotPresent() {
return isEmpty();
}
/**
* Verifies that the actual {@link java.util.OptionalLong} is empty.
* <p>
* Assertion will pass :
* <pre><code class='java'> assertThat(OptionalLong.empty()).isEmpty();</code></pre>
* <p>
* Assertion will fail :
* <pre><code class='java'> assertThat(OptionalLong.of(10)).isEmpty();</code></pre>
*
* @return this assertion object.
* @throws AssertionError if actual value is present.
* @throws AssertionError if actual is null.
*/
public SELF isEmpty() {
isNotNull();
if (actual.isPresent()) throwAssertionError(shouldBeEmpty(actual));
return myself;
}
/**
* Verifies that there is a value present in the actual {@link java.util.OptionalLong}, it's an alias of {@link #isPresent()}.
* <p>
* Assertion will pass :
* <pre><code class='java'> assertThat(OptionalLong.of(10)).isNotEmpty();</code></pre>
* <p>
* Assertion will fail :
* <pre><code class='java'> assertThat(OptionalLong.empty()).isNotEmpty();</code></pre>
*
* @return this assertion object.
* @throws AssertionError if actual value is empty.
* @throws AssertionError if actual is null.
*/
public SELF isNotEmpty() {
return isPresent();
}
/**
* Verifies that the actual {@link java.util.OptionalLong} has the value in argument.
* <p>
* Assertion will pass :
* <pre><code class='java'> assertThat(OptionalLong.of(8)).hasValue(8);
* assertThat(OptionalLong.of(8)).hasValue(Integer.valueOf(8));</code></pre>
* <p>
* Assertion will fail :
* <pre><code class='java'> assertThat(OptionalLong.empty()).hasValue(8);
* assertThat(OptionalLong.of(7)).hasValue(8);</code></pre>
*
* @param expectedValue the expected value inside the {@link java.util.OptionalLong}.
* @return this assertion object.
* @throws AssertionError if actual value is empty.
* @throws AssertionError if actual is null.
* @throws AssertionError if actual has not the value as expected.
*/
public SELF hasValue(long expectedValue) {<FILL_FUNCTION_BODY>}
}
|
isNotNull();
if (!actual.isPresent()) throwAssertionError(shouldContain(expectedValue));
if (expectedValue != actual.getAsLong())
throw Failures.instance().failure(info, shouldContain(actual, expectedValue), actual.getAsLong(), expectedValue);
return myself;
| 1,089
| 80
| 1,169
|
<methods>public ASSERT asInstanceOf(InstanceOfAssertFactory<?,ASSERT>) ,public AbstractListAssert<?,List<?>,java.lang.Object,ObjectAssert<java.lang.Object>> asList() ,public AbstractStringAssert<?> asString() ,public SELF describedAs(org.assertj.core.description.Description) ,public java.lang.String descriptionText() ,public SELF doesNotHave(Condition<? super java.util.OptionalLong>) ,public SELF doesNotHaveSameClassAs(java.lang.Object) ,public SELF doesNotHaveSameHashCodeAs(java.lang.Object) ,public SELF doesNotHaveToString(java.lang.String) ,public transient SELF doesNotHaveToString(java.lang.String, java.lang.Object[]) ,public boolean equals(java.lang.Object) ,public org.assertj.core.api.WritableAssertionInfo getWritableAssertionInfo() ,public SELF has(Condition<? super java.util.OptionalLong>) ,public SELF hasSameClassAs(java.lang.Object) ,public SELF hasSameHashCodeAs(java.lang.Object) ,public SELF hasToString(java.lang.String) ,public transient SELF hasToString(java.lang.String, java.lang.Object[]) ,public int hashCode() ,public SELF is(Condition<? super java.util.OptionalLong>) ,public SELF isEqualTo(java.lang.Object) ,public SELF isExactlyInstanceOf(Class<?>) ,public transient SELF isIn(java.lang.Object[]) ,public SELF isIn(Iterable<?>) ,public SELF isInstanceOf(Class<?>) ,public transient SELF isInstanceOfAny(Class<?>[]) ,public SELF isInstanceOfSatisfying(Class<T>, Consumer<T>) ,public SELF isNot(Condition<? super java.util.OptionalLong>) ,public SELF isNotEqualTo(java.lang.Object) ,public SELF isNotExactlyInstanceOf(Class<?>) ,public transient SELF isNotIn(java.lang.Object[]) ,public SELF isNotIn(Iterable<?>) ,public SELF isNotInstanceOf(Class<?>) ,public transient SELF isNotInstanceOfAny(Class<?>[]) ,public SELF isNotNull() ,public transient SELF isNotOfAnyClassIn(Class<?>[]) ,public SELF isNotSameAs(java.lang.Object) ,public void isNull() ,public transient SELF isOfAnyClassIn(Class<?>[]) ,public SELF isSameAs(java.lang.Object) ,public SELF matches(Predicate<? super java.util.OptionalLong>) ,public SELF matches(Predicate<? super java.util.OptionalLong>, java.lang.String) ,public transient SELF overridingErrorMessage(java.lang.String, java.lang.Object[]) ,public SELF overridingErrorMessage(Supplier<java.lang.String>) ,public SELF satisfies(Condition<? super java.util.OptionalLong>) ,public final transient SELF satisfies(Consumer<? super java.util.OptionalLong>[]) ,public final transient SELF satisfies(ThrowingConsumer<? super java.util.OptionalLong>[]) ,public final transient SELF satisfiesAnyOf(Consumer<? super java.util.OptionalLong>[]) ,public final transient SELF satisfiesAnyOf(ThrowingConsumer<? super java.util.OptionalLong>[]) ,public static void setCustomRepresentation(org.assertj.core.presentation.Representation) ,public static void setDescriptionConsumer(Consumer<org.assertj.core.description.Description>) ,public static void setPrintAssertionsDescription(boolean) ,public SELF usingComparator(Comparator<? super java.util.OptionalLong>) ,public SELF usingComparator(Comparator<? super java.util.OptionalLong>, java.lang.String) ,public SELF usingDefaultComparator() ,public transient SELF withFailMessage(java.lang.String, java.lang.Object[]) ,public SELF withFailMessage(Supplier<java.lang.String>) ,public SELF withRepresentation(org.assertj.core.presentation.Representation) ,public SELF withThreadDumpOnError() <variables>private static final java.lang.String ORG_ASSERTJ,protected final non-sealed java.util.OptionalLong actual,org.assertj.core.error.AssertionErrorCreator assertionErrorCreator,org.assertj.core.internal.Conditions conditions,static org.assertj.core.presentation.Representation customRepresentation,private static Consumer<org.assertj.core.description.Description> descriptionConsumer,public org.assertj.core.api.WritableAssertionInfo info,protected final non-sealed SELF myself,protected org.assertj.core.internal.Objects objects,static boolean printAssertionsDescription,public static boolean throwUnsupportedExceptionOnEquals
|
assertj_assertj
|
assertj/assertj-core/src/main/java/org/assertj/core/api/AbstractPeriodAssert.java
|
AbstractPeriodAssert
|
isNegative
|
class AbstractPeriodAssert<SELF extends AbstractPeriodAssert<SELF>> extends AbstractAssert<SELF, Period> {
/**
* Creates a new <code>{@link org.assertj.core.api.AbstractPeriodAssert}</code>
* @param period the actual value to verify
* @param selfType the "self type"
*/
protected AbstractPeriodAssert(Period period, Class<?> selfType) {
super(period, selfType);
}
/**
* Verifies that the actual {@code Period} has the given years.
* <p>
* Example :
* <pre><code class='java'> // assertion will pass
* assertThat(Period.ofYears(5)).hasYears(5);
*
* // assertion will fail
* assertThat(Period.ofYears(5)).hasYears(1);</code></pre>
*
* @param expectedYears the expected years value
* @return this assertion object
* @throws AssertionError if the actual {@code Period} is {@code null}
* @throws AssertionError if the actual {@code Period} does not have the given years
* @since 3.17.0
*/
public SELF hasYears(int expectedYears) {
isNotNull();
int actualYears = actual.getYears();
if (expectedYears != actualYears) {
throw Failures.instance().failure(info, shouldHaveYears(actual, actualYears, expectedYears), actualYears, expectedYears);
}
return myself;
}
/**
* Verifies that the actual {@code Period} has the given months.
* <p>
* Example :
* <pre><code class='java'> // assertion will pass
* assertThat(Period.ofMonths(5)).hasMonths(5);
*
* // assertion will fail
* assertThat(Period.ofMonths(5)).hasMonths(1);</code></pre>
*
* @param expectedMonths the expected months value
* @return this assertion object
* @throws AssertionError if the actual {@code Period} is {@code null}
* @throws AssertionError if the actual {@code Period} does not have the given months
* @since 3.17.0
*/
public SELF hasMonths(int expectedMonths) {
isNotNull();
int actualMonths = actual.getMonths();
if (expectedMonths != actualMonths) {
throw Failures.instance().failure(info, shouldHaveMonths(actual, actualMonths, expectedMonths), actualMonths,
expectedMonths);
}
return myself;
}
/**
* Verifies that the actual {@code Period} has the given days.
* <p>
* Example :
* <pre><code class='java'> // assertion will pass
* assertThat(Period.ofDays(5)).hasDays(5);
*
* // assertion will fail
* assertThat(Period.ofDays(5)).hasDays(1);</code></pre>
*
* @param expectedDays the expected days value
* @return this assertion object
* @throws AssertionError if the actual {@code Period} is {@code null}
* @throws AssertionError if the actual {@code Period} does not have the given days
* @since 3.17.0
*/
public SELF hasDays(int expectedDays) {
isNotNull();
int actualDays = actual.getDays();
if (expectedDays != actualDays) {
throw Failures.instance().failure(info, shouldHaveDays(actual, actualDays, expectedDays), actualDays, expectedDays);
}
return myself;
}
/**
* Verifies that the actual {@code Period} is positive (i.e. is greater than {@link Period#ZERO}).
* <p>
* Example :
* <pre><code class='java'> // assertion will pass
* assertThat(Period.ofMonths(5)).isPositive();
*
* // assertion will fail
* assertThat(Period.ofMonths(-2)).isPositive();</code></pre>
* @return this assertion object
* @throws AssertionError if the actual {@code Period} is {@code null}
* @throws AssertionError if the actual {@code Period} is not greater than {@link Period#ZERO}
* @since 3.17.0
*/
public SELF isPositive() {
isNotNull();
boolean negative = actual.isNegative();
if (negative || Period.ZERO.equals(actual)) throw Failures.instance().failure(info, shouldBePositive(actual));
return myself;
}
/**
* Verifies that the actual {@code Period} is negative (i.e. is less than {@link Period#ZERO}).
* <p>
* Example :
* <pre><code class='java'> // assertion will pass
* assertThat(Period.ofMonths(-5)).isNegative();
*
* // assertion will fail
* assertThat(Period.ofMonths(2)).isNegative();</code></pre>
* @return this assertion object
* @throws AssertionError if the actual {@code Period} is {@code null}
* @throws AssertionError if the actual {@code Period} is not greater than {@link Period#ZERO}
* @since 3.17.0
*/
public SELF isNegative() {<FILL_FUNCTION_BODY>}
}
|
isNotNull();
boolean negative = actual.isNegative();
if (!negative || Period.ZERO.equals(actual)) throw Failures.instance().failure(info, shouldBeNegative(actual));
return myself;
| 1,419
| 59
| 1,478
|
<methods>public ASSERT asInstanceOf(InstanceOfAssertFactory<?,ASSERT>) ,public AbstractListAssert<?,List<?>,java.lang.Object,ObjectAssert<java.lang.Object>> asList() ,public AbstractStringAssert<?> asString() ,public SELF describedAs(org.assertj.core.description.Description) ,public java.lang.String descriptionText() ,public SELF doesNotHave(Condition<? super java.time.Period>) ,public SELF doesNotHaveSameClassAs(java.lang.Object) ,public SELF doesNotHaveSameHashCodeAs(java.lang.Object) ,public SELF doesNotHaveToString(java.lang.String) ,public transient SELF doesNotHaveToString(java.lang.String, java.lang.Object[]) ,public boolean equals(java.lang.Object) ,public org.assertj.core.api.WritableAssertionInfo getWritableAssertionInfo() ,public SELF has(Condition<? super java.time.Period>) ,public SELF hasSameClassAs(java.lang.Object) ,public SELF hasSameHashCodeAs(java.lang.Object) ,public SELF hasToString(java.lang.String) ,public transient SELF hasToString(java.lang.String, java.lang.Object[]) ,public int hashCode() ,public SELF is(Condition<? super java.time.Period>) ,public SELF isEqualTo(java.lang.Object) ,public SELF isExactlyInstanceOf(Class<?>) ,public transient SELF isIn(java.lang.Object[]) ,public SELF isIn(Iterable<?>) ,public SELF isInstanceOf(Class<?>) ,public transient SELF isInstanceOfAny(Class<?>[]) ,public SELF isInstanceOfSatisfying(Class<T>, Consumer<T>) ,public SELF isNot(Condition<? super java.time.Period>) ,public SELF isNotEqualTo(java.lang.Object) ,public SELF isNotExactlyInstanceOf(Class<?>) ,public transient SELF isNotIn(java.lang.Object[]) ,public SELF isNotIn(Iterable<?>) ,public SELF isNotInstanceOf(Class<?>) ,public transient SELF isNotInstanceOfAny(Class<?>[]) ,public SELF isNotNull() ,public transient SELF isNotOfAnyClassIn(Class<?>[]) ,public SELF isNotSameAs(java.lang.Object) ,public void isNull() ,public transient SELF isOfAnyClassIn(Class<?>[]) ,public SELF isSameAs(java.lang.Object) ,public SELF matches(Predicate<? super java.time.Period>) ,public SELF matches(Predicate<? super java.time.Period>, java.lang.String) ,public transient SELF overridingErrorMessage(java.lang.String, java.lang.Object[]) ,public SELF overridingErrorMessage(Supplier<java.lang.String>) ,public SELF satisfies(Condition<? super java.time.Period>) ,public final transient SELF satisfies(Consumer<? super java.time.Period>[]) ,public final transient SELF satisfies(ThrowingConsumer<? super java.time.Period>[]) ,public final transient SELF satisfiesAnyOf(Consumer<? super java.time.Period>[]) ,public final transient SELF satisfiesAnyOf(ThrowingConsumer<? super java.time.Period>[]) ,public static void setCustomRepresentation(org.assertj.core.presentation.Representation) ,public static void setDescriptionConsumer(Consumer<org.assertj.core.description.Description>) ,public static void setPrintAssertionsDescription(boolean) ,public SELF usingComparator(Comparator<? super java.time.Period>) ,public SELF usingComparator(Comparator<? super java.time.Period>, java.lang.String) ,public SELF usingDefaultComparator() ,public transient SELF withFailMessage(java.lang.String, java.lang.Object[]) ,public SELF withFailMessage(Supplier<java.lang.String>) ,public SELF withRepresentation(org.assertj.core.presentation.Representation) ,public SELF withThreadDumpOnError() <variables>private static final java.lang.String ORG_ASSERTJ,protected final non-sealed java.time.Period actual,org.assertj.core.error.AssertionErrorCreator assertionErrorCreator,org.assertj.core.internal.Conditions conditions,static org.assertj.core.presentation.Representation customRepresentation,private static Consumer<org.assertj.core.description.Description> descriptionConsumer,public org.assertj.core.api.WritableAssertionInfo info,protected final non-sealed SELF myself,protected org.assertj.core.internal.Objects objects,static boolean printAssertionsDescription,public static boolean throwUnsupportedExceptionOnEquals
|
assertj_assertj
|
assertj/assertj-core/src/main/java/org/assertj/core/api/AbstractPredicateAssert.java
|
AbstractPredicateAssert
|
acceptsForProxy
|
class AbstractPredicateAssert<SELF extends AbstractPredicateAssert<SELF, T>, T> extends
AbstractAssert<SELF, Predicate<T>> {
@VisibleForTesting
Iterables iterables = Iterables.instance();
protected AbstractPredicateAssert(Predicate<T> actual, Class<?> selfType) {
super(actual, selfType);
}
/**
* Verifies that the {@link Predicate} evaluates all given values to {@code true}.
* <p>
* Example :
* <pre><code class='java'> Predicate<String> ballSportPredicate = sport -> sport.contains("ball");
*
* // assertion succeeds:
* assertThat(ballSportPredicate).accepts("football")
* .accepts("football", "basketball", "handball");
*
* // assertions fail because of curling :p
* assertThat(ballSportPredicate).accepts("curling")
* assertThat(ballSportPredicate).accepts("football", "basketball", "curling");</code></pre>
*
* @param values values the actual {@code Predicate} should accept.
* @return this assertion object.
* @throws AssertionError if the actual {@code Predicate} does not accept all the given {@code Iterable}'s elements.
*/
@SafeVarargs
public final SELF accepts(T... values) {
return acceptsForProxy(values);
}
// This method is protected in order to be proxied for SoftAssertions / Assumptions.
// The public method for it (the one not ending with "ForProxy") is marked as final and annotated with @SafeVarargs
// in order to avoid compiler warning in user code
protected SELF acceptsForProxy(T[] values) {<FILL_FUNCTION_BODY>}
/**
* Verifies that the {@link Predicate} evaluates all given values to {@code false}.
* <p>
* Example :
* <pre><code class='java'> Predicate<String> ballSportPredicate = sport -> sport.contains("ball");
*
* // assertion succeeds:
* assertThat(ballSportPredicate).rejects("curling")
* .rejects("curling", "judo", "marathon");
*
* // assertion fails because of football:
* assertThat(ballSportPredicate).rejects("football");
* assertThat(ballSportPredicate).rejects("curling", "judo", "football");</code></pre>
*
* @param values values the actual {@code Predicate} should reject.
* @return this assertion object.
* @throws AssertionError if the actual {@code Predicate} accepts one of the given {@code Iterable}'s elements.
*/
@SafeVarargs
public final SELF rejects(T... values) {
return rejectsForProxy(values);
}
// This method is protected in order to be proxied for SoftAssertions / Assumptions.
// The public method for it (the one not ending with "ForProxy") is marked as final and annotated with @SafeVarargs
// in order to avoid compiler warning in user code
protected SELF rejectsForProxy(T[] values) {
isNotNull();
if (values.length == 1) {
if (actual.test(values[0])) throwAssertionError(shouldNotAccept(actual, values[0], PredicateDescription.GIVEN));
} else iterables.assertNoneMatch(info, list(values), actual, PredicateDescription.GIVEN);
return myself;
}
/**
* Verifies that the {@link Predicate} evaluates all given {@link Iterable}'s elements to {@code true}.
* <p>
* Example :
* <pre><code class='java'> Predicate<String> ballSportPredicate = sport -> sport.contains("ball");
*
* // assertion succeeds:
* assertThat(ballSportPredicate).acceptsAll(list("football", "basketball", "handball"));
*
* // assertion fails because of curling :p
* assertThat(ballSportPredicate).acceptsAll(list("football", "basketball", "curling"));</code></pre>
*
* @param iterable {@code Iterable} whose elements the actual {@code Predicate} should accept.
* @return this assertion object.
* @throws AssertionError if the actual {@code Predicate} does not accept all the given {@code Iterable}'s elements.
*/
public SELF acceptsAll(Iterable<? extends T> iterable) {
isNotNull();
iterables.assertAllMatch(info, iterable, actual, PredicateDescription.GIVEN);
return myself;
}
/**
* Verifies that the {@link Predicate} evaluates all given {@link Iterable}'s elements to {@code false}.
* <p>
* Example :
* <pre><code class='java'> Predicate<String> ballSportPredicate = sport -> sport.contains("ball");
*
* // assertion succeeds:
* assertThat(ballSportPredicate).rejectsAll(list("curling", "judo", "marathon"));
*
* // assertion fails because of football:
* assertThat(ballSportPredicate).rejectsAll(list("curling", "judo", "football"));</code></pre>
*
* @param iterable {@code Iterable} whose elements the actual {@code Predicate} should reject.
* @return this assertion object.
* @throws AssertionError if the actual {@code Predicate} accepts one of the given {@code Iterable}'s elements.
*/
public SELF rejectsAll(Iterable<? extends T> iterable) {
isNotNull();
iterables.assertNoneMatch(info, iterable, actual, PredicateDescription.GIVEN);
return myself;
}
}
|
isNotNull();
if (values.length == 1) {
if (!actual.test(values[0])) throwAssertionError(shouldAccept(actual, values[0], PredicateDescription.GIVEN));
} else iterables.assertAllMatch(info, list(values), actual, PredicateDescription.GIVEN);
return myself;
| 1,524
| 85
| 1,609
|
<methods>public ASSERT asInstanceOf(InstanceOfAssertFactory<?,ASSERT>) ,public AbstractListAssert<?,List<?>,java.lang.Object,ObjectAssert<java.lang.Object>> asList() ,public AbstractStringAssert<?> asString() ,public SELF describedAs(org.assertj.core.description.Description) ,public java.lang.String descriptionText() ,public SELF doesNotHave(Condition<? super Predicate<T>>) ,public SELF doesNotHaveSameClassAs(java.lang.Object) ,public SELF doesNotHaveSameHashCodeAs(java.lang.Object) ,public SELF doesNotHaveToString(java.lang.String) ,public transient SELF doesNotHaveToString(java.lang.String, java.lang.Object[]) ,public boolean equals(java.lang.Object) ,public org.assertj.core.api.WritableAssertionInfo getWritableAssertionInfo() ,public SELF has(Condition<? super Predicate<T>>) ,public SELF hasSameClassAs(java.lang.Object) ,public SELF hasSameHashCodeAs(java.lang.Object) ,public SELF hasToString(java.lang.String) ,public transient SELF hasToString(java.lang.String, java.lang.Object[]) ,public int hashCode() ,public SELF is(Condition<? super Predicate<T>>) ,public SELF isEqualTo(java.lang.Object) ,public SELF isExactlyInstanceOf(Class<?>) ,public transient SELF isIn(java.lang.Object[]) ,public SELF isIn(Iterable<?>) ,public SELF isInstanceOf(Class<?>) ,public transient SELF isInstanceOfAny(Class<?>[]) ,public SELF isInstanceOfSatisfying(Class<T>, Consumer<T>) ,public SELF isNot(Condition<? super Predicate<T>>) ,public SELF isNotEqualTo(java.lang.Object) ,public SELF isNotExactlyInstanceOf(Class<?>) ,public transient SELF isNotIn(java.lang.Object[]) ,public SELF isNotIn(Iterable<?>) ,public SELF isNotInstanceOf(Class<?>) ,public transient SELF isNotInstanceOfAny(Class<?>[]) ,public SELF isNotNull() ,public transient SELF isNotOfAnyClassIn(Class<?>[]) ,public SELF isNotSameAs(java.lang.Object) ,public void isNull() ,public transient SELF isOfAnyClassIn(Class<?>[]) ,public SELF isSameAs(java.lang.Object) ,public SELF matches(Predicate<? super Predicate<T>>) ,public SELF matches(Predicate<? super Predicate<T>>, java.lang.String) ,public transient SELF overridingErrorMessage(java.lang.String, java.lang.Object[]) ,public SELF overridingErrorMessage(Supplier<java.lang.String>) ,public SELF satisfies(Condition<? super Predicate<T>>) ,public final transient SELF satisfies(Consumer<? super Predicate<T>>[]) ,public final transient SELF satisfies(ThrowingConsumer<? super Predicate<T>>[]) ,public final transient SELF satisfiesAnyOf(Consumer<? super Predicate<T>>[]) ,public final transient SELF satisfiesAnyOf(ThrowingConsumer<? super Predicate<T>>[]) ,public static void setCustomRepresentation(org.assertj.core.presentation.Representation) ,public static void setDescriptionConsumer(Consumer<org.assertj.core.description.Description>) ,public static void setPrintAssertionsDescription(boolean) ,public SELF usingComparator(Comparator<? super Predicate<T>>) ,public SELF usingComparator(Comparator<? super Predicate<T>>, java.lang.String) ,public SELF usingDefaultComparator() ,public transient SELF withFailMessage(java.lang.String, java.lang.Object[]) ,public SELF withFailMessage(Supplier<java.lang.String>) ,public SELF withRepresentation(org.assertj.core.presentation.Representation) ,public SELF withThreadDumpOnError() <variables>private static final java.lang.String ORG_ASSERTJ,protected final non-sealed Predicate<T> actual,org.assertj.core.error.AssertionErrorCreator assertionErrorCreator,org.assertj.core.internal.Conditions conditions,static org.assertj.core.presentation.Representation customRepresentation,private static Consumer<org.assertj.core.description.Description> descriptionConsumer,public org.assertj.core.api.WritableAssertionInfo info,protected final non-sealed SELF myself,protected org.assertj.core.internal.Objects objects,static boolean printAssertionsDescription,public static boolean throwUnsupportedExceptionOnEquals
|
assertj_assertj
|
assertj/assertj-core/src/main/java/org/assertj/core/api/AbstractSoftAssertions.java
|
AbstractSoftAssertions
|
fail
|
class AbstractSoftAssertions extends DefaultAssertionErrorCollector
implements SoftAssertionsProvider, InstanceOfAssertFactories {
final SoftProxies proxies;
protected AbstractSoftAssertions() {
// pass itself as an AssertionErrorCollector instance
proxies = new SoftProxies(this);
}
private static final AssertionErrorCreator ASSERTION_ERROR_CREATOR = new AssertionErrorCreator();
public static void assertAll(AssertionErrorCollector collector) {
List<AssertionError> errors = collector.assertionErrorsCollected();
if (!errors.isEmpty()) throw ASSERTION_ERROR_CREATOR.multipleSoftAssertionsError(errors);
}
@Override
public void assertAll() {
assertAll(this);
}
@Override
public <SELF extends Assert<? extends SELF, ? extends ACTUAL>, ACTUAL> SELF proxy(Class<SELF> assertClass,
Class<ACTUAL> actualClass, ACTUAL actual) {
return proxies.createSoftAssertionProxy(assertClass, actualClass, actual);
}
/**
* Fails with the given message.
*
* @param <T> dummy return value type
* @param failureMessage error message.
* @return nothing, it's just to be used in {@code doSomething(optional.orElseGet(() -> softly.fail("boom")));}.
* @since 2.6.0 / 3.6.0
*/
@CanIgnoreReturnValue
public <T> T fail(String failureMessage) {
AssertionError error = Failures.instance().failure(failureMessage);
collectAssertionError(error);
return null;
}
/**
* Fails with an empty message to be used in code like:
* <pre><code class='java'> doSomething(optional.orElseGet(() -> softly.fail()));</code></pre>
*
* @param <T> dummy return value type
* @return nothing, it's just to be used in {@code doSomething(optional.orElseGet(() -> softly.fail()));}.
* @since 3.26.0
*/
@CanIgnoreReturnValue
public <T> T fail() {<FILL_FUNCTION_BODY>}
/**
* Fails with the given message built like {@link String#format(String, Object...)}.
*
* @param <T> dummy return value type
* @param failureMessage error message.
* @param args Arguments referenced by the format specifiers in the format string.
* @return nothing, it's just to be used in {@code doSomething(optional.orElseGet(() -> softly.fail("boom")));}.
* @since 2.6.0 / 3.6.0
*/
@CanIgnoreReturnValue
public <T> T fail(String failureMessage, Object... args) {
return fail(format(failureMessage, args));
}
/**
* Fails with the given message and with the {@link Throwable} that caused the failure.
*
* @param <T> dummy return value type
* @param failureMessage error message.
* @param realCause cause of the error.
* @return nothing, it's just to be used in {@code doSomething(optional.orElseGet(() -> softly.fail("boom")));}.
* @since 2.6.0 / 3.6.0
*/
@CanIgnoreReturnValue
public <T> T fail(String failureMessage, Throwable realCause) {
AssertionError error = Failures.instance().failure(failureMessage);
error.initCause(realCause);
collectAssertionError(error);
return null;
}
/**
* Fails with the {@link Throwable} that caused the failure and an empty message.
* <p>
* Example:
* <pre><code class='java'> doSomething(optional.orElseGet(() -> softly.fail(cause)));</code></pre>
*
* @param <T> dummy return value type
* @param realCause cause of the error.
* @return nothing, it's just to be used in {@code doSomething(optional.orElseGet(() -> softly.fail(cause)));}.
* @since 3.26.0
*/
@CanIgnoreReturnValue
public <T> T fail(Throwable realCause) {
return fail("", realCause);
}
/**
* Fails with a message explaining that a {@link Throwable} of given class was expected to be thrown
* but had not been.
*
* @param throwableClass the Throwable class that was expected to be thrown.
* @throws AssertionError with a message explaining that a {@link Throwable} of given class was expected to be thrown but had
* not been.
* @since 2.6.0 / 3.6.0
*
* {@link Fail#shouldHaveThrown(Class)} can be used as a replacement.
*/
public void failBecauseExceptionWasNotThrown(Class<? extends Throwable> throwableClass) {
shouldHaveThrown(throwableClass);
}
/**
* Fails with a message explaining that a {@link Throwable} of given class was expected to be thrown
* but had not been.
*
* @param throwableClass the Throwable class that was expected to be thrown.
* @throws AssertionError with a message explaining that a {@link Throwable} of given class was expected to be thrown but had
* not been.
* @since 2.6.0 / 3.6.0
*/
public void shouldHaveThrown(Class<? extends Throwable> throwableClass) {
AssertionError error = Failures.instance().expectedThrowableNotThrown(throwableClass);
collectAssertionError(error);
}
/**
* Returns a copy of list of soft assertions collected errors.
* @return a copy of list of soft assertions collected errors.
*/
public List<Throwable> errorsCollected() {
return decorateErrorsCollected(super.assertionErrorsCollected());
}
}
|
// pass an empty string because passing null results in a "null" error message.
return fail("");
| 1,584
| 28
| 1,612
|
<methods>public void <init>() ,public void addAfterAssertionErrorCollected(org.assertj.core.api.AfterAssertionErrorCollected) ,public List<java.lang.AssertionError> assertionErrorsCollected() ,public void collectAssertionError(java.lang.AssertionError) ,public Optional<org.assertj.core.api.AssertionErrorCollector> getDelegate() ,public void setAfterAssertionErrorCollected(org.assertj.core.api.AfterAssertionErrorCollected) ,public void setDelegate(org.assertj.core.api.AssertionErrorCollector) ,public void succeeded() ,public boolean wasSuccess() <variables>private final List<org.assertj.core.api.AfterAssertionErrorCollected> callbacks,private final List<java.lang.AssertionError> collectedAssertionErrors,private org.assertj.core.api.AssertionErrorCollector delegate,private volatile boolean wasSuccess
|
assertj_assertj
|
assertj/assertj-core/src/main/java/org/assertj/core/api/AbstractTemporalAssert.java
|
AbstractTemporalAssert
|
isCloseTo
|
class AbstractTemporalAssert<SELF extends AbstractTemporalAssert<SELF, TEMPORAL>, TEMPORAL extends Temporal>
extends AbstractAssert<SELF, TEMPORAL> {
@VisibleForTesting
Comparables comparables;
/**
* Creates a new <code>{@link org.assertj.core.api.AbstractTemporalAssert}</code>.
* @param selfType the "self type"
* @param actual the actual value to verify
*/
protected AbstractTemporalAssert(TEMPORAL actual, Class<?> selfType) {
super(actual, selfType);
comparables = new Comparables();
}
@VisibleForTesting
protected TEMPORAL getActual() {
return actual;
}
/**
* Verifies that the actual {@link Temporal} is close to the other according to the given {@link TemporalOffset}.
* <p>
* You can build the offset parameter using {@link Assertions#within(long, TemporalUnit)} or {@link Assertions#byLessThan(long, TemporalUnit)}.
* <p>
* Example:
* <pre><code class='java'> LocalTime _07_10 = LocalTime.of(7, 10);
* LocalTime _07_42 = LocalTime.of(7, 42);
*
* // assertions succeed:
* assertThat(_07_10).isCloseTo(_07_42, within(1, ChronoUnit.HOURS));
* assertThat(_07_10).isCloseTo(_07_42, within(32, ChronoUnit.MINUTES));
*
* // assertions fail:
* assertThat(_07_10).isCloseTo(_07_42, byLessThan(32, ChronoUnit.MINUTES));
* assertThat(_07_10).isCloseTo(_07_42, within(10, ChronoUnit.SECONDS));</code></pre>
*
* @param other the temporal to compare actual to
* @param offset the offset used for comparison
* @return this assertion object
* @throws NullPointerException if {@code Temporal} or {@code TemporalOffset} parameter is {@code null}.
* @throws AssertionError if the actual {@code Temporal} is {@code null}.
* @throws AssertionError if the actual {@code Temporal} is not close to the given one for a provided offset.
*/
public SELF isCloseTo(TEMPORAL other, TemporalOffset<? super TEMPORAL> offset) {<FILL_FUNCTION_BODY>}
/**
* Same assertion as {@link #isCloseTo(Temporal, TemporalOffset)} but the {@code TEMPORAL} is built from a given String that
* follows predefined ISO date format <a href=
* "http://docs.oracle.com/javase/8/docs/api/java/time/format/DateTimeFormatter.html"
* >Predefined Formatters</a> to allow calling {@link #parse(String)})} method.
* <p>
* Example :
* <pre><code class='java'> assertThat(LocalTime.parse("07:10:30")).isCloseTo("07:12:11", within(5, ChronoUnit.MINUTES));</code></pre>
* @param otherAsString String representing a {@code TEMPORAL}.
* @param offset the offset used for comparison
* @return this assertion object.
* @throws AssertionError if the actual {@code Temporal} is {@code null}.
* @throws NullPointerException if temporal string representation or {@code TemporalOffset} parameter is {@code null}.
* @throws AssertionError if the actual {@code Temporal} is {@code null}.
* @throws AssertionError if the actual {@code Temporal} is not close to the given within the provided offset.
*/
public SELF isCloseTo(String otherAsString, TemporalOffset<? super TEMPORAL> offset) {
requireNonNull(otherAsString, "The String representing of the temporal object to compare actual with should not be null");
return isCloseTo(parse(otherAsString), offset);
}
/**
* Obtains an instance of {@code TEMPORAL} from a string representation in ISO date format.
* @param temporalAsString the string to parse, not null
* @return the parsed {@code TEMPORAL}, not null
*/
protected abstract TEMPORAL parse(String temporalAsString);
/** {@inheritDoc} */
@Override
@CheckReturnValue
public SELF usingComparator(Comparator<? super TEMPORAL> customComparator) {
return usingComparator(customComparator, null);
}
/** {@inheritDoc} */
@Override
@CheckReturnValue
public SELF usingComparator(Comparator<? super TEMPORAL> customComparator, String customComparatorDescription) {
this.comparables = new Comparables(new ComparatorBasedComparisonStrategy(customComparator, customComparatorDescription));
return super.usingComparator(customComparator, customComparatorDescription);
}
/** {@inheritDoc} */
@Override
@CheckReturnValue
public SELF usingDefaultComparator() {
this.comparables = new Comparables();
return super.usingDefaultComparator();
}
}
|
Objects.instance().assertNotNull(info, actual);
requireNonNull(other, "The temporal object to compare actual with should not be null");
requireNonNull(offset, "The offset should not be null");
if (offset.isBeyondOffset(actual, other)) {
throw Failures.instance().failure(info,
shouldBeCloseTo(actual, other,
offset.getBeyondOffsetDifferenceDescription(actual, other)));
}
return myself;
| 1,398
| 122
| 1,520
|
<methods>public ASSERT asInstanceOf(InstanceOfAssertFactory<?,ASSERT>) ,public AbstractListAssert<?,List<?>,java.lang.Object,ObjectAssert<java.lang.Object>> asList() ,public AbstractStringAssert<?> asString() ,public SELF describedAs(org.assertj.core.description.Description) ,public java.lang.String descriptionText() ,public SELF doesNotHave(Condition<? super TEMPORAL>) ,public SELF doesNotHaveSameClassAs(java.lang.Object) ,public SELF doesNotHaveSameHashCodeAs(java.lang.Object) ,public SELF doesNotHaveToString(java.lang.String) ,public transient SELF doesNotHaveToString(java.lang.String, java.lang.Object[]) ,public boolean equals(java.lang.Object) ,public org.assertj.core.api.WritableAssertionInfo getWritableAssertionInfo() ,public SELF has(Condition<? super TEMPORAL>) ,public SELF hasSameClassAs(java.lang.Object) ,public SELF hasSameHashCodeAs(java.lang.Object) ,public SELF hasToString(java.lang.String) ,public transient SELF hasToString(java.lang.String, java.lang.Object[]) ,public int hashCode() ,public SELF is(Condition<? super TEMPORAL>) ,public SELF isEqualTo(java.lang.Object) ,public SELF isExactlyInstanceOf(Class<?>) ,public transient SELF isIn(java.lang.Object[]) ,public SELF isIn(Iterable<?>) ,public SELF isInstanceOf(Class<?>) ,public transient SELF isInstanceOfAny(Class<?>[]) ,public SELF isInstanceOfSatisfying(Class<T>, Consumer<T>) ,public SELF isNot(Condition<? super TEMPORAL>) ,public SELF isNotEqualTo(java.lang.Object) ,public SELF isNotExactlyInstanceOf(Class<?>) ,public transient SELF isNotIn(java.lang.Object[]) ,public SELF isNotIn(Iterable<?>) ,public SELF isNotInstanceOf(Class<?>) ,public transient SELF isNotInstanceOfAny(Class<?>[]) ,public SELF isNotNull() ,public transient SELF isNotOfAnyClassIn(Class<?>[]) ,public SELF isNotSameAs(java.lang.Object) ,public void isNull() ,public transient SELF isOfAnyClassIn(Class<?>[]) ,public SELF isSameAs(java.lang.Object) ,public SELF matches(Predicate<? super TEMPORAL>) ,public SELF matches(Predicate<? super TEMPORAL>, java.lang.String) ,public transient SELF overridingErrorMessage(java.lang.String, java.lang.Object[]) ,public SELF overridingErrorMessage(Supplier<java.lang.String>) ,public SELF satisfies(Condition<? super TEMPORAL>) ,public final transient SELF satisfies(Consumer<? super TEMPORAL>[]) ,public final transient SELF satisfies(ThrowingConsumer<? super TEMPORAL>[]) ,public final transient SELF satisfiesAnyOf(Consumer<? super TEMPORAL>[]) ,public final transient SELF satisfiesAnyOf(ThrowingConsumer<? super TEMPORAL>[]) ,public static void setCustomRepresentation(org.assertj.core.presentation.Representation) ,public static void setDescriptionConsumer(Consumer<org.assertj.core.description.Description>) ,public static void setPrintAssertionsDescription(boolean) ,public SELF usingComparator(Comparator<? super TEMPORAL>) ,public SELF usingComparator(Comparator<? super TEMPORAL>, java.lang.String) ,public SELF usingDefaultComparator() ,public transient SELF withFailMessage(java.lang.String, java.lang.Object[]) ,public SELF withFailMessage(Supplier<java.lang.String>) ,public SELF withRepresentation(org.assertj.core.presentation.Representation) ,public SELF withThreadDumpOnError() <variables>private static final java.lang.String ORG_ASSERTJ,protected final non-sealed TEMPORAL actual,org.assertj.core.error.AssertionErrorCreator assertionErrorCreator,org.assertj.core.internal.Conditions conditions,static org.assertj.core.presentation.Representation customRepresentation,private static Consumer<org.assertj.core.description.Description> descriptionConsumer,public org.assertj.core.api.WritableAssertionInfo info,protected final non-sealed SELF myself,protected org.assertj.core.internal.Objects objects,static boolean printAssertionsDescription,public static boolean throwUnsupportedExceptionOnEquals
|
assertj_assertj
|
assertj/assertj-core/src/main/java/org/assertj/core/api/AssumptionExceptionFactory.java
|
AssumptionExceptionFactory
|
buildAssumptionException
|
class AssumptionExceptionFactory {
private static PreferredAssumptionException preferredAssumptionException = Configuration.PREFERRED_ASSUMPTION_EXCEPTION;
static RuntimeException assumptionNotMet(AssertionError assertionError) throws ReflectiveOperationException {
Class<?> assumptionExceptionClass = preferredAssumptionException.getAssumptionExceptionClass();
return buildAssumptionException(assumptionExceptionClass, assertionError);
}
@VisibleForTesting
public static PreferredAssumptionException getPreferredAssumptionException() {
return preferredAssumptionException;
}
static void setPreferredAssumptionException(PreferredAssumptionException preferredAssumptionException) {
ConfigurationProvider.loadRegisteredConfiguration();
Objects.requireNonNull(preferredAssumptionException, "preferredAssumptionException must not be null");
AssumptionExceptionFactory.preferredAssumptionException = preferredAssumptionException;
}
private static RuntimeException buildAssumptionException(Class<?> assumptionExceptionClass,
AssertionError assertionError) throws ReflectiveOperationException {<FILL_FUNCTION_BODY>}
}
|
return (RuntimeException) assumptionExceptionClass.getConstructor(String.class, Throwable.class)
.newInstance("assumption was not met due to: "
+ assertionError.getMessage(), assertionError);
| 269
| 55
| 324
|
<no_super_class>
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.