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
|
|---|---|---|---|---|---|---|---|---|---|
apache_ignite
|
ignite/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/persistence/snapshot/dump/WriteOnlyZipFileIOFactory.java
|
WriteOnlyZipFileIOFactory
|
create
|
class WriteOnlyZipFileIOFactory extends BufferedFileIOFactory {
/** */
private static final long serialVersionUID = 0L;
/** */
public WriteOnlyZipFileIOFactory(FileIOFactory factory) {
super(factory);
}
/** {@inheritDoc} */
@Override public WriteOnlyZipFileIO create(File file, OpenOption... modes) throws IOException {<FILL_FUNCTION_BODY>}
}
|
A.ensure(file.getName().endsWith(ZIP_SUFFIX), "File name should end with " + ZIP_SUFFIX);
String entryName = file.getName().substring(0, file.getName().length() - ZIP_SUFFIX.length());
return new WriteOnlyZipFileIO(factory.create(file, modes), entryName);
| 111
| 93
| 204
|
<methods>public void <init>(org.apache.ignite.internal.processors.cache.persistence.file.FileIOFactory) ,public transient org.apache.ignite.internal.processors.cache.persistence.snapshot.dump.BufferedFileIO create(java.io.File, java.nio.file.OpenOption[]) throws java.io.IOException<variables>protected final non-sealed org.apache.ignite.internal.processors.cache.persistence.file.FileIOFactory factory,private static final long serialVersionUID
|
apache_ignite
|
ignite/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/persistence/tree/io/BPlusLeafIO.java
|
BPlusLeafIO
|
copyItems
|
class BPlusLeafIO<L> extends BPlusIO<L> {
/**
* @param type Page type.
* @param ver Page format version.
* @param itemSize Single item size on page.
*/
protected BPlusLeafIO(int type, int ver, int itemSize) {
super(type, ver, true, true, itemSize);
}
/** {@inheritDoc} */
@Override public int getMaxCount(long pageAddr, int pageSize) {
return (pageSize - ITEMS_OFF) / getItemSize();
}
/** {@inheritDoc} */
@Override public final void copyItems(long srcPageAddr, long dstPageAddr, int srcIdx, int dstIdx, int cnt,
boolean cpLeft) throws IgniteCheckedException {<FILL_FUNCTION_BODY>}
/** {@inheritDoc} */
@Override public final int offset(int idx) {
assert idx >= 0 : idx;
return ITEMS_OFF + idx * getItemSize();
}
}
|
assert srcIdx != dstIdx || srcPageAddr != dstPageAddr;
assertPageType(dstPageAddr);
PageHandler.copyMemory(srcPageAddr, offset(srcIdx), dstPageAddr, offset(dstIdx),
cnt * getItemSize());
| 265
| 77
| 342
|
<methods>public final boolean canGetRow() ,public void compactPage(java.nio.ByteBuffer, java.nio.ByteBuffer, int) ,public abstract void copyItems(long, long, int, int, int, boolean) throws org.apache.ignite.IgniteCheckedException,public final int getCount(long) ,public final long getForward(long) ,public int getFreeSpace(int, long) ,public final int getItemSize() ,public int getItemsEnd(long) ,public abstract L getLookupRow(BPlusTree<L,?>, long, int) throws org.apache.ignite.IgniteCheckedException,public abstract int getMaxCount(long, int) ,public final long getRemoveId(long) ,public void initNewPage(long, long, int, org.apache.ignite.internal.processors.cache.persistence.pagemem.PageMetrics) ,public byte[] insert(long, int, L, byte[], long, boolean) throws org.apache.ignite.IgniteCheckedException,public final boolean isLeaf() ,public boolean merge(BPlusIO<L>, long, int, long, long, boolean, int) throws org.apache.ignite.IgniteCheckedException,public abstract int offset(int) ,public void remove(long, int, int) throws org.apache.ignite.IgniteCheckedException,public void restorePage(java.nio.ByteBuffer, int) ,public final void setCount(long, int) ,public final void setForward(long, long) ,public final void setRemoveId(long, long) ,public void splitExistingPage(long, int, long) ,public void splitForwardPage(long, long, long, int, int, int, org.apache.ignite.internal.processors.cache.persistence.pagemem.PageMetrics) throws org.apache.ignite.IgniteCheckedException,public final byte[] store(long, int, L, byte[], boolean) throws org.apache.ignite.IgniteCheckedException,public abstract void store(long, int, BPlusIO<L>, long, int) throws org.apache.ignite.IgniteCheckedException,public abstract void storeByOffset(long, int, L) throws org.apache.ignite.IgniteCheckedException,public void visit(long, IgniteInClosure<L>) <variables>private static final int CNT_OFF,private static final int FORWARD_OFF,protected static final int ITEMS_OFF,private static final int REMOVE_ID_OFF,private final non-sealed boolean canGetRow,protected final non-sealed int itemSize,private final non-sealed boolean leaf
|
apache_ignite
|
ignite/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/persistence/tree/io/PagePartitionMetaIOV3.java
|
PagePartitionMetaIOV3
|
setEncryptedPageCount
|
class PagePartitionMetaIOV3 extends PagePartitionMetaIOV2 {
/** Last reencrypted page index offset. */
private static final int ENCRYPT_PAGE_IDX_OFF = GAPS_LINK + 8;
/** Total pages to be reencrypted offset. */
protected static final int ENCRYPT_PAGE_MAX_OFF = ENCRYPT_PAGE_IDX_OFF + 4;
/**
* @param ver Version.
*/
public PagePartitionMetaIOV3(int ver) {
super(ver);
}
/** {@inheritDoc} */
@Override public void initNewPage(long pageAddr, long pageId, int pageSize, PageMetrics metrics) {
super.initNewPage(pageAddr, pageId, pageSize, metrics);
setEncryptedPageIndex(pageAddr, 0);
setEncryptedPageCount(pageAddr, 0);
}
/**
* @param pageAddr Page address.
* @return Index of the last reencrypted page.
*/
@Override public int getEncryptedPageIndex(long pageAddr) {
return PageUtils.getInt(pageAddr, ENCRYPT_PAGE_IDX_OFF);
}
/**
* @param pageAddr Page address.
* @param pageIdx Index of the last reencrypted page.
*
* @return {@code true} if value has changed as a result of this method's invocation.
*/
@Override public boolean setEncryptedPageIndex(long pageAddr, int pageIdx) {
assertPageType(pageAddr);
if (getEncryptedPageIndex(pageAddr) == pageIdx)
return false;
PageUtils.putLong(pageAddr, ENCRYPT_PAGE_IDX_OFF, pageIdx);
return true;
}
/**
* @param pageAddr Page address.
* @return Total pages to be reencrypted.
*/
@Override public int getEncryptedPageCount(long pageAddr) {
return PageUtils.getInt(pageAddr, ENCRYPT_PAGE_MAX_OFF);
}
/**
* @param pageAddr Page address.
* @param pagesCnt Total pages to be reencrypted.
*
* @return {@code true} if value has changed as a result of this method's invocation.
*/
@Override public boolean setEncryptedPageCount(long pageAddr, int pagesCnt) {<FILL_FUNCTION_BODY>}
/** {@inheritDoc} */
@Override protected void printFields(long pageAddr, GridStringBuilder sb) {
super.printFields(pageAddr, sb);
sb.a(",\n\tencryptedPageIndex=").a(getEncryptedPageIndex(pageAddr))
.a(",\n\tencryptedPageCount=").a(getEncryptedPageCount(pageAddr));
}
/**
* Upgrade page to PagePartitionMetaIOV3.
*
* @param pageAddr Page address.
*/
@Override public void upgradePage(long pageAddr) {
assert PageIO.getType(pageAddr) == getType();
int ver = PageIO.getVersion(pageAddr);
assert ver < getVersion();
if (ver < 2)
super.upgradePage(pageAddr);
PageIO.setVersion(pageAddr, getVersion());
setEncryptedPageIndex(pageAddr, 0);
setEncryptedPageCount(pageAddr, 0);
}
}
|
assertPageType(pageAddr);
if (getEncryptedPageCount(pageAddr) == pagesCnt)
return false;
PageUtils.putInt(pageAddr, ENCRYPT_PAGE_MAX_OFF, pagesCnt);
return true;
| 881
| 70
| 951
|
<methods>public void <init>(int) ,public long getGapsLink(long) ,public long getPartitionMetaStoreReuseListRoot(long) ,public long getPendingTreeRoot(long) ,public void initNewPage(long, long, int, org.apache.ignite.internal.processors.cache.persistence.pagemem.PageMetrics) ,public boolean setGapsLink(long, long) ,public void setPartitionMetaStoreReuseListRoot(long, long) ,public void setPendingTreeRoot(long, long) ,public void upgradePage(long) <variables>protected static final int GAPS_LINK,public static final int PART_META_REUSE_LIST_ROOT_OFF,private static final int PENDING_TREE_ROOT_OFF
|
apache_ignite
|
ignite/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/persistence/tree/io/SimpleDataPageIO.java
|
SimpleDataPageIO
|
writeSizeFragment
|
class SimpleDataPageIO extends AbstractDataPageIO<SimpleDataRow> {
/** */
public static final IOVersions<SimpleDataPageIO> VERSIONS = new IOVersions<>(
new SimpleDataPageIO(1)
);
/**
* @param ver Page format version.
*/
public SimpleDataPageIO(int ver) {
super(T_DATA_PART, ver);
}
/**
* Constructor is intended for extending types.
* @param type IO type.
* @param ver Page format version.
*/
public SimpleDataPageIO(int type, int ver) {
super(type, ver);
}
/** {@inheritDoc} */
@Override protected void writeFragmentData(
final SimpleDataRow row,
final ByteBuffer buf,
final int rowOff,
final int payloadSize
) throws IgniteCheckedException {
assertPageType(buf);
int written = writeSizeFragment(row, buf, rowOff, payloadSize);
if (payloadSize == written)
return;
int start = rowOff > 4 ? rowOff - 4 : 0;
final int len = Math.min(row.value().length - start, payloadSize - written);
if (len > 0) {
buf.put(row.value(), start, len);
written += len;
}
assert written == payloadSize;
}
/** */
private int writeSizeFragment(final SimpleDataRow row, final ByteBuffer buf, final int rowOff,
final int payloadSize) {<FILL_FUNCTION_BODY>}
/** {@inheritDoc} */
@Override protected void writeRowData(
long pageAddr,
int dataOff,
int payloadSize,
SimpleDataRow row,
boolean newRow
) throws IgniteCheckedException {
assertPageType(pageAddr);
long addr = pageAddr + dataOff;
if (newRow)
PageUtils.putShort(addr, 0, (short)payloadSize);
PageUtils.putInt(addr, 2, row.value().length);
PageUtils.putBytes(addr, 6, row.value());
}
/** {@inheritDoc} */
@Override protected void printPage(long addr, int pageSize, GridStringBuilder sb) throws IgniteCheckedException {
sb.a("SimpleDataPageIO [\n");
printPageLayout(addr, pageSize, sb);
sb.a("\n]");
}
}
|
final int size = 4;
if (rowOff >= size)
return 0;
if (rowOff == 0 && payloadSize >= size) {
buf.putInt(row.value().length);
return size;
}
ByteBuffer buf2 = ByteBuffer.allocate(size);
buf2.order(buf.order());
buf2.putInt(row.value().length);
int len = Math.min(size - rowOff, payloadSize);
buf.put(buf2.array(), rowOff, len);
return len;
| 628
| 146
| 774
|
<methods>public void addRow(long, long, org.apache.ignite.internal.processors.cache.persistence.freelist.SimpleDataRow, int, int) throws org.apache.ignite.IgniteCheckedException,public int addRow(long, byte[], int) throws org.apache.ignite.IgniteCheckedException,public int addRowFragment(org.apache.ignite.internal.pagemem.PageMemory, long, long, org.apache.ignite.internal.processors.cache.persistence.freelist.SimpleDataRow, int, int, int) throws org.apache.ignite.IgniteCheckedException,public void addRowFragment(long, long, byte[], long, int) throws org.apache.ignite.IgniteCheckedException,public void compactPage(java.nio.ByteBuffer, java.nio.ByteBuffer, int) ,public List<U> forAllItems(long, CC<U>) throws org.apache.ignite.IgniteCheckedException,public int getDirectCount(long) ,public long getFreeListPageId(long) ,public int getFreeSpace(int, long) ,public int getFreeSpace(long) ,public int getPayloadOffset(long, int, int, int) ,public int getRealFreeSpace(long) ,public int getRowsCount(long) ,public void initNewPage(long, long, int, org.apache.ignite.internal.processors.cache.persistence.pagemem.PageMetrics) ,public boolean isEmpty(long) ,public org.apache.ignite.internal.processors.cache.persistence.tree.io.DataPagePayload readPayload(long, int, int) ,public long removeRow(long, int, int) throws org.apache.ignite.IgniteCheckedException,public void restorePage(java.nio.ByteBuffer, int) ,public void setFreeListPageId(long, long) ,public boolean updateRow(long, int, int, byte[], org.apache.ignite.internal.processors.cache.persistence.freelist.SimpleDataRow, int) throws org.apache.ignite.IgniteCheckedException<variables>private static final int DIRECT_CNT_OFF,private static final int FIRST_ENTRY_OFF,private static final int FRAGMENTED_FLAG,private static final int FREE_LIST_PAGE_ID_OFF,private static final int FREE_SPACE_OFF,private static final int INDIRECT_CNT_OFF,public static final int ITEMS_OFF,public static final int ITEM_SIZE,public static final int LINK_SIZE,public static final int MIN_DATA_PAGE_OVERHEAD,public static final int PAYLOAD_LEN_SIZE,private static final int SHOW_ITEM,private static final int SHOW_LINK,private static final int SHOW_PAYLOAD_LEN
|
apache_ignite
|
ignite/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/persistence/wal/aware/SegmentCompressStorage.java
|
SegmentCompressStorage
|
nextSegmentToCompressOrWait
|
class SegmentCompressStorage {
/** Logger. */
private final IgniteLogger log;
/** Flag of interrupt waiting on this object. */
private volatile boolean interrupted;
/** If WAL compaction enabled. */
private final boolean compactionEnabled;
/** Last successfully compressed segment. */
private volatile long lastCompressedIdx = -1L;
/** Last enqueued to compress segment. */
private long lastEnqueuedToCompressIdx = -1L;
/** Segments to compress queue. */
private final Queue<Long> segmentsToCompress = new ArrayDeque<>();
/** List of currently compressing segments. */
private final List<Long> compressingSegments = new ArrayList<>();
/** Compressed segment with maximal index. */
private long lastMaxCompressedIdx = -1L;
/**
* Constructor.
*
* @param log Logger.
* @param compactionEnabled If WAL compaction enabled.
*/
SegmentCompressStorage(IgniteLogger log, boolean compactionEnabled) {
this.log = log;
this.compactionEnabled = compactionEnabled;
}
/**
* Callback after segment compression finish.
*
* @param compressedIdx Index of compressed segment.
*/
synchronized void onSegmentCompressed(long compressedIdx) {
if (compressedIdx > lastMaxCompressedIdx)
lastMaxCompressedIdx = compressedIdx;
compressingSegments.remove(compressedIdx);
if (!compressingSegments.isEmpty())
this.lastCompressedIdx = Math.min(lastMaxCompressedIdx, compressingSegments.get(0) - 1);
else
this.lastCompressedIdx = lastMaxCompressedIdx;
notifyAll();
if (compressedIdx > lastEnqueuedToCompressIdx)
lastEnqueuedToCompressIdx = compressedIdx;
}
/**
* Method will wait activation of particular WAL segment index.
*
* @param awaitIdx absolute index {@link #lastCompressedIdx()}} to become true.
* @throws IgniteInterruptedCheckedException if interrupted.
*/
public synchronized void awaitSegmentCompressed(long awaitIdx) throws IgniteInterruptedCheckedException {
while (lastCompressedIdx() < awaitIdx && !interrupted) {
try {
wait(2000);
}
catch (InterruptedException e) {
throw new IgniteInterruptedCheckedException(e);
}
}
checkInterrupted();
}
/**
* @return Last compressed segment.
*/
long lastCompressedIdx() {
return lastCompressedIdx;
}
/**
* Pessimistically tries to reserve segment for compression in order to avoid concurrent truncation. Waits if
* there's no segment to archive right now.
*/
synchronized long nextSegmentToCompressOrWait() throws IgniteInterruptedCheckedException {<FILL_FUNCTION_BODY>}
/**
* Interrupt waiting on this object.
*/
synchronized void interrupt() {
interrupted = true;
notifyAll();
}
/**
* Check for interrupt flag was set.
*/
private void checkInterrupted() throws IgniteInterruptedCheckedException {
if (interrupted)
throw new IgniteInterruptedCheckedException("Interrupt waiting of change compressed idx");
}
/**
* Callback for waking up compressor when new segment is archived.
*/
synchronized void onSegmentArchived(long lastAbsArchivedIdx) {
while (lastEnqueuedToCompressIdx < lastAbsArchivedIdx && compactionEnabled) {
if (log.isDebugEnabled())
log.debug("Enqueuing segment for compression [idx=" + (lastEnqueuedToCompressIdx + 1) + ']');
segmentsToCompress.add(++lastEnqueuedToCompressIdx);
}
notifyAll();
}
/**
* Reset interrupted flag.
*/
public void reset() {
interrupted = false;
}
}
|
try {
while (segmentsToCompress.peek() == null && !interrupted)
wait();
}
catch (InterruptedException e) {
throw new IgniteInterruptedCheckedException(e);
}
checkInterrupted();
Long idx = segmentsToCompress.poll();
assert idx != null;
compressingSegments.add(idx);
return idx;
| 1,063
| 109
| 1,172
|
<no_super_class>
|
apache_ignite
|
ignite/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/persistence/wal/aware/SegmentCurrentStateStorage.java
|
SegmentCurrentStateStorage
|
nextAbsoluteSegmentIndex
|
class SegmentCurrentStateStorage extends SegmentObservable {
/** Flag of interrupt of waiting on this object. */
private volatile boolean interrupted;
/** Flag of force interrupt of waiting on this object. Needed for uninterrupted waiters. */
private volatile boolean forceInterrupted;
/** Total WAL segments count. */
private final int walSegmentsCnt;
/**
* Absolute current segment index WAL Manager writes to. Guarded by <code>this</code>. Incremented during rollover.
* Also may be directly set if WAL is resuming logging after start.
*/
private volatile long curAbsWalIdx = -1;
/** Last archived file absolute index. */
private volatile long lastAbsArchivedIdx = -1;
/**
* Constructor.
*
* @param walSegmentsCnt Total WAL segments count.
*/
SegmentCurrentStateStorage(int walSegmentsCnt) {
this.walSegmentsCnt = walSegmentsCnt;
}
/**
* Waiting until current WAL index will be greater or equal than given one.
*
* @param absSegIdx Target WAL index.
*/
synchronized void awaitSegment(long absSegIdx) throws IgniteInterruptedCheckedException {
try {
while (curAbsWalIdx < absSegIdx && !interrupted)
wait();
}
catch (InterruptedException e) {
throw new IgniteInterruptedCheckedException(e);
}
checkInterrupted();
}
/**
* Waiting until archivation of next segment will be allowed.
*/
synchronized long waitNextSegmentForArchivation() throws IgniteInterruptedCheckedException {
//We can archive segment if it less than current work segment so for archivate lastArchiveSegment + 1
// we should be ensure that currentWorkSegment = lastArchiveSegment + 2
awaitSegment(lastAbsArchivedIdx + 2);
return lastAbsArchivedIdx + 1;
}
/**
* Calculate next segment index or wait if needed. Uninterrupted waiting. - for force interrupt used
* forceInterrupted flag.
*
* @return Next absolute segment index.
*/
long nextAbsoluteSegmentIndex() throws IgniteInterruptedCheckedException {<FILL_FUNCTION_BODY>}
/**
* Update current WAL index.
*
* @param curAbsWalIdx New current WAL index.
*/
void curAbsWalIdx(long curAbsWalIdx) {
synchronized (this) {
this.curAbsWalIdx = curAbsWalIdx;
notifyAll();
}
notifyObservers(curAbsWalIdx);
}
/**
* @return Current WAL index.
*/
long curAbsWalIdx() {
return this.curAbsWalIdx;
}
/**
* Interrupt waiting on this object.
*/
synchronized void interrupt() {
interrupted = true;
notifyAll();
}
/**
* Interrupt waiting on this object.
*/
synchronized void forceInterrupt() {
interrupted = true;
forceInterrupted = true;
notifyAll();
}
/**
* Callback for waking up awaiting when new segment is archived.
*
* @param lastAbsArchivedIdx Last archived file absolute index.
*/
synchronized void onSegmentArchived(long lastAbsArchivedIdx) {
this.lastAbsArchivedIdx = lastAbsArchivedIdx;
notifyAll();
}
/**
* Check for interrupt flag was set.
*/
private void checkInterrupted() throws IgniteInterruptedCheckedException {
if (interrupted)
throw new IgniteInterruptedCheckedException("Interrupt waiting of change current idx");
}
/**
* Reset interrupted flag.
*/
public void reset() {
interrupted = false;
forceInterrupted = false;
}
}
|
long nextAbsIdx;
synchronized (this) {
try {
while ((curAbsWalIdx + 1) - lastAbsArchivedIdx > walSegmentsCnt && !forceInterrupted)
wait();
}
catch (InterruptedException e) {
throw new IgniteInterruptedCheckedException(e);
}
if (forceInterrupted)
throw new IgniteInterruptedCheckedException("Interrupt waiting of change archived idx");
nextAbsIdx = ++curAbsWalIdx;
notifyAll();
}
notifyObservers(nextAbsIdx);
return nextAbsIdx;
| 1,028
| 166
| 1,194
|
<methods><variables>private final Queue<Consumer<java.lang.Long>> observers
|
apache_ignite
|
ignite/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/persistence/wal/crc/FastCrc.java
|
FastCrc
|
calcCrc
|
class FastCrc {
/** CRC algo. */
private static final ThreadLocal<CRC32> CRC = ThreadLocal.withInitial(CRC32::new);
/** */
private final CRC32 crc = new CRC32();
/**
* Current value.
*/
private int val;
/** */
public FastCrc() {
reset();
}
/**
* Preparation for further calculations.
*/
public void reset() {
val = 0xffffffff;
crc.reset();
}
/**
* @return crc value.
*/
public int getValue() {
return val;
}
/**
* @param buf Input buffer.
* @param len Data length.
*/
public void update(final ByteBuffer buf, final int len) {
val = calcCrc(crc, buf, len);
}
/**
* @param buf Input buffer.
* @param len Data length.
*
* @return Crc checksum.
*/
public static int calcCrc(ByteBuffer buf, int len) {
CRC32 crcAlgo = CRC.get();
int res = calcCrc(crcAlgo, buf, len);
crcAlgo.reset();
return res;
}
/**
* @param file A file to calculate checksum over it.
* @return CRC32 checksum.
* @throws IOException If fails.
*/
public static int calcCrc(File file) throws IOException {<FILL_FUNCTION_BODY>}
/**
* @param crcAlgo CRC algorithm.
* @param buf Input buffer.
* @param len Buffer length.
*
* @return Crc checksum.
*/
private static int calcCrc(CRC32 crcAlgo, ByteBuffer buf, int len) {
int initLimit = buf.limit();
buf.limit(buf.position() + len);
crcAlgo.update(buf);
buf.limit(initLimit);
return ~(int)crcAlgo.getValue();
}
}
|
assert !file.isDirectory() : "CRC32 can't be calculated over directories";
CRC32 algo = new CRC32();
try (InputStream in = new CheckedInputStream(new FileInputStream(file), algo)) {
byte[] buf = new byte[1024];
while (in.read(buf) != -1)
;
}
return ~(int)algo.getValue();
| 562
| 112
| 674
|
<no_super_class>
|
apache_ignite
|
ignite/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/persistence/wal/filehandle/FsyncFileHandleManagerImpl.java
|
FsyncFileHandleManagerImpl
|
initHandle
|
class FsyncFileHandleManagerImpl implements FileHandleManager {
/** Context. */
protected final GridCacheSharedContext cctx;
/** Logger. */
protected final IgniteLogger log;
/** */
private final WALMode mode;
/** Persistence metrics tracker. */
private final DataStorageMetricsImpl metrics;
/** */
protected final RecordSerializer serializer;
/** Current handle supplier. */
private final Supplier<FileWriteHandle> currentHandleSupplier;
/** WAL segment size in bytes. This is maximum value, actual segments may be shorter. */
private final long maxWalSegmentSize;
/** Fsync delay. */
private final long fsyncDelay;
/** Thread local byte buffer size. */
private final int tlbSize;
/**
* @param cctx Context.
* @param metrics Data storage metrics.
* @param serializer Serializer.
* @param handle Current handle supplier.
* @param mode WAL mode.
* @param maxWalSegmentSize Max WAL segment size.
* @param fsyncDelay Fsync delay.
* @param tlbSize Thread local byte buffer size.
*/
public FsyncFileHandleManagerImpl(
GridCacheSharedContext cctx,
DataStorageMetricsImpl metrics,
RecordSerializer serializer,
Supplier<FileWriteHandle> handle,
WALMode mode,
long maxWalSegmentSize,
long fsyncDelay,
int tlbSize
) {
this.cctx = cctx;
this.log = cctx.logger(FsyncFileHandleManagerImpl.class);
this.mode = mode;
this.metrics = metrics;
this.serializer = serializer;
currentHandleSupplier = handle;
this.maxWalSegmentSize = maxWalSegmentSize;
this.fsyncDelay = fsyncDelay;
this.tlbSize = tlbSize;
}
/** {@inheritDoc} */
@Override public FileWriteHandle initHandle(SegmentIO fileIO, long position,
RecordSerializer serializer) throws IOException {<FILL_FUNCTION_BODY>}
/** {@inheritDoc} */
@Override public FileWriteHandle nextHandle(SegmentIO fileIO,
RecordSerializer serializer) throws IOException {
return new FsyncFileWriteHandle(
cctx, fileIO, metrics, serializer, 0,
mode, maxWalSegmentSize, tlbSize, fsyncDelay
);
}
/**
* @return Current handle.
*/
private FsyncFileWriteHandle currentHandle() {
return (FsyncFileWriteHandle)currentHandleSupplier.get();
}
/** {@inheritDoc} */
@Override public void onDeactivate() throws IgniteCheckedException {
FsyncFileWriteHandle currHnd = currentHandle();
if (mode == WALMode.BACKGROUND) {
if (currHnd != null)
currHnd.flushAllOnStop();
}
if (currHnd != null)
currHnd.close(false);
}
/** {@inheritDoc} */
@Override public void resumeLogging() {
//NOOP.
}
/** {@inheritDoc} */
@Override public WALPointer flush(WALPointer ptr, boolean explicitFsync) throws IgniteCheckedException, StorageException {
if (serializer == null || mode == WALMode.NONE)
return null;
FsyncFileWriteHandle cur = currentHandle();
// WAL manager was not started (client node).
if (cur == null)
return null;
WALPointer filePtr;
if (ptr == null) {
WALRecord rec = cur.head.get();
if (rec instanceof FsyncFileWriteHandle.FakeRecord)
return null;
filePtr = rec.position();
}
else
filePtr = ptr;
// No need to sync if was rolled over.
if (!cur.needFsync(filePtr))
return filePtr;
cur.fsync(filePtr, false);
return filePtr;
}
}
|
return new FsyncFileWriteHandle(
cctx, fileIO, metrics, serializer, position,
mode, maxWalSegmentSize, tlbSize, fsyncDelay
);
| 1,039
| 48
| 1,087
|
<no_super_class>
|
apache_ignite
|
ignite/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/persistence/wal/io/LockedReadFileInput.java
|
LockedReadFileInput
|
ensure
|
class LockedReadFileInput extends SimpleFileInput {
/** Segment for read. */
private final long segmentId;
/** Holder of actual information of latest manipulation on WAL segments. */
private final SegmentAware segmentAware;
/** Factory of file I/O for segment. */
private final SegmentIoFactory fileIOFactory;
/** Last read was from archive or not. */
private boolean isLastReadFromArchive;
/**
* @param buf Buffer for reading blocks of data into.
* @param initFileIo Initial File I/O for reading.
* @param segmentAware Holder of actual information of latest manipulation on WAL segments.
* @param segmentIOFactory Factory of file I/O for segment.
* @throws IOException if initFileIo would be fail during reading.
*/
LockedReadFileInput(
ByteBufferExpander buf,
SegmentIO initFileIo,
SegmentAware segmentAware,
SegmentIoFactory segmentIOFactory
) throws IOException {
super(initFileIo, buf);
this.segmentAware = segmentAware;
this.fileIOFactory = segmentIOFactory;
this.segmentId = initFileIo.getSegmentId();
isLastReadFromArchive = segmentAware.lastArchivedAbsoluteIndex() >= initFileIo.getSegmentId();
}
/** {@inheritDoc} */
@Override public void ensure(int requested) throws IOException {<FILL_FUNCTION_BODY>}
/**
* Refresh current file io.
*
* @throws IOException if old fileIO is fail during reading or new file is fail during creation.
*/
private void refreshIO() throws IOException {
FileIO io = fileIOFactory.build(segmentId);
io.position(io().position());
io().close();
this.io = io;
}
/**
* Resolving fileIo for segment.
*/
interface SegmentIoFactory {
/**
* @param segmentId Segment for IO action.
* @return {@link FileIO}.
* @throws IOException if creation would be fail.
*/
FileIO build(long segmentId) throws IOException;
}
}
|
int available = buffer().remaining();
if (available >= requested)
return;
// Segment deletion protection.
if (!segmentAware.reserve(segmentId))
throw new FileNotFoundException("Segment does not exist: " + segmentId);
try {
// Protection against transferring a segment to the archive by #archiver.
boolean readArchive = !segmentAware.lock(segmentId);
try {
if (readArchive && !isLastReadFromArchive) {
isLastReadFromArchive = true;
refreshIO();
}
super.ensure(requested);
}
finally {
if (!readArchive)
segmentAware.unlock(segmentId);
}
}
finally {
segmentAware.release(segmentId);
}
| 563
| 214
| 777
|
<methods>public void <init>(org.apache.ignite.internal.processors.cache.persistence.file.FileIO, org.apache.ignite.internal.processors.cache.persistence.wal.ByteBufferExpander) throws java.io.IOException,public java.nio.ByteBuffer buffer() ,public void ensure(int) throws java.io.IOException,public org.apache.ignite.internal.processors.cache.persistence.file.FileIO io() ,public long position() ,public boolean readBoolean() throws java.io.IOException,public byte readByte() throws java.io.IOException,public char readChar() throws java.io.IOException,public double readDouble() throws java.io.IOException,public float readFloat() throws java.io.IOException,public void readFully(byte[]) throws java.io.IOException,public void readFully(byte[], int, int) throws java.io.IOException,public int readInt() throws java.io.IOException,public java.lang.String readLine() throws java.io.IOException,public long readLong() throws java.io.IOException,public short readShort() throws java.io.IOException,public java.lang.String readUTF() throws java.io.IOException,public int readUnsignedByte() throws java.io.IOException,public int readUnsignedShort() throws java.io.IOException,public void seek(long) throws java.io.IOException,public int skipBytes(int) throws java.io.IOException,public org.apache.ignite.internal.processors.cache.persistence.wal.io.FileInput.Crc32CheckingFileInput startRead(boolean) <variables>private java.nio.ByteBuffer buf,private org.apache.ignite.internal.processors.cache.persistence.wal.ByteBufferExpander expBuf,protected org.apache.ignite.internal.processors.cache.persistence.file.FileIO io,private long pos
|
apache_ignite
|
ignite/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/persistence/wal/io/LockedSegmentFileInputFactory.java
|
LockedSegmentFileInputFactory
|
createFileInput
|
class LockedSegmentFileInputFactory implements SegmentFileInputFactory {
/** Holder of actual information of latest manipulation on WAL segments. */
private final SegmentAware segmentAware;
/** Manager of segment location. */
private final SegmentRouter segmentRouter;
/** {@link FileIO} factory definition.*/
private final FileIOFactory fileIOFactory;
/**
* @param segmentAware Holder of actual information of latest manipulation on WAL segments.
* @param segmentRouter Manager of segment location.
* @param fileIOFactory {@link FileIO} factory definition.
*/
public LockedSegmentFileInputFactory(
SegmentAware segmentAware,
SegmentRouter segmentRouter,
FileIOFactory fileIOFactory) {
this.segmentAware = segmentAware;
this.segmentRouter = segmentRouter;
this.fileIOFactory = fileIOFactory;
}
/** {@inheritDoc} */
@Override public FileInput createFileInput(SegmentIO segmentIO, ByteBufferExpander buf) throws IOException {<FILL_FUNCTION_BODY>}
}
|
return new LockedReadFileInput(
buf,
segmentIO,
segmentAware,
id -> {
FileDescriptor segment = segmentRouter.findSegment(id);
return segment.toReadOnlyIO(fileIOFactory);
}
);
| 278
| 70
| 348
|
<no_super_class>
|
apache_ignite
|
ignite/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/persistence/wal/scanner/PrintToLogHandler.java
|
PrintToLogHandler
|
finish
|
class PrintToLogHandler implements ScannerHandler {
/** */
private final IgniteLogger log;
/** */
private StringBuilder resultString = new StringBuilder();
/**
* @param log Logger.
*/
public PrintToLogHandler(IgniteLogger log) {
this.log = log;
}
/** {@inheritDoc} */
@Override public void handle(IgniteBiTuple<WALPointer, WALRecord> record) {
ensureNotFinished();
resultString
.append(DEFAULT_WAL_RECORD_PREFIX)
.append(toStringRecord(record.get2()))
.append(System.lineSeparator());
}
/** {@inheritDoc} */
@Override public void finish() {<FILL_FUNCTION_BODY>}
/**
*
*/
private void ensureNotFinished() {
if (resultString == null)
throw new IgniteException("This handler has been already finished.");
}
}
|
ensureNotFinished();
String msg = resultString.toString();
resultString = null;
if (log.isInfoEnabled())
log.info(msg);
| 251
| 48
| 299
|
<no_super_class>
|
apache_ignite
|
ignite/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/query/GridCacheQueryDetailMetricsAdapter.java
|
GridCacheQueryDetailMetricsAdapter
|
averageTime
|
class GridCacheQueryDetailMetricsAdapter implements QueryDetailMetrics, Externalizable {
/** */
private static final long serialVersionUID = 0L;
/** Query type to track metrics. */
private GridCacheQueryType qryType;
/** Textual query representation. */
private String qry;
/** Cache name. */
private String cache;
/** Number of executions. */
private int execs;
/** Number of completions executions. */
private int completions;
/** Number of failures. */
private int failures;
/** Minimum time of execution. */
private long minTime = -1;
/** Maximum time of execution. */
private long maxTime;
/** Sum of execution time of completions time. */
private long totalTime;
/** Sum of execution time of completions time. */
private long lastStartTime;
/** Cached metrics group key.*/
private GridCacheQueryDetailMetricsKey key;
/**
* Required by {@link Externalizable}.
*/
public GridCacheQueryDetailMetricsAdapter() {
// No-op.
}
/**
* Constructor with metrics.
*
* @param qryType Query type.
* @param qry Textual query representation.
* @param cache Cache name where query was executed.
* @param startTime Duration of queue execution.
* @param duration Duration of queue execution.
* @param failed {@code True} query executed unsuccessfully {@code false} otherwise.
*/
public GridCacheQueryDetailMetricsAdapter(GridCacheQueryType qryType, String qry, String cache, long startTime,
long duration, boolean failed) {
this.qryType = qryType;
this.qry = qryType == GridCacheQueryType.SCAN && qry == null ? cache : qry;
this.cache = cache;
if (failed) {
execs = 1;
failures = 1;
}
else {
execs = 1;
completions = 1;
totalTime = duration;
minTime = duration;
maxTime = duration;
}
lastStartTime = startTime;
}
/**
* Copy constructor.
*
* @param qryType Query type.
* @param qry Textual query representation.
* @param cache Cache name where query was executed.
*/
public GridCacheQueryDetailMetricsAdapter(GridCacheQueryType qryType, String qry, String cache,
int execs, int completions, int failures, long minTime, long maxTime, long totalTime, long lastStartTime,
GridCacheQueryDetailMetricsKey key) {
this.qryType = qryType;
this.qry = qry;
this.cache = cache;
this.execs = execs;
this.completions = completions;
this.failures = failures;
this.minTime = minTime;
this.maxTime = maxTime;
this.totalTime = totalTime;
this.lastStartTime = lastStartTime;
this.key = key;
}
/**
* @return Metrics group key.
*/
public GridCacheQueryDetailMetricsKey key() {
if (key == null)
key = new GridCacheQueryDetailMetricsKey(qryType, qry);
return key;
}
/**
* Aggregate metrics.
*
* @param m Other metrics to take into account.
* @return Aggregated metrics.
*/
public GridCacheQueryDetailMetricsAdapter aggregate(QueryDetailMetrics m) {
return new GridCacheQueryDetailMetricsAdapter(
qryType,
qry,
m.cache(),
execs + m.executions(),
completions + m.completions(),
failures + m.failures(),
minTime < 0 || minTime > m.minimumTime() ? m.minimumTime() : minTime,
maxTime < m.maximumTime() ? m.maximumTime() : maxTime,
totalTime + m.totalTime(),
lastStartTime < m.lastStartTime() ? m.lastStartTime() : lastStartTime,
key
);
}
/** {@inheritDoc} */
@Override public String queryType() {
return qryType.name();
}
/** {@inheritDoc} */
@Override public String query() {
return qry;
}
/** {@inheritDoc} */
@Override public String cache() {
return cache;
}
/** {@inheritDoc} */
@Override public int executions() {
return execs;
}
/** {@inheritDoc} */
@Override public int completions() {
return completions;
}
/** {@inheritDoc} */
@Override public int failures() {
return failures;
}
/** {@inheritDoc} */
@Override public long minimumTime() {
return minTime < 0 ? 0 : minTime;
}
/** {@inheritDoc} */
@Override public long maximumTime() {
return maxTime;
}
/** {@inheritDoc} */
@Override public double averageTime() {<FILL_FUNCTION_BODY>}
/** {@inheritDoc} */
@Override public long totalTime() {
return totalTime;
}
/** {@inheritDoc} */
@Override public long lastStartTime() {
return lastStartTime;
}
/** {@inheritDoc} */
@Override public void writeExternal(ObjectOutput out) throws IOException {
U.writeEnum(out, qryType);
U.writeString(out, qry);
U.writeString(out, cache);
out.writeInt(execs);
out.writeInt(completions);
out.writeLong(minTime);
out.writeLong(maxTime);
out.writeLong(totalTime);
out.writeLong(lastStartTime);
}
/** {@inheritDoc} */
@Override public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException {
qryType = GridCacheQueryType.fromOrdinal(in.readByte());
qry = U.readString(in);
cache = U.readString(in);
execs = in.readInt();
completions = in.readInt();
minTime = in.readLong();
maxTime = in.readLong();
totalTime = in.readLong();
lastStartTime = in.readLong();
}
/** {@inheritDoc} */
@Override public String toString() {
return S.toString(GridCacheQueryDetailMetricsAdapter.class, this);
}
}
|
double val = completions;
return val > 0 ? totalTime / val : 0;
| 1,674
| 27
| 1,701
|
<no_super_class>
|
apache_ignite
|
ignite/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/query/GridCacheQueryDetailMetricsKey.java
|
GridCacheQueryDetailMetricsKey
|
equals
|
class GridCacheQueryDetailMetricsKey {
/** Query type to track metrics. */
private final GridCacheQueryType qryType;
/** Textual query representation. */
private final String qry;
/** Pre-calculated hash code. */
private final int hash;
/**
* Constructor.
*
* @param qryType Query type.
* @param qry Textual query representation.
*/
public GridCacheQueryDetailMetricsKey(GridCacheQueryType qryType, String qry) {
assert qryType != null;
assert qryType != GridCacheQueryType.SQL_FIELDS || qry != null;
this.qryType = qryType;
this.qry = qry;
hash = 31 * qryType.hashCode() + (qry != null ? qry.hashCode() : 0);
}
/**
* @return Query type.
*/
public GridCacheQueryType getQueryType() {
return qryType;
}
/**
* @return Textual representation of query.
*/
public String getQuery() {
return qry;
}
/** {@inheritDoc} */
@Override public int hashCode() {
return hash;
}
/** {@inheritDoc} */
@Override public boolean equals(Object o) {<FILL_FUNCTION_BODY>}
}
|
if (this == o)
return true;
if (o == null || getClass() != o.getClass())
return false;
GridCacheQueryDetailMetricsKey other = (GridCacheQueryDetailMetricsKey)o;
return qryType == other.qryType && F.eq(qry, other.qry);
| 358
| 87
| 445
|
<no_super_class>
|
apache_ignite
|
ignite/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/query/GridCacheQueryMetricsAdapter.java
|
QueryMetricsSnapshot
|
readExternal
|
class QueryMetricsSnapshot implements QueryMetrics, Externalizable {
/** */
private static final long serialVersionUID = 0L;
/** Minimal query execution time. */
private long minTime;
/** Maximum query execution time. */
private long maxTime;
/** Average query execution time. */
private double avgTime;
/** Count of executed queries. */
private int execs;
/** Count of failed queries. */
private int fails;
/** Required by {@link Externalizable}. */
public QueryMetricsSnapshot() {
}
/**
* @param minTime Minimal query execution time.
* @param maxTime Maximum query execution time.
* @param avgTime Average query execution time.
* @param execs Count of executed queries.
* @param fails Count of failed queries.
*/
public QueryMetricsSnapshot(long minTime, long maxTime, double avgTime, int execs, int fails) {
this.minTime = minTime;
this.maxTime = maxTime;
this.avgTime = avgTime;
this.execs = execs;
this.fails = fails;
}
/** {@inheritDoc} */
@Override public void writeExternal(ObjectOutput out) throws IOException {
out.writeLong(minTime);
out.writeLong(maxTime);
out.writeDouble(avgTime);
out.writeInt(execs);
out.writeInt(fails);
}
/** {@inheritDoc} */
@Override public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException {<FILL_FUNCTION_BODY>}
/** {@inheritDoc} */
@Override public long minimumTime() {
return minTime;
}
/** {@inheritDoc} */
@Override public long maximumTime() {
return maxTime;
}
/** {@inheritDoc} */
@Override public double averageTime() {
return avgTime;
}
/** {@inheritDoc} */
@Override public int executions() {
return execs;
}
/** {@inheritDoc} */
@Override public int fails() {
return fails;
}
}
|
minTime = in.readLong();
maxTime = in.readLong();
avgTime = in.readDouble();
execs = in.readInt();
fails = in.readInt();
| 558
| 53
| 611
|
<no_super_class>
|
apache_ignite
|
ignite/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/query/GridCacheQuerySqlMetadataJobV2.java
|
GridCacheQuerySqlMetadataJobV2
|
call
|
class GridCacheQuerySqlMetadataJobV2 implements IgniteCallable<Collection<GridCacheQueryManager.CacheSqlMetadata>> {
/** */
private static final long serialVersionUID = 0L;
/** Number of fields to report when no fields defined. Includes _key and _val columns. */
private static final int NO_FIELDS_COLUMNS_COUNT = 2;
/** Grid */
@IgniteInstanceResource
private Ignite ignite;
/** {@inheritDoc} */
@Override public Collection<GridCacheQueryManager.CacheSqlMetadata> call() {<FILL_FUNCTION_BODY>}
}
|
final GridKernalContext ctx = ((IgniteKernal)ignite).context();
Collection<String> cacheNames = F.viewReadOnly(ctx.cache().caches(),
new C1<IgniteInternalCache<?, ?>, String>() {
@Override public String apply(IgniteInternalCache<?, ?> c) {
return c.name();
}
},
new P1<IgniteInternalCache<?, ?>>() {
@Override public boolean apply(IgniteInternalCache<?, ?> c) {
return !CU.isSystemCache(c.name()) && !DataStructuresProcessor.isDataStructureCache(c.name());
}
}
);
return F.transform(cacheNames, new C1<String, GridCacheQueryManager.CacheSqlMetadata>() {
@Override public GridCacheQueryManager.CacheSqlMetadata apply(String cacheName) {
Collection<GridQueryTypeDescriptor> types = ctx.query().types(cacheName);
Collection<String> names = U.newHashSet(types.size());
Map<String, String> keyClasses = U.newHashMap(types.size());
Map<String, String> valClasses = U.newHashMap(types.size());
Map<String, Map<String, String>> fields = U.newHashMap(types.size());
Map<String, Collection<GridCacheSqlIndexMetadata>> indexes = U.newHashMap(types.size());
Map<String, Set<String>> notNullFields = U.newHashMap(types.size());
for (GridQueryTypeDescriptor type : types) {
// Filter internal types (e.g., data structures).
if (type.name().startsWith("GridCache"))
continue;
names.add(type.name());
keyClasses.put(type.name(), type.keyClass().getName());
valClasses.put(type.name(), type.valueClass().getName());
int size = type.fields().isEmpty() ? NO_FIELDS_COLUMNS_COUNT : type.fields().size();
Map<String, String> fieldsMap = U.newLinkedHashMap(size);
HashSet<String> notNullFieldsSet = U.newHashSet(1);
// _KEY and _VAL are not included in GridIndexingTypeDescriptor.valueFields
if (type.fields().isEmpty()) {
fieldsMap.put("_KEY", type.keyClass().getName());
fieldsMap.put("_VAL", type.valueClass().getName());
}
for (Map.Entry<String, Class<?>> e : type.fields().entrySet()) {
String fieldName = e.getKey();
fieldsMap.put(fieldName.toUpperCase(), e.getValue().getName());
if (type.property(fieldName).notNull())
notNullFieldsSet.add(fieldName.toUpperCase());
}
fields.put(type.name(), fieldsMap);
notNullFields.put(type.name(), notNullFieldsSet);
Map<String, GridQueryIndexDescriptor> idxs = type.indexes();
Collection<GridCacheSqlIndexMetadata> indexesCol = new ArrayList<>(idxs.size());
for (Map.Entry<String, GridQueryIndexDescriptor> e : idxs.entrySet()) {
GridQueryIndexDescriptor desc = e.getValue();
// Add only SQL indexes.
if (desc.type() == QueryIndexType.SORTED) {
Collection<String> idxFields = new LinkedList<>();
Collection<String> descendings = new LinkedList<>();
for (String idxField : e.getValue().fields()) {
String idxFieldUpper = idxField.toUpperCase();
idxFields.add(idxFieldUpper);
if (desc.descending(idxField))
descendings.add(idxFieldUpper);
}
indexesCol.add(new GridCacheQueryManager.CacheSqlIndexMetadata(e.getKey().toUpperCase(),
idxFields, descendings, false));
}
}
indexes.put(type.name(), indexesCol);
}
return new GridCacheQuerySqlMetadataV2(cacheName, names, keyClasses, valClasses, fields, indexes,
notNullFields);
}
});
| 152
| 1,049
| 1,201
|
<no_super_class>
|
apache_ignite
|
ignite/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/query/IndexQueryDesc.java
|
IndexQueryDesc
|
toString
|
class IndexQueryDesc implements Serializable {
/** */
private static final long serialVersionUID = 0L;
/** */
private final List<IndexQueryCriterion> criteria;
/** */
private final String idxName;
/** */
private final String valType;
/** */
public IndexQueryDesc(List<IndexQueryCriterion> criteria, String idxName, String valType) {
this.criteria = criteria;
this.idxName = idxName;
this.valType = valType;
}
/** */
public List<IndexQueryCriterion> criteria() {
return criteria;
}
/** */
public String idxName() {
return idxName;
}
/** */
public String valType() {
return valType;
}
/** */
@Override public String toString() {<FILL_FUNCTION_BODY>}
}
|
List<String> fields = criteria == null ? null : criteria.stream().map(IndexQueryCriterion::field).collect(Collectors.toList());
return "IndexQuery[" +
"idxName=" + idxName + ", " +
"valType=" + valType + ", " +
"fields=" + fields + "]";
| 234
| 88
| 322
|
<no_super_class>
|
apache_ignite
|
ignite/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/query/QueryEntityTypeDescriptor.java
|
QueryEntityTypeDescriptor
|
addIndex
|
class QueryEntityTypeDescriptor {
/** Value field names and types with preserved order. */
@GridToStringInclude
private final Map<String, Class<?>> fields = new LinkedHashMap<>();
/** */
@GridToStringExclude
private final Map<String, QueryEntityClassProperty> props = new LinkedHashMap<>();
/** */
@GridToStringInclude
private final Set<String> keyProps = new HashSet<>();
/** */
@GridToStringInclude
private final Map<String, QueryEntityIndexDescriptor> indexes = new HashMap<>();
/** */
private Set<String> notNullFields = new HashSet<>();
/** Precision information. */
private Map<String, Integer> fieldsPrecision = new HashMap<>();
/** Scale information. */
private Map<String, Integer> fieldsScale = new HashMap<>();
/** */
private QueryEntityIndexDescriptor fullTextIdx;
/** */
private final Class<?> keyCls;
/** */
private final Class<?> valCls;
/** */
private boolean valTextIdx;
/**
* Constructor.
*
* @param keyCls QueryEntity key class.
* @param valCls QueryEntity value class.
*/
public QueryEntityTypeDescriptor(@NotNull Class<?> keyCls, @NotNull Class<?> valCls) {
this.keyCls = keyCls;
this.valCls = valCls;
}
/**
* @return Indexes.
*/
public Map<String, GridQueryIndexDescriptor> indexes() {
return Collections.<String, GridQueryIndexDescriptor>unmodifiableMap(indexes);
}
/**
* Adds index.
*
* @param idxName Index name.
* @param type Index type.
* @param inlineSize Inline size.
* @return Index descriptor.
*/
public QueryEntityIndexDescriptor addIndex(String idxName, QueryIndexType type, int inlineSize) {<FILL_FUNCTION_BODY>}
/**
* Adds field to index.
*
* @param idxName Index name.
* @param field Field name.
* @param orderNum Fields order number in index.
* @param descending Sorting order.
*/
public void addFieldToIndex(String idxName, String field, int orderNum,
boolean descending) {
QueryEntityIndexDescriptor desc = indexes.get(idxName);
if (desc == null)
desc = addIndex(idxName, QueryIndexType.SORTED, QueryIndex.DFLT_INLINE_SIZE);
desc.addField(field, orderNum, descending);
}
/**
* Adds field to text index.
*
* @param field Field name.
*/
public void addFieldToTextIndex(String field) {
if (fullTextIdx == null) {
fullTextIdx = new QueryEntityIndexDescriptor(QueryIndexType.FULLTEXT);
indexes.put(null, fullTextIdx);
}
fullTextIdx.addField(field, 0, false);
}
/**
* @return Value class.
*/
public Class<?> valueClass() {
return valCls;
}
/**
* @return Key class.
*/
public Class<?> keyClass() {
return keyCls;
}
/**
* Adds property to the type descriptor.
*
* @param prop Property.
* @param sqlAnn SQL annotation, can be {@code null}.
* @param key Property ownership flag (key or not).
* @param failOnDuplicate Fail on duplicate flag.
*/
public void addProperty(QueryEntityClassProperty prop, QuerySqlField sqlAnn, boolean key, boolean failOnDuplicate) {
String propName = prop.name();
if (sqlAnn != null && !F.isEmpty(sqlAnn.name()))
propName = sqlAnn.name();
if (props.put(propName, prop) != null && failOnDuplicate) {
throw new CacheException("Property with name '" + propName + "' already exists for " +
(key ? "key" : "value") + ": " +
"QueryEntity [key=" + keyCls.getName() + ", value=" + valCls.getName() + ']');
}
fields.put(prop.fullName(), prop.type());
if (key)
keyProps.add(prop.fullName());
}
/**
* Adds a notNull field.
*
* @param field notNull field.
*/
public void addNotNullField(String field) {
notNullFields.add(field);
}
/**
* Adds fieldsPrecision info.
*
* @param field Field.
* @param precision Precision.
*/
public void addPrecision(String field, Integer precision) {
fieldsPrecision.put(field, precision);
}
/**
* Adds fieldsScale info.
*
* @param field Field.
* @param scale Scale.
*/
public void addScale(String field, int scale) {
fieldsScale.put(field, scale);
}
/**
* @return notNull fields.
*/
public Set<String> notNullFields() {
return notNullFields;
}
/**
* @return Precision info for fields.
*/
public Map<String, Integer> fieldsPrecision() {
return fieldsPrecision;
}
/**
* @return Scale info for fields.
*/
public Map<String, Integer> fieldsScale() {
return fieldsScale;
}
/**
* @return Class properties.
*/
public Map<String, QueryEntityClassProperty> properties() {
return props;
}
/**
* @return Properties keys.
*/
public Set<String> keyProperties() {
return keyProps;
}
/**
* @return {@code true} If we need to have a fulltext index on value.
*/
public boolean valueTextIndex() {
return valTextIdx;
}
/**
* Sets if this value should be text indexed.
*
* @param valTextIdx Flag value.
*/
public void valueTextIndex(boolean valTextIdx) {
this.valTextIdx = valTextIdx;
}
/** {@inheritDoc} */
@Override public String toString() {
return S.toString(QueryEntityTypeDescriptor.class, this);
}
}
|
if (inlineSize < 0 && inlineSize != QueryIndex.DFLT_INLINE_SIZE)
throw new CacheException("Illegal inline size [idxName=" + idxName + ", inlineSize=" + inlineSize + ']');
QueryEntityIndexDescriptor idx = new QueryEntityIndexDescriptor(type, inlineSize);
if (indexes.put(idxName, idx) != null)
throw new CacheException("Index with name '" + idxName + "' already exists.");
return idx;
| 1,684
| 123
| 1,807
|
<no_super_class>
|
apache_ignite
|
ignite/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/query/continuous/CacheContinuousQueryEvent.java
|
CacheContinuousQueryEvent
|
toString
|
class CacheContinuousQueryEvent<K, V> extends CacheQueryEntryEvent<K, V> {
/** */
private static final long serialVersionUID = 0L;
/** */
private final GridCacheContext cctx;
/** Entry. */
@GridToStringExclude
private final CacheContinuousQueryEntry e;
/**
* @param src Source cache.
* @param cctx Cache context.
* @param e Entry.
*/
CacheContinuousQueryEvent(Cache src, GridCacheContext cctx, CacheContinuousQueryEntry e) {
super(src, e.eventType());
this.cctx = cctx;
this.e = e;
}
/**
* @return Entry.
*/
CacheContinuousQueryEntry entry() {
return e;
}
/**
* @return Partition ID.
*/
public int partitionId() {
return e.partition();
}
/** {@inheritDoc} */
@Override public K getKey() {
return (K)cctx.cacheObjectContext().unwrapBinaryIfNeeded(e.key(), e.isKeepBinary(), false, null);
}
/** {@inheritDoc} */
@Override protected V getNewValue() {
return (V)cctx.cacheObjectContext().unwrapBinaryIfNeeded(e.newValue(), e.isKeepBinary(), false, null);
}
/** {@inheritDoc} */
@Override public V getOldValue() {
return (V)cctx.cacheObjectContext().unwrapBinaryIfNeeded(e.oldValue(), e.isKeepBinary(), false, null);
}
/** {@inheritDoc} */
@Override public boolean isOldValueAvailable() {
return e.oldValue() != null;
}
/** {@inheritDoc} */
@Override public long getPartitionUpdateCounter() {
return e.updateCounter();
}
/** {@inheritDoc} */
@Override public String toString() {<FILL_FUNCTION_BODY>}
}
|
return S.toString(CacheContinuousQueryEvent.class, this,
"evtType", getEventType(), false,
"key", getKey(), true,
"newVal", getValue(), true,
"oldVal", getOldValue(), true,
"partCntr", getPartitionUpdateCounter(), false);
| 516
| 82
| 598
|
<methods>public void <init>(Cache, EventType) ,public abstract long getPartitionUpdateCounter() <variables>
|
apache_ignite
|
ignite/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/query/reducer/TextQueryReducer.java
|
TextQueryReducer
|
pageComparator
|
class TextQueryReducer<R> extends MergeSortCacheQueryReducer<R> {
/** */
private static final long serialVersionUID = 0L;
/** */
public TextQueryReducer(final Map<UUID, NodePageStream<R>> pageStreams) {
super(pageStreams);
}
/** {@inheritDoc} */
@Override protected CompletableFuture<Comparator<NodePage<R>>> pageComparator() {<FILL_FUNCTION_BODY>}
}
|
CompletableFuture<Comparator<NodePage<R>>> f = new CompletableFuture<>();
f.complete((o1, o2) -> -Float.compare(
((ScoredCacheEntry<?, ?>)o1.head()).score(), ((ScoredCacheEntry<?, ?>)o2.head()).score()));
return f;
| 128
| 88
| 216
|
<methods>public boolean hasNextX() throws org.apache.ignite.IgniteCheckedException,public R nextX() throws org.apache.ignite.IgniteCheckedException<variables>private PriorityQueue<NodePage<R>> nodePages,private java.util.UUID pendingNodeId,private static final long serialVersionUID
|
apache_ignite
|
ignite/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/transactions/IgniteTxKey.java
|
IgniteTxKey
|
equals
|
class IgniteTxKey implements Message {
/** */
private static final long serialVersionUID = 0L;
/** Key. */
@GridToStringInclude(sensitive = true)
private KeyCacheObject key;
/** Cache ID. */
private int cacheId;
/**
* Empty constructor required for {@link Externalizable}.
*/
public IgniteTxKey() {
// No-op.
}
/**
* @param key User key.
* @param cacheId Cache ID.
*/
public IgniteTxKey(KeyCacheObject key, int cacheId) {
this.key = key;
this.cacheId = cacheId;
}
/**
* @return User key.
*/
public KeyCacheObject key() {
return key;
}
/**
* @return Cache ID.
*/
public int cacheId() {
return cacheId;
}
/**
* @param ctx Context.
* @throws IgniteCheckedException If failed.
*/
public void prepareMarshal(GridCacheContext ctx) throws IgniteCheckedException {
key.prepareMarshal(ctx.cacheObjectContext());
}
/**
* @param ctx Context.
* @param ldr Class loader.
* @throws IgniteCheckedException If failed.
*/
public void finishUnmarshal(GridCacheContext ctx, ClassLoader ldr) throws IgniteCheckedException {
assert key != null;
key.finishUnmarshal(ctx.cacheObjectContext(), ldr);
}
/** {@inheritDoc} */
@Override public void onAckReceived() {
// No-op.
}
/** {@inheritDoc} */
@Override public boolean equals(Object o) {<FILL_FUNCTION_BODY>}
/** {@inheritDoc} */
@Override public int hashCode() {
int res = key.hashCode();
res = 31 * res + cacheId;
return res;
}
/** {@inheritDoc} */
@Override public boolean writeTo(ByteBuffer buf, MessageWriter writer) {
writer.setBuffer(buf);
if (!writer.isHeaderWritten()) {
if (!writer.writeHeader(directType(), fieldsCount()))
return false;
writer.onHeaderWritten();
}
switch (writer.state()) {
case 0:
if (!writer.writeInt("cacheId", cacheId))
return false;
writer.incrementState();
case 1:
if (!writer.writeMessage("key", key))
return false;
writer.incrementState();
}
return true;
}
/** {@inheritDoc} */
@Override public boolean readFrom(ByteBuffer buf, MessageReader reader) {
reader.setBuffer(buf);
if (!reader.beforeMessageRead())
return false;
switch (reader.state()) {
case 0:
cacheId = reader.readInt("cacheId");
if (!reader.isLastRead())
return false;
reader.incrementState();
case 1:
key = reader.readMessage("key");
if (!reader.isLastRead())
return false;
reader.incrementState();
}
return reader.afterMessageRead(IgniteTxKey.class);
}
/** {@inheritDoc} */
@Override public short directType() {
return 94;
}
/** {@inheritDoc} */
@Override public byte fieldsCount() {
return 2;
}
/** {@inheritDoc} */
@Override public String toString() {
return S.toString(IgniteTxKey.class, this);
}
}
|
if (this == o)
return true;
if (!(o instanceof IgniteTxKey))
return false;
IgniteTxKey that = (IgniteTxKey)o;
return cacheId == that.cacheId && key.equals(that.key);
| 958
| 71
| 1,029
|
<no_super_class>
|
apache_ignite
|
ignite/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/transactions/TxDeadlock.java
|
TxDeadlock
|
toString
|
class TxDeadlock {
/** Key prefix. */
private static final String KEY_PREFIX = "K";
/** Tx prefix. */
private static final String TX_PREFIX = "TX";
/** Tx locked keys. */
private final Map<GridCacheVersion, Set<IgniteTxKey>> txLockedKeys;
/** Tx requested keys. */
private final Map<IgniteTxKey, Set<GridCacheVersion>> txRequestedKeys;
/** Cycle. */
private final List<GridCacheVersion> cycle;
/** Transactions data: nearNodeId and threadId. */
private final Map<GridCacheVersion, T2<UUID, Long>> txs;
/**
* @param cycle Cycle.
* @param txs Transactions.
* @param txLockedKeys Tx locked keys.
* @param txRequestedKeys Tx requested keys.
*/
public TxDeadlock(
List<GridCacheVersion> cycle,
Map<GridCacheVersion, T2<UUID, Long>> txs,
Map<GridCacheVersion, Set<IgniteTxKey>> txLockedKeys,
Map<IgniteTxKey, Set<GridCacheVersion>> txRequestedKeys
) {
this.cycle = cycle;
this.txLockedKeys = txLockedKeys;
this.txRequestedKeys = txRequestedKeys;
this.txs = txs;
}
/**
* @return Deadlock represented as cycle of transaction in wait-for-graph.
*/
public List<GridCacheVersion> cycle() {
return cycle;
}
/**
* @param ctx Context.
*/
public String toString(GridCacheSharedContext ctx) {<FILL_FUNCTION_BODY>}
/**
* @param id Id.
* @param prefix Prefix.
* @param map Map.
*/
private static <T> String label(T id, String prefix, Map<T, String> map) {
String lb = map.get(id);
if (lb == null)
map.put(id, lb = prefix + (map.size() + 1));
return lb;
}
}
|
assert cycle != null && !cycle.isEmpty();
assert cycle.size() >= 3; // At least 2 transactions in cycle and the last is waiting for the first.
Map<IgniteTxKey, String> keyLabels = U.newLinkedHashMap(cycle.size() - 1);
Map<GridCacheVersion, String> txLabels = U.newLinkedHashMap(cycle.size() - 1);
StringBuilder sb = new StringBuilder("\nDeadlock detected:\n\n");
for (int i = cycle.size() - 1; i > 0; i--) {
GridCacheVersion txId = cycle.get(i);
Set<IgniteTxKey> keys = txLockedKeys.get(txId);
for (IgniteTxKey key : keys) {
Set<GridCacheVersion> txIds = txRequestedKeys.get(key);
if (txIds == null || txIds.isEmpty())
continue;
GridCacheVersion waitsTx = null;
for (GridCacheVersion ver : txIds) {
if (cycle.contains(ver)) {
waitsTx = ver;
break;
}
}
if (waitsTx != null) {
sb.append(label(key, KEY_PREFIX, keyLabels)).append(": ")
.append(label(txId, TX_PREFIX, txLabels)).append(" holds lock, ")
.append(label(waitsTx, TX_PREFIX, txLabels)).append(" waits lock.\n");
}
}
}
sb.append("\nTransactions:\n\n");
for (Map.Entry<GridCacheVersion, String> e : txLabels.entrySet()) {
T2<UUID, Long> tx = txs.get(e.getKey());
sb.append(e.getValue()).append(" [txId=").append(e.getKey())
.append(", nodeId=").append(tx.get1()).append(", threadId=").append(tx.get2())
.append("]\n");
}
sb.append("\nKeys:\n\n");
for (Map.Entry<IgniteTxKey, String> e : keyLabels.entrySet()) {
IgniteTxKey txKey = e.getKey();
try {
GridCacheContext cctx = ctx.cacheContext(txKey.cacheId());
Object val = txKey.key().value(cctx.cacheObjectContext(), true);
sb.append(e.getValue())
.append(" [");
if (S.includeSensitive())
sb.append("key=")
.append(val)
.append(", ");
sb.append("cache=")
.append(cctx.name())
.append("]\n");
}
catch (Exception ex) {
sb.append("Unable to unmarshall deadlock information for key [key=").append(e.getValue()).append("]\n");
}
}
return sb.toString();
| 546
| 758
| 1,304
|
<no_super_class>
|
apache_ignite
|
ignite/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/transactions/TxLocksRequest.java
|
TxLocksRequest
|
prepareMarshal
|
class TxLocksRequest extends GridCacheMessage {
/** Serial version UID. */
private static final long serialVersionUID = 0L;
/** Future ID. */
private long futId;
/** Tx keys. */
@GridToStringInclude
@GridDirectTransient
private Set<IgniteTxKey> txKeys;
/** Array of txKeys from {@link #txKeys}. Used during marshalling and unmarshalling. */
@GridToStringExclude
private IgniteTxKey[] txKeysArr;
/**
* Default constructor.
*/
public TxLocksRequest() {
// No-op.
}
/**
* @param futId Future ID.
* @param txKeys Target tx keys.
*/
public TxLocksRequest(long futId, Set<IgniteTxKey> txKeys) {
A.notEmpty(txKeys, "txKeys");
this.futId = futId;
this.txKeys = txKeys;
}
/** {@inheritDoc} */
@Override public int handlerId() {
return 0;
}
/** {@inheritDoc} */
@Override public boolean cacheGroupMessage() {
return false;
}
/**
* @return Future ID.
*/
public long futureId() {
return futId;
}
/**
* @return Tx keys.
*/
public Collection<IgniteTxKey> txKeys() {
return txKeys;
}
/** {@inheritDoc} */
@Override public String toString() {
return S.toString(TxLocksRequest.class, this);
}
/** {@inheritDoc} */
@Override public boolean addDeploymentInfo() {
return addDepInfo;
}
/** {@inheritDoc} */
@Override public void prepareMarshal(GridCacheSharedContext ctx) throws IgniteCheckedException {<FILL_FUNCTION_BODY>}
/** {@inheritDoc} */
@Override public void finishUnmarshal(GridCacheSharedContext ctx, ClassLoader ldr) throws IgniteCheckedException {
super.finishUnmarshal(ctx, ldr);
txKeys = U.newHashSet(txKeysArr.length);
for (IgniteTxKey key : txKeysArr) {
key.finishUnmarshal(ctx.cacheContext(key.cacheId()), ldr);
txKeys.add(key);
}
txKeysArr = null;
}
/** {@inheritDoc} */
@Override public boolean writeTo(ByteBuffer buf, MessageWriter writer) {
writer.setBuffer(buf);
if (!super.writeTo(buf, writer))
return false;
if (!writer.isHeaderWritten()) {
if (!writer.writeHeader(directType(), fieldsCount()))
return false;
writer.onHeaderWritten();
}
switch (writer.state()) {
case 3:
if (!writer.writeLong("futId", futId))
return false;
writer.incrementState();
case 4:
if (!writer.writeObjectArray("txKeysArr", txKeysArr, MessageCollectionItemType.MSG))
return false;
writer.incrementState();
}
return true;
}
/** {@inheritDoc} */
@Override public boolean readFrom(ByteBuffer buf, MessageReader reader) {
reader.setBuffer(buf);
if (!reader.beforeMessageRead())
return false;
if (!super.readFrom(buf, reader))
return false;
switch (reader.state()) {
case 3:
futId = reader.readLong("futId");
if (!reader.isLastRead())
return false;
reader.incrementState();
case 4:
txKeysArr = reader.readObjectArray("txKeysArr", MessageCollectionItemType.MSG, IgniteTxKey.class);
if (!reader.isLastRead())
return false;
reader.incrementState();
}
return reader.afterMessageRead(TxLocksRequest.class);
}
/** {@inheritDoc} */
@Override public short directType() {
return -24;
}
/** {@inheritDoc} */
@Override public byte fieldsCount() {
return 5;
}
/** {@inheritDoc} */
@Override public void onAckReceived() {
// No-op.
}
}
|
super.prepareMarshal(ctx);
txKeysArr = new IgniteTxKey[txKeys.size()];
int i = 0;
for (IgniteTxKey key : txKeys) {
key.prepareMarshal(ctx.cacheContext(key.cacheId()));
txKeysArr[i++] = key;
}
| 1,144
| 91
| 1,235
|
<methods>public non-sealed void <init>() ,public abstract boolean addDeploymentInfo() ,public abstract boolean cacheGroupMessage() ,public org.apache.ignite.IgniteCheckedException classError() ,public org.apache.ignite.internal.managers.deployment.GridDeploymentInfo deployInfo() ,public java.lang.Throwable error() ,public byte fieldsCount() ,public void finishUnmarshal(GridCacheSharedContext#RAW, java.lang.ClassLoader) throws org.apache.ignite.IgniteCheckedException,public final void finishUnmarshalCacheObjects(List<? extends org.apache.ignite.internal.processors.cache.CacheObject>, GridCacheContext#RAW, java.lang.ClassLoader) throws org.apache.ignite.IgniteCheckedException,public abstract int handlerId() ,public boolean ignoreClassErrors() ,public org.apache.ignite.internal.processors.affinity.AffinityTopologyVersion lastAffinityChangedTopologyVersion() ,public void lastAffinityChangedTopologyVersion(org.apache.ignite.internal.processors.affinity.AffinityTopologyVersion) ,public int lookupIndex() ,public long messageId() ,public org.apache.ignite.IgniteLogger messageLogger(GridCacheSharedContext#RAW) ,public static int nextIndexId() ,public void onAckReceived() ,public void onClassError(org.apache.ignite.IgniteCheckedException) ,public int partition() ,public boolean partitionExchangeMessage() ,public final void prepare(org.apache.ignite.internal.managers.deployment.GridDeploymentInfo) ,public void prepareMarshal(GridCacheSharedContext#RAW) throws org.apache.ignite.IgniteCheckedException,public final void prepareMarshalCacheObjects(List<? extends org.apache.ignite.internal.processors.cache.CacheObject>, GridCacheContext#RAW) throws org.apache.ignite.IgniteCheckedException,public boolean readFrom(java.nio.ByteBuffer, org.apache.ignite.plugin.extensions.communication.MessageReader) ,public java.lang.String toString() ,public org.apache.ignite.internal.processors.affinity.AffinityTopologyVersion topologyVersion() ,public boolean writeTo(java.nio.ByteBuffer, org.apache.ignite.plugin.extensions.communication.MessageWriter) <variables>public static final java.lang.String CACHE_MSG_INDEX_FIELD_NAME,public static final int MAX_CACHE_MSG_LOOKUP_INDEX,private static final long NULL_MSG_ID,protected boolean addDepInfo,private org.apache.ignite.internal.managers.deployment.GridDeploymentInfoBean depInfo,private org.apache.ignite.IgniteCheckedException err,protected boolean forceAddDepInfo,private org.apache.ignite.internal.processors.affinity.AffinityTopologyVersion lastAffChangedTopVer,private long msgId,private static final java.util.concurrent.atomic.AtomicInteger msgIdx,private static final long serialVersionUID,private boolean skipPrepare
|
apache_ignite
|
ignite/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/tree/AbstractDataLeafIO.java
|
AbstractDataLeafIO
|
visit
|
class AbstractDataLeafIO extends BPlusLeafIO<CacheSearchRow> implements RowLinkIO {
/**
* @param type Page type.
* @param ver Page format version.
* @param itemSize Single item size on page.
*/
public AbstractDataLeafIO(int type, int ver, int itemSize) {
super(type, ver, itemSize);
}
/** {@inheritDoc} */
@Override public void storeByOffset(long pageAddr, int off, CacheSearchRow row) {
assert row.link() != 0;
assertPageType(pageAddr);
PageUtils.putLong(pageAddr, off, row.link());
off += 8;
PageUtils.putInt(pageAddr, off, row.hash());
off += 4;
if (storeCacheId()) {
assert row.cacheId() != CU.UNDEFINED_CACHE_ID;
PageUtils.putInt(pageAddr, off, row.cacheId());
off += 4;
}
}
/** {@inheritDoc} */
@Override public void store(long dstPageAddr, int dstIdx, BPlusIO<CacheSearchRow> srcIo, long srcPageAddr,
int srcIdx) {
assertPageType(dstPageAddr);
RowLinkIO rowIo = (RowLinkIO)srcIo;
long link = rowIo.getLink(srcPageAddr, srcIdx);
int hash = rowIo.getHash(srcPageAddr, srcIdx);
int off = offset(dstIdx);
PageUtils.putLong(dstPageAddr, off, link);
off += 8;
PageUtils.putInt(dstPageAddr, off, hash);
off += 4;
if (storeCacheId()) {
int cacheId = rowIo.getCacheId(srcPageAddr, srcIdx);
assert cacheId != CU.UNDEFINED_CACHE_ID;
PageUtils.putInt(dstPageAddr, off, cacheId);
off += 4;
}
}
/** {@inheritDoc} */
@Override public final CacheSearchRow getLookupRow(BPlusTree<CacheSearchRow, ?> tree, long pageAddr, int idx)
throws IgniteCheckedException {
long link = getLink(pageAddr, idx);
int hash = getHash(pageAddr, idx);
int cacheId = storeCacheId() ? getCacheId(pageAddr, idx) : CU.UNDEFINED_CACHE_ID;
return ((CacheDataTree)tree).rowStore().keySearchRow(cacheId, hash, link);
}
/** {@inheritDoc} */
@Override public final long getLink(long pageAddr, int idx) {
assert idx < getCount(pageAddr) : "idx=" + idx + ", cnt=" + getCount(pageAddr);
return PageUtils.getLong(pageAddr, offset(idx));
}
/** {@inheritDoc} */
@Override public final int getHash(long pageAddr, int idx) {
return PageUtils.getInt(pageAddr, offset(idx) + 8);
}
/** {@inheritDoc} */
@Override public void visit(long pageAddr, IgniteInClosure<CacheSearchRow> c) {<FILL_FUNCTION_BODY>}
/**
* @return {@code True} if cache ID has to be stored.
*/
public boolean storeCacheId() {
return false;
}
}
|
assertPageType(pageAddr);
int cnt = getCount(pageAddr);
for (int i = 0; i < cnt; i++)
c.apply(new CacheDataRowAdapter(getLink(pageAddr, i)));
| 886
| 63
| 949
|
<methods>public final void copyItems(long, long, int, int, int, boolean) throws org.apache.ignite.IgniteCheckedException,public int getMaxCount(long, int) ,public final int offset(int) <variables>
|
apache_ignite
|
ignite/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/tree/AbstractPendingEntryLeafIO.java
|
AbstractPendingEntryLeafIO
|
store
|
class AbstractPendingEntryLeafIO extends BPlusLeafIO<PendingRow> implements PendingRowIO {
/**
* @param type Page type.
* @param ver Page format version.
* @param itemSize Single item size on page.
*/
AbstractPendingEntryLeafIO(int type, int ver, int itemSize) {
super(type, ver, itemSize);
}
/** {@inheritDoc} */
@Override public void storeByOffset(long pageAddr, int off, PendingRow row) throws IgniteCheckedException {
assert row.link != 0;
assert row.expireTime != 0;
assertPageType(pageAddr);
PageUtils.putLong(pageAddr, off, row.expireTime);
PageUtils.putLong(pageAddr, off + 8, row.link);
if (storeCacheId()) {
assert row.cacheId != CU.UNDEFINED_CACHE_ID;
PageUtils.putInt(pageAddr, off + 16, row.cacheId);
}
}
/** {@inheritDoc} */
@Override public void store(long dstPageAddr,
int dstIdx,
BPlusIO<PendingRow> srcIo,
long srcPageAddr,
int srcIdx) throws IgniteCheckedException {<FILL_FUNCTION_BODY>}
/** {@inheritDoc} */
@Override public PendingRow getLookupRow(BPlusTree<PendingRow, ?> tree, long pageAddr, int idx)
throws IgniteCheckedException {
return new PendingRow(getCacheId(pageAddr, idx), getExpireTime(pageAddr, idx), getLink(pageAddr, idx));
}
/** {@inheritDoc} */
@Override public long getExpireTime(long pageAddr, int idx) {
return PageUtils.getLong(pageAddr, offset(idx));
}
/** {@inheritDoc} */
@Override public long getLink(long pageAddr, int idx) {
return PageUtils.getLong(pageAddr, offset(idx) + 8);
}
/**
* @return {@code True} if cache ID has to be stored.
*/
protected abstract boolean storeCacheId();
}
|
assertPageType(dstPageAddr);
int dstOff = offset(dstIdx);
long link = ((PendingRowIO)srcIo).getLink(srcPageAddr, srcIdx);
long expireTime = ((PendingRowIO)srcIo).getExpireTime(srcPageAddr, srcIdx);
PageUtils.putLong(dstPageAddr, dstOff, expireTime);
PageUtils.putLong(dstPageAddr, dstOff + 8, link);
if (storeCacheId()) {
int cacheId = ((PendingRowIO)srcIo).getCacheId(srcPageAddr, srcIdx);
assert cacheId != CU.UNDEFINED_CACHE_ID;
PageUtils.putInt(dstPageAddr, dstOff + 16, cacheId);
}
| 563
| 215
| 778
|
<methods>public final void copyItems(long, long, int, int, int, boolean) throws org.apache.ignite.IgniteCheckedException,public int getMaxCount(long, int) ,public final int offset(int) <variables>
|
apache_ignite
|
ignite/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/tree/CacheDataRowStore.java
|
CacheDataRowStore
|
dataRow
|
class CacheDataRowStore extends RowStore {
/** Whether version should be skipped. */
private static final ThreadLocal<Boolean> SKIP_VER = ThreadLocal.withInitial(() -> false);
/**
* @return Skip version flag.
*/
public static boolean getSkipVersion() {
return SKIP_VER.get();
}
/**
* @param skipVer Skip version flag.
*/
public static void setSkipVersion(boolean skipVer) {
SKIP_VER.set(skipVer);
}
/** */
private final int partId;
/**
* @param grp Cache group.
* @param freeList Free list.
* @param partId Partition number.
*/
public CacheDataRowStore(CacheGroupContext grp, FreeList freeList, int partId) {
super(grp, freeList);
this.partId = partId;
}
/**
* @return Partition Id.
*/
public int getPartitionId() {
return partId;
}
/**
* @param cacheId Cache ID.
* @param hash Hash code.
* @param link Link.
* @return Search row.
*/
protected CacheSearchRow keySearchRow(int cacheId, int hash, long link) {
return dataRow(cacheId, hash, link, CacheDataRowAdapter.RowData.KEY_ONLY);
}
/**
* @param cacheId Cache ID.
* @param hash Hash code.
* @param link Link.
* @param rowData Required row data.
* @return Data row.
*/
protected CacheDataRow dataRow(int cacheId, int hash, long link, CacheDataRowAdapter.RowData rowData) {<FILL_FUNCTION_BODY>}
/**
* @param dataRow Data row.
* @param cacheId Cache ID.
*/
private <T extends DataRow> T initDataRow(T dataRow, int cacheId) {
if (dataRow.cacheId() == CU.UNDEFINED_CACHE_ID && grp.sharedGroup())
dataRow.cacheId(cacheId);
return dataRow;
}
}
|
DataRow dataRow = new DataRow(
grp,
hash,
link,
partId,
rowData,
SKIP_VER.get()
);
return initDataRow(dataRow, cacheId);
| 558
| 63
| 621
|
<methods>public void <init>(org.apache.ignite.internal.processors.cache.CacheGroupContext, FreeList#RAW) ,public void addRow(org.apache.ignite.internal.processors.cache.persistence.CacheDataRow, org.apache.ignite.internal.metric.IoStatisticsHolder) throws org.apache.ignite.IgniteCheckedException,public void addRows(Collection<? extends org.apache.ignite.internal.processors.cache.persistence.CacheDataRow>, org.apache.ignite.internal.metric.IoStatisticsHolder) throws org.apache.ignite.IgniteCheckedException,public FreeList#RAW freeList() ,public void removeRow(long, org.apache.ignite.internal.metric.IoStatisticsHolder) throws org.apache.ignite.IgniteCheckedException,public void setRowCacheCleaner(Supplier<org.apache.ignite.internal.processors.query.GridQueryRowCacheCleaner>) ,public void updateDataRow(long, PageHandler<S,R>, S, org.apache.ignite.internal.metric.IoStatisticsHolder) throws org.apache.ignite.IgniteCheckedException,public boolean updateRow(long, org.apache.ignite.internal.processors.cache.persistence.CacheDataRow, org.apache.ignite.internal.metric.IoStatisticsHolder) throws org.apache.ignite.IgniteCheckedException<variables>protected final non-sealed org.apache.ignite.internal.processors.cache.CacheObjectContext coctx,private final non-sealed GridCacheSharedContext#RAW ctx,private final non-sealed FreeList#RAW freeList,protected final non-sealed org.apache.ignite.internal.processors.cache.CacheGroupContext grp,protected final non-sealed org.apache.ignite.internal.pagemem.PageMemory pageMem,private final non-sealed boolean persistenceEnabled,private volatile Supplier<org.apache.ignite.internal.processors.query.GridQueryRowCacheCleaner> rowCacheCleaner
|
apache_ignite
|
ignite/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/tree/PendingEntriesTree.java
|
PendingEntriesTree
|
compare
|
class PendingEntriesTree extends BPlusTree<PendingRow, PendingRow> {
/** */
public static final Object WITHOUT_KEY = new Object();
/** */
private final CacheGroupContext grp;
/**
* @param grp Cache group.
* @param name Tree name.
* @param pageMem Page memory.
* @param metaPageId Meta page ID.
* @param reuseList Reuse list.
* @param initNew Initialize new index.
* @param pageLockTrackerManager Page lock tracker manager.
* @param pageFlag Default flag value for allocated pages.
* @throws IgniteCheckedException If failed.
*/
public PendingEntriesTree(
CacheGroupContext grp,
String name,
PageMemory pageMem,
long metaPageId,
ReuseList reuseList,
boolean initNew,
PageLockTrackerManager pageLockTrackerManager,
byte pageFlag
) throws IgniteCheckedException {
super(
name,
grp.groupId(),
grp.name(),
pageMem,
grp.dataRegion().config().isPersistenceEnabled() ? grp.shared().wal() : null,
grp.offheap().globalRemoveId(),
metaPageId,
reuseList,
grp.sharedGroup() ? CacheIdAwarePendingEntryInnerIO.VERSIONS : PendingEntryInnerIO.VERSIONS,
grp.sharedGroup() ? CacheIdAwarePendingEntryLeafIO.VERSIONS : PendingEntryLeafIO.VERSIONS,
pageFlag,
grp.shared().kernalContext().failure(),
pageLockTrackerManager
);
this.grp = grp;
assert !grp.dataRegion().config().isPersistenceEnabled() || grp.shared().database().checkpointLockIsHeldByThread();
initTree(initNew);
}
/** {@inheritDoc} */
@Override protected int compare(BPlusIO<PendingRow> iox, long pageAddr, int idx, PendingRow row) {<FILL_FUNCTION_BODY>}
/** {@inheritDoc} */
@Override public PendingRow getRow(BPlusIO<PendingRow> io, long pageAddr, int idx, Object flag)
throws IgniteCheckedException {
PendingRow row = io.getLookupRow(this, pageAddr, idx);
return flag == WITHOUT_KEY ? row : row.initKey(grp);
}
}
|
PendingRowIO io = (PendingRowIO)iox;
int cmp;
if (grp.sharedGroup()) {
assert row.cacheId != CU.UNDEFINED_CACHE_ID : "Cache ID is not provided!";
assert io.getCacheId(pageAddr, idx) != CU.UNDEFINED_CACHE_ID : "Cache ID is not stored!";
cmp = Integer.compare(io.getCacheId(pageAddr, idx), row.cacheId);
if (cmp != 0)
return cmp;
if (row.expireTime == 0 && row.link == 0) {
// A search row with a cache ID only is used as a cache bound.
// The found position will be shifted until the exact cache bound is found;
// See for details:
// o.a.i.i.p.c.database.tree.BPlusTree.ForwardCursor.findLowerBound()
// o.a.i.i.p.c.database.tree.BPlusTree.ForwardCursor.findUpperBound()
return cmp;
}
}
long expireTime = io.getExpireTime(pageAddr, idx);
cmp = Long.compare(expireTime, row.expireTime);
if (cmp != 0)
return cmp;
if (row.link == 0L)
return 0;
long link = io.getLink(pageAddr, idx);
return Long.compare(link, row.link);
| 628
| 391
| 1,019
|
<methods>public final long destroy() throws org.apache.ignite.IgniteCheckedException,public final long destroy(IgniteInClosure<org.apache.ignite.internal.processors.cache.tree.PendingRow>, boolean) throws org.apache.ignite.IgniteCheckedException,public boolean destroyed() ,public void enableSequentialWriteMode() ,public final GridCursor<org.apache.ignite.internal.processors.cache.tree.PendingRow> find(org.apache.ignite.internal.processors.cache.tree.PendingRow, org.apache.ignite.internal.processors.cache.tree.PendingRow) throws org.apache.ignite.IgniteCheckedException,public final GridCursor<org.apache.ignite.internal.processors.cache.tree.PendingRow> find(org.apache.ignite.internal.processors.cache.tree.PendingRow, org.apache.ignite.internal.processors.cache.tree.PendingRow, java.lang.Object) throws org.apache.ignite.IgniteCheckedException,public GridCursor<org.apache.ignite.internal.processors.cache.tree.PendingRow> find(org.apache.ignite.internal.processors.cache.tree.PendingRow, org.apache.ignite.internal.processors.cache.tree.PendingRow, TreeRowClosure<org.apache.ignite.internal.processors.cache.tree.PendingRow,org.apache.ignite.internal.processors.cache.tree.PendingRow>, java.lang.Object) throws org.apache.ignite.IgniteCheckedException,public GridCursor<org.apache.ignite.internal.processors.cache.tree.PendingRow> find(org.apache.ignite.internal.processors.cache.tree.PendingRow, org.apache.ignite.internal.processors.cache.tree.PendingRow, boolean, boolean, TreeRowClosure<org.apache.ignite.internal.processors.cache.tree.PendingRow,org.apache.ignite.internal.processors.cache.tree.PendingRow>, TreeRowFactory<org.apache.ignite.internal.processors.cache.tree.PendingRow,org.apache.ignite.internal.processors.cache.tree.PendingRow>, java.lang.Object) throws org.apache.ignite.IgniteCheckedException,public org.apache.ignite.internal.processors.cache.tree.PendingRow findFirst() throws org.apache.ignite.IgniteCheckedException,public org.apache.ignite.internal.processors.cache.tree.PendingRow findFirst(TreeRowClosure<org.apache.ignite.internal.processors.cache.tree.PendingRow,org.apache.ignite.internal.processors.cache.tree.PendingRow>) throws org.apache.ignite.IgniteCheckedException,public org.apache.ignite.internal.processors.cache.tree.PendingRow findLast() throws org.apache.ignite.IgniteCheckedException,public org.apache.ignite.internal.processors.cache.tree.PendingRow findLast(TreeRowClosure<org.apache.ignite.internal.processors.cache.tree.PendingRow,org.apache.ignite.internal.processors.cache.tree.PendingRow>) throws org.apache.ignite.IgniteCheckedException,public final R findOne(org.apache.ignite.internal.processors.cache.tree.PendingRow, java.lang.Object) throws org.apache.ignite.IgniteCheckedException,public final R findOne(org.apache.ignite.internal.processors.cache.tree.PendingRow, TreeRowClosure<org.apache.ignite.internal.processors.cache.tree.PendingRow,org.apache.ignite.internal.processors.cache.tree.PendingRow>, java.lang.Object) throws org.apache.ignite.IgniteCheckedException,public final org.apache.ignite.internal.processors.cache.tree.PendingRow findOne(org.apache.ignite.internal.processors.cache.tree.PendingRow) throws org.apache.ignite.IgniteCheckedException,public long getMetaPageId() ,public final org.apache.ignite.internal.processors.cache.tree.PendingRow getRow(BPlusIO<org.apache.ignite.internal.processors.cache.tree.PendingRow>, long, int) throws org.apache.ignite.IgniteCheckedException,public abstract org.apache.ignite.internal.processors.cache.tree.PendingRow getRow(BPlusIO<org.apache.ignite.internal.processors.cache.tree.PendingRow>, long, int, java.lang.Object) throws org.apache.ignite.IgniteCheckedException,public static void interruptAll() ,public void invoke(org.apache.ignite.internal.processors.cache.tree.PendingRow, java.lang.Object, InvokeClosure<org.apache.ignite.internal.processors.cache.tree.PendingRow>) throws org.apache.ignite.IgniteCheckedException,public final boolean isEmpty() throws org.apache.ignite.IgniteCheckedException,public void iterate(org.apache.ignite.internal.processors.cache.tree.PendingRow, org.apache.ignite.internal.processors.cache.tree.PendingRow, TreeRowClosure<org.apache.ignite.internal.processors.cache.tree.PendingRow,org.apache.ignite.internal.processors.cache.tree.PendingRow>) throws org.apache.ignite.IgniteCheckedException,public final BPlusInnerIO<org.apache.ignite.internal.processors.cache.tree.PendingRow> latestInnerIO() ,public final BPlusLeafIO<org.apache.ignite.internal.processors.cache.tree.PendingRow> latestLeafIO() ,public boolean markDestroyed() ,public final java.lang.String printTree() throws org.apache.ignite.IgniteCheckedException,public final org.apache.ignite.internal.processors.cache.tree.PendingRow put(org.apache.ignite.internal.processors.cache.tree.PendingRow) throws org.apache.ignite.IgniteCheckedException,public boolean putx(org.apache.ignite.internal.processors.cache.tree.PendingRow) throws org.apache.ignite.IgniteCheckedException,public final org.apache.ignite.internal.processors.cache.tree.PendingRow remove(org.apache.ignite.internal.processors.cache.tree.PendingRow) throws org.apache.ignite.IgniteCheckedException,public List<org.apache.ignite.internal.processors.cache.tree.PendingRow> remove(org.apache.ignite.internal.processors.cache.tree.PendingRow, org.apache.ignite.internal.processors.cache.tree.PendingRow, int) throws org.apache.ignite.IgniteCheckedException,public final boolean removex(org.apache.ignite.internal.processors.cache.tree.PendingRow) throws org.apache.ignite.IgniteCheckedException,public final int rootLevel() throws org.apache.ignite.IgniteCheckedException,public void setIos(IOVersions<? extends BPlusInnerIO<org.apache.ignite.internal.processors.cache.tree.PendingRow>>, IOVersions<? extends BPlusLeafIO<org.apache.ignite.internal.processors.cache.tree.PendingRow>>) ,public final long size() throws org.apache.ignite.IgniteCheckedException,public long size(TreeRowClosure<org.apache.ignite.internal.processors.cache.tree.PendingRow,org.apache.ignite.internal.processors.cache.tree.PendingRow>) throws org.apache.ignite.IgniteCheckedException,public java.lang.String toString() ,public static java.lang.String treeName(java.lang.String, java.lang.String) ,public final void validateTree() throws org.apache.ignite.IgniteCheckedException,public void visit(org.apache.ignite.internal.processors.cache.tree.PendingRow, org.apache.ignite.internal.processors.cache.tree.PendingRow, TreeVisitorClosure<org.apache.ignite.internal.processors.cache.tree.PendingRow,org.apache.ignite.internal.processors.cache.tree.PendingRow>) throws org.apache.ignite.IgniteCheckedException<variables>public static final java.lang.String CONC_DESTROY_MSG,private static final java.lang.Object[] EMPTY,public static final int IGNITE_BPLUS_TREE_LOCK_RETRIES_DEFAULT,private static final int LOCK_RETRIES,private final PageHandler<java.lang.Long,org.apache.ignite.internal.processors.cache.persistence.tree.BPlusTree.Bool> addRoot,private final non-sealed PageHandler<Get,org.apache.ignite.internal.processors.cache.persistence.tree.BPlusTree.Result> askNeighbor,private boolean canGetRowFromInner,private final PageHandler<java.lang.Void,org.apache.ignite.internal.processors.cache.persistence.tree.BPlusTree.Bool> cutRoot,private final java.util.concurrent.atomic.AtomicBoolean destroyed,private final non-sealed org.apache.ignite.internal.processors.failure.FailureProcessor failureProcessor,private final non-sealed java.util.concurrent.atomic.AtomicLong globalRmvId,private final PageHandler<java.lang.Long,org.apache.ignite.internal.processors.cache.persistence.tree.BPlusTree.Bool> initRoot,private IOVersions<? extends BPlusInnerIO<org.apache.ignite.internal.processors.cache.tree.PendingRow>> innerIos,private final non-sealed PageHandler<Put,org.apache.ignite.internal.processors.cache.persistence.tree.BPlusTree.Result> insert,private static volatile boolean interrupted,private IOVersions<? extends BPlusLeafIO<org.apache.ignite.internal.processors.cache.tree.PendingRow>> leafIos,private final non-sealed PageHandler<Remove,org.apache.ignite.internal.processors.cache.persistence.tree.BPlusTree.Result> lockBackAndRmvFromLeaf,private final non-sealed PageHandler<Remove,org.apache.ignite.internal.processors.cache.persistence.tree.BPlusTree.Result> lockBackAndTail,private final non-sealed PageHandler<Remove,org.apache.ignite.internal.processors.cache.persistence.tree.BPlusTree.Result> lockTail,private final non-sealed PageHandler<Update,org.apache.ignite.internal.processors.cache.persistence.tree.BPlusTree.Result> lockTailExact,private final non-sealed PageHandler<Remove,org.apache.ignite.internal.processors.cache.persistence.tree.BPlusTree.Result> lockTailForward,private final non-sealed float maxFill,protected final non-sealed long metaPageId,private final non-sealed float minFill,private final non-sealed PageHandler<Put,org.apache.ignite.internal.processors.cache.persistence.tree.BPlusTree.Result> replace,private final non-sealed PageHandler<Remove,org.apache.ignite.internal.processors.cache.persistence.tree.BPlusTree.Result> rmvFromLeaf,private final non-sealed PageHandler<Remove,org.apache.ignite.internal.processors.cache.persistence.tree.BPlusTree.Result> rmvRangeFromLeaf,private final non-sealed PageHandler<Get,org.apache.ignite.internal.processors.cache.persistence.tree.BPlusTree.Result> search,private boolean sequentialWriteOptsEnabled,public static final ThreadLocal<java.lang.Boolean> suspendFailureDiagnostic,public static PageHandlerWrapper<org.apache.ignite.internal.processors.cache.persistence.tree.BPlusTree.Result> testHndWrapper,private volatile org.apache.ignite.internal.processors.cache.persistence.tree.BPlusTree.TreeMetaData treeMeta,private final GridTreePrinter<java.lang.Long> treePrinter
|
apache_ignite
|
ignite/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/verify/RetrieveConflictPartitionValuesTask.java
|
RetrieveConflictValuesJob
|
execute
|
class RetrieveConflictValuesJob extends ComputeJobAdapter {
/** */
private static final long serialVersionUID = 0L;
/** Ignite instance. */
@IgniteInstanceResource
private IgniteEx ignite;
/** Injected logger. */
@LoggerResource
private IgniteLogger log;
/** Partition hash record. */
private PartitionHashRecord partHashRecord;
/** Entry hash records. */
private List<PartitionEntryHashRecord> entryHashRecords;
/** Partition key. */
private PartitionKey partKey;
/**
* @param arg Partition key.
*/
private RetrieveConflictValuesJob(T2<PartitionHashRecord, List<PartitionEntryHashRecord>> arg) {
partHashRecord = arg.get1();
entryHashRecords = arg.get2();
partKey = partHashRecord.partitionKey();
}
/** {@inheritDoc} */
@Override public Map<PartitionHashRecord, List<PartitionEntryHashRecord>> execute() throws IgniteException {<FILL_FUNCTION_BODY>}
}
|
CacheGroupContext grpCtx = ignite.context().cache().cacheGroup(partKey.groupId());
if (grpCtx == null)
return Collections.emptyMap();
GridDhtLocalPartition part = grpCtx.topology().localPartition(partKey.partitionId());
if (part == null || !part.reserve())
return Collections.emptyMap();
HashMap<Integer, GridCacheContext> cacheIdToCtx = new HashMap<>();
for (GridCacheContext ctx : grpCtx.caches())
cacheIdToCtx.put(ctx.cacheId(), ctx);
try {
if (part.state() != GridDhtPartitionState.OWNING)
return Collections.emptyMap();
if (part.updateCounter() != partHashRecord.updateCounter()) {
throw new IgniteException("Cluster is not idle: update counter of partition " + partKey.toString() +
" changed during hash calculation [before=" + partHashRecord.updateCounter() +
", after=" + part.updateCounter() + "]");
}
for (PartitionEntryHashRecord entryHashRecord : entryHashRecords) {
GridCacheContext ctx = cacheIdToCtx.get(entryHashRecord.cacheId());
if (ctx == null)
continue;
KeyCacheObject key = grpCtx.shared().kernalContext().cacheObjects().toKeyCacheObject(
grpCtx.cacheObjectContext(), entryHashRecord.key().cacheObjectType(), entryHashRecord.keyBytes());
CacheDataRow row = part.dataStore().find(ctx, key);
if (row == null)
continue;
CacheObject val = row.value();
Object o = CacheObjectUtils.unwrapBinaryIfNeeded(grpCtx.cacheObjectContext(), val, true, true);
if (o != null)
entryHashRecord.valueString(o.toString());
entryHashRecord.valueBytes(row.value().valueBytes(grpCtx.cacheObjectContext()));
}
}
catch (IgniteCheckedException e) {
U.error(log, "Can't retrieve value for partition " + partKey.toString(), e);
return Collections.emptyMap();
}
finally {
part.release();
}
return new T2<>(partHashRecord, entryHashRecords);
| 272
| 596
| 868
|
<methods>public non-sealed void <init>() ,public org.apache.ignite.compute.ComputeJobResultPolicy result(org.apache.ignite.compute.ComputeJobResult, List<org.apache.ignite.compute.ComputeJobResult>) throws org.apache.ignite.IgniteException<variables>private static final long serialVersionUID
|
apache_ignite
|
ignite/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/version/GridCacheVersionConflictContext.java
|
GridCacheVersionConflictContext
|
toString
|
class GridCacheVersionConflictContext<K, V> {
/** Old entry. */
@GridToStringInclude
private final GridCacheVersionedEntry<K, V> oldEntry;
/** New entry. */
@GridToStringInclude
private final GridCacheVersionedEntry<K, V> newEntry;
/** Object context. */
private final CacheObjectValueContext ctx;
/** Current state. */
private State state;
/** Current merge value. */
@GridToStringExclude
private V mergeVal;
/** TTL. */
private long ttl;
/** Expire time. */
private long expireTime;
/** Manual resolve flag. */
private boolean manualResolve;
/**
* Constructor.
*
* @param oldEntry Old entry.
* @param newEntry New entry.
*/
public GridCacheVersionConflictContext(CacheObjectValueContext ctx, GridCacheVersionedEntry<K, V> oldEntry,
GridCacheVersionedEntry<K, V> newEntry) {
assert oldEntry != null && newEntry != null;
assert oldEntry.ttl() >= 0 && newEntry.ttl() >= 0;
this.oldEntry = oldEntry;
this.newEntry = newEntry;
this.ctx = ctx;
// Set initial state.
useNew();
}
/**
* Gets old (existing) cache entry.
*
* @return Old (existing) cache entry.
*/
public GridCacheVersionedEntry<K, V> oldEntry() {
return oldEntry;
}
/**
* Gets new cache entry.
*
* @return New cache entry.
*/
public GridCacheVersionedEntry<K, V> newEntry() {
return newEntry;
}
/**
* Gets cache object context.
*
* @return Cache object context.
*/
public CacheObjectValueContext valueContext() {
return ctx;
}
/**
* Force cache to ignore new entry and leave old (existing) entry unchanged.
*/
public void useOld() {
state = State.USE_OLD;
}
/**
* Force cache to apply new entry overwriting old (existing) entry.
*/
public void useNew() {
state = State.USE_NEW;
ttl = newEntry.ttl();
}
/**
* Force cache to use neither old, nor new, but some other value passed as argument. In this case old
* value will be replaced with merge value and update will be considered as local.
* <p>
* Also in case of merge you have to specify new TTL and expire time explicitly. For unlimited TTL use {@code 0}.
*
* @param mergeVal Merge value or {@code null} to force remove.
* @param ttl Time to live in milliseconds (must be non-negative).
* @param expireTime Expire time.
*/
public void merge(@Nullable V mergeVal, long ttl, long expireTime) {
if (ttl < 0)
throw new IllegalArgumentException("TTL must be non-negative: " + ttl);
state = State.MERGE;
this.mergeVal = mergeVal;
this.ttl = ttl;
this.expireTime = expireTime;
}
/**
* @return {@code True} in case old value should be used.
*/
public boolean isUseOld() {
return state == State.USE_OLD;
}
/**
* @return {@code True} in case new value should be used.
*/
public boolean isUseNew() {
return state == State.USE_NEW;
}
/**
* @return {@code True} in case merge is to be performed.
*/
public boolean isMerge() {
return state == State.MERGE;
}
/**
* Set manual resolve class.
*/
public void manualResolve() {
this.manualResolve = true;
}
/**
* @return Manual resolve flag.
*/
public boolean isManualResolve() {
return manualResolve;
}
/**
* @return Value to merge (if any).
*/
@Nullable public V mergeValue() {
return mergeVal;
}
/**
* @return TTL.
*/
public long ttl() {
return ttl;
}
/**
* @return Expire time.
*/
public long expireTime() {
return isUseNew() ? newEntry.expireTime() : isUseOld() ? oldEntry.expireTime() : expireTime;
}
/** {@inheritDoc} */
@Override public String toString() {<FILL_FUNCTION_BODY>}
/**
* State.
*/
private enum State {
/** Use old. */
USE_OLD,
/** Use new. */
USE_NEW,
/** Merge. */
MERGE
}
}
|
return state == State.MERGE ?
S.toString(GridCacheVersionConflictContext.class, this, "mergeValue", mergeVal, true) :
S.toString(GridCacheVersionConflictContext.class, this);
| 1,288
| 58
| 1,346
|
<no_super_class>
|
apache_ignite
|
ignite/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/warmup/WarmUpMXBeanImpl.java
|
WarmUpMXBeanImpl
|
stopWarmUp
|
class WarmUpMXBeanImpl implements WarmUpMXBean {
/** Cache processor. */
@GridToStringExclude
private final GridCacheProcessor cacheProc;
/**
* Constructor.
*
* @param cacheProc Cache processor.
*/
public WarmUpMXBeanImpl(GridCacheProcessor cacheProc) {
this.cacheProc = cacheProc;
}
/** {@inheritDoc} */
@Override public void stopWarmUp() {<FILL_FUNCTION_BODY>}
/** {@inheritDoc} */
@Override public String toString() {
return S.toString(WarmUpMXBeanImpl.class, this);
}
}
|
try {
cacheProc.stopWarmUp();
}
catch (IgniteCheckedException e) {
throw new IgniteException(e);
}
| 179
| 46
| 225
|
<no_super_class>
|
apache_ignite
|
ignite/modules/core/src/main/java/org/apache/ignite/internal/processors/cluster/BaselineTopologyHistory.java
|
BaselineTopologyHistory
|
restoreHistory
|
class BaselineTopologyHistory implements Serializable {
/** */
private static final long serialVersionUID = 0L;
/** */
private static final String METASTORE_BLT_HIST_PREFIX = "bltHist-";
/** */
private final Queue<BaselineTopologyHistoryItem> bufferedForStore =
new ConcurrentLinkedQueue<>();
/** */
private final List<BaselineTopologyHistoryItem> hist = new ArrayList<>();
/** */
void restoreHistory(ReadOnlyMetastorage metastorage, int lastId) throws IgniteCheckedException {<FILL_FUNCTION_BODY>}
/** */
BaselineTopologyHistory tailFrom(int id) {
BaselineTopologyHistory tail = new BaselineTopologyHistory();
for (BaselineTopologyHistoryItem item : hist) {
if (item.id() >= id)
tail.hist.add(item);
}
return tail;
}
/** */
void writeHistoryItem(ReadWriteMetastorage metastorage, BaselineTopologyHistoryItem histItem)
throws IgniteCheckedException {
if (histItem == null)
return;
hist.add(histItem);
metastorage.write(METASTORE_BLT_HIST_PREFIX + histItem.id(), histItem);
}
/** */
void removeHistory(ReadWriteMetastorage metastorage) throws IgniteCheckedException {
if (hist.isEmpty())
return;
for (BaselineTopologyHistoryItem histItem : hist)
metastorage.remove(METASTORE_BLT_HIST_PREFIX + histItem.id());
hist.clear();
}
/** */
boolean isCompatibleWith(BaselineTopology blt) {
BaselineTopologyHistoryItem histBlt = hist.get(blt.id());
return histBlt.branchingHistory().contains(blt.branchingPointHash());
}
/** */
boolean isEmpty() {
return hist.isEmpty();
}
/** */
void bufferHistoryItemForStore(BaselineTopologyHistoryItem histItem) {
hist.add(histItem);
bufferedForStore.add(histItem);
}
/** */
public List<BaselineTopologyHistoryItem> history() {
return Collections.unmodifiableList(hist);
}
/** */
void flushHistoryItems(ReadWriteMetastorage metastorage) throws IgniteCheckedException {
while (!bufferedForStore.isEmpty()) {
BaselineTopologyHistoryItem item = bufferedForStore.remove();
metastorage.write(METASTORE_BLT_HIST_PREFIX + item.id(), item);
}
}
}
|
for (int i = 0; i < lastId; i++) {
BaselineTopologyHistoryItem histItem = (BaselineTopologyHistoryItem)metastorage.read(METASTORE_BLT_HIST_PREFIX + i);
if (histItem != null)
hist.add(histItem);
else
throw new IgniteCheckedException("Restoring of BaselineTopology history has failed, " +
"expected history item not found for id=" + i
);
}
| 704
| 129
| 833
|
<no_super_class>
|
apache_ignite
|
ignite/modules/core/src/main/java/org/apache/ignite/internal/processors/cluster/ClientSetClusterStateComputeRequest.java
|
ClientSetClusterStateComputeRequest
|
run
|
class ClientSetClusterStateComputeRequest implements IgniteRunnable {
/** */
private static final long serialVersionUID = 0L;
/** */
private final ClusterState state;
/** If {@code true}, cluster deactivation will be forced. */
private final boolean forceDeactivation;
/** */
private final BaselineTopology baselineTopology;
/** */
private final boolean forceChangeBaselineTopology;
/** Ignite. */
@IgniteInstanceResource
private IgniteEx ig;
/**
* @param state New cluster state.
* @param forceDeactivation If {@code true}, cluster deactivation will be forced.
* @param blt New baseline topology.
* @param forceBlt Force change cluster state.
*/
ClientSetClusterStateComputeRequest(
ClusterState state,
boolean forceDeactivation,
BaselineTopology blt,
boolean forceBlt
) {
this.state = state;
this.baselineTopology = blt;
this.forceChangeBaselineTopology = forceBlt;
this.forceDeactivation = forceDeactivation;
}
/** {@inheritDoc} */
@Override public void run() {<FILL_FUNCTION_BODY>}
}
|
try {
ig.context().state().changeGlobalState(
state,
forceDeactivation,
baselineTopology != null ? baselineTopology.currentBaseline() : null,
forceChangeBaselineTopology
).get();
}
catch (IgniteCheckedException ex) {
throw new IgniteException(ex);
}
| 323
| 91
| 414
|
<no_super_class>
|
apache_ignite
|
ignite/modules/core/src/main/java/org/apache/ignite/internal/processors/cluster/ClusterNodeMetrics.java
|
ClusterNodeMetrics
|
cacheMetrics
|
class ClusterNodeMetrics implements Serializable {
/** */
private static final long serialVersionUID = 0L;
/** */
private final byte[] metrics;
/** */
private final Map<Integer, CacheMetrics> cacheMetrics;
/**
* @param metrics Metrics.
* @param cacheMetrics Cache metrics.
*/
ClusterNodeMetrics(ClusterMetrics metrics, Map<Integer, CacheMetrics> cacheMetrics) {
this.metrics = ClusterMetricsSnapshot.serialize(metrics);
this.cacheMetrics = cacheMetrics;
}
/**
* @return Metrics.
*/
byte[] metrics() {
return metrics;
}
/**
* @return Cache metrics.
*/
Map<Integer, CacheMetrics> cacheMetrics() {<FILL_FUNCTION_BODY>}
}
|
return cacheMetrics != null ? cacheMetrics : Collections.<Integer, CacheMetrics>emptyMap();
| 210
| 27
| 237
|
<no_super_class>
|
apache_ignite
|
ignite/modules/core/src/main/java/org/apache/ignite/internal/processors/cluster/baseline/autoadjust/BaselineAutoAdjustExecutor.java
|
BaselineAutoAdjustExecutor
|
execute
|
class BaselineAutoAdjustExecutor {
/** */
private final IgniteLogger log;
/** */
private final IgniteClusterImpl cluster;
/** Service for execute this task in async. */
private final ExecutorService executorService;
/** {@code true} if baseline auto-adjust enabled. */
private final BooleanSupplier isBaselineAutoAdjustEnabled;
/** This protect from execution more than one task at same moment. */
private final Lock executionGuard = new ReentrantLock();
/**
* @param log Logger.
* @param cluster Ignite cluster.
* @param executorService Thread pool for changing baseline.
* @param enabledSupplier Supplier return {@code true} if baseline auto-adjust enabled.
*/
public BaselineAutoAdjustExecutor(IgniteLogger log, IgniteClusterImpl cluster, ExecutorService executorService,
BooleanSupplier enabledSupplier) {
this.log = log;
this.cluster = cluster;
this.executorService = executorService;
isBaselineAutoAdjustEnabled = enabledSupplier;
}
/**
* Try to set baseline if all conditions it allowed.
*
* @param data Data for operation.
*/
public void execute(BaselineAutoAdjustData data) {<FILL_FUNCTION_BODY>}
/**
* @param data Baseline data for adjust.
* @return {@code true} If baseline auto-adjust shouldn't be executed for given data.
*/
public boolean isExecutionExpired(BaselineAutoAdjustData data) {
return data.isInvalidated() || !isBaselineAutoAdjustEnabled.getAsBoolean();
}
}
|
executorService.submit(() -> {
if (isExecutionExpired(data))
return;
executionGuard.lock();
try {
if (isExecutionExpired(data))
return;
cluster.triggerBaselineAutoAdjust(data.getTargetTopologyVersion());
}
catch (IgniteException e) {
log.error("Error during baseline changing", e);
}
finally {
data.onAdjust();
executionGuard.unlock();
}
}
);
| 420
| 136
| 556
|
<no_super_class>
|
apache_ignite
|
ignite/modules/core/src/main/java/org/apache/ignite/internal/processors/cluster/baseline/autoadjust/BaselineAutoAdjustScheduler.java
|
BaselineMultiplyUseTimeoutObject
|
onTimeout
|
class BaselineMultiplyUseTimeoutObject implements GridTimeoutObject {
/** Interval between logging of info about next baseline auto-adjust. */
private static final long AUTO_ADJUST_LOG_INTERVAL =
getLong(IGNITE_BASELINE_AUTO_ADJUST_LOG_INTERVAL, DFLT_BASELINE_AUTO_ADJUST_LOG_INTERVAL);
/** Last data for set new baseline. */
private final BaselineAutoAdjustData baselineAutoAdjustData;
/** Executor of set baseline operation. */
private final BaselineAutoAdjustExecutor baselineAutoAdjustExecutor;
/** Timeout processor. */
private final GridTimeoutProcessor timeoutProcessor;
/** */
private final IgniteLogger log;
/** End time of whole life of this object. It represent time when auto-adjust will be executed. */
private final long totalEndTime;
/** Timeout ID. */
private final IgniteUuid id = IgniteUuid.randomUuid();
/** End time of one iteration of this timeout object. */
private long endTime;
/**
* @param data Data for changing baseline.
* @param executionTimeout Delay after which set baseline should be started.
* @param executor Executor of set baseline operation.
* @param processor Timeout processor.
* @param log Log object.
*/
protected BaselineMultiplyUseTimeoutObject(
BaselineAutoAdjustData data,
long executionTimeout,
BaselineAutoAdjustExecutor executor,
GridTimeoutProcessor processor,
IgniteLogger log
) {
baselineAutoAdjustData = data;
baselineAutoAdjustExecutor = executor;
timeoutProcessor = processor;
this.log = log;
endTime = calculateEndTime(executionTimeout);
this.totalEndTime = U.currentTimeMillis() + executionTimeout;
}
/**
* @param timeout Remaining time to baseline adjust.
* @return Calculated end time to next iteration.
*/
private long calculateEndTime(long timeout) {
return U.currentTimeMillis() + (AUTO_ADJUST_LOG_INTERVAL < timeout ? AUTO_ADJUST_LOG_INTERVAL : timeout);
}
/** {@inheritDoc}. */
@Override public IgniteUuid timeoutId() {
return id;
}
/** {@inheritDoc}. */
@Override public long endTime() {
return endTime;
}
/** {@inheritDoc}. */
@Override public void onTimeout() {<FILL_FUNCTION_BODY>}
/**
* @return End time of whole life of this object. It represent time when auto-adjust will be executed.
*/
public long getTotalEndTime() {
return totalEndTime;
}
}
|
if (baselineAutoAdjustExecutor.isExecutionExpired(baselineAutoAdjustData))
return;
long lastScheduledTaskTime = totalEndTime - System.currentTimeMillis();
if (lastScheduledTaskTime <= 0) {
if (log.isInfoEnabled())
log.info("Baseline auto-adjust will be executed right now.");
baselineAutoAdjustExecutor.execute(baselineAutoAdjustData);
}
else {
if (log.isInfoEnabled())
log.info("Baseline auto-adjust will be executed in '" + lastScheduledTaskTime + "' ms.");
endTime = calculateEndTime(lastScheduledTaskTime);
timeoutProcessor.addTimeoutObject(this);
}
| 694
| 186
| 880
|
<no_super_class>
|
apache_ignite
|
ignite/modules/core/src/main/java/org/apache/ignite/internal/processors/compress/FileSystemUtils.java
|
FileSystemUtils
|
punchHole
|
class FileSystemUtils {
/** */
private static final String NATIVE_FS_LINUX_CLASS =
"org.apache.ignite.internal.processors.compress.NativeFileSystemLinux";
/** */
private static final NativeFileSystem fs;
/** */
private static volatile Throwable err;
/** */
static {
NativeFileSystem x = null;
try {
if (IgniteComponentType.COMPRESSION.inClassPath()) {
if (U.isLinux())
x = U.newInstance(NATIVE_FS_LINUX_CLASS);
}
}
catch (Throwable e) {
err = e;
}
fs = x;
}
/**
*/
public static void checkSupported() {
Throwable e = err;
if (e != null || fs == null)
throw new IgniteException("Native file system API is not supported on " + U.osString(), e);
}
/**
* @param path File system path.
* @return File system block size or negative value if not supported.
*/
public static int getFileSystemBlockSize(Path path) {
return fs == null ? -1 : fs.getFileSystemBlockSize(path);
}
/**
* @param fd Native file descriptor.
* @return File system block size or negative value if not supported.
*/
public static int getFileSystemBlockSize(int fd) {
return fs == null ? -1 : fs.getFileSystemBlockSize(fd);
}
/**
* !!! Use with caution. May produce unexpected results.
*
* Known to work correctly on Linux EXT4 and Btrfs,
* while on XSF it returns meaningful result only after
* file reopening.
*
* @param fd Native file descriptor.
* @return Approximate system dependent size of the sparse file or negative
* value if not supported.
*/
public static long getSparseFileSize(int fd) {
return fs == null ? -1 : fs.getSparseFileSize(fd);
}
/**
* @param fd Native file descriptor.
* @param off Offset of the hole.
* @param len Length of the hole.
* @param fsBlockSize File system block size.
* @return Actual punched hole size.
*/
public static long punchHole(int fd, long off, long len, int fsBlockSize) {<FILL_FUNCTION_BODY>}
}
|
assert off >= 0;
assert len > 0;
checkSupported();
if (len < fsBlockSize)
return 0;
// TODO maybe optimize for power of 2
if (off % fsBlockSize != 0) {
long end = off + len;
off = (off / fsBlockSize + 1) * fsBlockSize;
len = end - off;
if (len <= 0)
return 0;
}
len = len / fsBlockSize * fsBlockSize;
if (len > 0)
fs.punchHole(fd, off, len);
return len;
| 644
| 165
| 809
|
<no_super_class>
|
apache_ignite
|
ignite/modules/core/src/main/java/org/apache/ignite/internal/processors/configuration/distributed/SimpleDistributedProperty.java
|
SimpleDistributedProperty
|
parseNonNegativeInteger
|
class SimpleDistributedProperty<T extends Serializable> implements DistributedChangeableProperty<T> {
/** Name of property. */
private final String name;
/** Description of property. */
private final String description;
/** Property value. */
protected volatile T val;
/** Sign of attachment to the processor. */
private volatile boolean attached = false;
/** Listeners of property update. */
private final ConcurrentLinkedQueue<DistributePropertyListener<? super T>> updateListeners = new ConcurrentLinkedQueue<>();
/**
* Specific consumer for update value in cluster. It is null when property doesn't ready to update value on cluster
* wide.
*/
@GridToStringExclude
private volatile PropertyUpdateClosure clusterWideUpdater;
/** Property value parser. */
@GridToStringExclude
private final Function<String, T> parser;
/**
* @param name Name of property.
* @param parser Property value parser.
* @param description Description of property.
*/
public SimpleDistributedProperty(String name, Function<String, T> parser, String description) {
this.name = name;
this.parser = parser;
this.description = description;
}
/** {@inheritDoc} */
@Override public boolean propagate(T newVal) throws IgniteCheckedException {
ensureClusterWideUpdateIsReady();
clusterWideUpdater.update(name, newVal).get();
return true;
}
/**
* @throws DetachedPropertyException If this property have not been attached to processor yet, please call {@link
* DistributedConfigurationProcessor#registerProperty(DistributedChangeableProperty)} before this method.
* @throws NotWritablePropertyException If this property don't ready to cluster wide update yet, perhaps cluster is
* not active yet.
*/
private void ensureClusterWideUpdateIsReady() throws DetachedPropertyException, NotWritablePropertyException {
if (!attached)
throw new DetachedPropertyException(name);
if (clusterWideUpdater == null)
throw new NotWritablePropertyException(name);
}
/** {@inheritDoc} */
@Override public GridFutureAdapter<?> propagateAsync(T newVal) throws IgniteCheckedException {
ensureClusterWideUpdateIsReady();
return clusterWideUpdater.update(name, newVal);
}
/** {@inheritDoc} */
@Override public GridFutureAdapter<?> propagateAsync(T expectedVal, T newVal) throws IgniteCheckedException {
ensureClusterWideUpdateIsReady();
return clusterWideUpdater.casUpdate(name, expectedVal, newVal);
}
/** {@inheritDoc} */
@Override public T get() {
return val;
}
/** {@inheritDoc} */
@Override public T getOrDefault(T dfltVal) {
return val == null ? dfltVal : val;
}
/** {@inheritDoc} */
@Override public String getName() {
return name;
}
/** {@inheritDoc} */
@Override public String description() {
return description;
}
/** {@inheritDoc} */
@Override public void addListener(DistributePropertyListener<? super T> listener) {
updateListeners.add(listener);
}
/** {@inheritDoc} */
@Override public void onAttached() {
attached = true;
}
/** {@inheritDoc} */
@Override public void onReadyForUpdate(@NotNull PropertyUpdateClosure updater) {
this.clusterWideUpdater = updater;
}
/** {@inheritDoc} */
@Override public void localUpdate(Serializable newVal) {
T oldVal = val;
val = (T)newVal;
updateListeners.forEach(listener -> listener.onUpdate(name, oldVal, val));
}
/** {@inheritDoc} */
@Override public T parse(String str) {
if (parser == null)
throw new IgniteException("The parser is not specified for property [name=" + name + ']');
return parser.apply(str);
}
/** {@inheritDoc} */
@Override public String toString() {
return S.toString(SimpleDistributedProperty.class, this);
}
/**
* @param val String to parse.
* @return Integer value.
*/
public static Integer parseNonNegativeInteger(String val) {<FILL_FUNCTION_BODY>}
/**
* @param val String to parse.
* @return Long value.
*/
public static Long parseNonNegativeLong(String val) {
if (val == null || val.trim().isEmpty())
return null;
long intVal = Long.parseLong(val);
if (intVal < 0)
throw new IllegalArgumentException("The value must not be negative");
return intVal;
}
/**
* @param val String value.
* @return String set.
*/
public static HashSet<String> parseStringSet(String val) {
HashSet<String> set = new HashSet<>();
if (val == null || val.trim().isEmpty())
return set;
String[] vals = val.split("\\W+");
set.addAll(Arrays.asList(vals));
return set;
}
}
|
if (val == null || val.trim().isEmpty())
return null;
int intVal = Integer.parseInt(val);
if (intVal < 0)
throw new IllegalArgumentException("The value must not be negative");
return intVal;
| 1,369
| 67
| 1,436
|
<no_super_class>
|
apache_ignite
|
ignite/modules/core/src/main/java/org/apache/ignite/internal/processors/continuous/GridContinuousMessage.java
|
GridContinuousMessage
|
writeTo
|
class GridContinuousMessage implements Message {
/** */
private static final long serialVersionUID = 0L;
/** Message type. */
private GridContinuousMessageType type;
/** Routine ID. */
private UUID routineId;
/** Optional message data. */
@GridToStringInclude(sensitive = true)
@GridDirectTransient
private Object data;
/** */
@GridDirectCollection(Message.class)
private Collection<Message> msgs;
/** Serialized message data. */
private byte[] dataBytes;
/** Future ID for synchronous event notifications. */
private IgniteUuid futId;
/**
* Required by {@link Externalizable}.
*/
public GridContinuousMessage() {
// No-op.
}
/**
* @param type Message type.
* @param routineId Consume ID.
* @param futId Future ID.
* @param data Optional message data.
* @param msgs If {@code true} then data is collection of messages.
*/
GridContinuousMessage(GridContinuousMessageType type,
@Nullable UUID routineId,
@Nullable IgniteUuid futId,
@Nullable Object data,
boolean msgs) {
assert type != null;
assert routineId != null || type == MSG_EVT_ACK;
this.type = type;
this.routineId = routineId;
this.futId = futId;
if (msgs)
this.msgs = (Collection)data;
else
this.data = data;
}
/**
* @return Message type.
*/
public GridContinuousMessageType type() {
return type;
}
/**
* @return Consume ID.
*/
public UUID routineId() {
return routineId;
}
/**
* @return {@code True} is data is collection of messages.
*/
public boolean messages() {
return msgs != null;
}
/**
* @return Message data.
*/
public <T> T data() {
return msgs != null ? (T)msgs : (T)data;
}
/**
* @param data Message data.
*/
public void data(Object data) {
this.data = data;
}
/**
* @return Serialized message data.
*/
public byte[] dataBytes() {
return dataBytes;
}
/**
* @param dataBytes Serialized message data.
*/
public void dataBytes(byte[] dataBytes) {
this.dataBytes = dataBytes;
}
/** {@inheritDoc} */
@Override public void onAckReceived() {
// No-op.
}
/**
* @return Future ID for synchronous event notification.
*/
@Nullable public IgniteUuid futureId() {
return futId;
}
/** {@inheritDoc} */
@Override public boolean writeTo(ByteBuffer buf, MessageWriter writer) {<FILL_FUNCTION_BODY>}
/** {@inheritDoc} */
@Override public boolean readFrom(ByteBuffer buf, MessageReader reader) {
reader.setBuffer(buf);
if (!reader.beforeMessageRead())
return false;
switch (reader.state()) {
case 0:
dataBytes = reader.readByteArray("dataBytes");
if (!reader.isLastRead())
return false;
reader.incrementState();
case 1:
futId = reader.readIgniteUuid("futId");
if (!reader.isLastRead())
return false;
reader.incrementState();
case 2:
msgs = reader.readCollection("msgs", MessageCollectionItemType.MSG);
if (!reader.isLastRead())
return false;
reader.incrementState();
case 3:
routineId = reader.readUuid("routineId");
if (!reader.isLastRead())
return false;
reader.incrementState();
case 4:
byte typeOrd;
typeOrd = reader.readByte("type");
if (!reader.isLastRead())
return false;
type = GridContinuousMessageType.fromOrdinal(typeOrd);
reader.incrementState();
}
return reader.afterMessageRead(GridContinuousMessage.class);
}
/** {@inheritDoc} */
@Override public short directType() {
return 61;
}
/** {@inheritDoc} */
@Override public byte fieldsCount() {
return 5;
}
/** {@inheritDoc} */
@Override public String toString() {
return S.toString(GridContinuousMessage.class, this);
}
}
|
writer.setBuffer(buf);
if (!writer.isHeaderWritten()) {
if (!writer.writeHeader(directType(), fieldsCount()))
return false;
writer.onHeaderWritten();
}
switch (writer.state()) {
case 0:
if (!writer.writeByteArray("dataBytes", dataBytes))
return false;
writer.incrementState();
case 1:
if (!writer.writeIgniteUuid("futId", futId))
return false;
writer.incrementState();
case 2:
if (!writer.writeCollection("msgs", msgs, MessageCollectionItemType.MSG))
return false;
writer.incrementState();
case 3:
if (!writer.writeUuid("routineId", routineId))
return false;
writer.incrementState();
case 4:
if (!writer.writeByte("type", type != null ? (byte)type.ordinal() : -1))
return false;
writer.incrementState();
}
return true;
| 1,252
| 285
| 1,537
|
<no_super_class>
|
apache_ignite
|
ignite/modules/core/src/main/java/org/apache/ignite/internal/processors/continuous/GridContinuousQueryBatch.java
|
GridContinuousQueryBatch
|
add
|
class GridContinuousQueryBatch extends GridContinuousBatchAdapter {
/** Entries size included filtered entries. */
private final AtomicInteger size = new AtomicInteger();
/** {@inheritDoc} */
@Override public void add(Object obj) {<FILL_FUNCTION_BODY>}
/**
* @return Entries count.
*/
public int entriesCount() {
return size.get();
}
}
|
assert obj != null;
assert obj instanceof CacheContinuousQueryEntry || obj instanceof List;
if (obj instanceof CacheContinuousQueryEntry) {
buf.add(obj);
size.incrementAndGet();
}
else {
List<Object> objs = (List<Object>)obj;
buf.addAll(objs);
size.addAndGet(objs.size());
}
| 110
| 112
| 222
|
<methods>public non-sealed void <init>() ,public void add(java.lang.Object) ,public Collection<java.lang.Object> collect() ,public int size() <variables>protected final FastSizeDeque<java.lang.Object> buf
|
apache_ignite
|
ignite/modules/core/src/main/java/org/apache/ignite/internal/processors/datastreamer/DataStreamerCacheUpdaters.java
|
BatchedSorted
|
receive
|
class BatchedSorted<K, V> implements StreamReceiver<K, V> {
/** */
private static final long serialVersionUID = 0L;
/** {@inheritDoc} */
@Override public void receive(IgniteCache<K, V> cache, Collection<Map.Entry<K, V>> entries) {<FILL_FUNCTION_BODY>}
}
|
assert cache != null;
assert !F.isEmpty(entries);
Map<K, V> putAll = null;
Set<K> rmvAll = null;
for (Map.Entry<K, V> entry : entries) {
K key = entry.getKey();
assert key instanceof Comparable;
V val = entry.getValue();
if (val == null) {
if (rmvAll == null)
rmvAll = new TreeSet<>();
rmvAll.add(key);
}
else {
if (putAll == null)
putAll = new TreeMap<>();
putAll.put(key, val);
}
}
updateAll(cache, rmvAll, putAll);
| 93
| 197
| 290
|
<no_super_class>
|
apache_ignite
|
ignite/modules/core/src/main/java/org/apache/ignite/internal/processors/datastreamer/DataStreamerFuture.java
|
DataStreamerFuture
|
cancel
|
class DataStreamerFuture extends GridFutureAdapter<Object> {
/** Data loader. */
@GridToStringExclude
private DataStreamerImpl dataLdr;
/**
* @param dataLdr Data streamer.
*/
DataStreamerFuture(DataStreamerImpl dataLdr) {
assert dataLdr != null;
this.dataLdr = dataLdr;
}
/** {@inheritDoc} */
@Override public boolean cancel() throws IgniteCheckedException {<FILL_FUNCTION_BODY>}
/** {@inheritDoc} */
@Override public String toString() {
return S.toString(DataStreamerFuture.class, this, super.toString());
}
}
|
if (onCancelled()) {
dataLdr.closeEx(true);
return true;
}
return false;
| 180
| 39
| 219
|
<methods>public non-sealed void <init>() ,public boolean cancel() throws org.apache.ignite.IgniteCheckedException,public IgniteInternalFuture<T> chain(IgniteClosure<? super IgniteInternalFuture<java.lang.Object>,T>) ,public IgniteInternalFuture<T> chain(IgniteOutClosure<T>) ,public IgniteInternalFuture<T> chain(IgniteClosure<? super IgniteInternalFuture<java.lang.Object>,T>, java.util.concurrent.Executor) ,public IgniteInternalFuture<T> chain(IgniteOutClosure<T>, java.util.concurrent.Executor) ,public IgniteInternalFuture<T> chainCompose(IgniteClosure<? super IgniteInternalFuture<java.lang.Object>,IgniteInternalFuture<T>>) ,public IgniteInternalFuture<T> chainCompose(IgniteClosure<? super IgniteInternalFuture<java.lang.Object>,IgniteInternalFuture<T>>, java.util.concurrent.Executor) ,public java.lang.Throwable error() ,public java.lang.Object get() throws org.apache.ignite.IgniteCheckedException,public java.lang.Object get(long) throws org.apache.ignite.IgniteCheckedException,public java.lang.Object get(long, java.util.concurrent.TimeUnit) throws org.apache.ignite.IgniteCheckedException,public java.lang.Object getUninterruptibly() throws org.apache.ignite.IgniteCheckedException,public void ignoreInterrupts() ,public boolean isCancelled() ,public boolean isDone() ,public boolean isFailed() ,public void listen(IgniteInClosure<? super IgniteInternalFuture<java.lang.Object>>) ,public void listen(org.apache.ignite.lang.IgniteRunnable) ,public org.apache.ignite.IgniteLogger logger() ,public boolean onCancelled() ,public final boolean onDone() ,public final boolean onDone(java.lang.Object) ,public final boolean onDone(java.lang.Throwable) ,public boolean onDone(java.lang.Object, java.lang.Throwable) ,public void reset() ,public java.lang.Object result() ,public java.lang.String toString() <variables>private static final java.lang.Object CANCELLED,private static final java.lang.String DONE,private static final org.apache.ignite.internal.util.future.GridFutureAdapter.Node INIT,private volatile boolean ignoreInterrupts,private volatile java.lang.Object state,private static final AtomicReferenceFieldUpdater<GridFutureAdapter#RAW,java.lang.Object> stateUpdater
|
apache_ignite
|
ignite/modules/core/src/main/java/org/apache/ignite/internal/processors/datastructures/CollocatedQueueItemKey.java
|
CollocatedQueueItemKey
|
equals
|
class CollocatedQueueItemKey implements QueueItemKey {
/** */
private IgniteUuid queueId;
/** */
@AffinityKeyMapped
private int queueNameHash;
/** */
private long idx;
/**
* @param queueId Queue unique ID.
* @param queueName Queue name.
* @param idx Item index.
*/
public CollocatedQueueItemKey(IgniteUuid queueId, String queueName, long idx) {
this.queueId = queueId;
this.queueNameHash = queueName.hashCode();
this.idx = idx;
}
/** {@inheritDoc} */
@Override public boolean equals(Object o) {<FILL_FUNCTION_BODY>}
/** {@inheritDoc} */
@Override public int hashCode() {
int res = queueId.hashCode();
res = 31 * res + (int)(idx ^ (idx >>> 32));
return res;
}
/** {@inheritDoc} */
@Override public String toString() {
return S.toString(CollocatedQueueItemKey.class, this);
}
}
|
if (this == o)
return true;
if (o == null || getClass() != o.getClass())
return false;
CollocatedQueueItemKey itemKey = (CollocatedQueueItemKey)o;
return idx == itemKey.idx && queueId.equals(itemKey.queueId);
| 297
| 84
| 381
|
<no_super_class>
|
apache_ignite
|
ignite/modules/core/src/main/java/org/apache/ignite/internal/processors/datastructures/CollocatedSetItemKey.java
|
CollocatedSetItemKey
|
hashCode
|
class CollocatedSetItemKey implements SetItemKey {
/** */
private IgniteUuid setId;
/** */
@GridToStringInclude(sensitive = true)
private Object item;
/** */
@AffinityKeyMapped
private int setNameHash;
/**
* @param setName Set name.
* @param setId Set unique ID.
* @param item Set item.
*/
public CollocatedSetItemKey(String setName, IgniteUuid setId, Object item) {
this.setNameHash = setName.hashCode();
this.setId = setId;
this.item = item;
}
/** {@inheritDoc} */
@Override public IgniteUuid setId() {
return setId;
}
/** {@inheritDoc} */
@Override public Object item() {
return item;
}
/** {@inheritDoc} */
@Override public int hashCode() {<FILL_FUNCTION_BODY>}
/** {@inheritDoc} */
@Override public boolean equals(Object o) {
if (this == o)
return true;
if (o == null || getClass() != o.getClass())
return false;
CollocatedSetItemKey that = (CollocatedSetItemKey)o;
return setId.equals(that.setId) && item.equals(that.item);
}
/** {@inheritDoc} */
@Override public String toString() {
return S.toString(CollocatedSetItemKey.class, this);
}
}
|
int res = setId.hashCode();
res = 31 * res + item.hashCode();
return res;
| 405
| 35
| 440
|
<no_super_class>
|
apache_ignite
|
ignite/modules/core/src/main/java/org/apache/ignite/internal/processors/datastructures/GridCacheAtomicStampedValue.java
|
GridCacheAtomicStampedValue
|
deployClass
|
class GridCacheAtomicStampedValue<T, S> extends AtomicDataStructureValue implements GridPeerDeployAware {
/** */
private static final long serialVersionUID = 0L;
/** Value. */
private T val;
/** Stamp. */
private S stamp;
/**
* Constructor.
*
* @param val Initial value.
* @param stamp Initial stamp.
*/
public GridCacheAtomicStampedValue(T val, S stamp) {
this.val = val;
this.stamp = stamp;
}
/**
* Empty constructor required for {@link Externalizable}.
*/
public GridCacheAtomicStampedValue() {
// No-op.
}
/** {@inheritDoc} */
@Override public DataStructureType type() {
return DataStructureType.ATOMIC_STAMPED;
}
/**
* @param val New value.
* @param stamp New stamp.
*/
public void set(T val, S stamp) {
this.val = val;
this.stamp = stamp;
}
/**
* @return Current value and stamp.
*/
public IgniteBiTuple<T, S> get() {
return F.t(val, stamp);
}
/**
* @return val Current value.
*/
public T value() {
return val;
}
/**
* @return Current stamp.
*/
public S stamp() {
return stamp;
}
/** {@inheritDoc} */
@Override public void writeExternal(ObjectOutput out) throws IOException {
out.writeObject(val);
out.writeObject(stamp);
}
/** {@inheritDoc} */
@Override public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException {
val = (T)in.readObject();
stamp = (S)in.readObject();
}
/** {@inheritDoc} */
@Override public Class<?> deployClass() {<FILL_FUNCTION_BODY>}
/** {@inheritDoc} */
@Override public ClassLoader classLoader() {
return deployClass().getClassLoader();
}
/** {@inheritDoc} */
@Override public String toString() {
return GridToStringBuilder.toString(GridCacheAtomicStampedValue.class, this);
}
}
|
ClassLoader clsLdr = getClass().getClassLoader();
// First of all check classes that may be loaded by class loader other than application one.
return stamp != null && !clsLdr.equals(stamp.getClass().getClassLoader()) ?
stamp.getClass() : val != null ? val.getClass() : getClass();
| 610
| 88
| 698
|
<methods>public non-sealed void <init>() ,public abstract org.apache.ignite.internal.processors.datastructures.DataStructureType type() <variables>private static final long serialVersionUID
|
apache_ignite
|
ignite/modules/core/src/main/java/org/apache/ignite/internal/processors/datastructures/GridCacheCountDownLatchValue.java
|
GridCacheCountDownLatchValue
|
readExternal
|
class GridCacheCountDownLatchValue extends VolatileAtomicDataStructureValue implements Cloneable {
/** */
private static final long serialVersionUID = 0L;
/** Count. */
@GridToStringInclude(sensitive = true)
private int cnt;
/** Initial count. */
@GridToStringInclude(sensitive = true)
private int initCnt;
/** Auto delete flag. */
private boolean autoDel;
/** */
private long gridStartTime;
/**
* Constructor.
*
* @param cnt Initial count.
* @param del {@code True} to auto delete on count down to 0.
* @param gridStartTime Cluster start time.
*/
public GridCacheCountDownLatchValue(int cnt, boolean del, long gridStartTime) {
assert cnt >= 0;
this.cnt = cnt;
initCnt = cnt;
autoDel = del;
this.gridStartTime = gridStartTime;
}
/**
* Empty constructor required for {@link Externalizable}.
*/
public GridCacheCountDownLatchValue() {
// No-op.
}
/** {@inheritDoc} */
@Override public DataStructureType type() {
return DataStructureType.COUNT_DOWN_LATCH;
}
/** {@inheritDoc} */
@Override public long gridStartTime() {
return gridStartTime;
}
/**
* @param cnt New count.
*/
public void set(int cnt) {
this.cnt = cnt;
}
/**
* @return Current count.
*/
public int get() {
return cnt;
}
/**
* @return Initial count.
*/
public int initialCount() {
return initCnt;
}
/**
* @return Auto-delete flag.
*/
public boolean autoDelete() {
return autoDel;
}
/** {@inheritDoc} */
@Override public Object clone() throws CloneNotSupportedException {
return super.clone();
}
/** {@inheritDoc} */
@Override public void writeExternal(ObjectOutput out) throws IOException {
out.writeInt(cnt);
out.writeInt(initCnt);
out.writeBoolean(autoDel);
out.writeLong(gridStartTime);
}
/** {@inheritDoc} */
@Override public void readExternal(ObjectInput in) throws IOException {<FILL_FUNCTION_BODY>}
/** {@inheritDoc} */
@Override public String toString() {
return S.toString(GridCacheCountDownLatchValue.class, this);
}
}
|
cnt = in.readInt();
initCnt = in.readInt();
autoDel = in.readBoolean();
gridStartTime = in.readLong();
| 698
| 45
| 743
|
<methods>public non-sealed void <init>() ,public abstract long gridStartTime() <variables>private static final long serialVersionUID
|
apache_ignite
|
ignite/modules/core/src/main/java/org/apache/ignite/internal/processors/datastructures/GridCacheQueueHeaderKey.java
|
GridCacheQueueHeaderKey
|
equals
|
class GridCacheQueueHeaderKey implements Externalizable, GridCacheInternal {
/** */
private static final long serialVersionUID = 0L;
/** */
private String name;
/**
* Required by {@link Externalizable}.
*/
public GridCacheQueueHeaderKey() {
// No-op.
}
/**
* @param name Queue name.
*/
public GridCacheQueueHeaderKey(String name) {
this.name = name;
}
/**
* @return Queue name.
*/
public String queueName() {
return name;
}
/** {@inheritDoc} */
@Override public void writeExternal(ObjectOutput out) throws IOException {
U.writeString(out, name);
}
/** {@inheritDoc} */
@Override public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException {
name = U.readString(in);
}
/** {@inheritDoc} */
@Override public boolean equals(Object o) {<FILL_FUNCTION_BODY>}
/** {@inheritDoc} */
@Override public int hashCode() {
return name.hashCode();
}
/** {@inheritDoc} */
@Override public String toString() {
return S.toString(GridCacheQueueHeaderKey.class, this);
}
}
|
if (this == o)
return true;
if (o == null || getClass() != o.getClass())
return false;
GridCacheQueueHeaderKey queueKey = (GridCacheQueueHeaderKey)o;
return name.equals(queueKey.name);
| 342
| 73
| 415
|
<no_super_class>
|
apache_ignite
|
ignite/modules/core/src/main/java/org/apache/ignite/internal/processors/datastructures/GridCacheSemaphoreState.java
|
GridCacheSemaphoreState
|
readExternal
|
class GridCacheSemaphoreState extends VolatileAtomicDataStructureValue implements Cloneable {
/** */
private static final long serialVersionUID = 0L;
/** Permission count. */
private int cnt;
/** Map containing number of acquired permits for each node waiting on this semaphore. */
@GridToStringInclude
private Map<UUID, Integer> waiters;
/** FailoverSafe flag. */
private boolean failoverSafe;
/** Flag indicating that semaphore is no longer safe to use. */
private boolean broken;
/** */
private long gridStartTime;
/**
* Constructor.
*
* @param cnt Number of permissions.
* @param waiters Waiters map.
* @param failoverSafe Failover safe flag.
* @param gridStartTime Cluster start time.
*/
public GridCacheSemaphoreState(int cnt, @Nullable Map<UUID, Integer> waiters, boolean failoverSafe, long gridStartTime) {
this.cnt = cnt;
this.waiters = waiters;
this.failoverSafe = failoverSafe;
this.gridStartTime = gridStartTime;
}
/**
* Empty constructor required for {@link Externalizable}.
*/
public GridCacheSemaphoreState() {
// No-op.
}
/** {@inheritDoc} */
@Override public DataStructureType type() {
return DataStructureType.SEMAPHORE;
}
/** {@inheritDoc} */
@Override public long gridStartTime() {
return gridStartTime;
}
/**
* @param cnt New count.
*/
public void setCount(int cnt) {
this.cnt = cnt;
}
/**
* @return Current count.
*/
public int getCount() {
return cnt;
}
/**
* @return Waiters.
*/
public Map<UUID, Integer> getWaiters() {
return waiters;
}
/**
* @param waiters Map containing the number of permissions acquired by each node.
*/
public void setWaiters(Map<UUID, Integer> waiters) {
this.waiters = waiters;
}
/**
* @return failoverSafe flag.
*/
public boolean isFailoverSafe() {
return failoverSafe;
}
/**
* @return broken flag.
*/
public boolean isBroken() {
return broken;
}
/**
*
* @param broken Flag indicating that this semaphore should be no longer used.
*/
public void setBroken(boolean broken) {
this.broken = broken;
}
/** {@inheritDoc} */
@Override public Object clone() throws CloneNotSupportedException {
return super.clone();
}
/** {@inheritDoc} */
@Override public void writeExternal(ObjectOutput out) throws IOException {
out.writeInt(cnt);
out.writeBoolean(failoverSafe);
out.writeLong(gridStartTime);
out.writeBoolean(waiters != null);
if (waiters != null) {
out.writeInt(waiters.size());
for (Map.Entry<UUID, Integer> e : waiters.entrySet()) {
U.writeUuid(out, e.getKey());
out.writeInt(e.getValue());
}
}
out.writeBoolean(broken);
}
/** {@inheritDoc} */
@Override public void readExternal(ObjectInput in) throws IOException {<FILL_FUNCTION_BODY>}
/** {@inheritDoc} */
@Override public String toString() {
return S.toString(GridCacheSemaphoreState.class, this);
}
}
|
cnt = in.readInt();
failoverSafe = in.readBoolean();
gridStartTime = in.readLong();
if (in.readBoolean()) {
int size = in.readInt();
waiters = U.newHashMap(size);
for (int i = 0; i < size; i++)
waiters.put(U.readUuid(in), in.readInt());
}
broken = in.readBoolean();
| 974
| 120
| 1,094
|
<methods>public non-sealed void <init>() ,public abstract long gridStartTime() <variables>private static final long serialVersionUID
|
apache_ignite
|
ignite/modules/core/src/main/java/org/apache/ignite/internal/processors/datastructures/GridTransactionalCacheQueueImpl.java
|
GridTransactionalCacheQueueImpl
|
call
|
class GridTransactionalCacheQueueImpl<T> extends GridCacheQueueAdapter<T> {
/**
* @param queueName Queue name.
* @param hdr Queue header.
* @param cctx Cache context.
*/
public GridTransactionalCacheQueueImpl(String queueName, GridCacheQueueHeader hdr, GridCacheContext<?, ?> cctx) {
super(queueName, hdr, cctx);
}
/** {@inheritDoc} */
@SuppressWarnings("unchecked")
@Override public boolean offer(final T item) throws IgniteException {
A.notNull(item, "item");
try {
return retryTopologySafe(new Callable<Boolean>() {
@Override public Boolean call() throws Exception {<FILL_FUNCTION_BODY>}
});
}
catch (IgniteCheckedException e) {
throw U.convertException(e);
}
catch (RuntimeException e) {
throw e;
}
catch (Exception e) {
throw new IgniteException(e.getMessage(), e);
}
}
/** {@inheritDoc} */
@SuppressWarnings("unchecked")
@Nullable @Override public T poll() throws IgniteException {
try {
return retryTopologySafe(new Callable<T>() {
@Override public T call() throws Exception {
T retVal;
while (true) {
try (GridNearTxLocal tx = cache.txStartEx(PESSIMISTIC, REPEATABLE_READ)) {
Long idx = (Long)cache.invoke(queueKey, new PollProcessor(id)).get();
if (idx != null) {
checkRemoved(idx);
retVal = (T)cache.getAndRemove(itemKey(idx));
if (retVal == null) { // Possible if data was lost.
tx.commit();
continue;
}
}
else
retVal = null;
tx.commit();
return retVal;
}
}
}
});
}
catch (IgniteCheckedException e) {
throw U.convertException(e);
}
catch (RuntimeException e) {
throw e;
}
catch (Exception e) {
throw new IgniteException(e.getMessage(), e);
}
}
/** {@inheritDoc} */
@SuppressWarnings("unchecked")
@Override public boolean addAll(final Collection<? extends T> items) {
A.notNull(items, "items");
try {
return retryTopologySafe(new Callable<Boolean>() {
@Override public Boolean call() throws Exception {
boolean retVal;
try (GridNearTxLocal tx = cache.txStartEx(PESSIMISTIC, REPEATABLE_READ)) {
Long idx = (Long)cache.invoke(queueKey, new AddProcessor(id, items.size())).get();
if (idx != null) {
checkRemoved(idx);
Map<QueueItemKey, T> putMap = new HashMap<>();
for (T item : items) {
putMap.put(itemKey(idx), item);
idx++;
}
cache.putAll(putMap);
retVal = true;
}
else
retVal = false;
tx.commit();
return retVal;
}
}
});
}
catch (IgniteCheckedException e) {
throw U.convertException(e);
}
catch (RuntimeException e) {
throw e;
}
catch (Exception e) {
throw new IgniteException(e.getMessage(), e);
}
}
/** {@inheritDoc} */
@SuppressWarnings("unchecked")
@Override protected void removeItem(final long rmvIdx) throws IgniteCheckedException {
try {
retryTopologySafe(new Callable<Object>() {
@Override public Object call() throws Exception {
try (GridNearTxLocal tx = cache.txStartEx(PESSIMISTIC, REPEATABLE_READ)) {
Long idx = (Long)cache.invoke(queueKey, new RemoveProcessor(id, rmvIdx)).get();
if (idx != null) {
checkRemoved(idx);
cache.remove(itemKey(idx));
}
tx.commit();
}
return null;
}
});
}
catch (RuntimeException e) {
throw e;
}
catch (Exception e) {
throw new IgniteCheckedException(e);
}
}
}
|
boolean retVal;
try (GridNearTxLocal tx = cache.txStartEx(PESSIMISTIC, REPEATABLE_READ)) {
Long idx = (Long)cache.invoke(queueKey, new AddProcessor(id, 1)).get();
if (idx != null) {
checkRemoved(idx);
cache.getAndPut(itemKey(idx), item);
retVal = true;
}
else
retVal = false;
tx.commit();
return retVal;
}
| 1,187
| 140
| 1,327
|
<methods>public boolean add(T) ,public R affinityCall(IgniteCallable<R>) ,public void affinityRun(org.apache.ignite.lang.IgniteRunnable) ,public boolean bounded() ,public int capacity() ,public void clear() ,public void clear(int) throws org.apache.ignite.IgniteException,public void close() ,public boolean collocated() ,public int drainTo(Collection<? super T>) ,public int drainTo(Collection<? super T>, int) ,public T element() ,public boolean equals(java.lang.Object) ,public int hashCode() ,public org.apache.ignite.lang.IgniteUuid id() ,public Iterator<T> iterator() ,public java.lang.String name() ,public boolean offer(T, long, java.util.concurrent.TimeUnit) throws org.apache.ignite.IgniteException,public void onClientDisconnected() ,public void onHeaderChanged(org.apache.ignite.internal.processors.datastructures.GridCacheQueueHeader) ,public void onKernalStop() ,public void onRemoved(boolean) ,public T peek() throws org.apache.ignite.IgniteException,public T poll(long, java.util.concurrent.TimeUnit) throws org.apache.ignite.IgniteException,public void put(T) throws org.apache.ignite.IgniteException,public int remainingCapacity() ,public T remove() ,public boolean removed() ,public int size() ,public T take() throws org.apache.ignite.IgniteException,public java.lang.String toString() ,public IgniteQueue<V1> withKeepBinary() <variables>private static final int DFLT_CLEAR_BATCH_SIZE,protected static final long QUEUE_REMOVED_IDX,protected final non-sealed GridCacheAdapter#RAW cache,private final non-sealed int cap,protected final non-sealed GridCacheContext<?,?> cctx,private final non-sealed boolean collocated,private final non-sealed org.apache.ignite.IgniteCompute compute,protected final non-sealed org.apache.ignite.lang.IgniteUuid id,protected final non-sealed org.apache.ignite.IgniteLogger log,protected final non-sealed org.apache.ignite.internal.processors.datastructures.GridCacheQueueHeaderKey queueKey,protected final non-sealed java.lang.String queueName,private final non-sealed java.util.concurrent.Semaphore readSem,private volatile boolean rmvd,private final non-sealed java.util.concurrent.Semaphore writeSem
|
apache_ignite
|
ignite/modules/core/src/main/java/org/apache/ignite/internal/processors/diagnostic/DiagnosticProcessor.java
|
DiagnosticProcessor
|
walDirs
|
class DiagnosticProcessor extends GridProcessorAdapter {
/** @see IgniteSystemProperties#IGNITE_DUMP_PAGE_LOCK_ON_FAILURE */
public static final boolean DFLT_DUMP_PAGE_LOCK_ON_FAILURE = true;
/** Value of the system property that enables page locks dumping on failure. */
private static final boolean IGNITE_DUMP_PAGE_LOCK_ON_FAILURE =
IgniteSystemProperties.getBoolean(IgniteSystemProperties.IGNITE_DUMP_PAGE_LOCK_ON_FAILURE,
DFLT_DUMP_PAGE_LOCK_ON_FAILURE);
/** Time formatter for dump file name. */
private static final DateTimeFormatter TIME_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd'_'HH-mm-ss_SSS");
/** Folder name for store diagnostic info. **/
public static final String DEFAULT_TARGET_FOLDER = "diagnostic";
/** Full path for store dubug info. */
private final Path diagnosticPath;
/** File I/O factory. */
@Nullable private final FileIOFactory fileIOFactory;
/**
* Constructor.
*
* @param ctx Kernal context.
*/
public DiagnosticProcessor(GridKernalContext ctx) throws IgniteCheckedException {
super(ctx);
diagnosticPath = U.resolveWorkDirectory(ctx.config().getWorkDirectory(), DEFAULT_TARGET_FOLDER, false)
.toPath();
fileIOFactory = isPersistenceEnabled(ctx.config()) ?
ctx.config().getDataStorageConfiguration().getFileIOFactory() : null;
}
/**
* Print diagnostic info about failure occurred on {@code ignite} instance.
* Failure details is contained in {@code failureCtx}.
*
* @param failureCtx Failure context.
*/
public void onFailure(FailureContext failureCtx) {
// Dump data structures page locks.
if (IGNITE_DUMP_PAGE_LOCK_ON_FAILURE)
ctx.cache().context().diagnostic().pageLockTracker().dumpLocksToLog();
CorruptedDataStructureException corruptedDataStructureEx =
X.cause(failureCtx.error(), CorruptedDataStructureException.class);
if (corruptedDataStructureEx != null && !F.isEmpty(corruptedDataStructureEx.pageIds()) && fileIOFactory != null) {
File[] walDirs = walDirs(ctx);
if (F.isEmpty(walDirs)) {
if (log.isInfoEnabled())
log.info("Skipping dump diagnostic info due to WAL not configured");
}
else {
try {
File corruptedPagesFile = corruptedPagesFile(
diagnosticPath,
fileIOFactory,
corruptedDataStructureEx.groupId(),
corruptedDataStructureEx.pageIds()
);
String walDirsStr = Arrays.stream(walDirs).map(File::getAbsolutePath)
.collect(joining(", ", "[", "]"));
String args = "walDir=" + walDirs[0].getAbsolutePath() + (walDirs.length == 1 ? "" :
" walArchiveDir=" + walDirs[1].getAbsolutePath());
if (ctx.config().getDataStorageConfiguration().getPageSize() != DFLT_PAGE_SIZE)
args += " pageSize=" + ctx.config().getDataStorageConfiguration().getPageSize();
args += " pages=" + corruptedPagesFile.getAbsolutePath();
log.warning(corruptedDataStructureEx.getClass().getSimpleName() + " has occurred. " +
"To diagnose it, make a backup of the following directories: " + walDirsStr + ". " +
"Then, run the following command: java -cp <classpath> " +
"org.apache.ignite.development.utils.IgniteWalConverter " + args);
}
catch (Throwable t) {
String pages = LongStream.of(corruptedDataStructureEx.pageIds())
.mapToObj(pageId -> corruptedDataStructureEx.groupId() + ":" + pageId)
.collect(joining("\n", "", ""));
log.error("Failed to dump diagnostic info of partition corruption. Page ids:\n" + pages, t);
}
}
}
}
/**
* Creation and filling of a file with pages that can be corrupted.
* Pages are written on each line in format "grpId:pageId".
* File name format "corruptedPages_yyyy-MM-dd'_'HH-mm-ss_SSS.txt".
*
* @param dirPath Path to the directory where the file will be created.
* @param ioFactory File I/O factory.
* @param grpId Cache group id.
* @param pageIds PageId's that can be corrupted.
* @return Created and filled file.
* @throws IOException If an I/O error occurs.
*/
public static File corruptedPagesFile(
Path dirPath,
FileIOFactory ioFactory,
int grpId,
long... pageIds
) throws IOException {
dirPath.toFile().mkdirs();
File f = dirPath.resolve("corruptedPages_" + LocalDateTime.now().format(TIME_FORMATTER) + ".txt").toFile();
assert !f.exists();
try (FileIO fileIO = ioFactory.create(f)) {
for (long pageId : pageIds) {
byte[] bytes = (grpId + ":" + pageId + U.nl()).getBytes(UTF_8);
int left = bytes.length;
while ((left - fileIO.writeFully(bytes, bytes.length - left, left)) > 0)
;
}
fileIO.force();
}
return f;
}
/**
* Getting the WAL directories.
* Note:
* Index 0: WAL working directory.
* Index 1: WAL archive directory (may be absent).
*
* @param ctx Kernal context.
* @return WAL directories.
*/
@Nullable static File[] walDirs(GridKernalContext ctx) {<FILL_FUNCTION_BODY>}
}
|
IgniteWriteAheadLogManager walMgr = ctx.cache().context().wal();
if (walMgr instanceof FileWriteAheadLogManager) {
SegmentRouter sr = ((FileWriteAheadLogManager)walMgr).getSegmentRouter();
if (sr != null) {
File workDir = sr.getWalWorkDir();
return sr.hasArchive() ? F.asArray(workDir, sr.getWalArchiveDir()) : F.asArray(workDir);
}
}
return null;
| 1,607
| 143
| 1,750
|
<methods>public void collectGridNodeData(org.apache.ignite.spi.discovery.DiscoveryDataBag) ,public void collectJoiningNodeData(org.apache.ignite.spi.discovery.DiscoveryDataBag) ,public org.apache.ignite.internal.GridComponent.DiscoveryDataExchangeType discoveryDataType() ,public void onDisconnected(IgniteFuture<?>) throws org.apache.ignite.IgniteCheckedException,public void onGridDataReceived(org.apache.ignite.spi.discovery.DiscoveryDataBag.GridDiscoveryData) ,public void onJoiningNodeDataReceived(org.apache.ignite.spi.discovery.DiscoveryDataBag.JoiningNodeDiscoveryData) ,public void onKernalStart(boolean) throws org.apache.ignite.IgniteCheckedException,public void onKernalStop(boolean) ,public IgniteInternalFuture<?> onReconnected(boolean) throws org.apache.ignite.IgniteCheckedException,public void printMemoryStats() ,public void start() throws org.apache.ignite.IgniteCheckedException,public void stop(boolean) throws org.apache.ignite.IgniteCheckedException,public java.lang.String toString() ,public org.apache.ignite.spi.IgniteNodeValidationResult validateNode(org.apache.ignite.cluster.ClusterNode) ,public org.apache.ignite.spi.IgniteNodeValidationResult validateNode(org.apache.ignite.cluster.ClusterNode, org.apache.ignite.spi.discovery.DiscoveryDataBag.JoiningNodeDiscoveryData) <variables>private static final java.lang.String DIAGNOSTIC_LOG_CATEGORY,protected final non-sealed org.apache.ignite.internal.GridKernalContext ctx,protected final non-sealed org.apache.ignite.IgniteLogger diagnosticLog,protected final non-sealed org.apache.ignite.IgniteLogger log
|
apache_ignite
|
ignite/modules/core/src/main/java/org/apache/ignite/internal/processors/marshaller/ClientRequestFuture.java
|
ClientRequestFuture
|
requestMapping
|
class ClientRequestFuture extends GridFutureAdapter<MappingExchangeResult> {
/** */
private static final AtomicReference<IgniteLogger> logRef = new AtomicReference<>();
/** */
private static IgniteLogger log;
/** */
private final GridIoManager ioMgr;
/** */
private final GridDiscoveryManager discoMgr;
/** */
private final MarshallerMappingItem item;
/** */
private final Map<MarshallerMappingItem, ClientRequestFuture> syncMap;
/** */
private final Queue<ClusterNode> aliveSrvNodes;
/** */
private ClusterNode pendingNode;
/**
* @param ctx Context.
* @param item Item.
* @param syncMap Sync map.
*/
ClientRequestFuture(
GridKernalContext ctx,
MarshallerMappingItem item,
Map<MarshallerMappingItem, ClientRequestFuture> syncMap
) {
ioMgr = ctx.io();
discoMgr = ctx.discovery();
aliveSrvNodes = new LinkedList<>(discoMgr.aliveServerNodes());
this.item = item;
this.syncMap = syncMap;
if (log == null)
log = U.logger(ctx, logRef, ClientRequestFuture.class);
}
/**
*
*/
void requestMapping() {<FILL_FUNCTION_BODY>}
/**
* @param nodeId Node ID.
* @param res Mapping Request Result.
*/
void onResponse(UUID nodeId, MappingExchangeResult res) {
MappingExchangeResult res0 = null;
synchronized (this) {
if (pendingNode != null && pendingNode.id().equals(nodeId))
res0 = res;
}
if (res0 != null)
onDone(res0);
}
/**
* If left node is actually the one latest mapping request was sent to,
* request is sent again to the next node in topology.
*
* @param leftNodeId Left node id.
*/
void onNodeLeft(UUID leftNodeId) {
boolean reqAgain = false;
synchronized (this) {
if (pendingNode != null && pendingNode.id().equals(leftNodeId)) {
aliveSrvNodes.remove(pendingNode);
pendingNode = null;
reqAgain = true;
}
}
if (reqAgain)
requestMapping();
}
/** {@inheritDoc} */
@Override public boolean onDone(@Nullable MappingExchangeResult res, @Nullable Throwable err) {
assert res != null;
boolean done = super.onDone(res, err);
if (done)
syncMap.remove(item);
return done;
}
}
|
boolean noSrvsInCluster;
synchronized (this) {
while (!aliveSrvNodes.isEmpty()) {
ClusterNode srvNode = aliveSrvNodes.poll();
try {
ioMgr.sendToGridTopic(
srvNode,
GridTopic.TOPIC_MAPPING_MARSH,
new MissingMappingRequestMessage(
item.platformId(),
item.typeId()),
GridIoPolicy.SYSTEM_POOL);
if (discoMgr.node(srvNode.id()) == null)
continue;
pendingNode = srvNode;
break;
}
catch (IgniteCheckedException ignored) {
U.warn(log,
"Failed to request marshaller mapping from remote node (proceeding with the next one): "
+ srvNode);
}
}
noSrvsInCluster = pendingNode == null;
}
if (noSrvsInCluster) {
onDone(MappingExchangeResult.createFailureResult(
new IgniteCheckedException(
"All server nodes have left grid, cannot request mapping [platformId: "
+ item.platformId()
+ "; typeId: "
+ item.typeId() + "]")));
}
| 721
| 331
| 1,052
|
<methods>public non-sealed void <init>() ,public boolean cancel() throws org.apache.ignite.IgniteCheckedException,public IgniteInternalFuture<T> chain(IgniteClosure<? super IgniteInternalFuture<org.apache.ignite.internal.processors.marshaller.MappingExchangeResult>,T>) ,public IgniteInternalFuture<T> chain(IgniteOutClosure<T>) ,public IgniteInternalFuture<T> chain(IgniteClosure<? super IgniteInternalFuture<org.apache.ignite.internal.processors.marshaller.MappingExchangeResult>,T>, java.util.concurrent.Executor) ,public IgniteInternalFuture<T> chain(IgniteOutClosure<T>, java.util.concurrent.Executor) ,public IgniteInternalFuture<T> chainCompose(IgniteClosure<? super IgniteInternalFuture<org.apache.ignite.internal.processors.marshaller.MappingExchangeResult>,IgniteInternalFuture<T>>) ,public IgniteInternalFuture<T> chainCompose(IgniteClosure<? super IgniteInternalFuture<org.apache.ignite.internal.processors.marshaller.MappingExchangeResult>,IgniteInternalFuture<T>>, java.util.concurrent.Executor) ,public java.lang.Throwable error() ,public org.apache.ignite.internal.processors.marshaller.MappingExchangeResult get() throws org.apache.ignite.IgniteCheckedException,public org.apache.ignite.internal.processors.marshaller.MappingExchangeResult get(long) throws org.apache.ignite.IgniteCheckedException,public org.apache.ignite.internal.processors.marshaller.MappingExchangeResult get(long, java.util.concurrent.TimeUnit) throws org.apache.ignite.IgniteCheckedException,public org.apache.ignite.internal.processors.marshaller.MappingExchangeResult getUninterruptibly() throws org.apache.ignite.IgniteCheckedException,public void ignoreInterrupts() ,public boolean isCancelled() ,public boolean isDone() ,public boolean isFailed() ,public void listen(IgniteInClosure<? super IgniteInternalFuture<org.apache.ignite.internal.processors.marshaller.MappingExchangeResult>>) ,public void listen(org.apache.ignite.lang.IgniteRunnable) ,public org.apache.ignite.IgniteLogger logger() ,public boolean onCancelled() ,public final boolean onDone() ,public final boolean onDone(org.apache.ignite.internal.processors.marshaller.MappingExchangeResult) ,public final boolean onDone(java.lang.Throwable) ,public boolean onDone(org.apache.ignite.internal.processors.marshaller.MappingExchangeResult, java.lang.Throwable) ,public void reset() ,public org.apache.ignite.internal.processors.marshaller.MappingExchangeResult result() ,public java.lang.String toString() <variables>private static final java.lang.Object CANCELLED,private static final java.lang.String DONE,private static final org.apache.ignite.internal.util.future.GridFutureAdapter.Node INIT,private volatile boolean ignoreInterrupts,private volatile java.lang.Object state,private static final AtomicReferenceFieldUpdater<GridFutureAdapter#RAW,java.lang.Object> stateUpdater
|
apache_ignite
|
ignite/modules/core/src/main/java/org/apache/ignite/internal/processors/marshaller/GridMarshallerMappingProcessor.java
|
MappingProposedListener
|
onCustomEvent
|
class MappingProposedListener implements CustomEventListener<MappingProposedMessage> {
/** {@inheritDoc} */
@Override public void onCustomEvent(
AffinityTopologyVersion topVer,
ClusterNode snd,
MappingProposedMessage msg
) {<FILL_FUNCTION_BODY>}
/**
* @param mappingItem Mapping item.
* @param conflictingClsName Conflicting class name.
*/
private IgniteCheckedException duplicateMappingException(
MarshallerMappingItem mappingItem,
String conflictingClsName
) {
return new IgniteCheckedException("Duplicate ID [platformId="
+ mappingItem.platformId()
+ ", typeId="
+ mappingItem.typeId()
+ ", oldCls="
+ conflictingClsName
+ ", newCls="
+ mappingItem.className() + "]");
}
}
|
if (!ctx.isStopping()) {
if (msg.duplicated())
return;
if (!msg.inConflict()) {
MarshallerMappingItem item = msg.mappingItem();
MappedName existingName = marshallerCtx.onMappingProposed(item);
if (existingName != null) {
String existingClsName = existingName.className();
if (existingClsName.equals(item.className()) && !existingName.accepted())
msg.markDuplicated();
else if (!existingClsName.equals(item.className()))
msg.conflictingWithClass(existingClsName);
}
}
else {
UUID origNodeId = msg.origNodeId();
if (origNodeId.equals(ctx.localNodeId())) {
GridFutureAdapter<MappingExchangeResult> fut = mappingExchangeSyncMap.get(msg.mappingItem());
assert fut != null : msg;
fut.onDone(MappingExchangeResult.createFailureResult(
duplicateMappingException(msg.mappingItem(), msg.conflictingClassName())));
}
}
}
| 231
| 292
| 523
|
<methods>public void collectGridNodeData(org.apache.ignite.spi.discovery.DiscoveryDataBag) ,public void collectJoiningNodeData(org.apache.ignite.spi.discovery.DiscoveryDataBag) ,public org.apache.ignite.internal.GridComponent.DiscoveryDataExchangeType discoveryDataType() ,public void onDisconnected(IgniteFuture<?>) throws org.apache.ignite.IgniteCheckedException,public void onGridDataReceived(org.apache.ignite.spi.discovery.DiscoveryDataBag.GridDiscoveryData) ,public void onJoiningNodeDataReceived(org.apache.ignite.spi.discovery.DiscoveryDataBag.JoiningNodeDiscoveryData) ,public void onKernalStart(boolean) throws org.apache.ignite.IgniteCheckedException,public void onKernalStop(boolean) ,public IgniteInternalFuture<?> onReconnected(boolean) throws org.apache.ignite.IgniteCheckedException,public void printMemoryStats() ,public void start() throws org.apache.ignite.IgniteCheckedException,public void stop(boolean) throws org.apache.ignite.IgniteCheckedException,public java.lang.String toString() ,public org.apache.ignite.spi.IgniteNodeValidationResult validateNode(org.apache.ignite.cluster.ClusterNode) ,public org.apache.ignite.spi.IgniteNodeValidationResult validateNode(org.apache.ignite.cluster.ClusterNode, org.apache.ignite.spi.discovery.DiscoveryDataBag.JoiningNodeDiscoveryData) <variables>private static final java.lang.String DIAGNOSTIC_LOG_CATEGORY,protected final non-sealed org.apache.ignite.internal.GridKernalContext ctx,protected final non-sealed org.apache.ignite.IgniteLogger diagnosticLog,protected final non-sealed org.apache.ignite.IgniteLogger log
|
apache_ignite
|
ignite/modules/core/src/main/java/org/apache/ignite/internal/processors/marshaller/MarshallerMappingItem.java
|
MarshallerMappingItem
|
equals
|
class MarshallerMappingItem implements Serializable {
/** */
private static final long serialVersionUID = 0L;
/** */
private final byte platformId;
/** */
private final int typeId;
/** */
private String clsName;
/**
* Class name may be null when instance is created to request missing mapping from cluster.
*
* @param platformId Platform id.
* @param typeId Type id.
* @param clsName Class name. May be null in case when the item is created to request missing mapping from grid.
*/
public MarshallerMappingItem(byte platformId, int typeId, @Nullable String clsName) {
this.platformId = platformId;
this.typeId = typeId;
this.clsName = clsName;
}
/** */
public int typeId() {
return typeId;
}
/** */
public byte platformId() {
return platformId;
}
/** */
public String className() {
return clsName;
}
/**
* @param clsName Class name.
*/
public void className(String clsName) {
this.clsName = clsName;
}
/** {@inheritDoc} */
@Override public boolean equals(Object obj) {<FILL_FUNCTION_BODY>}
/** {@inheritDoc} */
@Override public int hashCode() {
return 31 * 31 * ((int)platformId) + 31 * typeId + (clsName != null ? clsName.hashCode() : 0);
}
/** {@inheritDoc} */
@Override public String toString() {
return "[platformId: " + platformId + ", typeId:" + typeId + ", clsName: " + clsName + "]";
}
}
|
if (obj == this)
return true;
if (!(obj instanceof MarshallerMappingItem))
return false;
MarshallerMappingItem that = (MarshallerMappingItem)obj;
return platformId == that.platformId
&& typeId == that.typeId
&& (Objects.equals(clsName, that.clsName));
| 466
| 89
| 555
|
<no_super_class>
|
apache_ignite
|
ignite/modules/core/src/main/java/org/apache/ignite/internal/processors/marshaller/MissingMappingRequestMessage.java
|
MissingMappingRequestMessage
|
writeTo
|
class MissingMappingRequestMessage implements Message {
/** */
private static final long serialVersionUID = 0L;
/** */
private byte platformId;
/** */
private int typeId;
/**
* Default constructor.
*/
public MissingMappingRequestMessage() {
//No-op.
}
/**
* @param platformId Platform id.
* @param typeId Type id.
*/
MissingMappingRequestMessage(byte platformId, int typeId) {
this.platformId = platformId;
this.typeId = typeId;
}
/** {@inheritDoc} */
@Override public boolean writeTo(ByteBuffer buf, MessageWriter writer) {<FILL_FUNCTION_BODY>}
/** {@inheritDoc} */
@Override public boolean readFrom(ByteBuffer buf, MessageReader reader) {
reader.setBuffer(buf);
if (!reader.beforeMessageRead())
return false;
switch (reader.state()) {
case 0:
platformId = reader.readByte("platformId");
if (!reader.isLastRead())
return false;
reader.incrementState();
case 1:
typeId = reader.readInt("typeId");
if (!reader.isLastRead())
return false;
reader.incrementState();
}
return reader.afterMessageRead(MissingMappingRequestMessage.class);
}
/** {@inheritDoc} */
@Override public short directType() {
return 78;
}
/** {@inheritDoc} */
@Override public byte fieldsCount() {
return 2;
}
/** {@inheritDoc} */
@Override public void onAckReceived() {
// No-op.
}
/** */
public byte platformId() {
return platformId;
}
/** */
public int typeId() {
return typeId;
}
/** {@inheritDoc} */
@Override public String toString() {
return S.toString(MissingMappingRequestMessage.class, this);
}
}
|
writer.setBuffer(buf);
if (!writer.isHeaderWritten()) {
if (!writer.writeHeader(directType(), fieldsCount()))
return false;
writer.onHeaderWritten();
}
switch (writer.state()) {
case 0:
if (!writer.writeByte("platformId", platformId))
return false;
writer.incrementState();
case 1:
if (!writer.writeInt("typeId", typeId))
return false;
writer.incrementState();
}
return true;
| 538
| 149
| 687
|
<no_super_class>
|
apache_ignite
|
ignite/modules/core/src/main/java/org/apache/ignite/internal/processors/metastorage/persistence/DistributedMetaStorageHistoryCache.java
|
DistributedMetaStorageHistoryCache
|
equals
|
class DistributedMetaStorageHistoryCache {
/**
* Version of the oldest history item in the cache. For empty history it is expected to be zero until the
* first change.
*/
private long startingVer;
/**
* Looped array to store history items. Must always have size that is the power of two, 16 by default.
*/
private DistributedMetaStorageHistoryItem[] items;
/**
* Index of the first item. 0 if cache is empty.
*/
private int from;
/**
* Index next to the last one. 0 if cache is empty.
*/
private int to;
/**
* Approximate size of all cached history items.
*/
private long sizeApproximation;
/**
* Default constructor.
*/
public DistributedMetaStorageHistoryCache() {
items = new DistributedMetaStorageHistoryItem[16];
}
/**
* Get history item by the specific version.
*
* @param ver Specific version.
* @return Requested hitsory item or {@code null} if it's not found.
*/
public DistributedMetaStorageHistoryItem get(long ver) {
int size = size();
if (ver < startingVer || ver >= startingVer + size)
return null;
return items[(from + (int)(ver - startingVer)) & (items.length - 1)];
}
/**
* Add history item to the cache. Works in "append-only" mode.
*
* @param ver Specific version. Must be either the last version in current cache or the next version after it.
* @param item New history item. Expected to be the same as already stored one if {@code ver} is equal to the last
* version in the cache. Otherwise any non-null value is suitable.
*/
public void put(long ver, DistributedMetaStorageHistoryItem item) {
if (isEmpty()) {
assert from == 0;
assert to == 0;
startingVer = ver;
}
if (ver == startingVer + size()) {
items[to] = item;
sizeApproximation += item.estimateSize();
to = next(to);
if (from == to)
expandBuffer();
}
else {
assert ver == startingVer + size() - 1 : startingVer + " " + from + " " + to + " " + ver;
assert items[(to - 1) & (items.length - 1)].equals(item);
}
}
/**
* Remove oldest history item from the cache.
*
* @return Removed value.
*/
public DistributedMetaStorageHistoryItem removeOldest() {
DistributedMetaStorageHistoryItem oldItem = items[from];
sizeApproximation -= oldItem.estimateSize();
items[from] = null;
from = next(from);
++startingVer;
if (from == to) {
from = to = 0;
startingVer = 0L;
assert sizeApproximation == 0L;
}
return oldItem;
}
/**
* Number of elements in the cache.
*/
public int size() {
return (to - from) & (items.length - 1);
}
/**
* @return {@code true} if cache is empty, {@code false} otherwise.
*/
public boolean isEmpty() {
return sizeApproximation == 0;
}
/**
* Clear the history cache.
*/
public void clear() {
Arrays.fill(items, null);
from = to = 0;
sizeApproximation = startingVer = 0L;
}
/**
* @return Approximate size of all cached history items.
*/
public long sizeInBytes() {
return sizeApproximation;
}
/**
* @return All history items as array.
*/
public DistributedMetaStorageHistoryItem[] toArray() {
int size = size();
DistributedMetaStorageHistoryItem[] arr = new DistributedMetaStorageHistoryItem[size];
if (from <= to)
System.arraycopy(items, from, arr, 0, size);
else {
System.arraycopy(items, from, arr, 0, items.length - from);
System.arraycopy(items, 0, arr, items.length - from, to);
}
return arr;
}
/** */
private int next(int i) {
return (i + 1) & (items.length - 1);
}
/** */
private void expandBuffer() {
DistributedMetaStorageHistoryItem[] items = this.items;
DistributedMetaStorageHistoryItem[] newItems = new DistributedMetaStorageHistoryItem[items.length * 2];
System.arraycopy(items, from, newItems, 0, items.length - from);
System.arraycopy(items, 0, newItems, items.length - from, to);
from = 0;
to = items.length;
this.items = newItems;
}
/** {@inheritDoc} */
@Override public boolean equals(Object o) {<FILL_FUNCTION_BODY>}
}
|
if (this == o)
return true;
if (o == null || getClass() != o.getClass())
return false;
DistributedMetaStorageHistoryCache that = (DistributedMetaStorageHistoryCache)o;
int size = size();
if (size != that.size())
return false;
if (startingVer != that.startingVer)
return false;
for (long ver = startingVer; ver < startingVer + size; ver++) {
if (!get(ver).equals(that.get(ver)))
return false;
}
assert sizeInBytes() == that.sizeInBytes();
return true;
| 1,338
| 174
| 1,512
|
<no_super_class>
|
apache_ignite
|
ignite/modules/core/src/main/java/org/apache/ignite/internal/processors/metastorage/persistence/DistributedMetaStorageVersion.java
|
DistributedMetaStorageVersion
|
equals
|
class DistributedMetaStorageVersion extends IgniteDataTransferObject {
/** Serial version UID. */
private static final long serialVersionUID = 0L;
/** Version with id "0". */
public static final DistributedMetaStorageVersion INITIAL_VERSION = new DistributedMetaStorageVersion(0L, 1L);
/** Incremental rehashing considering new update information. */
private static long nextHash(long hash, DistributedMetaStorageHistoryItem update) {
return hash * 31L + update.longHash();
}
/**
* Id is basically a total number of distributed metastorage updates in current cluster.
* Increases incrementally on every update starting with zero.
*
* @see #INITIAL_VERSION
*/
@GridToStringInclude
private long id;
/**
* Hash of the whole updates list. Hashing algorinthm is almost the same as in {@link List#hashCode()}, but with
* {@code long} value instead of {@code int}.
*/
@GridToStringInclude
private long hash;
/** Default constructor for deserialization. */
public DistributedMetaStorageVersion() {
// No-op.
}
/**
* Constructor with all fields.
*
* @param id Id.
* @param hash Hash.
*/
private DistributedMetaStorageVersion(long id, long hash) {
this.id = id;
this.hash = hash;
}
/**
* Calculate next version considering passed update information.
*
* @param update Single update.
* @return Next version.
*/
public DistributedMetaStorageVersion nextVersion(DistributedMetaStorageHistoryItem update) {
return new DistributedMetaStorageVersion(id + 1, nextHash(hash, update));
}
/**
* Calculate next version considering passed update information.
*
* @param updates Updates collection.
* @return Next version.
*/
public DistributedMetaStorageVersion nextVersion(Collection<DistributedMetaStorageHistoryItem> updates) {
long hash = this.hash;
for (DistributedMetaStorageHistoryItem update : updates)
hash = nextHash(hash, update);
return new DistributedMetaStorageVersion(id + updates.size(), hash);
}
/**
* Calculate next version considering passed update information.
*
* @param updates Updates array.
* @param fromIdx Index of the first required update in the array.
* @param toIdx Index after the last required update in the array.
* @return Next version.
*/
public DistributedMetaStorageVersion nextVersion(
DistributedMetaStorageHistoryItem[] updates,
int fromIdx,
int toIdx // exclusive
) {
long hash = this.hash;
for (int idx = fromIdx; idx < toIdx; idx++)
hash = nextHash(hash, updates[idx]);
return new DistributedMetaStorageVersion(id + toIdx - fromIdx, hash);
}
/**
* Calculate next version considering passed update information.
*
* @param update Function that provides the update by specific version.
* @param fromVer Starting version, inclusive.
* @param toVer Ending version, inclusive.
* @return Next version.
*/
public DistributedMetaStorageVersion nextVersion(
LongFunction<DistributedMetaStorageHistoryItem> update,
long fromVer,
long toVer // inclusive
) {
assert fromVer <= toVer;
long hash = this.hash;
for (long idx = fromVer; idx <= toVer; idx++)
hash = nextHash(hash, update.apply(idx));
return new DistributedMetaStorageVersion(id + toVer + 1 - fromVer, hash);
}
/**
* Id is basically a total number of distributed metastorage updates in current cluster.
* Increases incrementally on every update starting with zero.
*
* @see #INITIAL_VERSION
*/
public long id() {
return id;
}
/**
* Hash of the whole updates list. Hashing algorinthm is almost the same as in {@link List#hashCode()}, but with
* {@code long} value instead of {@code int}.
*/
public long hash() {
return hash;
}
/** {@inheritDoc} */
@Override protected void writeExternalData(ObjectOutput out) throws IOException {
out.writeLong(id);
out.writeLong(hash);
}
/** {@inheritDoc} */
@Override protected void readExternalData(byte protoVer, ObjectInput in) throws IOException {
id = in.readLong();
hash = in.readLong();
}
/** {@inheritDoc} */
@Override public boolean equals(Object o) {<FILL_FUNCTION_BODY>}
/** {@inheritDoc} */
@Override public int hashCode() {
return 31 * Long.hashCode(id) + Long.hashCode(hash);
}
/** {@inheritDoc} */
@Override public String toString() {
return S.toString(DistributedMetaStorageVersion.class, this);
}
}
|
if (this == o)
return true;
if (o == null || getClass() != o.getClass())
return false;
DistributedMetaStorageVersion ver = (DistributedMetaStorageVersion)o;
return id == ver.id && hash == ver.hash;
| 1,300
| 75
| 1,375
|
<methods>public non-sealed void <init>() ,public byte getProtocolVersion() ,public void readExternal(java.io.ObjectInput) throws java.io.IOException, java.lang.ClassNotFoundException,public void writeExternal(java.io.ObjectOutput) throws java.io.IOException<variables>private static final int MAGIC,protected static final byte V1,protected static final byte V2,protected static final byte V3,protected static final byte V4,protected static final byte V5,protected static final byte V6,protected static final byte V7,protected static final byte V8,protected static final byte V9,private static final long serialVersionUID
|
apache_ignite
|
ignite/modules/core/src/main/java/org/apache/ignite/internal/processors/metric/MetricsMxBeanImpl.java
|
MetricsMxBeanImpl
|
resetMetrics
|
class MetricsMxBeanImpl implements MetricsMxBean {
/** Metric manager. */
private final GridMetricManager mmgr;
/** Logger. */
private final IgniteLogger log;
/**
* @param mmgr Metric manager.
* @param log Logger.
*/
public MetricsMxBeanImpl(GridMetricManager mmgr, IgniteLogger log) {
this.mmgr = mmgr;
this.log = log;
}
/** {@inheritDoc} */
@Override public void resetMetrics(String registry) {<FILL_FUNCTION_BODY>}
/** {@inheritDoc} */
@Override public void configureHitRateMetric(String name, long rateTimeInterval) {
try {
mmgr.configureHitRate(name, rateTimeInterval);
}
catch (IgniteCheckedException e) {
throw new IgniteException(e);
}
}
/** {@inheritDoc} */
@Override public void configureHistogramMetric(String name, long[] bounds) {
try {
mmgr.configureHistogram(name, bounds);
}
catch (IgniteCheckedException e) {
throw new IgniteException(e);
}
}
}
|
assert registry != null;
MetricRegistryImpl mreg = mmgr.registry(registry);
if (mreg != null)
mreg.reset();
else if (log.isInfoEnabled())
log.info("\"" + registry + "\" not found.");
| 315
| 74
| 389
|
<no_super_class>
|
apache_ignite
|
ignite/modules/core/src/main/java/org/apache/ignite/internal/processors/metric/PushMetricsExporterAdapter.java
|
PushMetricsExporterAdapter
|
onContextInitialized0
|
class PushMetricsExporterAdapter extends IgniteSpiAdapter implements MetricExporterSpi {
/** Default export period in milliseconds. */
public static final long DFLT_EXPORT_PERIOD = 60_000L;
/** Metric registry. */
protected ReadOnlyMetricManager mreg;
/** Metric filter. */
protected @Nullable Predicate<ReadOnlyMetricRegistry> filter;
/** Export period. */
private long period = DFLT_EXPORT_PERIOD;
/** Push spi executor. */
private ScheduledExecutorService execSvc;
/** Export task future. */
private ScheduledFuture<?> fut;
/** {@inheritDoc} */
@Override public void spiStart(@Nullable String igniteInstanceName) throws IgniteSpiException {
// No-op.
}
/** {@inheritDoc} */
@Override public void spiStop() throws IgniteSpiException {
fut.cancel(false);
execSvc.shutdown();
}
/**
* Callback to do the export of metrics info.
* Method will be called into some Ignite managed thread each {@link #getPeriod()} millisecond.
*/
public abstract void export();
/**
* Sets period in milliseconds after {@link #export()} method should be called.
*
* @param period Period in milliseconds.
*/
public void setPeriod(long period) {
this.period = period;
}
/** @return Period in milliseconds after {@link #export()} method should be called. */
public long getPeriod() {
return period;
}
/** {@inheritDoc} */
@Override public void setMetricRegistry(ReadOnlyMetricManager mreg) {
this.mreg = mreg;
}
/** {@inheritDoc} */
@Override public void setExportFilter(Predicate<ReadOnlyMetricRegistry> filter) {
this.filter = filter;
}
/** {@inheritDoc} */
@Override protected void onContextInitialized0(IgniteSpiContext spiCtx) throws IgniteSpiException {<FILL_FUNCTION_BODY>}
}
|
super.onContextInitialized0(spiCtx);
execSvc = Executors.newSingleThreadScheduledExecutor(new IgniteThreadFactory(igniteInstanceName,
"push-metrics-exporter"));
fut = execSvc.scheduleWithFixedDelay(() -> {
try {
export();
}
catch (Exception e) {
log.error("Metrics export error. " +
"This exporter will be stopped [spiClass=" + getClass() + ",name=" + getName() + ']', e);
throw e;
}
}, period, period, MILLISECONDS);
| 558
| 162
| 720
|
<methods>public long clientFailureDetectionTimeout() ,public long failureDetectionTimeout() ,public void failureDetectionTimeoutEnabled(boolean) ,public boolean failureDetectionTimeoutEnabled() ,public org.apache.ignite.internal.util.IgniteExceptionRegistry getExceptionRegistry() ,public java.lang.String getName() ,public Map<java.lang.String,java.lang.Object> getNodeAttributes() throws org.apache.ignite.spi.IgniteSpiException,public org.apache.ignite.spi.IgniteSpiContext getSpiContext() ,public org.apache.ignite.Ignite ignite() ,public Collection<java.lang.Object> injectables() ,public final void onBeforeStart() ,public void onClientDisconnected(IgniteFuture<?>) ,public void onClientReconnected(boolean) ,public final void onContextDestroyed() ,public final void onContextInitialized(org.apache.ignite.spi.IgniteSpiContext) throws org.apache.ignite.spi.IgniteSpiException,public org.apache.ignite.spi.IgniteSpiAdapter setName(java.lang.String) ,public final boolean started() <variables>private long clientFailureDetectionTimeout,private long failureDetectionTimeout,private boolean failureDetectionTimeoutEnabled,protected org.apache.ignite.Ignite ignite,protected java.lang.String igniteInstanceName,private org.apache.ignite.cluster.ClusterNode locNode,protected org.apache.ignite.IgniteLogger log,private java.lang.String name,private org.apache.ignite.internal.managers.eventstorage.GridLocalEventListener paramsLsnr,private volatile org.apache.ignite.spi.IgniteSpiContext spiCtx,private javax.management.ObjectName spiMBean,private long startTstamp,private final java.util.concurrent.atomic.AtomicBoolean startedFlag
|
apache_ignite
|
ignite/modules/core/src/main/java/org/apache/ignite/internal/processors/metric/SqlViewMetricExporterSpi.java
|
SqlViewMetricExporterSpi
|
onContextInitialized0
|
class SqlViewMetricExporterSpi extends IgniteSpiAdapter implements MetricExporterSpi {
/** System view name. */
public static final String SYS_VIEW_NAME = "metrics";
/** Metric Registry. */
private ReadOnlyMetricManager mreg;
/** {@inheritDoc} */
@Override protected void onContextInitialized0(IgniteSpiContext spiCtx) throws IgniteSpiException {<FILL_FUNCTION_BODY>}
/** {@inheritDoc} */
@Override public void spiStart(@Nullable String igniteInstanceName) throws IgniteSpiException {
// No-op.
}
/** {@inheritDoc} */
@Override public void spiStop() throws IgniteSpiException {
// No-op.
}
/** {@inheritDoc} */
@Override public void setMetricRegistry(ReadOnlyMetricManager mreg) {
this.mreg = mreg;
}
/** {@inheritDoc} */
@Override public void setExportFilter(Predicate<ReadOnlyMetricRegistry> filter) {
// No-op.
}
}
|
GridKernalContext ctx = ((IgniteEx)ignite()).context();
ctx.systemView().registerInnerCollectionView(
SYS_VIEW_NAME,
"Ignite metrics",
new MetricsViewWalker(),
mreg,
r -> r,
(r, m) -> new MetricsView(m)
);
if (log.isDebugEnabled())
log.debug(SYS_VIEW_NAME + " SQL view for metrics created.");
| 285
| 124
| 409
|
<methods>public long clientFailureDetectionTimeout() ,public long failureDetectionTimeout() ,public void failureDetectionTimeoutEnabled(boolean) ,public boolean failureDetectionTimeoutEnabled() ,public org.apache.ignite.internal.util.IgniteExceptionRegistry getExceptionRegistry() ,public java.lang.String getName() ,public Map<java.lang.String,java.lang.Object> getNodeAttributes() throws org.apache.ignite.spi.IgniteSpiException,public org.apache.ignite.spi.IgniteSpiContext getSpiContext() ,public org.apache.ignite.Ignite ignite() ,public Collection<java.lang.Object> injectables() ,public final void onBeforeStart() ,public void onClientDisconnected(IgniteFuture<?>) ,public void onClientReconnected(boolean) ,public final void onContextDestroyed() ,public final void onContextInitialized(org.apache.ignite.spi.IgniteSpiContext) throws org.apache.ignite.spi.IgniteSpiException,public org.apache.ignite.spi.IgniteSpiAdapter setName(java.lang.String) ,public final boolean started() <variables>private long clientFailureDetectionTimeout,private long failureDetectionTimeout,private boolean failureDetectionTimeoutEnabled,protected org.apache.ignite.Ignite ignite,protected java.lang.String igniteInstanceName,private org.apache.ignite.cluster.ClusterNode locNode,protected org.apache.ignite.IgniteLogger log,private java.lang.String name,private org.apache.ignite.internal.managers.eventstorage.GridLocalEventListener paramsLsnr,private volatile org.apache.ignite.spi.IgniteSpiContext spiCtx,private javax.management.ObjectName spiMBean,private long startTstamp,private final java.util.concurrent.atomic.AtomicBoolean startedFlag
|
apache_ignite
|
ignite/modules/core/src/main/java/org/apache/ignite/internal/processors/nodevalidation/OsDiscoveryNodeValidationProcessor.java
|
OsDiscoveryNodeValidationProcessor
|
validateNode
|
class OsDiscoveryNodeValidationProcessor extends GridProcessorAdapter implements DiscoveryNodeValidationProcessor {
/**
* @param ctx Kernal context.
*/
public OsDiscoveryNodeValidationProcessor(GridKernalContext ctx) {
super(ctx);
}
/** {@inheritDoc} */
@Nullable @Override public IgniteNodeValidationResult validateNode(ClusterNode node) {<FILL_FUNCTION_BODY>}
}
|
ClusterNode locNode = ctx.discovery().localNode();
// Check version.
String locBuildVer = locNode.attribute(ATTR_BUILD_VER);
String rmtBuildVer = node.attribute(ATTR_BUILD_VER);
if (!F.eq(rmtBuildVer, locBuildVer)) {
// OS nodes don't support rolling updates.
if (!locBuildVer.equals(rmtBuildVer)) {
String errMsg = "Local node and remote node have different version numbers " +
"(node will not join, Ignite does not support rolling updates, " +
"so versions must be exactly the same) " +
"[locBuildVer=" + locBuildVer + ", rmtBuildVer=" + rmtBuildVer +
", locNodeAddrs=" + U.addressesAsString(locNode) +
", rmtNodeAddrs=" + U.addressesAsString(node) +
", locNodeId=" + locNode.id() + ", rmtNodeId=" + node.id() + ']';
LT.warn(log, errMsg);
// Always output in debug.
if (log.isDebugEnabled())
log.debug(errMsg);
return new IgniteNodeValidationResult(node.id(), errMsg);
}
}
return null;
| 106
| 331
| 437
|
<methods>public void collectGridNodeData(org.apache.ignite.spi.discovery.DiscoveryDataBag) ,public void collectJoiningNodeData(org.apache.ignite.spi.discovery.DiscoveryDataBag) ,public org.apache.ignite.internal.GridComponent.DiscoveryDataExchangeType discoveryDataType() ,public void onDisconnected(IgniteFuture<?>) throws org.apache.ignite.IgniteCheckedException,public void onGridDataReceived(org.apache.ignite.spi.discovery.DiscoveryDataBag.GridDiscoveryData) ,public void onJoiningNodeDataReceived(org.apache.ignite.spi.discovery.DiscoveryDataBag.JoiningNodeDiscoveryData) ,public void onKernalStart(boolean) throws org.apache.ignite.IgniteCheckedException,public void onKernalStop(boolean) ,public IgniteInternalFuture<?> onReconnected(boolean) throws org.apache.ignite.IgniteCheckedException,public void printMemoryStats() ,public void start() throws org.apache.ignite.IgniteCheckedException,public void stop(boolean) throws org.apache.ignite.IgniteCheckedException,public java.lang.String toString() ,public org.apache.ignite.spi.IgniteNodeValidationResult validateNode(org.apache.ignite.cluster.ClusterNode) ,public org.apache.ignite.spi.IgniteNodeValidationResult validateNode(org.apache.ignite.cluster.ClusterNode, org.apache.ignite.spi.discovery.DiscoveryDataBag.JoiningNodeDiscoveryData) <variables>private static final java.lang.String DIAGNOSTIC_LOG_CATEGORY,protected final non-sealed org.apache.ignite.internal.GridKernalContext ctx,protected final non-sealed org.apache.ignite.IgniteLogger diagnosticLog,protected final non-sealed org.apache.ignite.IgniteLogger log
|
apache_ignite
|
ignite/modules/core/src/main/java/org/apache/ignite/internal/processors/odbc/ClientAsyncResponse.java
|
ClientAsyncResponse
|
error
|
class ClientAsyncResponse extends ClientResponse implements ClientListenerAsyncResponse {
/** Future for response. */
private final IgniteInternalFuture<? extends ClientListenerResponse> fut;
/**
* Constructs async response.
*/
public ClientAsyncResponse(long reqId, IgniteInternalFuture<? extends ClientListenerResponse> fut) {
super(reqId);
this.fut = fut;
}
/** {@inheritDoc} */
@Override public IgniteInternalFuture<? extends ClientListenerResponse> future() {
return fut;
}
/** {@inheritDoc} */
@Override public int status() {
assert fut.isDone();
try {
return fut.get().status();
}
catch (Exception e) {
return STATUS_FAILED;
}
}
/** {@inheritDoc} */
@Override protected void status(int status) {
throw new IllegalStateException();
}
/** {@inheritDoc} */
@Override public String error() {<FILL_FUNCTION_BODY>}
/** {@inheritDoc} */
@Override protected void error(String err) {
throw new IllegalStateException();
}
/** {@inheritDoc} */
@Override public void onSent() {
assert fut.isDone();
try {
fut.get().onSent();
}
catch (Exception ignore) {
// Ignore.
}
}
}
|
assert fut.isDone();
try {
return fut.get().error();
}
catch (Exception e) {
return e.getMessage();
}
| 362
| 46
| 408
|
<methods>public void <init>(long) ,public void <init>(long, java.lang.String) ,public void <init>(long, int, java.lang.String) ,public void encode(org.apache.ignite.internal.processors.platform.client.ClientConnectionContext, org.apache.ignite.internal.binary.BinaryRawWriterEx, org.apache.ignite.internal.processors.platform.client.ClientAffinityTopologyVersion) ,public void encode(org.apache.ignite.internal.processors.platform.client.ClientConnectionContext, org.apache.ignite.internal.binary.BinaryRawWriterEx) ,public long requestId() <variables>private final non-sealed long reqId
|
apache_ignite
|
ignite/modules/core/src/main/java/org/apache/ignite/internal/processors/odbc/jdbc/JdbcBatchExecuteRequest.java
|
JdbcBatchExecuteRequest
|
readBinary
|
class JdbcBatchExecuteRequest extends JdbcRequest {
/** Schema name. */
private String schemaName;
/** Sql query. */
@GridToStringInclude(sensitive = true)
private List<JdbcQuery> queries;
/** Client auto commit flag state. */
private boolean autoCommit;
/**
* Last stream batch flag - whether open streamers on current connection
* must be flushed and closed after this batch.
*/
private boolean lastStreamBatch;
/**
* Default constructor.
*/
public JdbcBatchExecuteRequest() {
super(BATCH_EXEC);
}
/**
* Constructor for child requests.
* @param type Request type/
*/
protected JdbcBatchExecuteRequest(byte type) {
super(type);
}
/**
* @param schemaName Schema name.
* @param queries Queries.
* @param autoCommit Client auto commit flag state.
* @param lastStreamBatch {@code true} in case the request is the last batch at the stream.
*/
public JdbcBatchExecuteRequest(String schemaName, List<JdbcQuery> queries, boolean autoCommit,
boolean lastStreamBatch) {
super(BATCH_EXEC);
assert lastStreamBatch || !F.isEmpty(queries);
this.schemaName = schemaName;
this.queries = queries;
this.autoCommit = autoCommit;
this.lastStreamBatch = lastStreamBatch;
}
/**
* Constructor for child requests.
*
* @param type Request type.
* @param schemaName Schema name.
* @param queries Queries.
* @param autoCommit Client auto commit flag state.
* @param lastStreamBatch {@code true} in case the request is the last batch at the stream.
*/
protected JdbcBatchExecuteRequest(byte type, String schemaName, List<JdbcQuery> queries, boolean autoCommit,
boolean lastStreamBatch) {
super(type);
assert lastStreamBatch || !F.isEmpty(queries);
this.schemaName = schemaName;
this.queries = queries;
this.autoCommit = autoCommit;
this.lastStreamBatch = lastStreamBatch;
}
/**
* @return Schema name.
*/
@Nullable public String schemaName() {
return schemaName;
}
/**
* @return Queries.
*/
public List<JdbcQuery> queries() {
return queries;
}
/**
* @return Auto commit flag.
*/
boolean autoCommit() {
return autoCommit;
}
/**
* @return Last stream batch flag.
*/
public boolean isLastStreamBatch() {
return lastStreamBatch;
}
/** {@inheritDoc} */
@Override public void writeBinary(
BinaryWriterExImpl writer,
JdbcProtocolContext protoCtx
) throws BinaryObjectException {
super.writeBinary(writer, protoCtx);
writer.writeString(schemaName);
if (!F.isEmpty(queries)) {
writer.writeInt(queries.size());
for (JdbcQuery q : queries)
q.writeBinary(writer, protoCtx);
}
else
writer.writeInt(0);
if (protoCtx.isStreamingSupported())
writer.writeBoolean(lastStreamBatch);
if (protoCtx.isAutoCommitSupported())
writer.writeBoolean(autoCommit);
}
/** {@inheritDoc} */
@Override public void readBinary(
BinaryReaderExImpl reader,
JdbcProtocolContext protoCtx
) throws BinaryObjectException {<FILL_FUNCTION_BODY>}
/** {@inheritDoc} */
@Override public String toString() {
return S.toString(JdbcBatchExecuteRequest.class, this, super.toString());
}
}
|
super.readBinary(reader, protoCtx);
schemaName = reader.readString();
int n = reader.readInt();
queries = new ArrayList<>(n);
for (int i = 0; i < n; ++i) {
JdbcQuery qry = new JdbcQuery();
qry.readBinary(reader, protoCtx);
queries.add(qry);
}
if (protoCtx.isStreamingSupported())
lastStreamBatch = reader.readBoolean();
if (protoCtx.isAutoCommitSupported())
autoCommit = reader.readBoolean();
| 1,002
| 161
| 1,163
|
<methods>public void <init>(byte) ,public void readBinary(org.apache.ignite.internal.binary.BinaryReaderExImpl, org.apache.ignite.internal.processors.odbc.jdbc.JdbcProtocolContext) throws org.apache.ignite.binary.BinaryObjectException,public static org.apache.ignite.internal.processors.odbc.jdbc.JdbcRequest readRequest(org.apache.ignite.internal.binary.BinaryReaderExImpl, org.apache.ignite.internal.processors.odbc.jdbc.JdbcProtocolContext) throws org.apache.ignite.binary.BinaryObjectException,public static long readRequestId(byte[]) ,public static byte readType(byte[]) ,public long requestId() ,public java.lang.String toString() ,public byte type() ,public void writeBinary(org.apache.ignite.internal.binary.BinaryWriterExImpl, org.apache.ignite.internal.processors.odbc.jdbc.JdbcProtocolContext) throws org.apache.ignite.binary.BinaryObjectException<variables>public static final byte BATCH_EXEC,static final byte BATCH_EXEC_ORDERED,public static final byte BINARY_TYPE_GET,public static final byte BINARY_TYPE_NAME_GET,public static final byte BINARY_TYPE_NAME_PUT,public static final byte BINARY_TYPE_PUT,static final byte BULK_LOAD_BATCH,public static final byte CACHE_PARTITIONS,public static final byte META_COLUMNS,public static final byte META_INDEXES,public static final byte META_PARAMS,public static final byte META_PRIMARY_KEYS,public static final byte META_SCHEMAS,public static final byte META_TABLES,static final byte QRY_CANCEL,static final byte QRY_CLOSE,public static final byte QRY_EXEC,static final byte QRY_FETCH,public static final byte QRY_META,private static final java.util.concurrent.atomic.AtomicLong REQ_ID_GENERATOR,private long reqId,private byte type
|
apache_ignite
|
ignite/modules/core/src/main/java/org/apache/ignite/internal/processors/odbc/jdbc/JdbcBinaryTypeGetResult.java
|
JdbcBinaryTypeGetResult
|
readBinary
|
class JdbcBinaryTypeGetResult extends JdbcResult {
/** ID of initial request. */
private long reqId;
/** Binary type metadata. */
private BinaryMetadata meta;
/** Default constructor for deserialization purpose. */
JdbcBinaryTypeGetResult() {
super(BINARY_TYPE_GET);
}
/**
* @param reqId ID of initial request.
* @param meta Metadata of binary type.
*/
public JdbcBinaryTypeGetResult(long reqId, BinaryMetadata meta) {
super(BINARY_TYPE_GET);
this.reqId = reqId;
this.meta = meta;
}
/**
* Returns metadata of binary type.
*
* @return Metadata of binary type.
*/
public BinaryMetadata meta() {
return meta;
}
/**
* Returns ID of initial request.
*
* @return ID of initial request.
*/
public long reqId() {
return reqId;
}
/** {@inheritDoc} */
@Override public void writeBinary(BinaryWriterExImpl writer, JdbcProtocolContext protoCtx)
throws BinaryObjectException {
super.writeBinary(writer, protoCtx);
writer.writeLong(reqId);
try {
meta.writeTo(writer);
}
catch (IOException e) {
throw new BinaryObjectException(e);
}
}
/** {@inheritDoc} */
@Override public void readBinary(BinaryReaderExImpl reader, JdbcProtocolContext protoCtx)
throws BinaryObjectException {<FILL_FUNCTION_BODY>}
/** {@inheritDoc} */
@Override public String toString() {
return S.toString(JdbcBinaryTypeGetResult.class, this);
}
}
|
super.readBinary(reader, protoCtx);
reqId = reader.readLong();
meta = new BinaryMetadata();
try {
meta.readFrom(reader);
}
catch (IOException e) {
throw new BinaryObjectException(e);
}
| 463
| 75
| 538
|
<methods>public void <init>(byte) ,public void readBinary(org.apache.ignite.internal.binary.BinaryReaderExImpl, org.apache.ignite.internal.processors.odbc.jdbc.JdbcProtocolContext) throws org.apache.ignite.binary.BinaryObjectException,public static org.apache.ignite.internal.processors.odbc.jdbc.JdbcResult readResult(org.apache.ignite.internal.binary.BinaryReaderExImpl, org.apache.ignite.internal.processors.odbc.jdbc.JdbcProtocolContext) throws org.apache.ignite.binary.BinaryObjectException,public java.lang.String toString() ,public void writeBinary(org.apache.ignite.internal.binary.BinaryWriterExImpl, org.apache.ignite.internal.processors.odbc.jdbc.JdbcProtocolContext) throws org.apache.ignite.binary.BinaryObjectException<variables>public static final byte BATCH_EXEC,static final byte BATCH_EXEC_ORDERED,static final byte BINARY_TYPE_GET,static final byte BINARY_TYPE_NAME_GET,static final byte BULK_LOAD_ACK,static final byte CACHE_PARTITIONS,static final byte META_COLUMNS,static final byte META_COLUMNS_V2,static final byte META_COLUMNS_V3,static final byte META_COLUMNS_V4,static final byte META_INDEXES,static final byte META_PARAMS,static final byte META_PRIMARY_KEYS,static final byte META_SCHEMAS,static final byte META_TABLES,static final byte QRY_EXEC,static final byte QRY_EXEC_MULT,static final byte QRY_FETCH,static final byte QRY_META,static final byte UPDATE_BINARY_SCHEMA_ACK,private byte type
|
apache_ignite
|
ignite/modules/core/src/main/java/org/apache/ignite/internal/processors/odbc/jdbc/JdbcColumnMeta.java
|
JdbcColumnMeta
|
hashCode
|
class JdbcColumnMeta implements JdbcRawBinarylizable {
/** Cache name. */
private String schemaName;
/** Table name. */
private String tblName;
/** Column name. */
private String colName;
/** Data type. */
private int dataType;
/** Data type. */
private String dataTypeName;
/** Data type. */
private String dataTypeClass;
/**
* Default constructor is used for serialization.
*/
JdbcColumnMeta() {
// No-op.
}
/**
* @param info Field metadata.
*/
JdbcColumnMeta(GridQueryFieldMetadata info) {
this.schemaName = info.schemaName();
this.tblName = info.typeName();
this.colName = info.fieldName();
dataType = JdbcThinUtils.type(info.fieldTypeName());
dataTypeName = JdbcThinUtils.typeName(info.fieldTypeName());
dataTypeClass = info.fieldTypeName();
}
/**
* @param schemaName Schema.
* @param tblName Table.
* @param colName Column.
* @param cls Type.
*/
public JdbcColumnMeta(String schemaName, String tblName, String colName, Class<?> cls) {
this.schemaName = schemaName;
this.tblName = tblName;
this.colName = colName;
String type = cls.getName();
dataType = JdbcThinUtils.type(type);
dataTypeName = JdbcThinUtils.typeName(type);
dataTypeClass = type;
}
/**
* @return Schema name.
*/
public String schemaName() {
return schemaName;
}
/**
* @return Table name.
*/
public String tableName() {
return tblName;
}
/**
* @return Column name.
*/
public String columnName() {
return colName;
}
/**
* @return Column's data type.
*/
public int dataType() {
return dataType;
}
/**
* @return Column's data type name.
*/
public String dataTypeName() {
return dataTypeName;
}
/**
* @return Column's data type class.
*/
public String dataTypeClass() {
return dataTypeClass;
}
/**
* @return Column's default value.
*/
public String defaultValue() {
return null;
}
/**
* @return Column's precision.
*/
public int precision() {
return -1;
}
/**
* @return Column's scale.
*/
public int scale() {
return -1;
}
/**
* Return 'nullable' flag in compatibility mode (according with column name and column type).
*
* @return {@code true} in case the column allows null values. Otherwise returns {@code false}
*/
public boolean isNullable() {
return JdbcUtils.nullable(colName, dataTypeClass);
}
/** {@inheritDoc} */
@Override public void writeBinary(
BinaryWriterExImpl writer,
JdbcProtocolContext protoCtx
) {
writer.writeString(schemaName);
writer.writeString(tblName);
writer.writeString(colName);
writer.writeInt(dataType);
writer.writeString(dataTypeName);
writer.writeString(dataTypeClass);
}
/** {@inheritDoc} */
@Override public void readBinary(
BinaryReaderExImpl reader,
JdbcProtocolContext protoCtx
) {
schemaName = reader.readString();
tblName = reader.readString();
colName = reader.readString();
dataType = reader.readInt();
dataTypeName = reader.readString();
dataTypeClass = reader.readString();
}
/** {@inheritDoc} */
@Override public boolean equals(Object o) {
if (this == o)
return true;
if (o == null || getClass() != o.getClass())
return false;
JdbcColumnMeta meta = (JdbcColumnMeta)o;
return F.eq(schemaName, meta.schemaName) && F.eq(tblName, meta.tblName) && F.eq(colName, meta.colName);
}
/** {@inheritDoc} */
@Override public int hashCode() {<FILL_FUNCTION_BODY>}
/** {@inheritDoc} */
@Override public String toString() {
return S.toString(JdbcColumnMeta.class, this);
}
}
|
int result = schemaName != null ? schemaName.hashCode() : 0;
result = 31 * result + (tblName != null ? tblName.hashCode() : 0);
result = 31 * result + colName.hashCode();
return result;
| 1,219
| 73
| 1,292
|
<no_super_class>
|
apache_ignite
|
ignite/modules/core/src/main/java/org/apache/ignite/internal/processors/odbc/jdbc/JdbcMetaColumnsRequest.java
|
JdbcMetaColumnsRequest
|
readBinary
|
class JdbcMetaColumnsRequest extends JdbcRequest {
/** Schema name pattern. */
private String schemaName;
/** Table name pattern. */
private String tblName;
/** Column name pattern. */
private String colName;
/**
* Default constructor is used for deserialization.
*/
JdbcMetaColumnsRequest() {
super(META_COLUMNS);
}
/**
* @param schemaName Schema name.
* @param tblName Table name.
* @param colName Column name.
*/
public JdbcMetaColumnsRequest(String schemaName, String tblName, String colName) {
super(META_COLUMNS);
this.schemaName = schemaName;
this.tblName = tblName;
this.colName = colName;
}
/**
* @return Schema name pattern.
*/
@Nullable public String schemaName() {
return schemaName;
}
/**
* @return Table name pattern.
*/
public String tableName() {
return tblName;
}
/**
* @return Column name pattern.
*/
public String columnName() {
return colName;
}
/** {@inheritDoc} */
@Override public void writeBinary(
BinaryWriterExImpl writer,
JdbcProtocolContext protoCtx
) throws BinaryObjectException {
super.writeBinary(writer, protoCtx);
writer.writeString(schemaName);
writer.writeString(tblName);
writer.writeString(colName);
}
/** {@inheritDoc} */
@Override public void readBinary(
BinaryReaderExImpl reader,
JdbcProtocolContext protoCtx
) throws BinaryObjectException {<FILL_FUNCTION_BODY>}
/** {@inheritDoc} */
@Override public String toString() {
return S.toString(JdbcMetaColumnsRequest.class, this);
}
}
|
super.readBinary(reader, protoCtx);
schemaName = reader.readString();
tblName = reader.readString();
colName = reader.readString();
| 504
| 48
| 552
|
<methods>public void <init>(byte) ,public void readBinary(org.apache.ignite.internal.binary.BinaryReaderExImpl, org.apache.ignite.internal.processors.odbc.jdbc.JdbcProtocolContext) throws org.apache.ignite.binary.BinaryObjectException,public static org.apache.ignite.internal.processors.odbc.jdbc.JdbcRequest readRequest(org.apache.ignite.internal.binary.BinaryReaderExImpl, org.apache.ignite.internal.processors.odbc.jdbc.JdbcProtocolContext) throws org.apache.ignite.binary.BinaryObjectException,public static long readRequestId(byte[]) ,public static byte readType(byte[]) ,public long requestId() ,public java.lang.String toString() ,public byte type() ,public void writeBinary(org.apache.ignite.internal.binary.BinaryWriterExImpl, org.apache.ignite.internal.processors.odbc.jdbc.JdbcProtocolContext) throws org.apache.ignite.binary.BinaryObjectException<variables>public static final byte BATCH_EXEC,static final byte BATCH_EXEC_ORDERED,public static final byte BINARY_TYPE_GET,public static final byte BINARY_TYPE_NAME_GET,public static final byte BINARY_TYPE_NAME_PUT,public static final byte BINARY_TYPE_PUT,static final byte BULK_LOAD_BATCH,public static final byte CACHE_PARTITIONS,public static final byte META_COLUMNS,public static final byte META_INDEXES,public static final byte META_PARAMS,public static final byte META_PRIMARY_KEYS,public static final byte META_SCHEMAS,public static final byte META_TABLES,static final byte QRY_CANCEL,static final byte QRY_CLOSE,public static final byte QRY_EXEC,static final byte QRY_FETCH,public static final byte QRY_META,private static final java.util.concurrent.atomic.AtomicLong REQ_ID_GENERATOR,private long reqId,private byte type
|
apache_ignite
|
ignite/modules/core/src/main/java/org/apache/ignite/internal/processors/odbc/jdbc/JdbcRequest.java
|
JdbcRequest
|
readRequest
|
class JdbcRequest extends ClientListenerRequestNoId implements JdbcRawBinarylizable {
/** Execute sql query request. */
public static final byte QRY_EXEC = 2;
/** Fetch query results request. */
static final byte QRY_FETCH = 3;
/** Close query request. */
static final byte QRY_CLOSE = 4;
/** Get query columns metadata request. */
public static final byte QRY_META = 5;
/** Batch queries. */
public static final byte BATCH_EXEC = 6;
/** Get tables metadata request. */
public static final byte META_TABLES = 7;
/** Get columns metadata request. */
public static final byte META_COLUMNS = 8;
/** Get indexes metadata request. */
public static final byte META_INDEXES = 9;
/** Get SQL query parameters metadata request. */
public static final byte META_PARAMS = 10;
/** Get primary keys metadata request. */
public static final byte META_PRIMARY_KEYS = 11;
/** Get schemas metadata request. */
public static final byte META_SCHEMAS = 12;
/** Send a batch of a data from client to server. */
static final byte BULK_LOAD_BATCH = 13;
/** Ordered batch request. */
static final byte BATCH_EXEC_ORDERED = 14;
/** Execute cancel request. */
static final byte QRY_CANCEL = 15;
/** Get cache partitions distributions. */
public static final byte CACHE_PARTITIONS = 16;
/** Get binary type schema request. */
public static final byte BINARY_TYPE_GET = 17;
/** Update binary type schema request. */
public static final byte BINARY_TYPE_PUT = 18;
/** Get binary type name request. */
public static final byte BINARY_TYPE_NAME_GET = 19;
/** Update binary type name request. */
public static final byte BINARY_TYPE_NAME_PUT = 20;
/** Request Id generator. */
private static final AtomicLong REQ_ID_GENERATOR = new AtomicLong();
/** Request type. */
private byte type;
/** Request id. */
private long reqId;
/**
* @param type Command type.
*/
public JdbcRequest(byte type) {
this.type = type;
reqId = REQ_ID_GENERATOR.incrementAndGet();
}
/** {@inheritDoc} */
@Override public void writeBinary(
BinaryWriterExImpl writer,
JdbcProtocolContext protoCtx
) throws BinaryObjectException {
writer.writeByte(type);
if (protoCtx.isAffinityAwarenessSupported())
writer.writeLong(reqId);
}
/** {@inheritDoc} */
@Override public void readBinary(
BinaryReaderExImpl reader,
JdbcProtocolContext protoCtx
) throws BinaryObjectException {
if (protoCtx.isAffinityAwarenessSupported())
reqId = reader.readLong();
}
/** {@inheritDoc} */
@Override public long requestId() {
return reqId;
}
/**
* @return Request type.
*/
public byte type() {
return type;
}
/**
* @param reader Binary reader.
* @param protoCtx Protocol context.
* @return Request object.
* @throws BinaryObjectException On error.
*/
public static JdbcRequest readRequest(
BinaryReaderExImpl reader,
JdbcProtocolContext protoCtx
) throws BinaryObjectException {<FILL_FUNCTION_BODY>}
/**
* Reads JdbcRequest command type.
*
* @param msg Jdbc request as byte array.
* @return Command type.
*/
public static byte readType(byte[] msg) {
return msg[0];
}
/**
* Reads JdbcRequest Id.
*
* @param msg Jdbc request as byte array.
* @return Request Id.
*/
public static long readRequestId(byte[] msg) {
BinaryInputStream stream = new BinaryHeapInputStream(msg);
stream.position(1);
return stream.readLong();
}
/** {@inheritDoc} */
@Override public String toString() {
return S.toString(JdbcRequest.class, this);
}
}
|
int reqType = reader.readByte();
JdbcRequest req;
switch (reqType) {
case QRY_EXEC:
req = new JdbcQueryExecuteRequest();
break;
case QRY_FETCH:
req = new JdbcQueryFetchRequest();
break;
case QRY_META:
req = new JdbcQueryMetadataRequest();
break;
case QRY_CLOSE:
req = new JdbcQueryCloseRequest();
break;
case BATCH_EXEC:
req = new JdbcBatchExecuteRequest();
break;
case META_TABLES:
req = new JdbcMetaTablesRequest();
break;
case META_COLUMNS:
req = new JdbcMetaColumnsRequest();
break;
case META_INDEXES:
req = new JdbcMetaIndexesRequest();
break;
case META_PARAMS:
req = new JdbcMetaParamsRequest();
break;
case META_PRIMARY_KEYS:
req = new JdbcMetaPrimaryKeysRequest();
break;
case META_SCHEMAS:
req = new JdbcMetaSchemasRequest();
break;
case BULK_LOAD_BATCH:
req = new JdbcBulkLoadBatchRequest();
break;
case BATCH_EXEC_ORDERED:
req = new JdbcOrderedBatchExecuteRequest();
break;
case QRY_CANCEL:
req = new JdbcQueryCancelRequest();
break;
case CACHE_PARTITIONS:
req = new JdbcCachePartitionsRequest();
break;
case BINARY_TYPE_NAME_PUT:
req = new JdbcBinaryTypeNamePutRequest();
break;
case BINARY_TYPE_NAME_GET:
req = new JdbcBinaryTypeNameGetRequest();
break;
case BINARY_TYPE_PUT:
req = new JdbcBinaryTypePutRequest();
break;
case BINARY_TYPE_GET:
req = new JdbcBinaryTypeGetRequest();
break;
default:
throw new IgniteException("Unknown SQL listener request ID: [request ID=" + reqType + ']');
}
req.readBinary(reader, protoCtx);
return req;
| 1,161
| 627
| 1,788
|
<methods>public non-sealed void <init>() ,public long requestId() <variables>
|
apache_ignite
|
ignite/modules/core/src/main/java/org/apache/ignite/internal/processors/odbc/jdbc/JdbcRequestHandlerWorker.java
|
JdbcRequestHandlerWorker
|
body
|
class JdbcRequestHandlerWorker extends GridWorker {
/** Requests queue.*/
private final LinkedBlockingQueue<T2<JdbcRequest, GridFutureAdapter<ClientListenerResponse>>> queue =
new LinkedBlockingQueue<>();
/** Handler.*/
private final JdbcRequestHandler hnd;
/** Context.*/
private final GridKernalContext ctx;
/** Response */
private static final ClientListenerResponse ERR_RESPONSE = new JdbcResponse(IgniteQueryErrorCode.UNKNOWN,
"Connection closed.");
/**
* Constructor.
* @param igniteInstanceName Instance name.
* @param log Logger.
* @param hnd Handler.
* @param ctx Kernal context.
*/
JdbcRequestHandlerWorker(@Nullable String igniteInstanceName, IgniteLogger log, JdbcRequestHandler hnd,
GridKernalContext ctx) {
super(igniteInstanceName, "jdbc-request-handler-worker", log);
A.notNull(hnd, "hnd");
this.hnd = hnd;
this.ctx = ctx;
}
/**
* Start this worker.
*/
void start() {
new IgniteThread(this).start();
}
/** {@inheritDoc} */
@Override protected void body() throws InterruptedException, IgniteInterruptedCheckedException {<FILL_FUNCTION_BODY>}
/**
* Initiate request processing.
* @param req Request.
* @return Future to track request processing.
*/
GridFutureAdapter<ClientListenerResponse> process(JdbcRequest req) {
GridFutureAdapter<ClientListenerResponse> fut = new GridFutureAdapter<>();
queue.add(new T2<>(req, fut));
return fut;
}
}
|
try {
while (!isCancelled()) {
T2<JdbcRequest, GridFutureAdapter<ClientListenerResponse>> req = queue.take();
GridFutureAdapter<ClientListenerResponse> fut = req.get2();
try {
JdbcResponse res = hnd.doHandle(req.get1());
fut.onDone(res);
}
catch (Exception e) {
fut.onDone(e);
}
}
}
finally {
// Notify indexing that this worker is being stopped.
try {
ctx.query().onClientDisconnect();
}
catch (Exception ignored) {
// No-op.
}
// Drain the queue on stop.
T2<JdbcRequest, GridFutureAdapter<ClientListenerResponse>> req = queue.poll();
while (req != null) {
req.get2().onDone(ERR_RESPONSE);
req = queue.poll();
}
}
| 462
| 253
| 715
|
<methods>public void blockingSectionBegin() ,public void blockingSectionEnd() ,public void cancel() ,public long heartbeatTs() ,public java.lang.String igniteInstanceName() ,public boolean isCancelled() ,public boolean isDone() ,public void join() throws java.lang.InterruptedException,public java.lang.String name() ,public final void run() ,public java.lang.Thread runner() ,public java.lang.String toString() ,public void updateHeartbeat() <variables>private static final AtomicLongFieldUpdater<org.apache.ignite.internal.util.worker.GridWorker> HEARTBEAT_UPDATER,private volatile boolean finished,private volatile long heartbeatTs,private final non-sealed java.lang.String igniteInstanceName,protected final java.util.concurrent.atomic.AtomicBoolean isCancelled,protected final non-sealed org.apache.ignite.IgniteLogger log,private final non-sealed org.apache.ignite.internal.util.worker.GridWorkerListener lsnr,private final java.lang.Object mux,private final non-sealed java.lang.String name,private volatile java.lang.Thread runner
|
apache_ignite
|
ignite/modules/core/src/main/java/org/apache/ignite/internal/processors/odbc/jdbc/JdbcResult.java
|
JdbcResult
|
readResult
|
class JdbcResult implements JdbcRawBinarylizable {
/** Execute sql result. */
static final byte QRY_EXEC = 2;
/** Fetch query results. */
static final byte QRY_FETCH = 3;
/** Query result's columns metadata result. */
static final byte QRY_META = 5;
/** Batch queries. */
public static final byte BATCH_EXEC = 6;
/** Tables metadata result. */
static final byte META_TABLES = 7;
/** Columns metadata result. */
static final byte META_COLUMNS = 8;
/** Indexes metadata result. */
static final byte META_INDEXES = 9;
/** SQL query parameters metadata result. */
static final byte META_PARAMS = 10;
/** Primary keys metadata result. */
static final byte META_PRIMARY_KEYS = 11;
/** Database schemas metadata result. */
static final byte META_SCHEMAS = 12;
/** Multiple statements query results. */
static final byte QRY_EXEC_MULT = 13;
/** Columns metadata result V2. */
static final byte META_COLUMNS_V2 = 14;
/** Columns metadata result V3. */
static final byte META_COLUMNS_V3 = 15;
/** A request to send file from client to server. */
static final byte BULK_LOAD_ACK = 16;
/** Columns metadata result V4. */
static final byte META_COLUMNS_V4 = 17;
/** A result of the processing ordered batch request. */
static final byte BATCH_EXEC_ORDERED = 18;
/** A result of the processing cache partitions distributions request. */
static final byte CACHE_PARTITIONS = 19;
/** A result of the successfully updated binary schema. */
static final byte UPDATE_BINARY_SCHEMA_ACK = 20;
/** Get binary type schema result. */
static final byte BINARY_TYPE_GET = 21;
/** Get binary type name result. */
static final byte BINARY_TYPE_NAME_GET = 22;
/** Success status. */
private byte type;
/**
* Constructs result.
*
* @param type Type of results.
*/
public JdbcResult(byte type) {
this.type = type;
}
/** {@inheritDoc} */
@Override public void writeBinary(
BinaryWriterExImpl writer,
JdbcProtocolContext protoCtx
) throws BinaryObjectException {
writer.writeByte(type);
}
/** {@inheritDoc} */
@Override public void readBinary(
BinaryReaderExImpl reader,
JdbcProtocolContext protoCtx
) throws BinaryObjectException {
}
/**
* @param reader Binary reader.
* @param protoCtx Binary context.
* @return Request object.
* @throws BinaryObjectException On error.
*/
public static JdbcResult readResult(
BinaryReaderExImpl reader,
JdbcProtocolContext protoCtx
) throws BinaryObjectException {<FILL_FUNCTION_BODY>}
/** {@inheritDoc} */
@Override public String toString() {
return S.toString(JdbcResult.class, this);
}
}
|
int resId = reader.readByte();
JdbcResult res;
switch (resId) {
case QRY_EXEC:
res = new JdbcQueryExecuteResult();
break;
case QRY_FETCH:
res = new JdbcQueryFetchResult();
break;
case QRY_META:
res = new JdbcQueryMetadataResult();
break;
case BATCH_EXEC:
res = new JdbcBatchExecuteResult();
break;
case META_TABLES:
res = new JdbcMetaTablesResult();
break;
case META_COLUMNS:
res = new JdbcMetaColumnsResult();
break;
case META_INDEXES:
res = new JdbcMetaIndexesResult();
break;
case META_PARAMS:
res = new JdbcMetaParamsResult();
break;
case META_PRIMARY_KEYS:
res = new JdbcMetaPrimaryKeysResult();
break;
case META_SCHEMAS:
res = new JdbcMetaSchemasResult();
break;
case QRY_EXEC_MULT:
res = new JdbcQueryExecuteMultipleStatementsResult();
break;
case META_COLUMNS_V2:
res = new JdbcMetaColumnsResultV2();
break;
case META_COLUMNS_V3:
res = new JdbcMetaColumnsResultV3();
break;
case BULK_LOAD_ACK:
res = new JdbcBulkLoadAckResult();
break;
case META_COLUMNS_V4:
res = new JdbcMetaColumnsResultV4();
break;
case BATCH_EXEC_ORDERED:
res = new JdbcOrderedBatchExecuteResult();
break;
case CACHE_PARTITIONS:
res = new JdbcCachePartitionsResult();
break;
case UPDATE_BINARY_SCHEMA_ACK:
res = new JdbcUpdateBinarySchemaResult();
break;
case BINARY_TYPE_GET:
res = new JdbcBinaryTypeGetResult();
break;
case BINARY_TYPE_NAME_GET:
res = new JdbcBinaryTypeNameGetResult();
break;
default:
throw new IgniteException("Unknown SQL listener request ID: [request ID=" + resId + ']');
}
res.readBinary(reader, protoCtx);
return res;
| 867
| 673
| 1,540
|
<no_super_class>
|
apache_ignite
|
ignite/modules/core/src/main/java/org/apache/ignite/internal/processors/odbc/odbc/OdbcTableMeta.java
|
OdbcTableMeta
|
hashCode
|
class OdbcTableMeta {
/** Catalog name. */
private final String catalog;
/** Schema name. */
private final String schema;
/** Table name. */
private final String table;
/** Table type. */
private final String tableType;
/**
* @param catalog Catalog name.
* @param schema Schema name.
* @param table Table name.
* @param tableType Table type.
*/
public OdbcTableMeta(String catalog, String schema, String table, String tableType) {
this.catalog = catalog;
this.schema = OdbcUtils.addQuotationMarksIfNeeded(schema);
this.table = table;
this.tableType = tableType;
}
/** {@inheritDoc} */
@Override public int hashCode() {<FILL_FUNCTION_BODY>}
/** {@inheritDoc} */
@Override public boolean equals(Object o) {
if (o instanceof OdbcTableMeta) {
OdbcTableMeta other = (OdbcTableMeta)o;
return this == other ||
Objects.equals(catalog, other.catalog) && Objects.equals(schema, other.schema) &&
Objects.equals(table, other.table) && Objects.equals(tableType, other.tableType);
}
return false;
}
/**
* Write in a binary format.
*
* @param writer Binary writer.
*/
public void writeBinary(BinaryRawWriterEx writer) {
writer.writeString(catalog);
writer.writeString(schema);
writer.writeString(table);
writer.writeString(tableType);
}
}
|
int hash = Objects.hashCode(catalog);
hash = 31 * hash + Objects.hashCode(schema);
hash = 31 * hash + Objects.hashCode(table);
hash = 31 * hash + Objects.hashCode(tableType);
return hash;
| 430
| 76
| 506
|
<no_super_class>
|
apache_ignite
|
ignite/modules/core/src/main/java/org/apache/ignite/internal/processors/platform/PlatformAbstractBootstrap.java
|
PlatformAbstractBootstrap
|
start
|
class PlatformAbstractBootstrap implements PlatformBootstrap {
/** {@inheritDoc} */
@Override public PlatformProcessor start(IgniteConfiguration cfg, @Nullable GridSpringResourceContext springCtx,
long envPtr) {<FILL_FUNCTION_BODY>}
/** {@inheritDoc} */
@Override public void init(long dataPtr) {
final PlatformInputStream input = new PlatformExternalMemory(null, dataPtr).input();
Ignition.setClientMode(input.readBoolean());
processInput(input);
}
/**
* Get configuration transformer closure.
*
* @param envPtr Environment pointer.
* @return Closure.
*/
protected abstract IgniteClosure<IgniteConfiguration, IgniteConfiguration> closure(long envPtr);
/**
* Processes any additional input data.
*
* @param input Input stream.
*/
protected void processInput(PlatformInputStream input) {
// No-op.
}
}
|
IgniteConfiguration cfg0 = closure(envPtr).apply(cfg);
try {
IgniteEx node = (IgniteEx)IgnitionEx.start(cfg0, springCtx);
return node.context().platform();
}
catch (IgniteCheckedException e) {
throw U.convertException(e);
}
| 245
| 90
| 335
|
<no_super_class>
|
apache_ignite
|
ignite/modules/core/src/main/java/org/apache/ignite/internal/processors/platform/PlatformNoopProcessor.java
|
PlatformNoopProcessor
|
context
|
class PlatformNoopProcessor extends GridProcessorAdapter implements PlatformProcessor {
/** */
public PlatformNoopProcessor(GridKernalContext ctx) {
super(ctx);
}
/** {@inheritDoc} */
@Override public Ignite ignite() {
return null;
}
/** {@inheritDoc} */
@Override public long environmentPointer() {
return 0;
}
/** {@inheritDoc} */
@Override public PlatformContext context() {<FILL_FUNCTION_BODY>}
/** {@inheritDoc} */
@Override public boolean hasContext() {
return false;
}
/** {@inheritDoc} */
@Override public void releaseStart() {
// No-op.
}
/** {@inheritDoc} */
@Override public void awaitStart() throws IgniteCheckedException {
// No-op.
}
/** {@inheritDoc} */
@Override public void registerStore(PlatformCacheStore store, boolean convertBinary)
throws IgniteCheckedException {
// No-op.
}
/** {@inheritDoc} */
@Override public PlatformCacheManager cacheManager() {
return null;
}
/** {@inheritDoc} */
@Override public void setThreadLocal(Object value) {
// No-op.
}
}
|
throw new IgniteException("Platforms are not available [nodeId=" + ctx.grid().localNode().id() + "] " +
"(Use Apache.Ignite.Core.Ignition.Start() or Apache.Ignite.exe to start Ignite.NET nodes; " +
"ignite::Ignition::Start() or ignite.exe to start Ignite C++ nodes).");
| 331
| 95
| 426
|
<methods>public void collectGridNodeData(org.apache.ignite.spi.discovery.DiscoveryDataBag) ,public void collectJoiningNodeData(org.apache.ignite.spi.discovery.DiscoveryDataBag) ,public org.apache.ignite.internal.GridComponent.DiscoveryDataExchangeType discoveryDataType() ,public void onDisconnected(IgniteFuture<?>) throws org.apache.ignite.IgniteCheckedException,public void onGridDataReceived(org.apache.ignite.spi.discovery.DiscoveryDataBag.GridDiscoveryData) ,public void onJoiningNodeDataReceived(org.apache.ignite.spi.discovery.DiscoveryDataBag.JoiningNodeDiscoveryData) ,public void onKernalStart(boolean) throws org.apache.ignite.IgniteCheckedException,public void onKernalStop(boolean) ,public IgniteInternalFuture<?> onReconnected(boolean) throws org.apache.ignite.IgniteCheckedException,public void printMemoryStats() ,public void start() throws org.apache.ignite.IgniteCheckedException,public void stop(boolean) throws org.apache.ignite.IgniteCheckedException,public java.lang.String toString() ,public org.apache.ignite.spi.IgniteNodeValidationResult validateNode(org.apache.ignite.cluster.ClusterNode) ,public org.apache.ignite.spi.IgniteNodeValidationResult validateNode(org.apache.ignite.cluster.ClusterNode, org.apache.ignite.spi.discovery.DiscoveryDataBag.JoiningNodeDiscoveryData) <variables>private static final java.lang.String DIAGNOSTIC_LOG_CATEGORY,protected final non-sealed org.apache.ignite.internal.GridKernalContext ctx,protected final non-sealed org.apache.ignite.IgniteLogger diagnosticLog,protected final non-sealed org.apache.ignite.IgniteLogger log
|
apache_ignite
|
ignite/modules/core/src/main/java/org/apache/ignite/internal/processors/platform/cache/expiry/PlatformExpiryPolicy.java
|
PlatformExpiryPolicy
|
convert
|
class PlatformExpiryPolicy implements ExpiryPolicy {
/** Duration: unchanged. */
private static final long DUR_UNCHANGED = -2;
/** Duration: eternal. */
private static final long DUR_ETERNAL = -1;
/** Duration: zero. */
private static final long DUR_ZERO = 0;
/** Expiry for create. */
private final Duration create;
/** Expiry for update. */
private final Duration update;
/** Expiry for access. */
private final Duration access;
/**
* Constructor.
*
* @param create Expiry for create.
* @param update Expiry for update.
* @param access Expiry for access.
*/
public PlatformExpiryPolicy(long create, long update, long access) {
this.create = convert(create);
this.update = convert(update);
this.access = convert(access);
}
/** {@inheritDoc} */
@Override public Duration getExpiryForCreation() {
return create;
}
/** {@inheritDoc} */
@Override public Duration getExpiryForUpdate() {
return update;
}
/** {@inheritDoc} */
@Override public Duration getExpiryForAccess() {
return access;
}
/**
* Convert encoded duration to actual duration.
*
* @param dur Encoded duration.
* @return Actual duration.
*/
private static Duration convert(long dur) {<FILL_FUNCTION_BODY>}
/**
* Convert actual duration to encoded duration for serialization.
*
* @param dur Actual duration.
* @return Encoded duration.
*/
public static long convertDuration(Duration dur) {
if (dur == null)
return DUR_UNCHANGED;
else if (dur.isEternal())
return DUR_ETERNAL;
else if (dur.isZero())
return DUR_ZERO;
else
return dur.getTimeUnit().toMillis(dur.getDurationAmount());
}
}
|
if (dur == DUR_UNCHANGED)
return null;
else if (dur == DUR_ETERNAL)
return Duration.ETERNAL;
else if (dur == DUR_ZERO)
return Duration.ZERO;
else {
assert dur > 0;
return new Duration(TimeUnit.MILLISECONDS, dur);
}
| 546
| 108
| 654
|
<no_super_class>
|
apache_ignite
|
ignite/modules/core/src/main/java/org/apache/ignite/internal/processors/platform/cache/query/PlatformAbstractQueryCursor.java
|
PlatformAbstractQueryCursor
|
processInLongOutLong
|
class PlatformAbstractQueryCursor<T> extends PlatformAbstractTarget implements AutoCloseable {
/** Get multiple entries. */
private static final int OP_GET_ALL = 1;
/** Get all entries. */
private static final int OP_GET_BATCH = 2;
/** Get single entry. */
private static final int OP_GET_SINGLE = 3;
/** Start iterating. */
private static final int OP_ITERATOR = 4;
/** Close iterator. */
private static final int OP_ITERATOR_CLOSE = 5;
/** Close iterator. */
private static final int OP_ITERATOR_HAS_NEXT = 6;
/** Underlying cursor. */
private final QueryCursorEx<T> cursor;
/** Batch size size. */
private final int batchSize;
/** Underlying iterator. */
private Iterator<T> iter;
/**
* Constructor.
*
* @param platformCtx Context.
* @param cursor Underlying cursor.
* @param batchSize Batch size.
*/
PlatformAbstractQueryCursor(PlatformContext platformCtx, QueryCursorEx<T> cursor, int batchSize) {
super(platformCtx);
this.cursor = cursor;
this.batchSize = batchSize;
}
/** {@inheritDoc} */
@Override public void processOutStream(int type, final BinaryRawWriterEx writer) throws IgniteCheckedException {
switch (type) {
case OP_GET_BATCH: {
assert iter != null : "iterator() has not been called";
try {
int cntPos = writer.reserveInt();
int cnt = 0;
while (cnt < batchSize && iter.hasNext()) {
write(writer, iter.next());
cnt++;
}
writer.writeInt(cntPos, cnt);
writer.writeBoolean(iter.hasNext());
if (!iter.hasNext())
cursor.close();
}
catch (Exception err) {
throw PlatformUtils.unwrapQueryException(err);
}
break;
}
case OP_GET_SINGLE: {
assert iter != null : "iterator() has not been called";
try {
if (iter.hasNext()) {
write(writer, iter.next());
return;
}
}
catch (Exception err) {
throw PlatformUtils.unwrapQueryException(err);
}
throw new IgniteCheckedException("No more data available.");
}
case OP_GET_ALL: {
try {
int pos = writer.reserveInt();
Consumer<T> consumer = new Consumer<>(this, writer);
cursor.getAll(consumer);
writer.writeInt(pos, consumer.cnt);
}
catch (Exception err) {
throw PlatformUtils.unwrapQueryException(err);
}
break;
}
default:
super.processOutStream(type, writer);
}
}
/** {@inheritDoc} */
@Override public long processInLongOutLong(int type, long val) throws IgniteCheckedException {<FILL_FUNCTION_BODY>}
/** {@inheritDoc} */
@Override public void close() throws Exception {
cursor.close();
}
/**
* Write value to the stream. Extension point to perform conversions on the object before writing it.
*
* @param writer Writer.
* @param val Value.
*/
protected abstract void write(BinaryRawWriterEx writer, T val);
/**
* Gets the cursor.
*
* @return Cursor.
*/
public QueryCursorEx<T> cursor() {
return cursor;
}
/**
* Query cursor consumer.
*/
private static class Consumer<T> implements QueryCursorEx.Consumer<T> {
/** Current query cursor. */
private final PlatformAbstractQueryCursor<T> cursor;
/** Writer. */
private final BinaryRawWriterEx writer;
/** Count. */
private int cnt;
/**
* Constructor.
*
* @param writer Writer.
*/
Consumer(PlatformAbstractQueryCursor<T> cursor, BinaryRawWriterEx writer) {
this.cursor = cursor;
this.writer = writer;
}
/** {@inheritDoc} */
@Override public void consume(T val) throws IgniteCheckedException {
cursor.write(writer, val);
cnt++;
}
}
}
|
switch (type) {
case OP_ITERATOR:
iter = cursor.iterator();
return TRUE;
case OP_ITERATOR_CLOSE:
cursor.close();
return TRUE;
case OP_ITERATOR_HAS_NEXT:
assert iter != null : "iterator() has not been called";
return iter.hasNext() ? TRUE : FALSE;
}
return super.processInLongOutLong(type, val);
| 1,172
| 124
| 1,296
|
<methods>public java.lang.Exception convertException(java.lang.Exception) ,public org.apache.ignite.internal.processors.platform.PlatformContext platformContext() ,public long processInLongOutLong(int, long) throws org.apache.ignite.IgniteCheckedException,public org.apache.ignite.internal.processors.platform.PlatformTarget processInObjectStreamOutObjectStream(int, org.apache.ignite.internal.processors.platform.PlatformTarget, org.apache.ignite.internal.binary.BinaryRawReaderEx, org.apache.ignite.internal.binary.BinaryRawWriterEx) throws org.apache.ignite.IgniteCheckedException,public org.apache.ignite.internal.processors.platform.PlatformAsyncResult processInStreamAsync(int, org.apache.ignite.internal.binary.BinaryRawReaderEx) throws org.apache.ignite.IgniteCheckedException,public long processInStreamOutLong(int, org.apache.ignite.internal.binary.BinaryRawReaderEx) throws org.apache.ignite.IgniteCheckedException,public long processInStreamOutLong(int, org.apache.ignite.internal.binary.BinaryRawReaderEx, org.apache.ignite.internal.processors.platform.memory.PlatformMemory) throws org.apache.ignite.IgniteCheckedException,public org.apache.ignite.internal.processors.platform.PlatformTarget processInStreamOutObject(int, org.apache.ignite.internal.binary.BinaryRawReaderEx) throws org.apache.ignite.IgniteCheckedException,public void processInStreamOutStream(int, org.apache.ignite.internal.binary.BinaryRawReaderEx, org.apache.ignite.internal.binary.BinaryRawWriterEx) throws org.apache.ignite.IgniteCheckedException,public org.apache.ignite.internal.processors.platform.PlatformTarget processOutObject(int) throws org.apache.ignite.IgniteCheckedException,public void processOutStream(int, org.apache.ignite.internal.binary.BinaryRawWriterEx) throws org.apache.ignite.IgniteCheckedException,public static T throwUnsupported(int) throws org.apache.ignite.IgniteCheckedException<variables>protected static final int ERROR,protected static final int FALSE,protected static final int TRUE,protected final non-sealed org.apache.ignite.IgniteLogger log,protected final non-sealed org.apache.ignite.internal.processors.platform.PlatformContext platformCtx
|
apache_ignite
|
ignite/modules/core/src/main/java/org/apache/ignite/internal/processors/platform/client/ClientGetIdleTimeoutRequest.java
|
ClientGetIdleTimeoutRequest
|
getEffectiveIdleTimeout
|
class ClientGetIdleTimeoutRequest extends ClientRequest {
/**
* Constructor.
*
* @param reader Reader.
*/
ClientGetIdleTimeoutRequest(BinaryRawReader reader) {
super(reader);
}
/** {@inheritDoc} */
@Override public ClientResponse process(ClientConnectionContext ctx) {
return new ClientLongResponse(requestId(), getEffectiveIdleTimeout(ctx));
}
/**
* Gets the effective idle timeout.
*
* @param ctx Context.
* @return Idle timeout.
*/
private static long getEffectiveIdleTimeout(ClientConnectionContext ctx) {<FILL_FUNCTION_BODY>}
}
|
ClientConnectorConfiguration cfg = ctx.kernalContext().config().getClientConnectorConfiguration();
return cfg == null ? ClientConnectorConfiguration.DFLT_IDLE_TIMEOUT : cfg.getIdleTimeout();
| 174
| 57
| 231
|
<methods>public void <init>(org.apache.ignite.binary.BinaryRawReader) ,public void <init>(long) ,public boolean isAsync(org.apache.ignite.internal.processors.platform.client.ClientConnectionContext) ,public org.apache.ignite.internal.processors.platform.client.ClientResponse process(org.apache.ignite.internal.processors.platform.client.ClientConnectionContext) ,public IgniteInternalFuture<org.apache.ignite.internal.processors.platform.client.ClientResponse> processAsync(org.apache.ignite.internal.processors.platform.client.ClientConnectionContext) ,public long requestId() <variables>private final non-sealed long reqId
|
apache_ignite
|
ignite/modules/core/src/main/java/org/apache/ignite/internal/processors/platform/client/ClientRequest.java
|
ClientRequest
|
processAsync
|
class ClientRequest implements ClientListenerRequest {
/** Request id. */
private final long reqId;
/**
* Constructor.
*
* @param reader Reader.
*/
public ClientRequest(BinaryRawReader reader) {
reqId = reader.readLong();
}
/**
* Constructor.
*
* @param reqId Request id.
*/
public ClientRequest(long reqId) {
this.reqId = reqId;
}
/** {@inheritDoc} */
@Override public long requestId() {
return reqId;
}
/**
* Processes the request.
*
* @return Response.
*/
public ClientResponse process(ClientConnectionContext ctx) {
return new ClientResponse(reqId);
}
/**
* Processes the request asynchronously.
*
* @return Future for response.
*/
public IgniteInternalFuture<ClientResponse> processAsync(ClientConnectionContext ctx) {<FILL_FUNCTION_BODY>}
/**
* @param ctx Client connection context.
* @return {@code True} if request should be processed asynchronously.
*/
public boolean isAsync(ClientConnectionContext ctx) {
return false;
}
}
|
throw new IllegalStateException("Async operation is not implemented for request " + getClass().getName());
| 322
| 25
| 347
|
<no_super_class>
|
apache_ignite
|
ignite/modules/core/src/main/java/org/apache/ignite/internal/processors/platform/client/binary/ClientBinaryTypeGetResponse.java
|
ClientBinaryTypeGetResponse
|
encode
|
class ClientBinaryTypeGetResponse extends ClientResponse {
/** Meta. */
private final BinaryMetadata meta;
/**
* Constructor.
*
* @param requestId Request id.
*/
ClientBinaryTypeGetResponse(long requestId, BinaryMetadata meta) {
super(requestId);
this.meta = meta;
}
/** {@inheritDoc} */
@Override public void encode(ClientConnectionContext ctx, BinaryRawWriterEx writer) {<FILL_FUNCTION_BODY>}
}
|
super.encode(ctx, writer);
if (meta != null) {
writer.writeBoolean(true); // Not null.
PlatformUtils.writeBinaryMetadata(writer, meta, true);
}
else {
writer.writeBoolean(false); // Null.
}
| 134
| 77
| 211
|
<methods>public void <init>(long) ,public void <init>(long, java.lang.String) ,public void <init>(long, int, java.lang.String) ,public void encode(org.apache.ignite.internal.processors.platform.client.ClientConnectionContext, org.apache.ignite.internal.binary.BinaryRawWriterEx, org.apache.ignite.internal.processors.platform.client.ClientAffinityTopologyVersion) ,public void encode(org.apache.ignite.internal.processors.platform.client.ClientConnectionContext, org.apache.ignite.internal.binary.BinaryRawWriterEx) ,public long requestId() <variables>private final non-sealed long reqId
|
apache_ignite
|
ignite/modules/core/src/main/java/org/apache/ignite/internal/processors/platform/client/cache/ClientCacheGetAndPutRequest.java
|
ClientCacheGetAndPutRequest
|
process0
|
class ClientCacheGetAndPutRequest extends ClientCacheKeyValueRequest {
/**
* Ctor.
*
* @param reader Reader.
*/
public ClientCacheGetAndPutRequest(BinaryRawReaderEx reader) {
super(reader);
}
/** {@inheritDoc} */
@Override public ClientResponse process0(ClientConnectionContext ctx) {<FILL_FUNCTION_BODY>}
/** {@inheritDoc} */
@Override public IgniteInternalFuture<ClientResponse> processAsync0(ClientConnectionContext ctx) {
return chainFuture(cache(ctx).getAndPutAsync(key(), val()), v -> new ClientObjectResponse(requestId(), v));
}
}
|
Object res = cache(ctx).getAndPut(key(), val());
return new ClientObjectResponse(requestId(), res);
| 170
| 34
| 204
|
<methods>public java.lang.Object val() <variables>private final non-sealed java.lang.Object val
|
apache_ignite
|
ignite/modules/core/src/main/java/org/apache/ignite/internal/processors/platform/client/cache/ClientCacheGetNamesResponse.java
|
ClientCacheGetNamesResponse
|
encode
|
class ClientCacheGetNamesResponse extends ClientResponse {
/** Cache names. */
private final Collection<String> cacheNames;
/**
* Constructor.
*
* @param reqId Request id.
* @param cacheNames Cache names.
*/
ClientCacheGetNamesResponse(long reqId, Collection<String> cacheNames) {
super(reqId);
assert cacheNames != null;
this.cacheNames = cacheNames;
}
/** {@inheritDoc} */
@Override public void encode(ClientConnectionContext ctx, BinaryRawWriterEx writer) {<FILL_FUNCTION_BODY>}
}
|
super.encode(ctx, writer);
writer.writeInt(cacheNames.size());
for (String name : cacheNames) {
writer.writeString(name);
}
| 160
| 50
| 210
|
<methods>public void <init>(long) ,public void <init>(long, java.lang.String) ,public void <init>(long, int, java.lang.String) ,public void encode(org.apache.ignite.internal.processors.platform.client.ClientConnectionContext, org.apache.ignite.internal.binary.BinaryRawWriterEx, org.apache.ignite.internal.processors.platform.client.ClientAffinityTopologyVersion) ,public void encode(org.apache.ignite.internal.processors.platform.client.ClientConnectionContext, org.apache.ignite.internal.binary.BinaryRawWriterEx) ,public long requestId() <variables>private final non-sealed long reqId
|
apache_ignite
|
ignite/modules/core/src/main/java/org/apache/ignite/internal/processors/platform/client/cache/ClientCacheGetOrCreateWithConfigurationRequest.java
|
ClientCacheGetOrCreateWithConfigurationRequest
|
process
|
class ClientCacheGetOrCreateWithConfigurationRequest extends ClientRequest {
/** Cache configuration. */
private final CacheConfiguration cacheCfg;
/**
* Constructor.
*
* @param reader Reader.
* @param protocolCtx Client protocol context.
*/
public ClientCacheGetOrCreateWithConfigurationRequest(BinaryRawReader reader, ClientProtocolContext protocolCtx) {
super(reader);
cacheCfg = ClientCacheConfigurationSerializer.read(reader, protocolCtx);
}
/** {@inheritDoc} */
@Override public ClientResponse process(ClientConnectionContext ctx) {<FILL_FUNCTION_BODY>}
}
|
checkClientCacheConfiguration(cacheCfg);
try {
ctx.kernalContext().grid().getOrCreateCache(cacheCfg);
}
catch (CacheExistsException e) {
throw new IgniteClientException(ClientStatus.CACHE_EXISTS, e.getMessage());
}
return super.process(ctx);
| 159
| 88
| 247
|
<methods>public void <init>(org.apache.ignite.binary.BinaryRawReader) ,public void <init>(long) ,public boolean isAsync(org.apache.ignite.internal.processors.platform.client.ClientConnectionContext) ,public org.apache.ignite.internal.processors.platform.client.ClientResponse process(org.apache.ignite.internal.processors.platform.client.ClientConnectionContext) ,public IgniteInternalFuture<org.apache.ignite.internal.processors.platform.client.ClientResponse> processAsync(org.apache.ignite.internal.processors.platform.client.ClientConnectionContext) ,public long requestId() <variables>private final non-sealed long reqId
|
apache_ignite
|
ignite/modules/core/src/main/java/org/apache/ignite/internal/processors/platform/client/cache/ClientCacheNodePartitionsRequest.java
|
ClientCacheNodePartitionsRequest
|
process
|
class ClientCacheNodePartitionsRequest extends ClientCacheRequest {
/**
* Initializes a new instance of ClientRawRequest class.
* @param reader Reader.
*/
public ClientCacheNodePartitionsRequest(BinaryRawReader reader) {
super(reader);
}
/** {@inheritDoc} */
@Override public ClientResponse process(ClientConnectionContext ctx) {<FILL_FUNCTION_BODY>}
}
|
IgniteCache cache = cache(ctx);
GridDiscoveryManager discovery = ctx.kernalContext().discovery();
Collection<ClusterNode> nodes = discovery.discoCache().cacheNodes(cache.getName());
Affinity aff = ctx.kernalContext().affinity().affinityProxy(cache.getName());
ArrayList<ClientConnectableNodePartitions> res = new ArrayList<>();
for (ClusterNode node : nodes) {
Integer port = node.attribute(ClientListenerProcessor.CLIENT_LISTENER_PORT);
if (port == null)
continue;
Collection<String> addrs = node.addresses();
int[] parts = aff.primaryPartitions(node);
res.add(new ClientConnectableNodePartitions(port, addrs, parts));
}
return new ClientCacheNodePartitionsResponse(requestId(), res);
| 104
| 217
| 321
|
<methods>public static org.apache.ignite.internal.processors.cache.DynamicCacheDescriptor cacheDescriptor(org.apache.ignite.internal.processors.platform.client.ClientConnectionContext, int) <variables>private static final byte FLAG_WITH_EXPIRY_POLICY,private static final byte KEEP_BINARY_FLAG_MASK,private static final byte TRANSACTIONAL_FLAG_MASK,private final non-sealed int cacheId,private final non-sealed ExpiryPolicy expiryPolicy,private final non-sealed byte flags
|
apache_ignite
|
ignite/modules/core/src/main/java/org/apache/ignite/internal/processors/platform/client/cache/ClientCachePartitionAwarenessGroup.java
|
ClientCachePartitionAwarenessGroup
|
equals
|
class ClientCachePartitionAwarenessGroup {
/** Partition mapping. If {@code null} then cache must be excluded in partition awareness usage (e.g. REPLICATED cache). */
private final @Nullable ClientCachePartitionMapping mapping;
/** {@code true} if the RendezvousAffinityFunction is used with the default affinity key mapper. */
private final boolean dfltAffinity;
/** Descriptor of the associated caches. */
private final Map<Integer, CacheConfiguration<?, ?>> cacheCfgs = new HashMap<>();
/**
* @param mapping Partition mapping.
* @param dfltAffinity {@code true} if the default affinity or a custom affinity mapper was used.
*/
public ClientCachePartitionAwarenessGroup(@Nullable ClientCachePartitionMapping mapping, boolean dfltAffinity) {
this.mapping = mapping;
this.dfltAffinity = dfltAffinity;
}
/**
* Write mapping using binary writer.
*
* @param proc Binary processor.
* @param writer Binary Writer.
* @param cpctx Protocol context.
*/
public void write(CacheObjectBinaryProcessorImpl proc, BinaryRawWriter writer, ClientProtocolContext cpctx) {
boolean isPartitionAwarenessApplicable = mapping != null;
writer.writeBoolean(isPartitionAwarenessApplicable);
writer.writeInt(cacheCfgs.size());
if (isPartitionAwarenessApplicable) {
for (Map.Entry<Integer, CacheConfiguration<?, ?>> entry: cacheCfgs.entrySet()) {
writer.writeInt(entry.getKey());
writeCacheKeyConfiguration(writer, proc, entry.getValue().getKeyConfiguration());
}
mapping.write(writer);
if (cpctx.isFeatureSupported(ClientBitmaskFeature.ALL_AFFINITY_MAPPINGS))
writer.writeBoolean(dfltAffinity);
}
else {
for (int cacheId : cacheCfgs.keySet())
writer.writeInt(cacheId);
}
}
/**
* Add caches to the same affinity group.
* @param descs Cache descriptors.
*/
public void addAll(List<DynamicCacheDescriptor> descs) {
for (DynamicCacheDescriptor desc : descs)
cacheCfgs.putIfAbsent(desc.cacheId(), desc.cacheConfiguration());
}
/** */
private static void writeCacheKeyConfiguration(
BinaryRawWriter writer,
CacheObjectBinaryProcessorImpl binProc,
CacheKeyConfiguration[] keyCfgs
) {
if (keyCfgs == null) {
writer.writeInt(0);
return;
}
writer.writeInt(keyCfgs.length);
for (CacheKeyConfiguration keyCfg : keyCfgs) {
int keyTypeId = binProc.typeId(keyCfg.getTypeName());
int affKeyFieldId = binProc.binaryContext().fieldId(keyTypeId, keyCfg.getAffinityKeyFieldName());
writer.writeInt(keyTypeId);
writer.writeInt(affKeyFieldId);
}
}
/** {@inheritDoc} */
@Override public boolean equals(Object o) {<FILL_FUNCTION_BODY>}
/** {@inheritDoc} */
@Override public int hashCode() {
return Objects.hash(mapping, dfltAffinity);
}
}
|
if (this == o)
return true;
if (o == null || getClass() != o.getClass())
return false;
ClientCachePartitionAwarenessGroup grp = (ClientCachePartitionAwarenessGroup)o;
return dfltAffinity == grp.dfltAffinity && Objects.equals(mapping, grp.mapping);
| 888
| 97
| 985
|
<no_super_class>
|
apache_ignite
|
ignite/modules/core/src/main/java/org/apache/ignite/internal/processors/platform/client/cache/ClientCacheQueryContinuousHandle.java
|
ClientCacheQueryContinuousHandle
|
onUpdated
|
class ClientCacheQueryContinuousHandle implements CacheEntryUpdatedListener<Object, Object>, ClientCloseableResource {
/** */
private final ClientConnectionContext ctx;
/** */
private final AtomicBoolean closeGuard = new AtomicBoolean();
/** */
private volatile Long id;
/** */
private volatile QueryCursor<?> cur;
/**
* Ctor.
* @param ctx Context.
*/
public ClientCacheQueryContinuousHandle(ClientConnectionContext ctx) {
assert ctx != null;
this.ctx = ctx;
}
/** {@inheritDoc} */
@Override public void onUpdated(Iterable<CacheEntryEvent<?, ?>> iterable) throws CacheEntryListenerException {<FILL_FUNCTION_BODY>}
/**
* Sets the cursor.
* @param cur Cursor.
*/
public void setCursor(QueryCursor<?> cur) {
this.cur = cur;
}
/**
* Sets the cursor id.
* @param id Cursor id.
*/
public void startNotifications(long id) {
this.id = id;
}
/** {@inheritDoc} */
@Override public void close() {
if (closeGuard.compareAndSet(false, true)) {
assert cur != null;
cur.close();
ctx.decrementCursors();
}
}
}
|
// Client is not yet ready to receive notifications - skip them.
if (id == null)
return;
ClientCacheEntryEventNotification notification = new ClientCacheEntryEventNotification(
ClientMessageParser.OP_QUERY_CONTINUOUS_EVENT_NOTIFICATION, id, iterable);
ctx.notifyClient(notification);
| 360
| 86
| 446
|
<no_super_class>
|
apache_ignite
|
ignite/modules/core/src/main/java/org/apache/ignite/internal/processors/platform/client/cache/ClientCacheQueryRequest.java
|
ClientCacheQueryRequest
|
updateAffinityMetrics
|
class ClientCacheQueryRequest extends ClientCacheDataRequest {
/** */
ClientCacheQueryRequest(BinaryRawReader reader) {
super(reader);
}
/** */
protected void updateAffinityMetrics(ClientConnectionContext ctx, int part) {<FILL_FUNCTION_BODY>}
}
|
DynamicCacheDescriptor desc = cacheDescriptor(ctx);
CacheConfiguration<?, ?> cfg = desc.cacheConfiguration();
if (cfg.getCacheMode() == CacheMode.PARTITIONED && cfg.isStatisticsEnabled()) {
String cacheName = desc.cacheName();
try {
GridKernalContext kctx = ctx.kernalContext();
if (kctx.affinity().mapPartitionToNode(cacheName, part, null).isLocal())
kctx.clientListener().metrics().onAffinityQryHit();
else
kctx.clientListener().metrics().onAffinityQryMiss();
}
catch (Exception ignored) {
// No-op.
}
}
| 76
| 184
| 260
|
<methods>public boolean isTransactional() ,public int txId() <variables>private final non-sealed int txId
|
apache_ignite
|
ignite/modules/core/src/main/java/org/apache/ignite/internal/processors/platform/client/cache/ClientCacheScanQueryRequest.java
|
ClientCacheScanQueryRequest
|
createFilter
|
class ClientCacheScanQueryRequest extends ClientCacheQueryRequest implements ClientTxAwareRequest {
/** Local flag. */
private final boolean loc;
/** Page size. */
private final int pageSize;
/** Partition. */
private final Integer part;
/** Filter platform. */
private final byte filterPlatform;
/** Filter object. */
private final Object filterObj;
/**
* Ctor.
*
* @param reader Reader.
*/
public ClientCacheScanQueryRequest(BinaryRawReaderEx reader) {
super(reader);
filterObj = reader.readObjectDetached();
filterPlatform = filterObj == null ? 0 : reader.readByte();
pageSize = reader.readInt();
int part0 = reader.readInt();
part = part0 < 0 ? null : part0;
loc = reader.readBoolean();
}
/** {@inheritDoc} */
@Override public ClientResponse process(ClientConnectionContext ctx) {
IgniteCache<Object, Object> cache = filterPlatform == ClientPlatform.JAVA && !isKeepBinary() ?
rawCache(ctx) : cache(ctx);
ScanQuery qry = new ScanQuery()
.setLocal(loc)
.setPageSize(pageSize)
.setPartition(part)
.setFilter(createFilter(ctx.kernalContext(), filterObj, filterPlatform));
if (part != null)
updateAffinityMetrics(ctx, part);
ctx.incrementCursors();
try {
QueryCursor cur = cache.query(qry);
ClientCacheEntryQueryCursor cliCur = new ClientCacheEntryQueryCursor(cur, pageSize, ctx);
long cursorId = ctx.resources().put(cliCur);
cliCur.id(cursorId);
return new ClientCacheQueryResponse(requestId(), cliCur);
}
catch (Exception e) {
ctx.decrementCursors();
throw e;
}
}
/**
* Creates the filter.
*
* @return Filter.
* @param ctx Context.
*/
private static IgniteBiPredicate createFilter(GridKernalContext ctx, Object filterObj, byte filterPlatform) {<FILL_FUNCTION_BODY>}
}
|
if (filterObj == null)
return null;
switch (filterPlatform) {
case ClientPlatform.JAVA:
return ((BinaryObject)filterObj).deserialize();
case ClientPlatform.DOTNET:
PlatformContext platformCtx = ctx.platform().context();
String curPlatform = platformCtx.platform();
if (!PlatformUtils.PLATFORM_DOTNET.equals(curPlatform)) {
throw new IgniteException("ScanQuery filter platform is " + PlatformUtils.PLATFORM_DOTNET +
", current platform is " + curPlatform);
}
return platformCtx.createCacheEntryFilter(filterObj, 0);
case ClientPlatform.CPP:
default:
throw new UnsupportedOperationException("Invalid client ScanQuery filter code: " + filterPlatform);
}
| 579
| 207
| 786
|
<no_super_class>
|
apache_ignite
|
ignite/modules/core/src/main/java/org/apache/ignite/internal/processors/platform/client/cluster/ClientClusterGroupGetNodesDetailsRequest.java
|
ClientClusterGroupGetNodesDetailsRequest
|
process
|
class ClientClusterGroupGetNodesDetailsRequest extends ClientRequest {
/** Node ids. */
private final UUID[] nodeIds;
/**
* Constructor.
*
* @param reader Reader.
*/
public ClientClusterGroupGetNodesDetailsRequest(BinaryRawReader reader) {
super(reader);
int cnt = reader.readInt();
nodeIds = new UUID[cnt];
for (int i = 0; i < cnt; i++) {
nodeIds[i] = new UUID(reader.readLong(), reader.readLong());
}
}
/** {@inheritDoc} */
@Override public ClientResponse process(ClientConnectionContext ctx) {<FILL_FUNCTION_BODY>}
}
|
IgniteClusterEx cluster = ctx.kernalContext().grid().cluster();
ClusterGroup clusterGrp = cluster.forNodeIds(Arrays.asList(nodeIds));
return new ClientClusterGroupGetNodesDetailsResponse(requestId(), clusterGrp.nodes());
| 182
| 67
| 249
|
<methods>public void <init>(org.apache.ignite.binary.BinaryRawReader) ,public void <init>(long) ,public boolean isAsync(org.apache.ignite.internal.processors.platform.client.ClientConnectionContext) ,public org.apache.ignite.internal.processors.platform.client.ClientResponse process(org.apache.ignite.internal.processors.platform.client.ClientConnectionContext) ,public IgniteInternalFuture<org.apache.ignite.internal.processors.platform.client.ClientResponse> processAsync(org.apache.ignite.internal.processors.platform.client.ClientConnectionContext) ,public long requestId() <variables>private final non-sealed long reqId
|
apache_ignite
|
ignite/modules/core/src/main/java/org/apache/ignite/internal/processors/platform/client/cluster/ClientClusterGroupProjection.java
|
ClientClusterGroupProjection
|
apply
|
class ClientClusterGroupProjection {
/** */
private static final short ATTRIBUTE = 1;
/** */
private static final short SERVER_NODES = 2;
/**
* Projection items.
*/
private final ProjectionItem[] prjItems;
/**
* Constructor.
*
* @param prjItems Projection items.
*/
private ClientClusterGroupProjection(ProjectionItem[] prjItems) {
this.prjItems = prjItems;
}
/**
* Reads projection from a stream.
*
* @param reader Reader.
* @return Projection.
*/
public static ClientClusterGroupProjection read(BinaryRawReader reader) {
int cnt = reader.readInt();
ProjectionItem[] items = cnt == 0 ? null : new ProjectionItem[cnt];
for (int i = 0; i < cnt; i++) {
short code = reader.readShort();
switch (code) {
case ATTRIBUTE: {
items[i] = new ForAttributeProjectionItem(reader);
break;
}
case SERVER_NODES: {
items[i] = new ForServerNodesProjectionItem(reader);
break;
}
default:
throw new UnsupportedOperationException("Unknown code: " + code);
}
}
return new ClientClusterGroupProjection(items);
}
/**
* Applies projection.
*
* @param clusterGrp Source cluster group.
* @return New cluster group instance with the projection.
*/
public ClusterGroup apply(ClusterGroup clusterGrp) {<FILL_FUNCTION_BODY>}
/**
* Projection item.
*/
private interface ProjectionItem {
/**
* Applies projection to the cluster group.
*
* @param clusterGrp Cluster group.
* @return Cluster group with current projection.
*/
ClusterGroup apply(ClusterGroup clusterGrp);
}
/**
* Attribute projection item.
*/
private static final class ForAttributeProjectionItem implements ProjectionItem {
/**
* Attribute name.
*/
private final String name;
/**
* Attribute value.
*/
private final Object val;
/**
* Ctor.
*
* @param reader Reader.
*/
public ForAttributeProjectionItem(BinaryRawReader reader) {
name = reader.readString();
val = reader.readObject();
}
/**
* {@inheritDoc}
*/
@Override public ClusterGroup apply(ClusterGroup clusterGrp) {
return clusterGrp.forAttribute(name, val);
}
}
/**
* Represents server nodes only projection item.
*/
private static final class ForServerNodesProjectionItem implements ProjectionItem {
/**
* Is for server nodes only.
*/
private final Boolean isForSrvNodes;
/**
* Ctor.
*
* @param reader Reader.
*/
public ForServerNodesProjectionItem(BinaryRawReader reader) {
isForSrvNodes = reader.readBoolean();
}
/**
* {@inheritDoc}
*/
@Override public ClusterGroup apply(ClusterGroup clusterGrp) {
return isForSrvNodes ? clusterGrp.forServers() : clusterGrp.forClients();
}
}
}
|
if (prjItems != null) {
for (ProjectionItem item : prjItems)
clusterGrp = item.apply(clusterGrp);
}
return clusterGrp;
| 877
| 52
| 929
|
<no_super_class>
|
apache_ignite
|
ignite/modules/core/src/main/java/org/apache/ignite/internal/processors/platform/client/compute/ClientComputeTask.java
|
ClientComputeTask
|
close
|
class ClientComputeTask implements ClientCloseableResource {
/** No failover flag mask. */
private static final byte NO_FAILOVER_FLAG_MASK = 0x01;
/** No result cache flag mask. */
private static final byte NO_RESULT_CACHE_FLAG_MASK = 0x02;
/** Keep binary flag mask. */
public static final byte KEEP_BINARY_FLAG_MASK = 0x04;
/** Context. */
private final ClientConnectionContext ctx;
/** Logger. */
private final IgniteLogger log;
/** Task id. */
private volatile long taskId;
/** Task future. */
private volatile ComputeTaskInternalFuture<Object> taskFut;
/** Task closed flag. */
private final AtomicBoolean closed = new AtomicBoolean();
/**
* Ctor.
*
* @param ctx Connection context.
*/
ClientComputeTask(ClientConnectionContext ctx) {
assert ctx != null;
this.ctx = ctx;
log = ctx.kernalContext().log(getClass());
}
/**
* @param taskId Task ID.
* @param taskName Task name.
* @param arg Task arguments.
* @param nodeIds Nodes to run task jobs.
* @param flags Flags for task.
* @param timeout Task timeout.
*/
void execute(long taskId, String taskName, Object arg, Set<UUID> nodeIds, byte flags, long timeout) {
assert taskName != null;
this.taskId = taskId;
GridTaskProcessor task = ctx.kernalContext().task();
IgnitePredicate<ClusterNode> nodePredicate = F.isEmpty(nodeIds) ? node -> !node.isClient() :
F.nodeForNodeIds(nodeIds);
TaskExecutionOptions opts = options()
.asPublicRequest()
.withProjectionPredicate(nodePredicate)
.withTimeout(timeout);
if ((flags & NO_FAILOVER_FLAG_MASK) != 0)
opts.withFailoverDisabled();
if ((flags & NO_RESULT_CACHE_FLAG_MASK) != 0)
opts.withResultCacheDisabled();
taskFut = task.execute(taskName, arg, opts);
// Fail fast.
if (taskFut.isDone() && taskFut.error() != null)
throw new IgniteClientException(ClientStatus.FAILED, taskFut.error().getMessage());
}
/**
* Callback for response sent event.
*/
void onResponseSent() {
// Listener should be registered only after response for this task was sent, to ensure that client doesn't
// receive notification before response for the task.
taskFut.listen(() -> {
try {
ClientNotification notification;
if (taskFut.error() != null) {
String msg = ctx.kernalContext().clientListener().sendServerExceptionStackTraceToClient()
? taskFut.error().getMessage() + U.nl() + X.getFullStackTrace(taskFut.error())
: taskFut.error().getMessage();
notification = new ClientNotification(OP_COMPUTE_TASK_FINISHED, taskId, msg);
}
else if (taskFut.isCancelled())
notification = new ClientNotification(OP_COMPUTE_TASK_FINISHED, taskId, "Task was cancelled");
else
notification = new ClientObjectNotification(OP_COMPUTE_TASK_FINISHED, taskId, taskFut.result());
ctx.notifyClient(notification);
}
finally {
// If task was explicitly closed before, resource is already released.
if (closed.compareAndSet(false, true)) {
ctx.decrementActiveTasksCount();
ctx.resources().release(taskId);
}
}
});
}
/**
* Gets task ID.
*/
long taskId() {
return taskId;
}
/**
* Closes the task resource.
*/
@Override public void close() {<FILL_FUNCTION_BODY>}
}
|
if (closed.compareAndSet(false, true)) {
ctx.decrementActiveTasksCount();
try {
if (taskFut != null)
taskFut.cancel();
}
catch (IgniteCheckedException e) {
log.warning("Failed to cancel task", e);
}
}
| 1,056
| 85
| 1,141
|
<no_super_class>
|
apache_ignite
|
ignite/modules/core/src/main/java/org/apache/ignite/internal/processors/platform/client/datastructures/ClientIgniteSetKeyRequest.java
|
ClientIgniteSetKeyRequest
|
process
|
class ClientIgniteSetKeyRequest extends ClientIgniteSetRequest {
/** Key. */
private final Object key;
/**
* Constructor.
*
* @param reader Reader.
*/
ClientIgniteSetKeyRequest(BinaryRawReaderEx reader) {
super(reader);
// Clients can enable deserialized values on server so that user objects are stored the same way
// as if we were using "thick" API.
// This is needed when both thick and thin APIs work with the same IgniteSet AND custom user types.
boolean keepBinary = reader.readBoolean();
key = keepBinary ? reader.readObjectDetached() : reader.readObject();
}
/** {@inheritDoc} */
@Override public ClientResponse process(ClientConnectionContext ctx) {<FILL_FUNCTION_BODY>}
/**
* Processes the key request.
*
* @param set Ignite set.
* @param key Key.
* @return Response.
*/
abstract ClientResponse process(IgniteSet<Object> set, Object key);
}
|
IgniteSet<Object> igniteSet = igniteSet(ctx);
if (igniteSet == null)
return notFoundResponse();
return process(igniteSet, key);
| 270
| 51
| 321
|
<methods>public void <init>(org.apache.ignite.binary.BinaryRawReader) ,public org.apache.ignite.internal.processors.platform.client.ClientResponse process(org.apache.ignite.internal.processors.platform.client.ClientConnectionContext) <variables>private final non-sealed int cacheId,private final non-sealed boolean collocated,private final non-sealed java.lang.String name
|
apache_ignite
|
ignite/modules/core/src/main/java/org/apache/ignite/internal/processors/platform/client/service/ClientServiceTopologyRequest.java
|
ClientServiceTopologyRequest
|
process
|
class ClientServiceTopologyRequest extends ClientRequest {
/** The service name. */
private final String name;
/**
* Creates the service topology request.
*
* @param reader Reader to read the {@link #name} from.
*/
public ClientServiceTopologyRequest(BinaryRawReader reader) {
super(reader);
name = reader.readString();
}
/** {@inheritDoc} */
@Override public ClientResponse process(ClientConnectionContext ctx) {<FILL_FUNCTION_BODY>}
}
|
Map<UUID, Integer> srvcTop;
try {
srvcTop = ctx.kernalContext().service().serviceTopology(name, 0);
}
catch (IgniteCheckedException e) {
throw new IgniteClientException(ClientStatus.FAILED, "Failed to get topology for service '" + name + "'.", e);
}
return new ClientServiceMappingsResponse(requestId(), F.isEmpty(srvcTop) ? Collections.emptyList() : srvcTop.keySet());
| 135
| 133
| 268
|
<methods>public void <init>(org.apache.ignite.binary.BinaryRawReader) ,public void <init>(long) ,public boolean isAsync(org.apache.ignite.internal.processors.platform.client.ClientConnectionContext) ,public org.apache.ignite.internal.processors.platform.client.ClientResponse process(org.apache.ignite.internal.processors.platform.client.ClientConnectionContext) ,public IgniteInternalFuture<org.apache.ignite.internal.processors.platform.client.ClientResponse> processAsync(org.apache.ignite.internal.processors.platform.client.ClientConnectionContext) ,public long requestId() <variables>private final non-sealed long reqId
|
apache_ignite
|
ignite/modules/core/src/main/java/org/apache/ignite/internal/processors/platform/client/streamer/ClientDataStreamerAddDataRequest.java
|
ClientDataStreamerAddDataRequest
|
process
|
class ClientDataStreamerAddDataRequest extends ClientDataStreamerRequest {
/** */
private final long streamerId;
/** */
private final byte flags;
/** */
private final Collection<DataStreamerEntry> entries;
/**
* Constructor.
*
* @param reader Data reader.
*/
public ClientDataStreamerAddDataRequest(BinaryReaderExImpl reader) {
super(reader);
streamerId = reader.readLong();
flags = reader.readByte();
entries = ClientDataStreamerReader.read(reader);
}
/**
* {@inheritDoc}
*/
@Override public ClientResponse process(ClientConnectionContext ctx) {<FILL_FUNCTION_BODY>}
}
|
ClientDataStreamerHandle handle = ctx.resources().get(streamerId);
DataStreamerImpl<KeyCacheObject, CacheObject> dataStreamer =
(DataStreamerImpl<KeyCacheObject, CacheObject>)handle.getStreamer();
try {
if (entries != null)
dataStreamer.addData(entries);
if ((flags & FLUSH) != 0)
dataStreamer.flush();
if ((flags & CLOSE) != 0) {
dataStreamer.close();
ctx.resources().release(streamerId);
}
}
catch (IllegalStateException unused) {
return getInvalidNodeStateResponse();
}
return new ClientResponse(requestId());
| 189
| 188
| 377
|
<no_super_class>
|
apache_ignite
|
ignite/modules/core/src/main/java/org/apache/ignite/internal/processors/platform/compute/PlatformAbstractFunc.java
|
PlatformAbstractFunc
|
invoke
|
class PlatformAbstractFunc implements PlatformSecurityAwareJob, Serializable {
/** */
private static final long serialVersionUID = 0L;
/** Serialized platform func. */
private final Object func;
/** Handle for local execution. */
@SuppressWarnings("TransientFieldNotInitialized")
private final transient long ptr;
/** Ignite instance. */
@IgniteInstanceResource
protected transient Ignite ignite;
/** Platform function name. */
private final String funcName;
/**
* Constructor.
*
* @param func Platform func.
* @param ptr Handle for local execution.
* @param funcName Platform function name.
*/
protected PlatformAbstractFunc(Object func, long ptr, String funcName) {
this.ptr = ptr;
assert func != null;
this.func = func;
this.funcName = funcName;
}
/**
* Invokes this instance.
*
* @return Invocation result.
*/
protected Object invoke() throws IgniteCheckedException {<FILL_FUNCTION_BODY>}
/** {@inheritDoc} */
@Override public String name() {
return funcName;
}
/**
* Performs platform callback.
*
* @param gate Gateway.
* @param memPtr Pointer.
*/
protected abstract void platformCallback(PlatformCallbackGateway gate, long memPtr);
}
|
assert ignite != null;
PlatformContext ctx = PlatformUtils.platformContext(ignite);
try (PlatformMemory mem = ctx.memory().allocate()) {
PlatformOutputStream out = mem.output();
if (ptr != 0) {
out.writeBoolean(true);
out.writeLong(ptr);
}
else {
out.writeBoolean(false);
ctx.writer(out).writeObject(func);
}
out.synchronize();
platformCallback(ctx.gateway(), mem.pointer());
PlatformInputStream in = mem.input();
in.synchronize();
return PlatformUtils.readInvocationResult(ctx, ctx.reader(in));
}
| 369
| 181
| 550
|
<no_super_class>
|
apache_ignite
|
ignite/modules/core/src/main/java/org/apache/ignite/internal/processors/platform/compute/PlatformAbstractJob.java
|
PlatformAbstractJob
|
runLocal
|
class PlatformAbstractJob implements PlatformJob, Externalizable {
/** Marker object denoting the job execution result is stored in native platform. */
static final Object LOC_JOB_RES = new Object();
/** Ignite instance. */
@IgniteInstanceResource
protected transient Ignite ignite;
/** Parent task; present only on local job instance. */
protected transient PlatformAbstractTask task;
/** Pointer to job in the native platform. */
protected transient long ptr;
/** Job. */
protected Object job;
/** Job name. */
protected String jobName;
/**
* {@link java.io.Externalizable} support.
*/
protected PlatformAbstractJob() {
// No-op.
}
/**
* Constructor.
*
* @param task Parent task.
* @param ptr Pointer.
* @param job Job.
* @param jobName Job name.
*/
protected PlatformAbstractJob(PlatformAbstractTask task, long ptr, Object job, String jobName) {
this.task = task;
this.ptr = ptr;
this.job = job;
this.jobName = jobName;
}
/** {@inheritDoc} */
@Nullable @Override public Object execute() {
try {
PlatformProcessor interopProc = PlatformUtils.platformProcessor(ignite);
interopProc.awaitStart();
return execute0(interopProc.context());
}
catch (IgniteCheckedException e) {
throw U.convertException(e);
}
}
/**
* Internal job execution routine.
*
* @param ctx Interop processor.
* @return Result.
* @throws org.apache.ignite.IgniteCheckedException If failed.
*/
protected abstract Object execute0(PlatformContext ctx) throws IgniteCheckedException;
/**
* Create job in native platform if needed.
*
* @param ctx Context.
* @return {@code True} if job was created, {@code false} if this is local job and creation is not necessary.
* @throws org.apache.ignite.IgniteCheckedException If failed.
*/
protected boolean createJob(PlatformContext ctx) throws IgniteCheckedException {
if (ptr == 0) {
try (PlatformMemory mem = ctx.memory().allocate()) {
PlatformOutputStream out = mem.output();
BinaryRawWriterEx writer = ctx.writer(out);
writer.writeObject(job);
out.synchronize();
ptr = ctx.gateway().computeJobCreate(mem.pointer());
}
return true;
}
else
return false;
}
/**
* Run local job.
*
* @param ctx Context.
* @param cancel Cancel flag.
* @return Result.
*/
protected Object runLocal(PlatformContext ctx, boolean cancel) {<FILL_FUNCTION_BODY>}
/** {@inheritDoc} */
@Override public long pointer() {
return ptr;
}
/** {@inheritDoc} */
@Override public Object job() {
return job;
}
/** {@inheritDoc} */
@Override public String name() {
return jobName;
}
}
|
// Local job, must execute it with respect to possible concurrent task completion.
if (task.onJobLock()) {
try {
ctx.gateway().computeJobExecuteLocal(ptr, cancel ? 1 : 0);
return LOC_JOB_RES;
}
finally {
task.onJobUnlock();
}
}
else
// Task has completed concurrently, no need to run the job.
return null;
| 833
| 117
| 950
|
<no_super_class>
|
apache_ignite
|
ignite/modules/core/src/main/java/org/apache/ignite/internal/processors/platform/compute/PlatformBroadcastingSingleClosureTask.java
|
PlatformBroadcastingSingleClosureTask
|
map
|
class PlatformBroadcastingSingleClosureTask extends PlatformAbstractTask {
/** */
private static final long serialVersionUID = 0L;
/** */
private PlatformJob job;
/**
* Constructor.
*
* @param ctx Platform context.
* @param taskPtr Task pointer.
*/
public PlatformBroadcastingSingleClosureTask(PlatformContext ctx, long taskPtr) {
super(ctx, taskPtr);
}
/** {@inheritDoc} */
@NotNull @Override public Map<? extends ComputeJob, ClusterNode> map(List<ClusterNode> subgrid,
@Nullable Object arg) {<FILL_FUNCTION_BODY>}
/**
* @param job Job.
*/
public void job(PlatformJob job) {
this.job = job;
}
}
|
assert job != null : "Job null-check must be performed in native platform.";
if (!F.isEmpty(subgrid)) {
Map<ComputeJob, ClusterNode> map = new HashMap<>(subgrid.size(), 1);
boolean first = true;
for (ClusterNode node : subgrid) {
if (first) {
map.put(job, node);
first = false;
}
else
map.put(ctx.createClosureJob(this, job.pointer(), job.job(), job.name()), node);
}
return map;
}
else
return Collections.emptyMap();
| 213
| 169
| 382
|
<methods>public void onDone(java.lang.Exception) ,public java.lang.Void reduce(List<org.apache.ignite.compute.ComputeJobResult>) ,public org.apache.ignite.compute.ComputeJobResultPolicy result(org.apache.ignite.compute.ComputeJobResult, List<org.apache.ignite.compute.ComputeJobResult>) <variables>protected final non-sealed org.apache.ignite.internal.processors.platform.PlatformContext ctx,protected boolean done,protected final java.util.concurrent.locks.ReadWriteLock lock,protected final non-sealed long taskPtr
|
apache_ignite
|
ignite/modules/core/src/main/java/org/apache/ignite/internal/processors/platform/compute/PlatformFullJob.java
|
PlatformFullJob
|
cancel
|
class PlatformFullJob extends PlatformAbstractJob {
/** */
private static final long serialVersionUID = 0L;
/** Job is initialized. */
private static final byte STATE_INIT = 0;
/** Job is running. */
private static final byte STATE_RUNNING = 1;
/** Job execution completed. */
private static final byte STATE_COMPLETED = 2;
/** Job cancelled. */
private static final byte STATE_CANCELLED = 3;
/** Platform context. */
private transient PlatformContext ctx;
/** Serialized job. */
private transient byte state;
/**
* {@link Externalizable} support.
*/
public PlatformFullJob() {
// No-op.
}
/**
* Constructor.
*
* @param ctx Platform context.
* @param task Parent task.
* @param ptr Job pointer.
* @param job Job.
* @param jobName Job name.
*/
public PlatformFullJob(PlatformContext ctx, PlatformAbstractTask task, long ptr, Object job, String jobName) {
super(task, ptr, job, jobName);
this.ctx = ctx;
}
/** {@inheritDoc} */
@Nullable @Override public Object execute0(PlatformContext ctx) throws IgniteCheckedException {
boolean cancel = false;
synchronized (this) {
// 1. Create job if necessary.
if (task == null) {
assert ptr == 0;
createJob(ctx);
}
else
assert ptr != 0;
// 2. Set correct state.
if (state == STATE_INIT)
state = STATE_RUNNING;
else {
assert state == STATE_CANCELLED;
cancel = true;
}
}
try {
if (task != null)
return runLocal(ctx, cancel);
else {
try (PlatformMemory mem = ctx.memory().allocate()) {
PlatformOutputStream out = mem.output();
out.writeLong(ptr);
out.writeBoolean(cancel); // cancel
out.synchronize();
ctx.gateway().computeJobExecute(mem.pointer());
PlatformInputStream in = mem.input();
in.synchronize();
BinaryRawReaderEx reader = ctx.reader(in);
return PlatformUtils.readInvocationResult(ctx, reader);
}
}
}
finally {
synchronized (this) {
if (task == null) {
assert ptr != 0;
ctx.gateway().computeJobDestroy(ptr);
}
if (state == STATE_RUNNING)
state = STATE_COMPLETED;
}
}
}
/** {@inheritDoc} */
@Override public void cancel() {<FILL_FUNCTION_BODY>}
/** {@inheritDoc} */
@Override public void writeExternal(ObjectOutput out) throws IOException {
if (job == null) {
assert ptr != 0;
try {
if (task != null) {
if (task.onJobLock()) {
try {
serialize();
}
finally {
task.onJobUnlock();
}
}
else
throw new IgniteCheckedException("Task already completed: " + task);
}
else
serialize();
}
catch (IgniteCheckedException e) {
throw new IOException("Failed to serialize interop job.", e);
}
}
assert job != null;
out.writeObject(job);
out.writeObject(jobName);
}
/** {@inheritDoc} */
@Override public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException {
job = in.readObject();
jobName = (String)in.readObject();
}
/**
* Internal job serialization routine.
*
* @throws org.apache.ignite.IgniteCheckedException If failed.
*/
private void serialize() throws IgniteCheckedException {
try (PlatformMemory mem = ctx.memory().allocate()) {
PlatformInputStream in = mem.input();
boolean res = ctx.gateway().computeJobSerialize(ptr, mem.pointer()) == 1;
in.synchronize();
BinaryRawReaderEx reader = ctx.reader(in);
if (res)
job = reader.readObjectDetached();
else
throw new IgniteCheckedException(reader.readString());
}
}
}
|
PlatformProcessor proc = PlatformUtils.platformProcessor(ignite);
synchronized (this) {
if (state == STATE_INIT)
state = STATE_CANCELLED;
else if (state == STATE_RUNNING) {
assert ptr != 0;
try {
proc.context().gateway().computeJobCancel(ptr);
}
finally {
state = STATE_CANCELLED;
}
}
}
| 1,171
| 123
| 1,294
|
<methods>public java.lang.Object execute() ,public java.lang.Object job() ,public java.lang.String name() ,public long pointer() <variables>static final java.lang.Object LOC_JOB_RES,protected transient org.apache.ignite.Ignite ignite,protected java.lang.Object job,protected java.lang.String jobName,protected transient long ptr,protected transient org.apache.ignite.internal.processors.platform.compute.PlatformAbstractTask task
|
apache_ignite
|
ignite/modules/core/src/main/java/org/apache/ignite/internal/processors/platform/datastreamer/PlatformStreamReceiverImpl.java
|
PlatformStreamReceiverImpl
|
receive
|
class PlatformStreamReceiverImpl extends PlatformAbstractPredicate implements PlatformStreamReceiver {
/** */
private static final long serialVersionUID = 0L;
/** */
private boolean keepBinary;
/**
* Constructor.
*/
public PlatformStreamReceiverImpl() {
super();
}
/**
* Constructor.
*
* @param pred .Net binary receiver.
* @param ptr Pointer to receiver in the native platform.
* @param ctx Kernal context.
*/
public PlatformStreamReceiverImpl(Object pred, long ptr, boolean keepBinary, PlatformContext ctx) {
super(pred, ptr, ctx);
assert pred != null;
this.keepBinary = keepBinary;
}
/** {@inheritDoc} */
@Override public void receive(IgniteCache<Object, Object> cache, Collection<Map.Entry<Object, Object>> collection)
throws IgniteException {<FILL_FUNCTION_BODY>}
/**
* @param ignite Ignite instance.
*/
@IgniteInstanceResource
public void setIgniteInstance(Ignite ignite) {
ctx = PlatformUtils.platformContext(ignite);
}
/** {@inheritDoc} */
@Override public void writeExternal(ObjectOutput out) throws IOException {
super.writeExternal(out);
out.writeBoolean(keepBinary);
}
/** {@inheritDoc} */
@Override public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException {
super.readExternal(in);
keepBinary = in.readBoolean();
}
}
|
assert ctx != null;
try (PlatformMemory mem = ctx.memory().allocate()) {
PlatformOutputStream out = mem.output();
out.writeLong(ptr);
out.writeBoolean(keepBinary);
BinaryRawWriterEx writer = ctx.writer(out);
writer.writeObject(pred);
writer.writeInt(collection.size());
for (Map.Entry<Object, Object> e : collection) {
writer.writeObject(e.getKey());
writer.writeObject(e.getValue());
}
out.synchronize();
PlatformCache cache0 = new PlatformCache(ctx, cache, keepBinary);
PlatformTargetProxy cacheProxy = new PlatformTargetProxyImpl(cache0, ctx);
ctx.gateway().dataStreamerStreamReceiverInvoke(ptr, cacheProxy, mem.pointer(), keepBinary);
}
| 406
| 219
| 625
|
<methods>public void <init>() ,public void readExternal(java.io.ObjectInput) throws java.io.IOException, java.lang.ClassNotFoundException,public void writeExternal(java.io.ObjectOutput) throws java.io.IOException<variables>protected transient org.apache.ignite.internal.processors.platform.PlatformContext ctx,protected java.lang.Object pred,protected transient long ptr
|
apache_ignite
|
ignite/modules/core/src/main/java/org/apache/ignite/internal/processors/platform/datastructures/PlatformAtomicSequence.java
|
PlatformAtomicSequence
|
processInLongOutLong
|
class PlatformAtomicSequence extends PlatformAbstractTarget {
/** */
private final IgniteAtomicSequence atomicSeq;
/** */
private static final int OP_ADD_AND_GET = 1;
/** */
private static final int OP_CLOSE = 2;
/** */
private static final int OP_GET = 3;
/** */
private static final int OP_GET_AND_ADD = 4;
/** */
private static final int OP_GET_AND_INCREMENT = 5;
/** */
private static final int OP_GET_BATCH_SIZE = 6;
/** */
private static final int OP_INCREMENT_AND_GET = 7;
/** */
private static final int OP_IS_CLOSED = 8;
/** */
private static final int OP_SET_BATCH_SIZE = 9;
/**
* Ctor.
* @param ctx Context.
* @param atomicSeq AtomicSequence to wrap.
*/
public PlatformAtomicSequence(PlatformContext ctx, IgniteAtomicSequence atomicSeq) {
super(ctx);
assert atomicSeq != null;
this.atomicSeq = atomicSeq;
}
/** {@inheritDoc} */
@Override public long processInLongOutLong(int type, long val) throws IgniteCheckedException {<FILL_FUNCTION_BODY>}
}
|
switch (type) {
case OP_ADD_AND_GET:
return atomicSeq.addAndGet(val);
case OP_GET_AND_ADD:
return atomicSeq.getAndAdd(val);
case OP_SET_BATCH_SIZE:
atomicSeq.batchSize((int)val);
return TRUE;
case OP_CLOSE:
atomicSeq.close();
return TRUE;
case OP_GET:
return atomicSeq.get();
case OP_GET_AND_INCREMENT:
return atomicSeq.getAndIncrement();
case OP_INCREMENT_AND_GET:
return atomicSeq.incrementAndGet();
case OP_IS_CLOSED:
return atomicSeq.removed() ? TRUE : FALSE;
case OP_GET_BATCH_SIZE:
return atomicSeq.batchSize();
}
return super.processInLongOutLong(type, val);
| 356
| 254
| 610
|
<methods>public java.lang.Exception convertException(java.lang.Exception) ,public org.apache.ignite.internal.processors.platform.PlatformContext platformContext() ,public long processInLongOutLong(int, long) throws org.apache.ignite.IgniteCheckedException,public org.apache.ignite.internal.processors.platform.PlatformTarget processInObjectStreamOutObjectStream(int, org.apache.ignite.internal.processors.platform.PlatformTarget, org.apache.ignite.internal.binary.BinaryRawReaderEx, org.apache.ignite.internal.binary.BinaryRawWriterEx) throws org.apache.ignite.IgniteCheckedException,public org.apache.ignite.internal.processors.platform.PlatformAsyncResult processInStreamAsync(int, org.apache.ignite.internal.binary.BinaryRawReaderEx) throws org.apache.ignite.IgniteCheckedException,public long processInStreamOutLong(int, org.apache.ignite.internal.binary.BinaryRawReaderEx) throws org.apache.ignite.IgniteCheckedException,public long processInStreamOutLong(int, org.apache.ignite.internal.binary.BinaryRawReaderEx, org.apache.ignite.internal.processors.platform.memory.PlatformMemory) throws org.apache.ignite.IgniteCheckedException,public org.apache.ignite.internal.processors.platform.PlatformTarget processInStreamOutObject(int, org.apache.ignite.internal.binary.BinaryRawReaderEx) throws org.apache.ignite.IgniteCheckedException,public void processInStreamOutStream(int, org.apache.ignite.internal.binary.BinaryRawReaderEx, org.apache.ignite.internal.binary.BinaryRawWriterEx) throws org.apache.ignite.IgniteCheckedException,public org.apache.ignite.internal.processors.platform.PlatformTarget processOutObject(int) throws org.apache.ignite.IgniteCheckedException,public void processOutStream(int, org.apache.ignite.internal.binary.BinaryRawWriterEx) throws org.apache.ignite.IgniteCheckedException,public static T throwUnsupported(int) throws org.apache.ignite.IgniteCheckedException<variables>protected static final int ERROR,protected static final int FALSE,protected static final int TRUE,protected final non-sealed org.apache.ignite.IgniteLogger log,protected final non-sealed org.apache.ignite.internal.processors.platform.PlatformContext platformCtx
|
apache_ignite
|
ignite/modules/core/src/main/java/org/apache/ignite/internal/processors/platform/dotnet/PlatformDotNetConsoleStream.java
|
PlatformDotNetConsoleStream
|
write
|
class PlatformDotNetConsoleStream extends OutputStream {
/** Indicates whether this is an error stream. */
private final boolean isErr;
/**
* Ctor.
*
* @param err Error stream flag.
*/
public PlatformDotNetConsoleStream(boolean err) {
isErr = err;
}
/** {@inheritDoc} */
@Override public void write(byte[] b, int off, int len) throws IOException {<FILL_FUNCTION_BODY>}
/** {@inheritDoc} */
@Override public void write(int b) throws IOException {
String s = String.valueOf((char)b);
PlatformCallbackGateway.consoleWrite(s, isErr);
}
}
|
String s = new String(b, off, len);
PlatformCallbackGateway.consoleWrite(s, isErr);
| 185
| 34
| 219
|
<methods>public void <init>() ,public void close() throws java.io.IOException,public void flush() throws java.io.IOException,public static java.io.OutputStream nullOutputStream() ,public abstract void write(int) throws java.io.IOException,public void write(byte[]) throws java.io.IOException,public void write(byte[], int, int) throws java.io.IOException<variables>
|
apache_ignite
|
ignite/modules/core/src/main/java/org/apache/ignite/internal/processors/platform/entityframework/PlatformDotNetEntityFrameworkCacheEntry.java
|
PlatformDotNetEntityFrameworkCacheEntry
|
readBinary
|
class PlatformDotNetEntityFrameworkCacheEntry implements Binarylizable {
/** Dependent entity set names. */
private String[] entitySets;
/** Cached data bytes. */
private byte[] data;
/**
* Ctor.
*/
public PlatformDotNetEntityFrameworkCacheEntry() {
// No-op.
}
/**
* Ctor.
*
* @param entitySets Entity set names.
* @param data Data bytes.
*/
PlatformDotNetEntityFrameworkCacheEntry(String[] entitySets, byte[] data) {
this.entitySets = entitySets;
this.data = data;
}
/**
* @return Dependent entity sets with versions.
*/
public String[] entitySets() {
return entitySets;
}
/**
* @return Cached data bytes.
*/
public byte[] data() {
return data;
}
/** {@inheritDoc} */
@Override public void writeBinary(BinaryWriter writer) throws BinaryObjectException {
final BinaryRawWriter raw = writer.rawWriter();
if (entitySets != null) {
raw.writeInt(entitySets.length);
for (String entitySet : entitySets)
raw.writeString(entitySet);
}
else
raw.writeInt(-1);
raw.writeByteArray(data);
}
/** {@inheritDoc} */
@Override public void readBinary(BinaryReader reader) throws BinaryObjectException {<FILL_FUNCTION_BODY>}
}
|
BinaryRawReader raw = reader.rawReader();
int cnt = raw.readInt();
if (cnt >= 0) {
entitySets = new String[cnt];
for (int i = 0; i < cnt; i++)
entitySets[i] = raw.readString();
}
else
entitySets = null;
data = raw.readByteArray();
| 405
| 108
| 513
|
<no_super_class>
|
apache_ignite
|
ignite/modules/core/src/main/java/org/apache/ignite/internal/processors/platform/events/PlatformLocalEventListener.java
|
PlatformLocalEventListener
|
apply
|
class PlatformLocalEventListener implements IgnitePredicate<Event> {
/** */
private static final long serialVersionUID = 0L;
/** Listener id. */
private final int id;
/** Ignite. */
@SuppressWarnings("unused")
@IgniteInstanceResource
private transient Ignite ignite;
/**
* Constructor.
*
* @param id Listener id.
*/
public PlatformLocalEventListener(int id) {
this.id = id;
}
/** {@inheritDoc} */
@Override public boolean apply(Event evt) {<FILL_FUNCTION_BODY>}
/** {@inheritDoc} */
@Override public boolean equals(Object o) {
return this == o || o != null && getClass() == o.getClass() && id == ((PlatformLocalEventListener)o).id;
}
/** {@inheritDoc} */
@Override public int hashCode() {
return id;
}
}
|
assert ignite != null;
PlatformContext ctx = PlatformUtils.platformContext(ignite);
assert ctx != null;
try (PlatformMemory mem = ctx.memory().allocate()) {
PlatformOutputStream out = mem.output();
BinaryRawWriterEx writer = ctx.writer(out);
writer.writeInt(id);
ctx.writeEvent(writer, evt);
out.synchronize();
long res = ctx.gateway().eventLocalListenerApply(mem.pointer());
return res != 0;
}
| 252
| 144
| 396
|
<no_super_class>
|
apache_ignite
|
ignite/modules/core/src/main/java/org/apache/ignite/internal/processors/platform/memory/PlatformBigEndianInputStreamImpl.java
|
PlatformBigEndianInputStreamImpl
|
readIntArray
|
class PlatformBigEndianInputStreamImpl extends PlatformInputStreamImpl {
/**
* Constructor.
*
* @param mem Memory chunk.
*/
public PlatformBigEndianInputStreamImpl(PlatformMemory mem) {
super(mem);
}
/** {@inheritDoc} */
@Override public short readShort() {
return Short.reverseBytes(super.readShort());
}
/** {@inheritDoc} */
@Override public short[] readShortArray(int cnt) {
short[] res = super.readShortArray(cnt);
for (int i = 0; i < cnt; i++)
res[i] = Short.reverseBytes(res[i]);
return res;
}
/** {@inheritDoc} */
@Override public char readChar() {
return Character.reverseBytes(super.readChar());
}
/** {@inheritDoc} */
@Override public char[] readCharArray(int cnt) {
char[] res = super.readCharArray(cnt);
for (int i = 0; i < cnt; i++)
res[i] = Character.reverseBytes(res[i]);
return res;
}
/** {@inheritDoc} */
@Override public int readInt() {
return Integer.reverseBytes(super.readInt());
}
/** {@inheritDoc} */
@Override public byte readBytePositioned(int pos) {
return super.readBytePositioned(pos);
}
/** {@inheritDoc} */
@Override public short readShortPositioned(int pos) {
return Short.reverseBytes(super.readShortPositioned(pos));
}
/** {@inheritDoc} */
@Override public int readIntPositioned(int pos) {
return Integer.reverseBytes(super.readIntPositioned(pos));
}
/** {@inheritDoc} */
@Override public int[] readIntArray(int cnt) {<FILL_FUNCTION_BODY>}
/** {@inheritDoc} */
@Override public float readFloat() {
return Float.intBitsToFloat(Integer.reverseBytes(Float.floatToIntBits(super.readFloat())));
}
/** {@inheritDoc} */
@Override public float[] readFloatArray(int cnt) {
float[] res = super.readFloatArray(cnt);
for (int i = 0; i < cnt; i++)
res[i] = Float.intBitsToFloat(Integer.reverseBytes(Float.floatToIntBits(res[i])));
return res;
}
/** {@inheritDoc} */
@Override public long readLong() {
return Long.reverseBytes(super.readLong());
}
/** {@inheritDoc} */
@Override public long[] readLongArray(int cnt) {
long[] res = super.readLongArray(cnt);
for (int i = 0; i < cnt; i++)
res[i] = Long.reverseBytes(res[i]);
return res;
}
/** {@inheritDoc} */
@Override public double readDouble() {
return Double.longBitsToDouble(Long.reverseBytes(Double.doubleToLongBits(super.readDouble())));
}
/** {@inheritDoc} */
@Override public double[] readDoubleArray(int cnt) {
double[] res = super.readDoubleArray(cnt);
for (int i = 0; i < cnt; i++)
res[i] = Double.longBitsToDouble(Long.reverseBytes(Double.doubleToLongBits(res[i])));
return res;
}
}
|
int[] res = super.readIntArray(cnt);
for (int i = 0; i < cnt; i++)
res[i] = Integer.reverseBytes(res[i]);
return res;
| 935
| 59
| 994
|
<methods>public void <init>(org.apache.ignite.internal.processors.platform.memory.PlatformMemory) ,public byte[] array() ,public byte[] arrayCopy() ,public int capacity() ,public boolean hasArray() ,public long offheapPointer() ,public int position() ,public void position(int) ,public long rawOffheapPointer() ,public int read(byte[], int, int) ,public boolean readBoolean() ,public boolean[] readBooleanArray(int) ,public byte readByte() ,public byte[] readByteArray(int) ,public byte readBytePositioned(int) ,public char readChar() ,public char[] readCharArray(int) ,public double readDouble() ,public double[] readDoubleArray(int) ,public float readFloat() ,public float[] readFloatArray(int) ,public int readInt() ,public int[] readIntArray(int) ,public int readIntPositioned(int) ,public long readLong() ,public long[] readLongArray(int) ,public short readShort() ,public short[] readShortArray(int) ,public short readShortPositioned(int) ,public int remaining() ,public void synchronize() <variables>private long data,private byte[] dataCopy,private int len,private final non-sealed org.apache.ignite.internal.processors.platform.memory.PlatformMemory mem,private int pos
|
apache_ignite
|
ignite/modules/core/src/main/java/org/apache/ignite/internal/processors/platform/memory/PlatformUnpooledMemory.java
|
PlatformUnpooledMemory
|
reallocate
|
class PlatformUnpooledMemory extends PlatformAbstractMemory {
/**
* Constructor.
*
* @param memPtr Cross-platform memory pointer.
*/
public PlatformUnpooledMemory(long memPtr) {
super(memPtr);
}
/** {@inheritDoc} */
@Override public void reallocate(int cap) {<FILL_FUNCTION_BODY>}
/** {@inheritDoc} */
@Override public void close() {
releaseUnpooled(memPtr);
}
}
|
// Try doubling capacity to avoid excessive allocations.
int doubledCap = PlatformMemoryUtils.capacity(memPtr) << 1;
if (doubledCap > cap)
cap = doubledCap;
reallocateUnpooled(memPtr, cap);
| 132
| 71
| 203
|
<methods>public int capacity() ,public long data() ,public org.apache.ignite.internal.processors.platform.memory.PlatformInputStream input() ,public int length() ,public org.apache.ignite.internal.processors.platform.memory.PlatformOutputStream output() ,public long pointer() <variables>private static final org.apache.ignite.internal.processors.platform.memory.PlatformAbstractMemory.StreamFactory STREAM_FACTORY,protected long memPtr
|
apache_ignite
|
ignite/modules/core/src/main/java/org/apache/ignite/internal/processors/query/DistributedSqlConfiguration.java
|
DistributedSqlConfiguration
|
onReadyToWrite
|
class DistributedSqlConfiguration {
/** */
private static final String QUERY_TIMEOUT_PROPERTY_NAME = "sql.defaultQueryTimeout";
/** Property update message. */
protected static final String PROPERTY_UPDATE_MESSAGE =
"SQL parameter '%s' was changed from '%s' to '%s'";
/** Default value of the query timeout. */
public static final int DFLT_QRY_TIMEOUT = 0;
/** Query timeout. */
private volatile DistributedChangeableProperty<Integer> dfltQryTimeout;
/**
* @param ctx Kernal context
* @param log Logger.
*/
protected DistributedSqlConfiguration(
GridKernalContext ctx,
IgniteLogger log
) {
ctx.internalSubscriptionProcessor().registerDistributedConfigurationListener(
new DistributedConfigurationLifecycleListener() {
@Override public void onReadyToRegister(DistributedPropertyDispatcher dispatcher) {
DistributedChangeableProperty<Integer> prop = dispatcher.property(QUERY_TIMEOUT_PROPERTY_NAME);
if (prop != null) {
dfltQryTimeout = prop;
return;
}
dfltQryTimeout = new SimpleDistributedProperty<>(
QUERY_TIMEOUT_PROPERTY_NAME,
SimpleDistributedProperty::parseNonNegativeInteger,
"Timeout in milliseconds for default query timeout. 0 means there is no timeout."
);
dfltQryTimeout.addListener(makeUpdateListener(PROPERTY_UPDATE_MESSAGE, log));
dispatcher.registerProperties(dfltQryTimeout);
}
@SuppressWarnings("deprecation")
@Override public void onReadyToWrite() {<FILL_FUNCTION_BODY>}
}
);
}
/**
* @return Default query timeout.
*/
public int defaultQueryTimeout() {
Integer t = dfltQryTimeout == null ? null : dfltQryTimeout.get();
return t != null ? t : DFLT_QRY_TIMEOUT;
}
/**
* @param timeout Default query timeout.
* @throws IgniteCheckedException if failed.
*/
public GridFutureAdapter<?> defaultQueryTimeout(int timeout) throws IgniteCheckedException {
A.ensure(timeout >= 0,
"default query timeout value must not be negative.");
if (dfltQryTimeout == null)
throw new IgniteCheckedException("Property " + QUERY_TIMEOUT_PROPERTY_NAME + " is not registered yet");
return dfltQryTimeout.propagateAsync(timeout);
}
}
|
if (ReadableDistributedMetaStorage.isSupported(ctx)) {
setDefaultValue(
dfltQryTimeout,
(int)ctx.config().getSqlConfiguration().getDefaultQueryTimeout(),
log);
}
else {
log.warning("Distributed metastorage is not supported. " +
"All distributed SQL configuration parameters are unavailable.");
// Set properties to default.
dfltQryTimeout.localUpdate((int)ctx.config().getSqlConfiguration().getDefaultQueryTimeout());
}
| 680
| 133
| 813
|
<no_super_class>
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.