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/events/SqlQueryExecutionEvent.java
SqlQueryExecutionEvent
toString
class SqlQueryExecutionEvent extends EventAdapter { /** */ private static final long serialVersionUID = 0L; /** Query text. */ private final String text; /** Query arguments. */ @GridToStringInclude(sensitive = true) private final Object[] args; /** Security subject ID. */ private final UUID subjId; /** * @param node Node where event was fired. * @param msg Event message. * @param text Query text. * @param args Query arguments. * @param subjId Security subject ID. */ public SqlQueryExecutionEvent( ClusterNode node, String msg, @Nullable String text, @Nullable Object[] args, @Nullable UUID subjId ) { super(node, msg, EVT_SQL_QUERY_EXECUTION); this.text = text; this.args = args; this.subjId = subjId; } /** * Gets query text. * <p> * Applicable for {@code SQL}, {@code SQL fields} queries. * * @return Query text. */ @Nullable public String text() { return text; } /** * Gets query arguments. * <p> * Applicable for {@code SQL} and {@code SQL fields} queries. * * @return Query arguments. */ @Nullable public Object[] arguments() { return args.clone(); } /** * Gets security subject ID. * * @return Security subject ID. */ @Nullable public UUID subjectId() { return subjId; } /** {@inheritDoc} */ @Override public String toString() {<FILL_FUNCTION_BODY>} }
return S.toString(SqlQueryExecutionEvent.class, this, "nodeId8", U.id8(node().id()), "msg", message(), "type", name(), "tstamp", timestamp());
463
58
521
<methods>public void <init>() ,public void <init>(org.apache.ignite.cluster.ClusterNode, java.lang.String, int) ,public int compareTo(org.apache.ignite.events.Event) ,public boolean equals(java.lang.Object) ,public int hashCode() ,public org.apache.ignite.lang.IgniteUuid id() ,public long localOrder() ,public void message(java.lang.String) ,public java.lang.String message() ,public java.lang.String name() ,public void node(org.apache.ignite.cluster.ClusterNode) ,public org.apache.ignite.cluster.ClusterNode node() ,public java.lang.String shortDisplay() ,public long timestamp() ,public java.lang.String toString() ,public void type(int) ,public int type() <variables>private final org.apache.ignite.lang.IgniteUuid id,private long locId,private java.lang.String msg,private org.apache.ignite.cluster.ClusterNode node,private static final long serialVersionUID,private final long tstamp,private int type
apache_ignite
ignite/modules/core/src/main/java/org/apache/ignite/internal/ComputeTaskInternalFuture.java
ComputeTaskInternalFuture
finishedFuture
class ComputeTaskInternalFuture<R> extends GridFutureAdapter<R> { /** */ private ComputeTaskSession ses; /** */ private GridKernalContext ctx; /** */ @GridToStringExclude private ComputeFuture<R> userFut; /** */ private transient IgniteLogger log; /** * @param ses Task session instance. * @param ctx Kernal context. */ public ComputeTaskInternalFuture(ComputeTaskSession ses, GridKernalContext ctx) { assert ses != null; assert ctx != null; this.ses = ses; this.ctx = ctx; userFut = new ComputeFuture<>(this); log = ctx.log(ComputeTaskInternalFuture.class); } /** * @param ctx Context. * @param taskCls Task class. * @param e Error. * @return Finished task future. */ public static <R> ComputeTaskInternalFuture<R> finishedFuture(final GridKernalContext ctx, final Class<?> taskCls, IgniteCheckedException e) {<FILL_FUNCTION_BODY>} /** * @return Future returned by public API. */ public ComputeTaskFuture<R> publicFuture() { return userFut; } /** * Gets task timeout. * * @return Task timeout. */ public ComputeTaskSession getTaskSession() { if (ses == null) throw new IllegalStateException("Cannot access task session after future has been deserialized."); return ses; } /** {@inheritDoc} */ @Override public boolean cancel() throws IgniteCheckedException { if (isCancelled()) return false; return ctx.task().cancel(ses.getId()); } /** {@inheritDoc} */ @Override public String toString() { return S.toString(ComputeTaskInternalFuture.class, this, "super", super.toString()); } /** {@inheritDoc} */ @Override public IgniteLogger logger() { return log; } /** * */ private static class ComputeFuture<R> extends IgniteFutureImpl<R> implements ComputeTaskFuture<R> { /** * @param fut Future. */ private ComputeFuture(ComputeTaskInternalFuture<R> fut) { super(fut); } /** {@inheritDoc} */ @Override public ComputeTaskSession getTaskSession() { return ((ComputeTaskInternalFuture<R>)fut).getTaskSession(); } } }
assert ctx != null; assert taskCls != null; assert e != null; final long time = U.currentTimeMillis(); final IgniteUuid id = IgniteUuid.fromUuid(ctx.localNodeId()); ComputeTaskSession ses = new ComputeTaskSession() { @Override public String getTaskName() { return taskCls.getName(); } @Override public UUID getTaskNodeId() { return ctx.localNodeId(); } @Override public long getStartTime() { return time; } @Override public long getEndTime() { return time; } @Override public IgniteUuid getId() { return id; } @Override public ClassLoader getClassLoader() { return null; } @Override public Collection<ComputeJobSibling> getJobSiblings() throws IgniteException { return Collections.emptyList(); } @Override public Collection<ComputeJobSibling> refreshJobSiblings() throws IgniteException { return Collections.emptyList(); } @Nullable @Override public ComputeJobSibling getJobSibling(IgniteUuid jobId) throws IgniteException { return null; } @Override public void setAttribute(Object key, @Nullable Object val) throws IgniteException { } @Nullable @Override public <K, V> V getAttribute(K key) { return null; } @Override public void setAttributes(Map<?, ?> attrs) throws IgniteException { // No-op. } @Override public Map<?, ?> getAttributes() { return Collections.emptyMap(); } @Override public void addAttributeListener(ComputeTaskSessionAttributeListener lsnr, boolean rewind) { // No-op. } @Override public boolean removeAttributeListener(ComputeTaskSessionAttributeListener lsnr) { return false; } @Override public <K, V> V waitForAttribute(K key, long timeout) throws InterruptedException { throw new InterruptedException("Session was closed."); } @Override public <K, V> boolean waitForAttribute(K key, @Nullable V val, long timeout) throws InterruptedException { throw new InterruptedException("Session was closed."); } @Override public Map<?, ?> waitForAttributes(Collection<?> keys, long timeout) throws InterruptedException { throw new InterruptedException("Session was closed."); } @Override public boolean waitForAttributes(Map<?, ?> attrs, long timeout) throws InterruptedException { throw new InterruptedException("Session was closed."); } @Override public void saveCheckpoint(String key, Object state) { throw new IgniteException("Session was closed."); } @Override public void saveCheckpoint(String key, Object state, ComputeTaskSessionScope scope, long timeout ) { throw new IgniteException("Session was closed."); } @Override public void saveCheckpoint(String key, Object state, ComputeTaskSessionScope scope, long timeout, boolean overwrite) { throw new IgniteException("Session was closed."); } @Nullable @Override public <T> T loadCheckpoint(String key) throws IgniteException { throw new IgniteException("Session was closed."); } @Override public boolean removeCheckpoint(String key) throws IgniteException { throw new IgniteException("Session was closed."); } @Override public Collection<UUID> getTopology() { return Collections.emptyList(); } @Override public IgniteFuture<?> mapFuture() { return new IgniteFinishedFutureImpl<Object>(); } }; ComputeTaskInternalFuture<R> fut = new ComputeTaskInternalFuture<>(ses, ctx); fut.onDone(e); return fut;
680
1,003
1,683
<methods>public non-sealed void <init>() ,public boolean cancel() throws org.apache.ignite.IgniteCheckedException,public IgniteInternalFuture<T> chain(IgniteClosure<? super IgniteInternalFuture<R>,T>) ,public IgniteInternalFuture<T> chain(IgniteOutClosure<T>) ,public IgniteInternalFuture<T> chain(IgniteClosure<? super IgniteInternalFuture<R>,T>, java.util.concurrent.Executor) ,public IgniteInternalFuture<T> chain(IgniteOutClosure<T>, java.util.concurrent.Executor) ,public IgniteInternalFuture<T> chainCompose(IgniteClosure<? super IgniteInternalFuture<R>,IgniteInternalFuture<T>>) ,public IgniteInternalFuture<T> chainCompose(IgniteClosure<? super IgniteInternalFuture<R>,IgniteInternalFuture<T>>, java.util.concurrent.Executor) ,public java.lang.Throwable error() ,public R get() throws org.apache.ignite.IgniteCheckedException,public R get(long) throws org.apache.ignite.IgniteCheckedException,public R get(long, java.util.concurrent.TimeUnit) throws org.apache.ignite.IgniteCheckedException,public R getUninterruptibly() throws org.apache.ignite.IgniteCheckedException,public void ignoreInterrupts() ,public boolean isCancelled() ,public boolean isDone() ,public boolean isFailed() ,public void listen(IgniteInClosure<? super IgniteInternalFuture<R>>) ,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(R) ,public final boolean onDone(java.lang.Throwable) ,public boolean onDone(R, java.lang.Throwable) ,public void reset() ,public R 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/GridLoggerProxy.java
GridLoggerProxy
enrich
class GridLoggerProxy implements IgniteLogger, LifecycleAware, Externalizable { /** */ private static final long serialVersionUID = 0L; /** */ private static ThreadLocal<IgniteBiTuple<String, Object>> stash = new ThreadLocal<IgniteBiTuple<String, Object>>() { @Override protected IgniteBiTuple<String, Object> initialValue() { return new IgniteBiTuple<>(); } }; /** */ private IgniteLogger impl; /** */ private String igniteInstanceName; /** */ private String id8; /** */ @GridToStringExclude private Object ctgr; /** Whether or not to log Ignite instance name. */ private static final boolean logIgniteInstanceName = System.getProperty(IGNITE_LOG_INSTANCE_NAME) != null || System.getProperty(IGNITE_LOG_GRID_NAME) != null; /** * No-arg constructor is required by externalization. */ public GridLoggerProxy() { // No-op. } /** * * @param impl Logger implementation to proxy to. * @param ctgr Optional logger category. * @param igniteInstanceName Ignite instance name (can be {@code null} for default grid). * @param id8 Node ID. */ public GridLoggerProxy(IgniteLogger impl, @Nullable Object ctgr, @Nullable String igniteInstanceName, String id8) { assert impl != null; this.impl = impl; this.ctgr = ctgr; this.igniteInstanceName = igniteInstanceName; this.id8 = id8; } /** {@inheritDoc} */ @Override public void start() { if (impl instanceof LifecycleAware) ((LifecycleAware)impl).start(); } /** {@inheritDoc} */ @Override public void stop() { U.stopLifecycleAware(this, Collections.singleton(impl)); } /** {@inheritDoc} */ @Override public IgniteLogger getLogger(Object ctgr) { assert ctgr != null; return new GridLoggerProxy(impl.getLogger(ctgr), ctgr, igniteInstanceName, id8); } /** {@inheritDoc} */ @Nullable @Override public String fileName() { return impl.fileName(); } /** {@inheritDoc} */ @Override public void trace(String msg) { impl.trace(enrich(msg)); } /** {@inheritDoc} */ @Override public void trace(@Nullable String marker, String msg) { impl.trace(marker, enrich(msg)); } /** {@inheritDoc} */ @Override public void debug(String msg) { impl.debug(enrich(msg)); } /** {@inheritDoc} */ @Override public void debug(@Nullable String marker, String msg) { impl.debug(marker, enrich(msg)); } /** {@inheritDoc} */ @Override public void info(String msg) { impl.info(enrich(msg)); } /** {@inheritDoc} */ @Override public void info(@Nullable String marker, String msg) { impl.info(marker, enrich(msg)); } /** {@inheritDoc} */ @Override public void warning(String msg) { impl.warning(enrich(msg)); } /** {@inheritDoc} */ @Override public void warning(String msg, Throwable e) { impl.warning(enrich(msg), e); } /** {@inheritDoc} */ @Override public void warning(@Nullable String marker, String msg, @Nullable Throwable e) { impl.warning(marker, enrich(msg), e); } /** {@inheritDoc} */ @Override public void error(String msg) { impl.error(enrich(msg)); } /** {@inheritDoc} */ @Override public void error(String msg, Throwable e) { impl.error(enrich(msg), e); } /** {@inheritDoc} */ @Override public void error(@Nullable String marker, String msg, @Nullable Throwable e) { impl.error(marker, enrich(msg), e); } /** {@inheritDoc} */ @Override public boolean isTraceEnabled() { return impl.isTraceEnabled(); } /** {@inheritDoc} */ @Override public boolean isDebugEnabled() { return impl.isDebugEnabled(); } /** {@inheritDoc} */ @Override public boolean isInfoEnabled() { return impl.isInfoEnabled(); } /** {@inheritDoc} */ @Override public boolean isQuiet() { return impl.isQuiet(); } /** * Gets the class name and parameters of the Logger type used. * * @return Logger information (name and parameters) */ public String getLoggerInfo() { return impl.toString(); } /** * Enriches the log message with Ignite instance name if * {@link org.apache.ignite.IgniteSystemProperties#IGNITE_LOG_INSTANCE_NAME} or * {@link org.apache.ignite.IgniteSystemProperties#IGNITE_LOG_GRID_NAME} system property is set. * * @param m Message to enrich. * @return Enriched message or the original one. */ private String enrich(@Nullable String m) {<FILL_FUNCTION_BODY>} /** {@inheritDoc} */ @Override public void writeExternal(ObjectOutput out) throws IOException { U.writeString(out, igniteInstanceName); out.writeObject(ctgr); } /** {@inheritDoc} */ @Override public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException { IgniteBiTuple<String, Object> t = stash.get(); t.set1(U.readString(in)); t.set2(in.readObject()); } /** * Reconstructs object on unmarshalling. * * @return Reconstructed object. * @throws ObjectStreamException Thrown in case of unmarshalling error. */ protected Object readResolve() throws ObjectStreamException { try { IgniteBiTuple<String, Object> t = stash.get(); Object ctgrR = t.get2(); IgniteLogger log = IgnitionEx.localIgnite().log(); return ctgrR != null ? log.getLogger(ctgrR) : log; } catch (IllegalStateException e) { throw U.withCause(new InvalidObjectException(e.getMessage()), e); } finally { stash.remove(); } } /** {@inheritDoc} */ @Override public String toString() { return S.toString(GridLoggerProxy.class, this); } }
return logIgniteInstanceName && m != null ? "<" + igniteInstanceName + '-' + id8 + "> " + m : m;
1,800
40
1,840
<no_super_class>
apache_ignite
ignite/modules/core/src/main/java/org/apache/ignite/internal/LongJVMPauseDetector.java
LongJVMPauseDetector
start
class LongJVMPauseDetector { /** Ignite JVM pause detector threshold default value. */ public static final int DEFAULT_JVM_PAUSE_DETECTOR_THRESHOLD = 500; /** @see IgniteSystemProperties#IGNITE_JVM_PAUSE_DETECTOR_PRECISION */ public static final int DFLT_JVM_PAUSE_DETECTOR_PRECISION = 50; /** @see IgniteSystemProperties#IGNITE_JVM_PAUSE_DETECTOR_LAST_EVENTS_COUNT */ public static final int DFLT_JVM_PAUSE_DETECTOR_LAST_EVENTS_COUNT = 20; /** Precision. */ private static final int PRECISION = getInteger(IGNITE_JVM_PAUSE_DETECTOR_PRECISION, DFLT_JVM_PAUSE_DETECTOR_PRECISION); /** Threshold. */ private static final int THRESHOLD = getInteger(IGNITE_JVM_PAUSE_DETECTOR_THRESHOLD, DEFAULT_JVM_PAUSE_DETECTOR_THRESHOLD); /** Event count. */ private static final int EVT_CNT = getInteger(IGNITE_JVM_PAUSE_DETECTOR_LAST_EVENTS_COUNT, DFLT_JVM_PAUSE_DETECTOR_LAST_EVENTS_COUNT); /** Disabled flag. */ private static final boolean DISABLED = getBoolean(IGNITE_JVM_PAUSE_DETECTOR_DISABLED); /** Logger. */ private final IgniteLogger log; /** Worker reference. */ private final AtomicReference<Thread> workerRef = new AtomicReference<>(); /** Long pause count. */ private long longPausesCnt; /** Long pause total duration. */ private long longPausesTotalDuration; /** Last detector's wake up time. */ private long lastWakeUpTime; /** Long pauses timestamps. */ @GridToStringInclude private final long[] longPausesTimestamps = new long[EVT_CNT]; /** Long pauses durations. */ @GridToStringInclude private final long[] longPausesDurations = new long[EVT_CNT]; /** * @param log Logger. */ public LongJVMPauseDetector(IgniteLogger log) { this.log = log; } /** * Starts worker if not started yet. */ public void start() {<FILL_FUNCTION_BODY>} /** * Stops the worker if one is created and running. */ public void stop() { final Thread worker = workerRef.getAndSet(null); if (worker != null && worker.isAlive() && !worker.isInterrupted()) worker.interrupt(); } /** * @return {@code false} if {@link IgniteSystemProperties#IGNITE_JVM_PAUSE_DETECTOR_DISABLED} set to {@code true}, * and {@code true} otherwise. */ public static boolean enabled() { return !DISABLED; } /** * @return Long JVM pauses count. */ synchronized long longPausesCount() { return longPausesCnt; } /** * @return Long JVM pauses total duration. */ synchronized long longPausesTotalDuration() { return longPausesTotalDuration; } /** * @return Last checker's wake up time. */ public synchronized long getLastWakeUpTime() { return lastWakeUpTime; } /** * @return Last long JVM pause events. */ synchronized Map<Long, Long> longPauseEvents() { final Map<Long, Long> evts = new TreeMap<>(); for (int i = 0; i < longPausesTimestamps.length && longPausesTimestamps[i] != 0; i++) evts.put(longPausesTimestamps[i], longPausesDurations[i]); return evts; } /** * @return Pair ({@code last long pause event time}, {@code pause time duration}) or {@code null}, if long pause * wasn't occurred. */ public synchronized @Nullable IgniteBiTuple<Long, Long> getLastLongPause() { int lastPauseIdx = (int)((EVT_CNT + longPausesCnt - 1) % EVT_CNT); if (longPausesTimestamps[lastPauseIdx] == 0) return null; return new IgniteBiTuple<>(longPausesTimestamps[lastPauseIdx], longPausesDurations[lastPauseIdx]); } /** {@inheritDoc} */ @Override public String toString() { return S.toString(LongJVMPauseDetector.class, this); } }
if (DISABLED) { if (log.isDebugEnabled()) log.debug("JVM Pause Detector is disabled."); return; } final Thread worker = new Thread("jvm-pause-detector-worker") { @Override public void run() { synchronized (LongJVMPauseDetector.this) { lastWakeUpTime = TimeUnit.NANOSECONDS.toMillis(System.nanoTime()); } if (log.isDebugEnabled()) log.debug(getName() + " has been started."); while (true) { try { Thread.sleep(PRECISION); final long now = TimeUnit.NANOSECONDS.toMillis(System.nanoTime()); final long pause = now - PRECISION - lastWakeUpTime; if (pause >= THRESHOLD) { log.warning("Possible too long JVM pause: " + pause + " milliseconds."); synchronized (LongJVMPauseDetector.this) { final int next = (int)(longPausesCnt % EVT_CNT); longPausesCnt++; longPausesTotalDuration += pause; longPausesTimestamps[next] = now; longPausesDurations[next] = pause; lastWakeUpTime = now; } } else { synchronized (LongJVMPauseDetector.this) { lastWakeUpTime = now; } } } catch (InterruptedException e) { if (workerRef.compareAndSet(this, null)) log.error(getName() + " has been interrupted.", e); else if (log.isDebugEnabled()) log.debug(getName() + " has been stopped."); break; } } } }; if (!workerRef.compareAndSet(null, worker)) { log.warning(LongJVMPauseDetector.class.getSimpleName() + " already started!"); return; } worker.setDaemon(true); worker.start(); if (log.isDebugEnabled()) log.debug("LongJVMPauseDetector was successfully started");
1,306
580
1,886
<no_super_class>
apache_ignite
ignite/modules/core/src/main/java/org/apache/ignite/internal/QueryMXBeanImpl.java
CancelContinuousOnInitiator
apply
class CancelContinuousOnInitiator implements IgniteClosure<UUID, Void> { /** */ private static final long serialVersionUID = 0L; /** Auto-injected grid instance. */ @IgniteInstanceResource private transient IgniteEx ignite; /** {@inheritDoc} */ @Override public Void apply(UUID routineId) {<FILL_FUNCTION_BODY>} }
IgniteInternalFuture<?> fut = ignite.context().continuous().stopRoutine(routineId); try { fut.get(); } catch (IgniteCheckedException e) { throw new IgniteException(e); } return null;
108
76
184
<no_super_class>
apache_ignite
ignite/modules/core/src/main/java/org/apache/ignite/internal/binary/BinaryArrayIdentityResolver.java
BinaryArrayIdentityResolver
hashCode0
class BinaryArrayIdentityResolver extends BinaryAbstractIdentityResolver { /** Singleton instance */ private static final BinaryArrayIdentityResolver INSTANCE = new BinaryArrayIdentityResolver(); /** * Get singleton instance. * * @return Singleton instance. */ public static BinaryArrayIdentityResolver instance() { return INSTANCE; } /** * Default constructor. */ public BinaryArrayIdentityResolver() { // No-op. } /** {@inheritDoc} */ @Override protected int hashCode0(BinaryObject obj) {<FILL_FUNCTION_BODY>} /** {@inheritDoc} */ @Override protected boolean equals0(BinaryObject o1, BinaryObject o2) { if (o1 instanceof BinaryObjectEx && o2 instanceof BinaryObjectEx) { BinaryObjectEx ex1 = (BinaryObjectEx)o1; BinaryObjectEx ex2 = (BinaryObjectEx)o2; if (ex1.typeId() != ex2.typeId()) return false; if (ex1 instanceof BinaryObjectExImpl) { // Handle regular object. assert ex2 instanceof BinaryObjectExImpl; BinaryObjectExImpl exx1 = (BinaryObjectExImpl)ex1; BinaryObjectExImpl exx2 = (BinaryObjectExImpl)ex2; if (exx1.hasArray()) return exx2.hasArray() ? equalsHeap(exx1, exx2) : equalsHeapOffheap(exx1, exx2); else return exx2.hasArray() ? equalsHeapOffheap(exx2, exx1) : equalsOffheap(exx1, exx2); } else { // Handle enums. assert ex1 instanceof BinaryEnumObjectImpl; assert ex2 instanceof BinaryEnumObjectImpl; return ex1.enumOrdinal() == ex2.enumOrdinal(); } } BinaryObject o = o1 instanceof BinaryObjectEx ? o2 : o1; throw new BinaryObjectException("Array identity resolver cannot be used with provided BinaryObject " + "implementation: " + o.getClass().getName()); } /** * Compare two heap objects. * * @param o1 Object 1. * @param o2 Object 2. * @return Result. */ private static boolean equalsHeap(BinaryObjectExImpl o1, BinaryObjectExImpl o2) { byte[] arr1 = o1.array(); byte[] arr2 = o2.array(); assert arr1 != null && arr2 != null; int i = o1.dataStartOffset(); int j = o2.dataStartOffset(); int end = o1.footerStartOffset(); // Check length. if (end - i != o2.footerStartOffset() - j) return false; for (; i < end; i++, j++) { if (arr1[i] != arr2[j]) return false; } return true; } /** * Compare heap and offheap objects. * * @param o1 Object 1 (heap). * @param o2 Object 2 (offheap). * @return Result. */ private static boolean equalsHeapOffheap(BinaryObjectExImpl o1, BinaryObjectExImpl o2) { byte[] arr1 = o1.array(); long ptr2 = o2.offheapAddress(); assert arr1 != null && ptr2 != 0; int i = o1.dataStartOffset(); int j = o2.dataStartOffset(); int end = o1.footerStartOffset(); // Check length. if (end - i != o2.footerStartOffset() - j) return false; for (; i < end; i++, j++) { if (arr1[i] != BinaryPrimitives.readByte(ptr2, j)) return false; } return true; } /** * Compare two offheap objects. * * @param o1 Object 1. * @param o2 Object 2. * @return Result. */ private static boolean equalsOffheap(BinaryObjectExImpl o1, BinaryObjectExImpl o2) { long ptr1 = o1.offheapAddress(); long ptr2 = o2.offheapAddress(); assert ptr1 != 0 && ptr2 != 0; int i = o1.dataStartOffset(); int j = o2.dataStartOffset(); int end = o1.footerStartOffset(); // Check length. if (end - i != o2.footerStartOffset() - j) return false; for (; i < end; i++, j++) { if (BinaryPrimitives.readByte(ptr1, i) != BinaryPrimitives.readByte(ptr2, j)) return false; } return true; } /** {@inheritDoc} */ @Override public String toString() { return S.toString(BinaryArrayIdentityResolver.class, this); } }
int hash = 1; if (obj instanceof BinaryObjectExImpl) { BinaryObjectExImpl ex = (BinaryObjectExImpl)obj; int start = ex.dataStartOffset(); int end = ex.footerStartOffset(); if (ex.hasArray()) { // Handle heap object. byte[] data = ex.array(); for (int i = start; i < end; i++) hash = 31 * hash + data[i]; } else { // Handle offheap object. long ptr = ex.offheapAddress(); for (int i = start; i < end; i++) hash = 31 * hash + BinaryPrimitives.readByte(ptr, i); } } else if (obj instanceof BinaryEnumObjectImpl) { int ord = obj.enumOrdinal(); // Construct hash as if it was an int serialized in little-endian form. hash = 31 * hash + (ord & 0x000000FF); hash = 31 * hash + (ord & 0x0000FF00); hash = 31 * hash + (ord & 0x00FF0000); hash = 31 * hash + (ord & 0xFF000000); } else throw new BinaryObjectException("Array identity resolver cannot be used with provided BinaryObject " + "implementation: " + obj.getClass().getName()); return hash;
1,348
384
1,732
<methods>public non-sealed void <init>() ,public boolean equals(org.apache.ignite.binary.BinaryObject, org.apache.ignite.binary.BinaryObject) ,public int hashCode(org.apache.ignite.binary.BinaryObject) <variables>
apache_ignite
ignite/modules/core/src/main/java/org/apache/ignite/internal/binary/BinaryContextHolder.java
BinaryContextHolder
set
class BinaryContextHolder { /** Context. */ private BinaryContext ctx; /** * @return Context. */ @Nullable public BinaryContext get() { return ctx; } /** * @param newCtx New context. * @return Previous context. */ @Nullable public BinaryContext set(@Nullable BinaryContext newCtx) {<FILL_FUNCTION_BODY>} }
BinaryContext oldCtx = ctx; ctx = newCtx; return oldCtx;
114
31
145
<no_super_class>
apache_ignite
ignite/modules/core/src/main/java/org/apache/ignite/internal/binary/BinaryFieldImpl.java
BinaryFieldImpl
fieldOrder
class BinaryFieldImpl implements BinaryFieldEx { /** Binary context that created this field. */ private final BinaryContext ctx; /** Type ID. */ private final int typeId; /** Well-known object schemas. */ @GridToStringExclude private final BinarySchemaRegistry schemas; /** Field name. */ private final String fieldName; /** Pre-calculated field ID. */ private final int fieldId; /** * Constructor. * * @param ctx Binary context. * @param typeId Type ID. * @param schemas Schemas. * @param fieldName Field name. * @param fieldId Field ID. */ public BinaryFieldImpl( BinaryContext ctx, int typeId, BinarySchemaRegistry schemas, String fieldName, int fieldId ) { assert ctx != null; assert typeId != 0; assert schemas != null; assert fieldId != 0; this.ctx = ctx; this.typeId = typeId; this.schemas = schemas; this.fieldName = fieldName; this.fieldId = fieldId; } /** {@inheritDoc} */ @Override public String name() { return fieldName; } /** * @return Field ID. */ public int fieldId() { return fieldId; } /** {@inheritDoc} */ @Override public boolean exists(BinaryObject obj) { BinaryObjectExImpl obj0 = (BinaryObjectExImpl)obj; return fieldOrder(obj0) != BinarySchema.ORDER_NOT_FOUND; } /** {@inheritDoc} */ @Override public <T> T value(BinaryObject obj) { BinaryObjectExImpl obj0 = (BinaryObjectExImpl)obj; int order = fieldOrder(obj0); return order != BinarySchema.ORDER_NOT_FOUND ? (T)obj0.fieldByOrder(order) : null; } /** {@inheritDoc} */ @Override public int typeId() { return typeId; } /** {@inheritDoc} */ @Override public boolean writeField(BinaryObject obj, ByteBuffer buf) { BinaryObjectExImpl obj0 = (BinaryObjectExImpl)obj; int order = fieldOrder(obj0); return obj0.writeFieldByOrder(order, buf); } /** {@inheritDoc} */ @Override public <F> F readField(ByteBuffer buf) { ByteOrder oldOrder = buf.order(); try { buf.order(ByteOrder.LITTLE_ENDIAN); int pos = buf.position(); byte hdr = buf.get(); Object val; switch (hdr) { case GridBinaryMarshaller.INT: val = buf.getInt(); break; case GridBinaryMarshaller.LONG: val = buf.getLong(); break; case GridBinaryMarshaller.BOOLEAN: val = buf.get() != 0; break; case GridBinaryMarshaller.SHORT: val = buf.getShort(); break; case GridBinaryMarshaller.BYTE: val = buf.get(); break; case GridBinaryMarshaller.CHAR: val = buf.getChar(); break; case GridBinaryMarshaller.FLOAT: val = buf.getFloat(); break; case GridBinaryMarshaller.DOUBLE: val = buf.getDouble(); break; case GridBinaryMarshaller.STRING: { int dataLen = buf.getInt(); byte[] data = new byte[dataLen]; buf.get(data); val = new String(data, 0, dataLen, UTF_8); break; } case GridBinaryMarshaller.DATE: { long time = buf.getLong(); val = new Date(time); break; } case GridBinaryMarshaller.TIMESTAMP: { long time = buf.getLong(); int nanos = buf.getInt(); Timestamp ts = new Timestamp(time); ts.setNanos(ts.getNanos() + nanos); val = ts; break; } case GridBinaryMarshaller.TIME: { long time = buf.getLong(); val = new Time(time); break; } case GridBinaryMarshaller.UUID: { long most = buf.getLong(); long least = buf.getLong(); val = new UUID(most, least); break; } case GridBinaryMarshaller.DECIMAL: { int scale = buf.getInt(); int dataLen = buf.getInt(); byte[] data = new byte[dataLen]; buf.get(data); boolean negative = data[0] < 0; if (negative) data[0] &= 0x7F; BigInteger intVal = new BigInteger(data); if (negative) intVal = intVal.negate(); val = new BigDecimal(intVal, scale); break; } case GridBinaryMarshaller.NULL: val = null; break; default: // Restore buffer position. buf.position(pos); val = BinaryUtils.unmarshal(BinaryByteBufferInputStream.create(buf), ctx, null); break; } return (F)val; } finally { buf.order(oldOrder); } } /** * Get relative field offset. * * @param obj Object. * @return Field offset. */ public int fieldOrder(BinaryObjectExImpl obj) {<FILL_FUNCTION_BODY>} /** {@inheritDoc} */ @Override public String toString() { return S.toString(BinaryFieldImpl.class, this); } }
if (typeId != obj.typeId()) { BinaryType expType = ctx.metadata(typeId); BinaryType actualType = obj.type(); String actualTypeName = null; Exception actualTypeNameEx = null; try { actualTypeName = actualType.typeName(); } catch (BinaryObjectException e) { actualTypeNameEx = new BinaryObjectException("Failed to get actual binary type name.", e); } throw new BinaryObjectException("Failed to get field because type ID of passed object differs" + " from type ID this " + BinaryField.class.getSimpleName() + " belongs to [expected=[typeId=" + typeId + ", typeName=" + (nonNull(expType) ? expType.typeName() : null) + "], actual=[typeId=" + actualType.typeId() + ", typeName=" + actualTypeName + "], fieldId=" + fieldId + ", fieldName=" + fieldName + ", fieldType=" + (nonNull(expType) ? expType.fieldTypeName(fieldName) : null) + ']', actualTypeNameEx); } int schemaId = obj.schemaId(); if (schemaId == 0) return BinarySchema.ORDER_NOT_FOUND; BinarySchema schema = schemas.schema(schemaId); if (schema == null) { schema = obj.createSchema(); schemas.addSchema(schemaId, schema); } assert schema != null; return schema.order(fieldId);
1,597
402
1,999
<no_super_class>
apache_ignite
ignite/modules/core/src/main/java/org/apache/ignite/internal/binary/BinaryReaderHandles.java
BinaryReaderHandles
put
class BinaryReaderHandles { /** Mode: empty. */ private static final int MODE_EMPTY = 0; /** Mode: single object. */ private static final int MODE_SINGLE = 1; /** Mode: multiple objects. */ private static final int MODE_MULTIPLE = 2; /** Position. */ private int singlePos; /** Data. This is either an object or a map. */ private Object data; /** Mode. */ private int mode = MODE_EMPTY; /** * Get object by position. * * @param pos Position. * @return Object. */ @Nullable public <T> T get(int pos) { switch (mode) { case MODE_EMPTY: return null; case MODE_SINGLE: return pos == singlePos ? (T)data : null; default: assert mode == MODE_MULTIPLE; return (T)((Map<Integer, Object>)data).get(pos); } } /** * Put object to registry and return previous position (if any). * * @param pos Position. * @param obj Object. */ @SuppressWarnings("unchecked") public void put(int pos, Object obj) {<FILL_FUNCTION_BODY>} }
assert pos >= 0; assert obj != null; switch (mode) { case MODE_EMPTY: this.singlePos = pos; this.data = obj; this.mode = MODE_SINGLE; break; case MODE_SINGLE: Map<Integer, Object> newData = new HashMap(3, 1.0f); newData.put(singlePos, data); newData.put(pos, obj); this.singlePos = -1; this.data = newData; this.mode = MODE_MULTIPLE; break; default: assert mode == MODE_MULTIPLE; Map<Integer, Object> data0 = (Map<Integer, Object>)data; data0.put(pos, obj); }
360
223
583
<no_super_class>
apache_ignite
ignite/modules/core/src/main/java/org/apache/ignite/internal/binary/BinarySchemaRegistry.java
BinarySchemaRegistry
addSchema
class BinarySchemaRegistry { /** Empty schema ID. */ private static final int EMPTY = 0; /** Whether registry still works in inline mode. */ private volatile boolean inline = true; /** First schema ID. */ private int schemaId1; /** Second schema ID. */ private int schemaId2; /** Third schema ID. */ private int schemaId3; /** Fourth schema ID. */ private int schemaId4; /** First schema. */ private BinarySchema schema1; /** Second schema. */ private BinarySchema schema2; /** Third schema. */ private BinarySchema schema3; /** Fourth schema. */ private BinarySchema schema4; /** Schemas with COW semantics. */ private volatile HashMap<Integer, BinarySchema> schemas; /** * Get schema for the given ID. We rely on very relaxed memory semantics here assuming that it is not critical * to return false-positive {@code null} values. * * @param schemaId Schema ID. * @return Schema or {@code null}. */ @Nullable public BinarySchema schema(int schemaId) { if (inline) { if (schemaId == schemaId1) return schema1; else if (schemaId == schemaId2) return schema2; else if (schemaId == schemaId3) return schema3; else if (schemaId == schemaId4) return schema4; } else { HashMap<Integer, BinarySchema> schemas0 = schemas; // Null can be observed here due to either data race or race condition when switching to non-inlined mode. // Both of them are benign for us because they lead only to unnecessary schema re-calc. if (schemas0 != null) return schemas0.get(schemaId); } return null; } /** * Add schema. * * @param schemaId Schema ID. * @param schema Schema. */ public synchronized void addSchema(int schemaId, BinarySchema schema) {<FILL_FUNCTION_BODY>} /** * @return List of known schemas. */ public synchronized List<BinarySchema> schemas() { List<BinarySchema> res = new ArrayList<>(); if (inline) { if (schemaId1 != EMPTY) res.add(schema1); if (schemaId2 != EMPTY) res.add(schema2); if (schemaId3 != EMPTY) res.add(schema3); if (schemaId4 != EMPTY) res.add(schema4); } else res.addAll(schemas.values()); return res; } }
if (inline) { // Check if this is already known schema. if (schemaId == schemaId1 || schemaId == schemaId2 || schemaId == schemaId3 || schemaId == schemaId4) return; // Try positioning new schema in inline mode. if (schemaId1 == EMPTY) { schemaId1 = schemaId; schema1 = schema; inline = true; // Forcing HB edge just in case. return; } if (schemaId2 == EMPTY) { schemaId2 = schemaId; schema2 = schema; inline = true; // Forcing HB edge just in case. return; } if (schemaId3 == EMPTY) { schemaId3 = schemaId; schema3 = schema; inline = true; // Forcing HB edge just in case. return; } if (schemaId4 == EMPTY) { schemaId4 = schemaId; schema4 = schema; inline = true; // Forcing HB edge just in case. return; } // No luck, switching to hash map mode. HashMap<Integer, BinarySchema> newSchemas = new HashMap<>(); newSchemas.put(schemaId1, schema1); newSchemas.put(schemaId2, schema2); newSchemas.put(schemaId3, schema3); newSchemas.put(schemaId4, schema4); newSchemas.put(schemaId, schema); schemas = newSchemas; inline = false; } else { HashMap<Integer, BinarySchema> newSchemas = new HashMap<>(schemas); newSchemas.put(schemaId, schema); schemas = newSchemas; }
726
474
1,200
<no_super_class>
apache_ignite
ignite/modules/core/src/main/java/org/apache/ignite/internal/binary/BinaryTreeMap.java
BinaryTreeMap
writeBinary
class BinaryTreeMap implements Binarylizable, Serializable { /** */ private static final long serialVersionUID = 0L; /** Original map. */ private TreeMap map; /** * Default constructor. */ public BinaryTreeMap() { // No-op. } /** * Constructor. * * @param map Original map. */ public BinaryTreeMap(TreeMap map) { this.map = map; } /** {@inheritDoc} */ @Override public void writeBinary(BinaryWriter writer) throws BinaryObjectException {<FILL_FUNCTION_BODY>} /** {@inheritDoc} */ @SuppressWarnings("unchecked") @Override public void readBinary(BinaryReader reader) throws BinaryObjectException { BinaryRawReader rawReader = reader.rawReader(); Comparator comp = rawReader.readObject(); map = comp == null ? new TreeMap() : new TreeMap(comp); int size = rawReader.readInt(); for (int i = 0; i < size; i++) map.put(rawReader.readObject(), rawReader.readObject()); } /** * Reconstructs object on unmarshalling. * * @return Reconstructed object. * @throws ObjectStreamException Thrown in case of unmarshalling error. */ protected Object readResolve() throws ObjectStreamException { return map; } }
BinaryRawWriter rawWriter = writer.rawWriter(); rawWriter.writeObject(map.comparator()); int size = map.size(); rawWriter.writeInt(size); for (Map.Entry<Object, Object> entry : ((TreeMap<Object, Object>)map).entrySet()) { rawWriter.writeObject(entry.getKey()); rawWriter.writeObject(entry.getValue()); }
381
111
492
<no_super_class>
apache_ignite
ignite/modules/core/src/main/java/org/apache/ignite/internal/binary/builder/BinaryLazyLinkedList.java
BinaryLazyLinkedList
listIterator
class BinaryLazyLinkedList extends AbstractList<Object> implements BinaryBuilderSerializationAware { /** */ private final BinaryBuilderReader reader; /** */ private final int off; /** */ private List<Object> delegate; /** * @param reader Reader. * @param size Size, */ BinaryLazyLinkedList(BinaryBuilderReader reader, int size) { this.reader = reader; off = reader.position() - 1/* flag */ - 4/* size */ - 1/* col type */; assert size >= 0; for (int i = 0; i < size; i++) reader.skipValue(); } /** * */ private void ensureDelegateInit() { if (delegate == null) { int size = reader.readIntPositioned(off + 1); reader.position(off + 1/* flag */ + 4/* size */ + 1/* col type */); delegate = new LinkedList<>(); for (int i = 0; i < size; i++) delegate.add(reader.parseValue()); } } /** {@inheritDoc} */ @Override public Object get(int idx) { ensureDelegateInit(); return BinaryUtils.unwrapLazy(delegate.get(idx)); } /** {@inheritDoc} */ @Override public boolean add(Object o) { ensureDelegateInit(); return delegate.add(o); } /** {@inheritDoc} */ @Override public void add(int idx, Object element) { ensureDelegateInit(); delegate.add(idx, element); } /** {@inheritDoc} */ @Override public Object set(int idx, Object element) { ensureDelegateInit(); return BinaryUtils.unwrapLazy(delegate.set(idx, element)); } /** {@inheritDoc} */ @Override public Object remove(int idx) { ensureDelegateInit(); return BinaryUtils.unwrapLazy(delegate.remove(idx)); } /** {@inheritDoc} */ @Override public void clear() { if (delegate == null) delegate = new LinkedList<>(); else delegate.clear(); } /** {@inheritDoc} */ @Override public boolean addAll(int idx, Collection<?> c) { ensureDelegateInit(); return delegate.addAll(idx, c); } /** {@inheritDoc} */ @Override protected void removeRange(int fromIdx, int toIdx) { ensureDelegateInit(); delegate.subList(fromIdx, toIdx).clear(); } /** {@inheritDoc} */ @Override public int size() { if (delegate == null) return reader.readIntPositioned(off + 1); return delegate.size(); } /** {@inheritDoc} */ @Override public ListIterator<Object> listIterator(final int idx) {<FILL_FUNCTION_BODY>} /** {@inheritDoc} */ @Override public Iterator<Object> iterator() { ensureDelegateInit(); return BinaryUtils.unwrapLazyIterator(super.iterator()); } /** {@inheritDoc} */ @Override public void writeTo(BinaryWriterExImpl writer, BinaryBuilderSerializer ctx) { if (delegate == null) { int size = reader.readIntPositioned(off + 1); int hdrSize = 1 /* flag */ + 4 /* size */ + 1 /* col type */; writer.write(reader.array(), off, hdrSize); reader.position(off + hdrSize); for (int i = 0; i < size; i++) { Object o = reader.parseValue(); ctx.writeValue(writer, o); } } else { writer.writeByte(GridBinaryMarshaller.COL); writer.writeInt(delegate.size()); byte colType = reader.array()[off + 1 /* flag */ + 4 /* size */]; writer.writeByte(colType); for (Object o : delegate) ctx.writeValue(writer, o); } } }
ensureDelegateInit(); return new ListIterator<Object>() { /** */ private final ListIterator<Object> delegate = BinaryLazyLinkedList.super.listIterator(idx); @Override public boolean hasNext() { return delegate.hasNext(); } @Override public Object next() { return BinaryUtils.unwrapLazy(delegate.next()); } @Override public boolean hasPrevious() { return delegate.hasPrevious(); } @Override public Object previous() { return BinaryUtils.unwrapLazy(delegate.previous()); } @Override public int nextIndex() { return delegate.nextIndex(); } @Override public int previousIndex() { return delegate.previousIndex(); } @Override public void remove() { delegate.remove(); } @Override public void set(Object o) { delegate.set(o); } @Override public void add(Object o) { delegate.add(o); } };
1,083
271
1,354
<methods>public boolean add(java.lang.Object) ,public void add(int, java.lang.Object) ,public boolean addAll(int, Collection<? extends java.lang.Object>) ,public void clear() ,public boolean equals(java.lang.Object) ,public abstract java.lang.Object get(int) ,public int hashCode() ,public int indexOf(java.lang.Object) ,public Iterator<java.lang.Object> iterator() ,public int lastIndexOf(java.lang.Object) ,public ListIterator<java.lang.Object> listIterator() ,public ListIterator<java.lang.Object> listIterator(int) ,public java.lang.Object remove(int) ,public java.lang.Object set(int, java.lang.Object) ,public List<java.lang.Object> subList(int, int) <variables>protected transient int modCount
apache_ignite
ignite/modules/core/src/main/java/org/apache/ignite/internal/binary/streams/BinaryHeapOutputStream.java
BinaryHeapOutputStream
ensureCapacity
class BinaryHeapOutputStream extends BinaryAbstractOutputStream { /** Allocator. */ private final BinaryMemoryAllocatorChunk chunk; /** Disable auto close flag. */ private final boolean disableAutoClose; /** Data. */ private byte[] data; /** * Constructor. * * @param cap Initial capacity. */ public BinaryHeapOutputStream(int cap) { this(cap, BinaryMemoryAllocator.THREAD_LOCAL.chunk()); } /** * Constructor. * * @param cap Capacity. * @param chunk Chunk. */ public BinaryHeapOutputStream(int cap, BinaryMemoryAllocatorChunk chunk) { this(cap, chunk, false); } /** * Constructor. * * @param cap Capacity. * @param chunk Chunk. * @param disableAutoClose Whether to disable resource release in {@link BinaryHeapOutputStream#close()} method * so that an explicit {@link BinaryHeapOutputStream#release()} call is required. */ public BinaryHeapOutputStream(int cap, BinaryMemoryAllocatorChunk chunk, boolean disableAutoClose) { this.chunk = chunk; this.disableAutoClose = disableAutoClose; data = chunk.allocate(cap); } /** {@inheritDoc} */ @Override public void close() { if (!disableAutoClose) release(); } /** * Releases pooled memory. */ public void release() { chunk.release(data, pos); } /** {@inheritDoc} */ @Override public void ensureCapacity(int cnt) {<FILL_FUNCTION_BODY>} /** {@inheritDoc} */ @Override public byte[] array() { return data; } /** {@inheritDoc} */ @Override public byte[] arrayCopy() { byte[] res = new byte[pos]; System.arraycopy(data, 0, res, 0, pos); return res; } /** {@inheritDoc} */ @Override public boolean hasArray() { return true; } /** {@inheritDoc} */ @Override protected void writeByteAndShift(byte val) { data[pos++] = val; } /** {@inheritDoc} */ @Override protected void copyAndShift(Object src, long off, int len) { GridUnsafe.copyMemory(src, off, data, GridUnsafe.BYTE_ARR_OFF + pos, len); shift(len); } /** {@inheritDoc} */ @Override protected void writeShortFast(short val) { long off = GridUnsafe.BYTE_ARR_OFF + pos; if (BIG_ENDIAN) GridUnsafe.putShortLE(data, off, val); else GridUnsafe.putShort(data, off, val); } /** {@inheritDoc} */ @Override protected void writeCharFast(char val) { long off = GridUnsafe.BYTE_ARR_OFF + pos; if (BIG_ENDIAN) GridUnsafe.putCharLE(data, off, val); else GridUnsafe.putChar(data, off, val); } /** {@inheritDoc} */ @Override protected void writeIntFast(int val) { long off = GridUnsafe.BYTE_ARR_OFF + pos; if (BIG_ENDIAN) GridUnsafe.putIntLE(data, off, val); else GridUnsafe.putInt(data, off, val); } /** {@inheritDoc} */ @Override protected void writeLongFast(long val) { long off = GridUnsafe.BYTE_ARR_OFF + pos; if (BIG_ENDIAN) GridUnsafe.putLongLE(data, off, val); else GridUnsafe.putLong(data, off, val); } /** {@inheritDoc} */ @Override public void unsafeWriteByte(byte val) { GridUnsafe.putByte(data, GridUnsafe.BYTE_ARR_OFF + pos++, val); } /** {@inheritDoc} */ @Override public void unsafeWriteShort(short val) { long off = GridUnsafe.BYTE_ARR_OFF + pos; if (BIG_ENDIAN) GridUnsafe.putShortLE(data, off, val); else GridUnsafe.putShort(data, off, val); shift(2); } /** {@inheritDoc} */ @Override public void unsafeWriteShort(int pos, short val) { long off = GridUnsafe.BYTE_ARR_OFF + pos; if (BIG_ENDIAN) GridUnsafe.putShortLE(data, off, val); else GridUnsafe.putShort(data, off, val); } /** {@inheritDoc} */ @Override public void unsafeWriteChar(char val) { long off = GridUnsafe.BYTE_ARR_OFF + pos; if (BIG_ENDIAN) GridUnsafe.putCharLE(data, off, val); else GridUnsafe.putChar(data, off, val); shift(2); } /** {@inheritDoc} */ @Override public void unsafeWriteInt(int val) { long off = GridUnsafe.BYTE_ARR_OFF + pos; if (BIG_ENDIAN) GridUnsafe.putIntLE(data, off, val); else GridUnsafe.putInt(data, off, val); shift(4); } /** {@inheritDoc} */ @Override public void unsafeWriteInt(int pos, int val) { long off = GridUnsafe.BYTE_ARR_OFF + pos; if (BIG_ENDIAN) GridUnsafe.putIntLE(data, off, val); else GridUnsafe.putInt(data, off, val); } /** {@inheritDoc} */ @Override public void unsafeWriteLong(long val) { long off = GridUnsafe.BYTE_ARR_OFF + pos; if (BIG_ENDIAN) GridUnsafe.putLongLE(data, off, val); else GridUnsafe.putLong(data, off, val); shift(8); } /** {@inheritDoc} */ @Override public int capacity() { return data.length; } }
// overflow-conscious code if (cnt - data.length > 0) { int newCap = capacity(data.length, cnt); data = chunk.reallocate(data, newCap); }
1,685
58
1,743
<methods>public non-sealed void <init>() ,public long offheapPointer() ,public void position(int) ,public long rawOffheapPointer() ,public void unsafeEnsure(int) ,public void unsafePosition(int) ,public void unsafeWriteBoolean(boolean) ,public void unsafeWriteDouble(double) ,public void unsafeWriteFloat(float) ,public void write(byte[], int, int) ,public void write(long, int) ,public void writeBoolean(boolean) ,public void writeBooleanArray(boolean[]) ,public void writeByte(byte) ,public void writeByteArray(byte[]) ,public void writeChar(char) ,public void writeCharArray(char[]) ,public void writeDouble(double) ,public void writeDoubleArray(double[]) ,public void writeFloat(float) ,public void writeFloatArray(float[]) ,public void writeInt(int) ,public void writeInt(int, int) ,public void writeIntArray(int[]) ,public void writeLong(long) ,public void writeLongArray(long[]) ,public void writeShort(short) ,public void writeShort(int, short) ,public void writeShortArray(short[]) <variables>protected static final int MAX_ARRAY_SIZE,private static final int MIN_CAP
apache_ignite
ignite/modules/core/src/main/java/org/apache/ignite/internal/binary/streams/BinaryOffheapOutputStream.java
BinaryOffheapOutputStream
writeIntFast
class BinaryOffheapOutputStream extends BinaryAbstractOutputStream { /** Pointer. */ private long ptr; /** Length of bytes that cen be used before resize is necessary. */ private int cap; /** * Constructor. * * @param cap Capacity. */ public BinaryOffheapOutputStream(int cap) { this(0, cap); } /** * Constructor. * * @param ptr Pointer to existing address. * @param cap Capacity. */ public BinaryOffheapOutputStream(long ptr, int cap) { this.ptr = ptr == 0 ? allocate(cap) : ptr; this.cap = cap; } /** {@inheritDoc} */ @Override public void close() { release(ptr); } /** {@inheritDoc} */ @Override public void ensureCapacity(int cnt) { // overflow-conscious code if (cnt - cap > 0) { int newCap = capacity(cap, cnt); ptr = reallocate(ptr, newCap); cap = newCap; } } /** {@inheritDoc} */ @Override public byte[] array() { return arrayCopy(); } /** {@inheritDoc} */ @Override public byte[] arrayCopy() { byte[] res = new byte[pos]; GridUnsafe.copyOffheapHeap(ptr, res, GridUnsafe.BYTE_ARR_OFF, pos); return res; } /** * @return Pointer. */ public long pointer() { return ptr; } /** {@inheritDoc} */ @Override public int capacity() { return cap; } /** {@inheritDoc} */ @Override protected void writeByteAndShift(byte val) { GridUnsafe.putByte(ptr + pos++, val); } /** {@inheritDoc} */ @Override protected void copyAndShift(Object src, long offset, int len) { GridUnsafe.copyHeapOffheap(src, offset, ptr + pos, len); shift(len); } /** {@inheritDoc} */ @Override protected void writeShortFast(short val) { long addr = ptr + pos; if (BIG_ENDIAN) GridUnsafe.putShortLE(addr, val); else GridUnsafe.putShort(addr, val); } /** {@inheritDoc} */ @Override protected void writeCharFast(char val) { long addr = ptr + pos; if (BIG_ENDIAN) GridUnsafe.putCharLE(addr, val); else GridUnsafe.putChar(addr, val); } /** {@inheritDoc} */ @Override protected void writeIntFast(int val) {<FILL_FUNCTION_BODY>} /** {@inheritDoc} */ @Override protected void writeLongFast(long val) { long addr = ptr + pos; if (BIG_ENDIAN) GridUnsafe.putLongLE(addr, val); else GridUnsafe.putLong(addr, val); } /** {@inheritDoc} */ @Override public boolean hasArray() { return false; } /** {@inheritDoc} */ @Override public void unsafeWriteByte(byte val) { GridUnsafe.putByte(ptr + pos++, val); } /** {@inheritDoc} */ @Override public void unsafeWriteShort(short val) { long addr = ptr + pos; if (BIG_ENDIAN) GridUnsafe.putShortLE(addr, val); else GridUnsafe.putShort(addr, val); shift(2); } /** {@inheritDoc} */ @Override public void unsafeWriteShort(int pos, short val) { long addr = ptr + pos; if (BIG_ENDIAN) GridUnsafe.putShortLE(addr, val); else GridUnsafe.putShort(addr, val); } /** {@inheritDoc} */ @Override public void unsafeWriteChar(char val) { long addr = ptr + pos; if (BIG_ENDIAN) GridUnsafe.putCharLE(addr, val); else GridUnsafe.putChar(addr, val); shift(2); } /** {@inheritDoc} */ @Override public void unsafeWriteInt(int val) { long addr = ptr + pos; if (BIG_ENDIAN) GridUnsafe.putIntLE(addr, val); else GridUnsafe.putInt(addr, val); shift(4); } /** {@inheritDoc} */ @Override public void unsafeWriteInt(int pos, int val) { long addr = ptr + pos; if (BIG_ENDIAN) GridUnsafe.putIntLE(addr, val); else GridUnsafe.putInt(addr, val); } /** {@inheritDoc} */ @Override public void unsafeWriteLong(long val) { long addr = ptr + pos; if (BIG_ENDIAN) GridUnsafe.putLongLE(addr, val); else GridUnsafe.putLong(addr, val); shift(8); } /** * Allocate memory. * * @param cap Capacity. * @return Pointer. */ protected long allocate(int cap) { return GridUnsafe.allocateMemory(cap); } /** * Reallocate memory. * * @param ptr Old pointer. * @param cap Capacity. * @return New pointer. */ protected long reallocate(long ptr, int cap) { return GridUnsafe.reallocateMemory(ptr, cap); } /** * Release memory. * * @param ptr Pointer. */ protected void release(long ptr) { GridUnsafe.freeMemory(ptr); } }
long addr = ptr + pos; if (BIG_ENDIAN) GridUnsafe.putIntLE(addr, val); else GridUnsafe.putInt(addr, val);
1,598
54
1,652
<methods>public non-sealed void <init>() ,public long offheapPointer() ,public void position(int) ,public long rawOffheapPointer() ,public void unsafeEnsure(int) ,public void unsafePosition(int) ,public void unsafeWriteBoolean(boolean) ,public void unsafeWriteDouble(double) ,public void unsafeWriteFloat(float) ,public void write(byte[], int, int) ,public void write(long, int) ,public void writeBoolean(boolean) ,public void writeBooleanArray(boolean[]) ,public void writeByte(byte) ,public void writeByteArray(byte[]) ,public void writeChar(char) ,public void writeCharArray(char[]) ,public void writeDouble(double) ,public void writeDoubleArray(double[]) ,public void writeFloat(float) ,public void writeFloatArray(float[]) ,public void writeInt(int) ,public void writeInt(int, int) ,public void writeIntArray(int[]) ,public void writeLong(long) ,public void writeLongArray(long[]) ,public void writeShort(short) ,public void writeShort(int, short) ,public void writeShortArray(short[]) <variables>protected static final int MAX_ARRAY_SIZE,private static final int MIN_CAP
apache_ignite
ignite/modules/core/src/main/java/org/apache/ignite/internal/cache/query/RangeIndexQueryCriterion.java
RangeIndexQueryCriterion
toString
class RangeIndexQueryCriterion implements IndexQueryCriterion { /** */ private static final long serialVersionUID = 0L; /** Index field name. */ private final String field; /** Lower bound. */ private final Object lower; /** Upper bound. */ private final Object upper; /** Should include lower value. */ private boolean lowerIncl; /** Should include upper value. */ private boolean upperIncl; /** Whether lower bound is explicitly set to {@code null}. */ private boolean lowerNull; /** Whether upper bound is explicitly set to {@code null}. */ private boolean upperNull; /** */ public RangeIndexQueryCriterion(String field, Object lower, Object upper) { this.field = field; this.lower = lower; this.upper = upper; } /** Swap boundaries. */ public RangeIndexQueryCriterion swap() { RangeIndexQueryCriterion c = new RangeIndexQueryCriterion(field, upper, lower); c.lowerIncl(upperIncl); c.upperIncl(lowerIncl); c.lowerNull(upperNull); c.upperNull(lowerNull); return c; } /** */ public Object lower() { return lower; } /** */ public Object upper() { return upper; } /** */ public void lowerIncl(boolean lowerIncl) { this.lowerIncl = lowerIncl; } /** */ public boolean lowerIncl() { return lowerIncl; } /** */ public void upperIncl(boolean upperIncl) { this.upperIncl = upperIncl; } /** */ public boolean upperIncl() { return upperIncl; } /** */ public void lowerNull(boolean lowerNull) { this.lowerNull = lowerNull; } /** */ public boolean lowerNull() { return lowerNull; } /** */ public void upperNull(boolean upperNull) { this.upperNull = upperNull; } /** */ public boolean upperNull() { return upperNull; } /** {@inheritDoc} */ @Override public String field() { return field; } /** {@inheritDoc} */ @Override public String toString() {<FILL_FUNCTION_BODY>} }
return field + (lowerIncl ? "[" : "(") + lower + "; " + upper + (upperIncl ? "]" : ")");
630
37
667
<no_super_class>
apache_ignite
ignite/modules/core/src/main/java/org/apache/ignite/internal/cache/query/index/IndexName.java
IndexName
fullName
class IndexName { /** Schema name of {@code null} if index is not related to SQL schema. */ private final @Nullable String schemaName; /** Schema name of {@code null} if index is not related to SQL table. */ private final @Nullable String tableName; /** Cache name. */ private final String cacheName; /** Index name. */ private final String idxName; /** */ public IndexName(String cacheName, @Nullable String schemaName, @Nullable String tableName, String idxName) { this.cacheName = cacheName; this.schemaName = schemaName; this.tableName = tableName; this.idxName = idxName; } /** * @return Full index name. */ public String fullName() {<FILL_FUNCTION_BODY>} /** * @return Index name. */ public String idxName() { return idxName; } /** * @return Table name. */ public String tableName() { return tableName; } /** * @return Schema name. */ public String schemaName() { return schemaName; } /** * @return Cache name. */ public String cacheName() { return cacheName; } }
StringBuilder bld = new StringBuilder(); if (schemaName != null) bld.append(schemaName).append("."); if (tableName != null) bld.append(tableName).append("."); return bld.append(idxName).toString();
342
76
418
<no_super_class>
apache_ignite
ignite/modules/core/src/main/java/org/apache/ignite/internal/cache/query/index/sorted/IndexKeyDefinition.java
IndexKeyDefinition
writeExternal
class IndexKeyDefinition implements Externalizable { /** */ private static final long serialVersionUID = 0L; /** Index key type. {@link IndexKeyType}. */ private IndexKeyType idxType; /** Order. */ private Order order; /** Precision for variable length key types. */ private int precision; /** */ public IndexKeyDefinition() { // No-op. } /** */ public IndexKeyDefinition(int idxTypeCode, Order order, long precision) { idxType = IndexKeyType.forCode(idxTypeCode); this.order = order; // Workaround due to wrong type conversion (int -> long). if (precision >= Integer.MAX_VALUE) this.precision = -1; else this.precision = (int)precision; } /** */ public Order order() { return order; } /** */ public IndexKeyType idxType() { return idxType; } /** */ public int precision() { return precision; } /** {@inheritDoc} */ @Override public void writeExternal(ObjectOutput out) throws IOException {<FILL_FUNCTION_BODY>} /** {@inheritDoc} */ @Override public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException { idxType = IndexKeyType.forCode(in.readInt()); order = new Order(U.readEnum(in, SortOrder.class), null); } }
// Send only required info for using in MergeSort algorithm. out.writeInt(idxType.code()); U.writeEnum(out, order.sortOrder());
386
44
430
<no_super_class>
apache_ignite
ignite/modules/core/src/main/java/org/apache/ignite/internal/cache/query/index/sorted/IndexPlainRowImpl.java
IndexPlainRowImpl
cacheDataRow
class IndexPlainRowImpl implements IndexRow { /** */ private final IndexKey[] keys; /** */ private final InlineIndexRowHandler rowHnd; /** Constructor. */ public IndexPlainRowImpl(IndexKey[] idxKeys, InlineIndexRowHandler rowHnd) { keys = idxKeys; this.rowHnd = rowHnd; } /** {@inheritDoc} */ @Override public IndexKey key(int idx) { return keys[idx]; } /** {@inheritDoc} */ @Override public int keysCount() { return keys.length; } /** {@inheritDoc} */ @Override public String toString() { return S.toString(IndexPlainRowImpl.class, this); } /** {@inheritDoc} */ @Override public long link() { assert false : "Should not get link by IndexPlainRowImpl"; return 0; } /** {@inheritDoc} */ @Override public InlineIndexRowHandler rowHandler() { return rowHnd; } /** {@inheritDoc} */ @Override public CacheDataRow cacheDataRow() {<FILL_FUNCTION_BODY>} /** {@inheritDoc} */ @Override public boolean indexPlainRow() { return true; } }
assert false : "Should not cache data row by IndexPlainRowImpl"; return null;
340
27
367
<no_super_class>
apache_ignite
ignite/modules/core/src/main/java/org/apache/ignite/internal/cache/query/index/sorted/IndexRowImpl.java
IndexRowImpl
key
class IndexRowImpl implements IndexRow { /** Object that contains info about original IgniteCache row. */ private final CacheDataRow cacheRow; /** Cache for index row keys. To avoid hit underlying cache for every comparation. */ private IndexKey[] keyCache; /** Schema of an index. */ private final InlineIndexRowHandler rowHnd; /** Constructor. */ public IndexRowImpl(InlineIndexRowHandler rowHnd, CacheDataRow row) { this(rowHnd, row, null); } /** * Constructor with prefilling of keys cache. */ public IndexRowImpl(InlineIndexRowHandler rowHnd, CacheDataRow row, IndexKey[] keys) { this.rowHnd = rowHnd; cacheRow = row; keyCache = keys; } /** * @return Indexed value. */ public CacheObject value() { return cacheRow.value(); } /** {@inheritDoc} */ @Override public IndexKey key(int idx) {<FILL_FUNCTION_BODY>} /** {@inheritDoc} */ @Override public int keysCount() { return rowHnd.indexKeyDefinitions().size(); } /** {@inheritDoc} */ @Override public long link() { return cacheRow.link(); } /** {@inheritDoc} */ @Override public InlineIndexRowHandler rowHandler() { return rowHnd; } /** {@inheritDoc} */ @Override public CacheDataRow cacheDataRow() { return cacheRow; } /** * @return Cache ID or {@code 0} if cache ID is not defined. */ public int cacheId() { return cacheDataRow().cacheId(); } /** Initialize a cache for index keys. Useful for inserting rows as there are a lot of comparisons. */ public void prepareCache() { keyCache = new IndexKey[rowHnd.indexKeyDefinitions().size()]; } /** {@inheritDoc} */ @Override public String toString() { SB sb = new SB("Row@"); sb.a(Integer.toHexString(System.identityHashCode(this))); Object v = rowHnd.cacheKey(cacheRow); sb.a("[ key: ").a(v == null ? "nil" : v.toString()); v = rowHnd.cacheValue(cacheRow); sb.a(", val: ").a(v == null ? "nil" : (S.includeSensitive() ? v.toString() : "Data hidden due to " + IGNITE_TO_STRING_INCLUDE_SENSITIVE + " flag.")); sb.a(" ][ "); if (v != null) { for (int i = 0, cnt = rowHnd.indexKeyDefinitions().size(); i < cnt; i++) { if (i != 0) sb.a(", "); try { v = key(i); sb.a(v == null ? "nil" : (S.includeSensitive() ? v.toString() : "data hidden")); } catch (Exception e) { sb.a("<value skipped on error: " + e.getMessage() + '>'); } } } sb.a(" ]"); return sb.toString(); } /** {@inheritDoc} */ @Override public boolean indexPlainRow() { return false; } }
if (keyCache != null && keyCache[idx] != null) return keyCache[idx]; IndexKey key = rowHnd.indexKey(idx, cacheRow); if (keyCache != null) keyCache[idx] = key; return key;
902
76
978
<no_super_class>
apache_ignite
ignite/modules/core/src/main/java/org/apache/ignite/internal/cache/query/index/sorted/QueryIndexDefinition.java
QueryIndexDefinition
toString
class QueryIndexDefinition implements SortedIndexDefinition { /** Wrapped key definitions. */ private final LinkedHashMap<String, IndexKeyDefinition> keyDefs; /** Type descriptor. */ private final GridQueryTypeDescriptor typeDesc; /** Cache info. */ private final GridCacheContextInfo<?, ?> cacheInfo; /** Index name. */ private final IndexName idxName; /** Index tree name. */ private final String treeName; /** Configured inline size. */ private final int inlineSize; /** Segments. */ private final int segments; /** Whether this index is primary key (unique) or not. */ private final boolean isPrimary; /** Whether this index is affinity key index or not. */ private final boolean isAffinity; /** Index row comparator. */ private final IndexRowComparator rowComparator; /** Index key type settings. */ private final IndexKeyTypeSettings keyTypeSettings; /** Index rows cache. */ private final IndexRowCache idxRowCache; /** Row handler factory. */ private final QueryIndexRowHandlerFactory rowHndFactory = new QueryIndexRowHandlerFactory(); /** */ public QueryIndexDefinition( GridQueryTypeDescriptor typeDesc, GridCacheContextInfo<?, ?> cacheInfo, IndexName idxName, String treeName, IndexRowCache idxRowCache, boolean isPrimary, boolean isAffinity, LinkedHashMap<String, IndexKeyDefinition> keyDefs, int cfgInlineSize, IndexKeyTypeSettings keyTypeSettings ) { this.typeDesc = typeDesc; this.cacheInfo = cacheInfo; this.idxName = idxName; this.treeName = treeName; this.idxRowCache = idxRowCache; this.segments = cacheInfo.cacheContext().config().getQueryParallelism(); this.inlineSize = cfgInlineSize; this.isPrimary = isPrimary; this.isAffinity = isAffinity; this.keyDefs = keyDefs; this.keyTypeSettings = keyTypeSettings; this.rowComparator = new IndexRowComparatorImpl(keyTypeSettings); } /** {@inheritDoc} */ @Override public String treeName() { return treeName; } /** {@inheritDoc} */ @Override public LinkedHashMap<String, IndexKeyDefinition> indexKeyDefinitions() { return keyDefs; } /** {@inheritDoc} */ @Override public IndexRowComparator rowComparator() { return rowComparator; } /** {@inheritDoc} */ @Override public int segments() { return segments; } /** {@inheritDoc} */ @Override public int inlineSize() { return inlineSize; } /** {@inheritDoc} */ @Override public boolean primary() { return isPrimary; } /** {@inheritDoc} */ @Override public boolean affinity() { return isAffinity; } /** {@inheritDoc} */ @Override public InlineIndexRowHandlerFactory rowHandlerFactory() { return rowHndFactory; } /** {@inheritDoc} */ @Override public IndexKeyTypeSettings keyTypeSettings() { return keyTypeSettings; } /** {@inheritDoc} */ @Override public IndexRowCache idxRowCache() { return idxRowCache; } /** {@inheritDoc} */ @Override public IndexName idxName() { return idxName; } /** {@inheritDoc} */ @Override public GridQueryTypeDescriptor typeDescriptor() { return typeDesc; } /** {@inheritDoc} */ @Override public GridCacheContextInfo<?, ?> cacheInfo() { return cacheInfo; } /** {@inheritDoc} */ @Override public String toString() {<FILL_FUNCTION_BODY>} }
String flds = String.join(", ", indexKeyDefinitions().keySet()); return "QueryIndex[name=" + idxName.idxName() + ", fields=" + flds + "]";
1,006
56
1,062
<no_super_class>
apache_ignite
ignite/modules/core/src/main/java/org/apache/ignite/internal/cache/query/index/sorted/QueryIndexRowHandler.java
QueryIndexRowHandler
indexKey
class QueryIndexRowHandler implements InlineIndexRowHandler { /** Cache info. */ private final GridCacheContextInfo<?, ?> cacheInfo; /** List of key types for inlined index keys. */ private final List<InlineIndexKeyType> keyTypes; /** List of index key definitions. */ private final List<IndexKeyDefinition> keyDefs; /** Index key type settings. */ private final IndexKeyTypeSettings keyTypeSettings; /** Query properties for each index key. */ private final GridQueryProperty[] props; /** */ public QueryIndexRowHandler( GridQueryTypeDescriptor type, GridCacheContextInfo<?, ?> cacheInfo, LinkedHashMap<String, IndexKeyDefinition> keyDefs, List<InlineIndexKeyType> keyTypes, IndexKeyTypeSettings keyTypeSettings ) { this.keyTypes = new ArrayList<>(keyTypes); this.keyDefs = new ArrayList<>(keyDefs.values()); props = new GridQueryProperty[keyDefs.size()]; int propIdx = 0; for (String propName : keyDefs.keySet()) { GridQueryProperty prop; if (propName.equals(QueryUtils.KEY_FIELD_NAME) || propName.equals(type.keyFieldName()) || propName.equals(type.keyFieldAlias())) prop = new KeyOrValPropertyWrapper(true, propName, type.keyClass()); else if (propName.equals(QueryUtils.VAL_FIELD_NAME) || propName.equals(type.valueFieldName()) || propName.equals(type.valueFieldAlias())) prop = new KeyOrValPropertyWrapper(false, propName, type.valueClass()); else prop = type.property(propName); assert prop != null : propName; props[propIdx++] = prop; } this.cacheInfo = cacheInfo; this.keyTypeSettings = keyTypeSettings; } /** {@inheritDoc} */ @Override public IndexKey indexKey(int idx, CacheDataRow row) {<FILL_FUNCTION_BODY>} /** {@inheritDoc} */ @Override public List<InlineIndexKeyType> inlineIndexKeyTypes() { return keyTypes; } /** {@inheritDoc} */ @Override public List<IndexKeyDefinition> indexKeyDefinitions() { return keyDefs; } /** {@inheritDoc} */ @Override public IndexKeyTypeSettings indexKeyTypeSettings() { return keyTypeSettings; } /** {@inheritDoc} */ @Override public int partition(CacheDataRow row) { Object key = unwrap(row.key()); return cacheInfo.cacheContext().affinity().partition(key); } /** {@inheritDoc} */ @Override public Object cacheKey(CacheDataRow row) { return unwrap(row.key()); } /** {@inheritDoc} */ @Override public Object cacheValue(CacheDataRow row) { return unwrap(row.value()); } /** */ private Object unwrap(CacheObject val) { Object o = getBinaryObject(val); if (o != null) return o; CacheObjectContext coctx = cacheInfo.cacheContext().cacheObjectContext(); return val.value(coctx, false); } /** */ private Object getBinaryObject(CacheObject o) { if (o instanceof BinaryObjectImpl) { ((BinaryObjectImpl)o).detachAllowed(true); o = ((BinaryObjectImpl)o).detach(); return o; } return null; } /** */ private class KeyOrValPropertyWrapper extends QueryUtils.KeyOrValProperty { /** */ public KeyOrValPropertyWrapper(boolean key, String name, Class<?> cls) { super(key, name, cls); } /** {@inheritDoc} */ @Override public Object value(Object key, Object val) { return key() ? unwrap((CacheObject)key) : unwrap((CacheObject)val); } } }
try { return IndexKeyFactory.wrap( props[idx].value(row.key(), row.value()), keyDefs.get(idx).idxType(), cacheInfo.cacheContext().cacheObjectContext(), keyTypeSettings ); } catch (IgniteCheckedException e) { throw new IgniteException(e); }
1,045
93
1,138
<no_super_class>
apache_ignite
ignite/modules/core/src/main/java/org/apache/ignite/internal/cache/query/index/sorted/inline/io/AbstractInnerIO.java
AbstractInnerIO
getLookupRow
class AbstractInnerIO extends BPlusInnerIO<IndexRow> implements InlineIO { /** * @param type Page type. * @param ver Page format version. * @param itemSize Single item size on page. */ AbstractInnerIO(int type, int ver, int itemSize) { super(type, ver, true, itemSize); } /** {@inheritDoc} */ @Override public void storeByOffset(long pageAddr, int off, IndexRow row) { assert row.link() != 0; assertPageType(pageAddr); IORowHandler.store(pageAddr, off, row); } /** {@inheritDoc} */ @Override public IndexRow getLookupRow(BPlusTree<IndexRow, ?> tree, long pageAddr, int idx) throws IgniteCheckedException {<FILL_FUNCTION_BODY>} /** {@inheritDoc} */ @Override public void store(long dstPageAddr, int dstIdx, BPlusIO<IndexRow> srcIo, long srcPageAddr, int srcIdx) { assertPageType(dstPageAddr); IORowHandler.store(dstPageAddr, offset(dstIdx), (InlineIO)srcIo, srcPageAddr, srcIdx); } /** {@inheritDoc} */ @Override public long link(long pageAddr, int idx) { return PageUtils.getLong(pageAddr, offset(idx)); } /** {@inheritDoc} */ @Override public int inlineSize() { return 0; } }
long link = PageUtils.getLong(pageAddr, offset(idx)); assert link != 0; return ((InlineIndexTree)tree).createIndexRow(link);
399
49
448
<methods>public final void copyItems(long, long, int, int, int, boolean) throws org.apache.ignite.IgniteCheckedException,public final long getLeft(long, int) ,public int getMaxCount(long, int) ,public final long getRight(long, int) ,public byte[] initNewRoot(long, long, long, org.apache.ignite.internal.cache.query.index.sorted.IndexRow, byte[], long, int, boolean, org.apache.ignite.internal.processors.cache.persistence.pagemem.PageMetrics) throws org.apache.ignite.IgniteCheckedException,public byte[] insert(long, int, org.apache.ignite.internal.cache.query.index.sorted.IndexRow, byte[], long, boolean) throws org.apache.ignite.IgniteCheckedException,public final int offset(int) ,public final void setLeft(long, int, long) <variables>private static final int SHIFT_LEFT,private static final int SHIFT_LINK,private final int SHIFT_RIGHT
apache_ignite
ignite/modules/core/src/main/java/org/apache/ignite/internal/cache/query/index/sorted/inline/io/AbstractLeafIO.java
AbstractLeafIO
getLookupRow
class AbstractLeafIO extends BPlusLeafIO<IndexRow> implements InlineIO { /** * @param type Page type. * @param ver Page format version. * @param itemSize Single item size on page. */ AbstractLeafIO(int type, int ver, int itemSize) { super(type, ver, itemSize); } /** {@inheritDoc} */ @Override public void storeByOffset(long pageAddr, int off, IndexRow row) { assert row.link() != 0; assertPageType(pageAddr); IORowHandler.store(pageAddr, off, row); } /** {@inheritDoc} */ @Override public IndexRow getLookupRow(BPlusTree<IndexRow, ?> tree, long pageAddr, int idx) throws IgniteCheckedException {<FILL_FUNCTION_BODY>} /** {@inheritDoc} */ @Override public void store(long dstPageAddr, int dstIdx, BPlusIO<IndexRow> srcIo, long srcPageAddr, int srcIdx) { assertPageType(dstPageAddr); IORowHandler.store(dstPageAddr, offset(dstIdx), (InlineIO)srcIo, srcPageAddr, srcIdx); } /** {@inheritDoc} */ @Override public long link(long pageAddr, int idx) { return PageUtils.getLong(pageAddr, offset(idx)); } /** {@inheritDoc} */ @Override public int inlineSize() { return 0; } }
long link = PageUtils.getLong(pageAddr, offset(idx)); assert link != 0; return ((InlineIndexTree)tree).createIndexRow(link);
400
49
449
<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/cache/query/index/sorted/inline/io/IORowHandler.java
IORowHandler
store
class IORowHandler { /** */ public static void store(long pageAddr, int off, IndexRow row) {<FILL_FUNCTION_BODY>} /** * @param dstPageAddr Destination page address. * @param dstOff Destination page offset. * @param srcIo Source IO. * @param srcPageAddr Source page address. * @param srcIdx Source index. */ static void store(long dstPageAddr, int dstOff, InlineIO srcIo, long srcPageAddr, int srcIdx) { long link = srcIo.link(srcPageAddr, srcIdx); PageUtils.putLong(dstPageAddr, dstOff, link); } }
// Write link after all inlined idx keys. PageUtils.putLong(pageAddr, off, row.link());
189
32
221
<no_super_class>
apache_ignite
ignite/modules/core/src/main/java/org/apache/ignite/internal/cache/query/index/sorted/inline/types/BytesInlineIndexKeyType.java
BytesInlineIndexKeyType
compare0
class BytesInlineIndexKeyType extends NullableInlineIndexKeyType<BytesIndexKey> { /** Compare binary unsigned. */ private final boolean compareBinaryUnsigned; /** */ public BytesInlineIndexKeyType() { this(IndexKeyType.BYTES); } /** */ public BytesInlineIndexKeyType(IndexKeyType type) { this(type, true); } /** */ public BytesInlineIndexKeyType(boolean compareBinaryUnsigned) { this(IndexKeyType.BYTES, compareBinaryUnsigned); } /** */ public BytesInlineIndexKeyType(IndexKeyType type, boolean compareBinaryUnsigned) { super(type, (short)-1); this.compareBinaryUnsigned = compareBinaryUnsigned; } /** {@inheritDoc} */ @Override public int compare0(long pageAddr, int off, IndexKey bytes) {<FILL_FUNCTION_BODY>} /** {@inheritDoc} */ @Override protected int put0(long pageAddr, int off, BytesIndexKey key, int maxSize) { short size; PageUtils.putByte(pageAddr, off, (byte)type().code()); byte[] val = (byte[])key.key(); if (val.length + 3 <= maxSize) { size = (short)val.length; PageUtils.putShort(pageAddr, off + 1, size); PageUtils.putBytes(pageAddr, off + 3, val); return size + 3; } else { size = (short)((maxSize - 3) | 0x8000); PageUtils.putShort(pageAddr, off + 1, size); PageUtils.putBytes(pageAddr, off + 3, Arrays.copyOfRange(val, 0, maxSize - 3)); return maxSize; } } /** {@inheritDoc} */ @Override protected BytesIndexKey get0(long pageAddr, int off) { byte[] arr = readBytes(pageAddr, off); return compareBinaryUnsigned ? new BytesIndexKey(arr) : new SignedBytesIndexKey(arr); } /** {@inheritDoc} */ @Override protected int inlineSize0(BytesIndexKey val) { byte[] arr = (byte[])val.key(); return arr.length + 3; } /** */ public boolean compareBinaryUnsigned() { return compareBinaryUnsigned; } }
long addr = pageAddr + off + 1; // Skip type. int len1 = PageUtils.getShort(pageAddr, off + 1) & 0x7FFF; addr += 2; // Skip size. byte[] arr = (byte[])bytes.key(); int len2 = arr.length; int len = Math.min(len1, len2); if (compareBinaryUnsigned) { for (int i = 0; i < len; i++) { int b1 = GridUnsafe.getByte(addr + i) & 0xff; int b2 = arr[i] & 0xff; if (b1 != b2) return Integer.signum(b1 - b2); } } else { for (int i = 0; i < len; i++) { byte b1 = GridUnsafe.getByte(addr + i); byte b2 = arr[i]; if (b1 != b2) return Integer.signum(b1 - b2); } } int res = Integer.signum(len1 - len2); if (inlinedFullValue(pageAddr, off, VARTYPE_HEADER_SIZE + 1)) return res; if (res >= 0) // There are two cases: // a) The values are equal but the stored value is truncated, so that it's bigger. // b) Even truncated current value is longer, so that it's bigger. return 1; return CANT_BE_COMPARE;
647
409
1,056
<methods>public int compare(long, int, int, org.apache.ignite.internal.cache.query.index.sorted.keys.IndexKey) ,public abstract int compare0(long, int, org.apache.ignite.internal.cache.query.index.sorted.keys.IndexKey) ,public org.apache.ignite.internal.cache.query.index.sorted.keys.IndexKey get(long, int, int) ,public int inlineSize(long, int) ,public int inlineSize() ,public int inlineSize(org.apache.ignite.internal.cache.query.index.sorted.keys.IndexKey) ,public boolean inlinedFullValue(long, int, int) ,public java.lang.Boolean isNull(long, int, int) ,public short keySize() ,public int put(long, int, org.apache.ignite.internal.cache.query.index.sorted.keys.IndexKey, int) ,public static byte[] readBytes(long, int) ,public org.apache.ignite.internal.cache.query.index.sorted.IndexKeyType type() <variables>public static final int CANT_BE_COMPARE,public static final int COMPARE_UNSUPPORTED,public static final int VARTYPE_HEADER_SIZE,protected final non-sealed short keySize,private final non-sealed org.apache.ignite.internal.cache.query.index.sorted.IndexKeyType type
apache_ignite
ignite/modules/core/src/main/java/org/apache/ignite/internal/cache/query/index/sorted/inline/types/DateInlineIndexKeyType.java
DateInlineIndexKeyType
put0
class DateInlineIndexKeyType extends NullableInlineIndexKeyType<DateIndexKey> { /** */ public DateInlineIndexKeyType() { super(IndexKeyType.DATE, (short)8); } /** {@inheritDoc} */ @Override public boolean isComparableTo(IndexKey key) { return key instanceof DateTimeIndexKey; } /** {@inheritDoc} */ @Override public int compare0(long pageAddr, int off, IndexKey key) { return -Integer.signum(((DateTimeIndexKey)key).compareTo(PageUtils.getLong(pageAddr, off + 1), 0)); } /** {@inheritDoc} */ @Override protected int put0(long pageAddr, int off, DateIndexKey key, int maxSize) {<FILL_FUNCTION_BODY>} /** {@inheritDoc} */ @Override protected DateIndexKey get0(long pageAddr, int off) { long dateVal = PageUtils.getLong(pageAddr, off + 1); if (dateVal > MAX_DATE_VALUE) dateVal = MAX_DATE_VALUE; else if (dateVal < MIN_DATE_VALUE) dateVal = MIN_DATE_VALUE; return new DateIndexKey(dateVal); } /** {@inheritDoc} */ @Override protected int inlineSize0(DateIndexKey key) { return keySize + 1; } }
PageUtils.putByte(pageAddr, off, (byte)type().code()); PageUtils.putLong(pageAddr, off + 1, key.dateValue()); return keySize + 1;
358
52
410
<methods>public int compare(long, int, int, org.apache.ignite.internal.cache.query.index.sorted.keys.IndexKey) ,public abstract int compare0(long, int, org.apache.ignite.internal.cache.query.index.sorted.keys.IndexKey) ,public org.apache.ignite.internal.cache.query.index.sorted.keys.IndexKey get(long, int, int) ,public int inlineSize(long, int) ,public int inlineSize() ,public int inlineSize(org.apache.ignite.internal.cache.query.index.sorted.keys.IndexKey) ,public boolean inlinedFullValue(long, int, int) ,public java.lang.Boolean isNull(long, int, int) ,public short keySize() ,public int put(long, int, org.apache.ignite.internal.cache.query.index.sorted.keys.IndexKey, int) ,public static byte[] readBytes(long, int) ,public org.apache.ignite.internal.cache.query.index.sorted.IndexKeyType type() <variables>public static final int CANT_BE_COMPARE,public static final int COMPARE_UNSUPPORTED,public static final int VARTYPE_HEADER_SIZE,protected final non-sealed short keySize,private final non-sealed org.apache.ignite.internal.cache.query.index.sorted.IndexKeyType type
apache_ignite
ignite/modules/core/src/main/java/org/apache/ignite/internal/cache/query/index/sorted/inline/types/DateValueUtils.java
DateValueUtils
defaultTzMillisFromUtc
class DateValueUtils { /** Calendar with UTC time zone instance. */ private static final ThreadLocal<Calendar> UTC_CALENDAR = ThreadLocal.withInitial( () -> Calendar.getInstance(TimeZone.getTimeZone("UTC"))); /** Cached default time zone. */ private static final TimeZone DEFAULT_TZ = TimeZone.getDefault(); /** Forbid instantiation of this class. Just hold constants there. */ private DateValueUtils() {} /** */ private static final int SHIFT_YEAR = 9; /** */ private static final int SHIFT_MONTH = 5; /** */ private static final long MONTH_MASK = ~(-1L << (SHIFT_YEAR - SHIFT_MONTH)); /** */ private static final long DAY_MASK = ~(-1L << SHIFT_MONTH); /** Min date value. */ public static final long MIN_DATE_VALUE = (-999_999_999L << SHIFT_YEAR) + (1 << SHIFT_MONTH) + 1; /** Max date value. */ public static final long MAX_DATE_VALUE = (999_999_999L << SHIFT_YEAR) + (12 << SHIFT_MONTH) + 31; /** The number of milliseconds per day. */ public static final long MILLIS_PER_DAY = 24 * 60 * 60 * 1000L; /** The number of nanoseconds per day. */ public static final long NANOS_PER_DAY = MILLIS_PER_DAY * 1_000_000; /** * Extract the year from a date value. */ private static int yearFromDateValue(long dateVal) { return (int)(dateVal >>> SHIFT_YEAR); } /** * Extract the month from a date value. */ private static int monthFromDateValue(long dateVal) { return (int)((dateVal >>> SHIFT_MONTH) & MONTH_MASK); } /** * Extract the day of month from a date value. */ private static int dayFromDateValue(long dateVal) { return (int)(dateVal & DAY_MASK); } /** * Construct date value from components. */ public static long dateValue(int year, int month, int day) { return ((long)year << SHIFT_YEAR) | month << SHIFT_MONTH | day; } /** * Convert date value to epoch milliseconds. */ public static long millisFromDateValue(long dateVal) { Calendar cal = UTC_CALENDAR.get(); cal.clear(); cal.set(yearFromDateValue(dateVal), monthFromDateValue(dateVal) - 1, dayFromDateValue(dateVal)); return cal.getTimeInMillis(); } /** * Convert epoch milliseconds to date value. */ public static long dateValueFromMillis(long millis) { Calendar cal = UTC_CALENDAR.get(); cal.setTimeInMillis(millis); return dateValue( cal.get(Calendar.ERA) == GregorianCalendar.BC ? 1 - cal.get(Calendar.YEAR) : cal.get(Calendar.YEAR), cal.get(Calendar.MONTH) + 1, cal.get(Calendar.DAY_OF_MONTH) ); } /** * Convert millis in default time zone to UTC millis. */ public static long utcMillisFromDefaultTz(long tzMillis) { return tzMillis + DEFAULT_TZ.getOffset(tzMillis); } /** * Convert millis in UTC to default time zone millis. */ public static long defaultTzMillisFromUtc(long utcMillis) {<FILL_FUNCTION_BODY>} /** */ public static Timestamp convertToTimestamp(LocalDateTime locDateTime) { LocalDate locDate = locDateTime.toLocalDate(); LocalTime locTime = locDateTime.toLocalTime(); long dateVal = dateValue(locDate.getYear(), locDate.getMonthValue(), locDate.getDayOfMonth()); long millis = millisFromDateValue(dateVal) + TimeUnit.NANOSECONDS.toMillis(locTime.toNanoOfDay()); long nanos = locTime.toNanoOfDay() % 1_000_000_000L; Timestamp res = new Timestamp(defaultTzMillisFromUtc(millis)); res.setNanos((int)nanos); return res; } /** */ public static Time convertToSqlTime(LocalTime locTime) { long millis = TimeUnit.NANOSECONDS.toMillis(locTime.toNanoOfDay()); return new Time(defaultTzMillisFromUtc(millis)); } /** */ public static Date convertToSqlDate(LocalDate locDate) { long dateVal = dateValue(locDate.getYear(), locDate.getMonthValue(), locDate.getDayOfMonth()); long millis = millisFromDateValue(dateVal); return new Date(defaultTzMillisFromUtc(millis)); } }
// Taking into account DST, offset can be changed after converting from UTC to time-zone. return utcMillis - DEFAULT_TZ.getOffset(utcMillis - DEFAULT_TZ.getOffset(utcMillis));
1,409
60
1,469
<no_super_class>
apache_ignite
ignite/modules/core/src/main/java/org/apache/ignite/internal/cache/query/index/sorted/inline/types/DoubleInlineIndexKeyType.java
DoubleInlineIndexKeyType
get0
class DoubleInlineIndexKeyType extends NumericInlineIndexKeyType<DoubleIndexKey> { /** */ public DoubleInlineIndexKeyType() { super(IndexKeyType.DOUBLE, (short)8); } /** {@inheritDoc} */ @Override public int compare0(long pageAddr, int off, IndexKey key) { double val = Double.longBitsToDouble(PageUtils.getLong(pageAddr, off + 1)); return -Integer.signum(((NumericIndexKey)key).compareTo(val)); } /** {@inheritDoc} */ @Override protected int put0(long pageAddr, int off, DoubleIndexKey key, int maxSize) { PageUtils.putByte(pageAddr, off, (byte)type().code()); PageUtils.putLong(pageAddr, off + 1, Double.doubleToLongBits((double)key.key())); return keySize + 1; } /** {@inheritDoc} */ @Override protected DoubleIndexKey get0(long pageAddr, int off) {<FILL_FUNCTION_BODY>} }
double key = Double.longBitsToDouble(PageUtils.getLong(pageAddr, off + 1)); return new DoubleIndexKey(key);
278
40
318
<methods>public boolean isComparableTo(org.apache.ignite.internal.cache.query.index.sorted.keys.IndexKey) <variables>
apache_ignite
ignite/modules/core/src/main/java/org/apache/ignite/internal/cache/query/index/sorted/inline/types/ShortInlineIndexKeyType.java
ShortInlineIndexKeyType
put0
class ShortInlineIndexKeyType extends NumericInlineIndexKeyType<ShortIndexKey> { /** */ public ShortInlineIndexKeyType() { super(IndexKeyType.SHORT, (short)2); } /** {@inheritDoc} */ @Override public int compare0(long pageAddr, int off, IndexKey key) { short val = PageUtils.getShort(pageAddr, off + 1); return -Integer.signum(((NumericIndexKey)key).compareTo(val)); } /** {@inheritDoc} */ @Override protected int put0(long pageAddr, int off, ShortIndexKey key, int maxSize) {<FILL_FUNCTION_BODY>} /** {@inheritDoc} */ @Override protected ShortIndexKey get0(long pageAddr, int off) { short key = PageUtils.getShort(pageAddr, off + 1); return new ShortIndexKey(key); } }
PageUtils.putByte(pageAddr, off, (byte)type().code()); PageUtils.putShort(pageAddr, off + 1, (short)key.key()); return keySize + 1;
240
54
294
<methods>public boolean isComparableTo(org.apache.ignite.internal.cache.query.index.sorted.keys.IndexKey) <variables>
apache_ignite
ignite/modules/core/src/main/java/org/apache/ignite/internal/cache/query/index/sorted/keys/BytesIndexKey.java
BytesIndexKey
compare
class BytesIndexKey implements IndexKey { /** */ protected final byte[] key; /** */ public BytesIndexKey(byte[] key) { this.key = key; } /** {@inheritDoc} */ @Override public Object key() { return key; } /** {@inheritDoc} */ @Override public IndexKeyType type() { return IndexKeyType.BYTES; } /** {@inheritDoc} */ @Override public int compare(IndexKey o) {<FILL_FUNCTION_BODY>} /** {@inheritDoc} */ @Override public String toString() { return Arrays.toString(key); } }
byte[] arr0 = key; byte[] arr1 = ((BytesIndexKey)o).key; if (arr0 == arr1) return 0; int commonLen = Math.min(arr0.length, arr1.length); int unSignArr0; int unSignArr1; for (int i = 0; i < commonLen; ++i) { unSignArr0 = arr0[i] & 255; unSignArr1 = arr1[i] & 255; if (unSignArr0 != unSignArr1) return unSignArr0 > unSignArr1 ? 1 : -1; } return Integer.signum(Integer.compare(arr0.length, arr1.length));
179
206
385
<no_super_class>
apache_ignite
ignite/modules/core/src/main/java/org/apache/ignite/internal/cache/query/index/sorted/keys/UuidIndexKey.java
UuidIndexKey
compare
class UuidIndexKey implements IndexKey { /** */ private final UUID key; /** */ public UuidIndexKey(UUID key) { this.key = key; } /** {@inheritDoc} */ @Override public Object key() { return key; } /** {@inheritDoc} */ @Override public IndexKeyType type() { return IndexKeyType.UUID; } /** {@inheritDoc} */ @Override public int compare(IndexKey o) {<FILL_FUNCTION_BODY>} /** {@inheritDoc} */ @Override public String toString() { return String.valueOf(key); } }
UUID okey = (UUID)o.key(); // Keep old logic. if (key.getMostSignificantBits() == okey.getMostSignificantBits()) return Long.compare(key.getLeastSignificantBits(), okey.getLeastSignificantBits()); else return key.getMostSignificantBits() > okey.getMostSignificantBits() ? 1 : -1;
175
109
284
<no_super_class>
apache_ignite
ignite/modules/core/src/main/java/org/apache/ignite/internal/client/GridClientFactory.java
GridClientFactory
stopAll
class GridClientFactory { /** Map that contain all opened clients. */ private static ConcurrentMap<UUID, GridClientImpl> openClients = new ConcurrentHashMap<>(); /** Lock to prevent concurrent adding of clients while stopAll is working. */ private static final ReadWriteLock busyLock = new ReentrantReadWriteLock(); /** * Ensure singleton. */ private GridClientFactory() { // No-op. } /** * Starts a client with given configuration. Starting client will be assigned a randomly generated * UUID which can be obtained by {@link GridClient#id()} method. * * @param cfg Client configuration. * @return Started client. * @throws GridClientException If client could not be created. */ public static GridClient start(GridClientConfiguration cfg) throws GridClientException { return start(cfg, false); } /** * Starts a client before node start with given configuration. * If node has already started, there will be an error. * * @param cfg Client configuration. * @return Started client. * @throws GridClientException If client could not be created. */ public static GridClientBeforeNodeStart startBeforeNodeStart( GridClientConfiguration cfg ) throws GridClientException { return start(cfg, true); } /** * Starts a client with given configuration. * * @param cfg Client configuration. * @param beforeNodeStart Before node start. * @return Started client. * @throws GridClientException If client could not be created. */ private static GridClientImpl start( GridClientConfiguration cfg, boolean beforeNodeStart ) throws GridClientException { busyLock.readLock().lock(); try { UUID clientId = UUID.randomUUID(); GridClientImpl client = new GridClientImpl(clientId, cfg, false, beforeNodeStart); GridClientImpl old = openClients.putIfAbsent(clientId, client); assert old == null : "Random unique UUID generation failed."; return client; } finally { busyLock.readLock().unlock(); } } /** * Waits for all open clients to finish their operations and stops them, This method * is equivalent to {@code stopAll(true)} method invocation. * * @see #stopAll(boolean) */ public static void stopAll() { stopAll(true); } /** * Stops all currently open clients. * * @param wait If {@code true} then each client will wait to finish all ongoing requests before * closing (however, no new requests will be accepted). If {@code false}, clients will be * closed immediately and all ongoing requests will be failed. */ @SuppressWarnings("TooBroadScope") public static void stopAll(boolean wait) {<FILL_FUNCTION_BODY>} /** * Waits for all pending requests for a particular client to be completed (no new requests will be * accepted) and then closes the client. This method is equivalent to {@code stop(clientId, true)}. * * @param clientId Identifier of client to close. * @see #stop(UUID, boolean) */ public static void stop(UUID clientId) { stop(clientId, true); } /** * Stops particular client. * * @param clientId Client identifier to close. * @param wait If {@code true} then client will wait to finish all ongoing requests before * closing (however, no new requests will be accepted). If {@code false}, client will be * closed immediately and all ongoing requests will be failed. */ public static void stop(UUID clientId, boolean wait) { busyLock.readLock().lock(); try { GridClientImpl client = openClients.remove(clientId); if (client != null) client.stop(wait); } finally { busyLock.readLock().unlock(); } } }
ConcurrentMap<UUID, GridClientImpl> old; busyLock.writeLock().lock(); try { old = openClients; openClients = new ConcurrentHashMap<>(); } finally { busyLock.writeLock().unlock(); } for (GridClientImpl client : old.values()) client.stop(wait);
1,038
99
1,137
<no_super_class>
apache_ignite
ignite/modules/core/src/main/java/org/apache/ignite/internal/client/balancer/GridClientRoundRobinBalancer.java
GridClientRoundRobinBalancer
onNodeAdded
class GridClientRoundRobinBalancer extends GridClientBalancerAdapter implements GridClientTopologyListener { /** Lock. */ private Lock lock = new ReentrantLock(); /** Nodes to share load. */ private LinkedList<UUID> nodeQueue = new LinkedList<>(); /** {@inheritDoc} */ @Override public GridClientNode balancedNode(Collection<? extends GridClientNode> nodes) throws GridClientException { assert !nodes.isEmpty(); if (isPreferDirectNodes()) { Collection<GridClientNode> direct = selectDirectNodes(nodes); int directSize = direct.size(); // If set of direct nodes is not empty and differ from original one // replace original set of nodes with directly available. if (directSize > 0 && directSize < nodes.size()) nodes = direct; } Map<UUID, GridClientNode> lookup = U.newHashMap(nodes.size()); for (GridClientNode node : nodes) lookup.put(node.nodeId(), node); lock.lock(); try { GridClientNode balanced = null; for (Iterator<UUID> iter = nodeQueue.iterator(); iter.hasNext();) { UUID nodeId = iter.next(); balanced = lookup.get(nodeId); if (balanced != null) { iter.remove(); break; } } if (balanced != null) { nodeQueue.addLast(balanced.nodeId()); return balanced; } throw new GridClientException("Passed nodes doesn't present in topology " + "[nodes=" + nodes + ", top=" + nodeQueue); } finally { lock.unlock(); } } /** {@inheritDoc} */ @Override public void onNodeAdded(GridClientNode node) {<FILL_FUNCTION_BODY>} /** {@inheritDoc} */ @Override public void onNodeRemoved(GridClientNode node) { lock.lock(); try { nodeQueue.remove(node.nodeId()); } finally { lock.unlock(); } } }
lock.lock(); try { nodeQueue.addFirst(node.nodeId()); } finally { lock.unlock(); }
547
43
590
<methods>public non-sealed void <init>() ,public boolean isPreferDirectNodes() ,public org.apache.ignite.internal.client.balancer.GridClientBalancerAdapter setPreferDirectNodes(boolean) <variables>private static final IgnitePredicate<org.apache.ignite.internal.client.GridClientNode> CONNECTABLE,private boolean preferDirectNodes
apache_ignite
ignite/modules/core/src/main/java/org/apache/ignite/internal/client/marshaller/jdk/GridClientJdkMarshaller.java
GridClientJdkMarshaller
marshal
class GridClientJdkMarshaller implements GridClientMarshaller { /** ID. */ public static final byte ID = 2; /** Class name filter. */ private final IgnitePredicate<String> clsFilter; /** * Default constructor. */ public GridClientJdkMarshaller() { this(null); } /** * @param clsFilter Class filter. */ public GridClientJdkMarshaller(IgnitePredicate<String> clsFilter) { this.clsFilter = clsFilter; } /** {@inheritDoc} */ @Override public ByteBuffer marshal(Object obj, int off) throws IOException {<FILL_FUNCTION_BODY>} /** {@inheritDoc} */ @Override public <T> T unmarshal(byte[] bytes) throws IOException { ByteArrayInputStream tmp = new ByteArrayInputStream(bytes); ObjectInput in = new ClientJdkInputStream(tmp, clsFilter); try { return (T)in.readObject(); } catch (ClassNotFoundException e) { throw new IOException("Failed to unmarshal target object: " + e.getMessage(), e); } } /** * Wrapper with class resolving control. */ private static class ClientJdkInputStream extends ObjectInputStream { /** Class name filter. */ private final IgnitePredicate<String> clsFilter; /** * @param in Input stream. * @param clsFilter Class filter. */ public ClientJdkInputStream(InputStream in, IgnitePredicate<String> clsFilter) throws IOException { super(in); this.clsFilter = clsFilter; } /** {@inheritDoc} */ @Override protected Class<?> resolveClass(ObjectStreamClass desc) throws IOException, ClassNotFoundException { String clsName = desc.getName(); if (clsFilter != null && !clsFilter.apply(clsName)) throw new RuntimeException("Deserialization of class " + clsName + " is disallowed."); return super.resolveClass(desc); } } }
GridByteArrayOutputStream bOut = new GridByteArrayOutputStream(); ObjectOutput out = new ObjectOutputStream(bOut); out.writeObject(obj); out.flush(); ByteBuffer buf = ByteBuffer.allocate(off + bOut.size()); buf.position(off); buf.put(bOut.internalArray(), 0, bOut.size()); buf.flip(); return buf;
538
113
651
<no_super_class>
apache_ignite
ignite/modules/core/src/main/java/org/apache/ignite/internal/client/marshaller/optimized/GridClientOptimizedMarshaller.java
GridClientOptimizedMarshaller
marshal
class GridClientOptimizedMarshaller implements GridClientMarshaller { /** ID. */ public static final byte ID = 1; /** Optimized marshaller. */ protected final OptimizedMarshaller opMarsh; /** * Default constructor. */ public GridClientOptimizedMarshaller() { opMarsh = new OptimizedMarshaller(); opMarsh.setContext(new ClientMarshallerContext()); } /** * Constructor. * * @param plugins Plugins. */ public GridClientOptimizedMarshaller(@Nullable List<PluginProvider> plugins) { opMarsh = new OptimizedMarshaller(); opMarsh.setContext(new ClientMarshallerContext(plugins)); } /** * Constructs optimized marshaller with specific parameters. * * @param requireSer Require serializable flag. * @param poolSize Object streams pool size. * @throws IOException If an I/O error occurs while writing stream header. * @throws IgniteException If this marshaller is not supported on the current JVM. * @see OptimizedMarshaller */ public GridClientOptimizedMarshaller(boolean requireSer, int poolSize) throws IOException { opMarsh = new OptimizedMarshaller(); opMarsh.setContext(new ClientMarshallerContext()); opMarsh.setRequireSerializable(requireSer); opMarsh.setPoolSize(poolSize); } /** {@inheritDoc} */ @Override public ByteBuffer marshal(Object obj, int off) throws IOException {<FILL_FUNCTION_BODY>} /** {@inheritDoc} */ @Override public <T> T unmarshal(byte[] bytes) throws IOException { try { return U.unmarshal(opMarsh, bytes, null); } catch (IgniteCheckedException e) { throw new IOException(e); } } /** */ private static class ClientMarshallerContext extends MarshallerContextImpl { /** */ public ClientMarshallerContext() { super(null, null); } /** * @param plugins Plugins. */ public ClientMarshallerContext(@Nullable List<PluginProvider> plugins) { super(plugins, null); } } }
try { if (!(obj instanceof GridClientMessage)) throw new IOException("Message serialization of given type is not supported: " + obj.getClass().getName()); byte[] bytes = U.marshal(opMarsh, obj); ByteBuffer buf = ByteBuffer.allocate(off + bytes.length); buf.position(off); buf.put(bytes); buf.flip(); return buf; } catch (IgniteCheckedException e) { throw new IOException(e); }
597
140
737
<no_super_class>
apache_ignite
ignite/modules/core/src/main/java/org/apache/ignite/internal/client/thin/ClientBinaryMarshaller.java
ClientBinaryMarshaller
createImpl
class ClientBinaryMarshaller { /** Metadata handler. */ private final BinaryMetadataHandler metaHnd; /** Marshaller context. */ private final MarshallerContext marshCtx; /** Re-using marshaller implementation from Ignite core. */ private GridBinaryMarshaller impl; /** * Constructor. */ ClientBinaryMarshaller(BinaryMetadataHandler metaHnd, MarshallerContext marshCtx) { this.metaHnd = metaHnd; this.marshCtx = marshCtx; impl = createImpl(null); } /** * Unmarshals Ignite binary object from input stream. * * @param in Input stream. * @return Binary object. */ public <T> T unmarshal(BinaryInputStream in) { return impl.unmarshal(in); } /** * Deserializes object from input stream. * * @param in Input stream. * @param hnds Object handles. */ public <T> T deserialize(BinaryInputStream in, BinaryReaderHandles hnds) { return impl.deserialize(in, null, hnds); } /** * Serializes Java object into a byte array. */ public byte[] marshal(Object obj) { return impl.marshal(obj, false); } /** * Configure marshaller with custom Ignite Binary Object configuration. */ public void setBinaryConfiguration(BinaryConfiguration binCfg) { impl = createImpl(binCfg); } /** * @return The marshaller context. */ public BinaryContext context() { return impl.context(); } /** Create new marshaller implementation. */ private GridBinaryMarshaller createImpl(BinaryConfiguration binCfg) {<FILL_FUNCTION_BODY>} }
IgniteConfiguration igniteCfg = new IgniteConfiguration(); if (binCfg == null) { binCfg = new BinaryConfiguration(); binCfg.setCompactFooter(false); } igniteCfg.setBinaryConfiguration(binCfg); BinaryContext ctx = new BinaryContext(metaHnd, igniteCfg, NullLogger.INSTANCE); BinaryMarshaller marsh = new BinaryMarshaller(); marsh.setContext(marshCtx); ctx.configure(marsh, binCfg); ctx.registerUserTypesSchema(); return new GridBinaryMarshaller(ctx);
491
172
663
<no_super_class>
apache_ignite
ignite/modules/core/src/main/java/org/apache/ignite/internal/client/thin/GenericQueryPager.java
GenericQueryPager
close
class GenericQueryPager<T> implements QueryPager<T> { /** Query op. */ private final ClientOperation qryOp; /** Query op. */ private final ClientOperation pageQryOp; /** Query writer. */ private final Consumer<PayloadOutputChannel> qryWriter; /** Channel. */ private final ReliableChannel ch; /** Has next. */ private boolean hasNext = true; /** Indicates if initial query response was received. */ private boolean hasFirstPage = false; /** Cursor id. */ private Long cursorId = null; /** Client channel on first query page. */ private ClientChannel clientCh; /** Cache ID, required only for affinity node calculation. */ private final int cacheId; /** Partition filter (-1 for all partitions), required only for affinity node calculation. */ private final int part; /** Constructor. */ GenericQueryPager( ReliableChannel ch, ClientOperation qryOp, ClientOperation pageQryOp, Consumer<PayloadOutputChannel> qryWriter, int cacheId, int part ) { this.ch = ch; this.qryOp = qryOp; this.pageQryOp = pageQryOp; this.qryWriter = qryWriter; this.cacheId = cacheId; this.part = part; } /** Constructor. */ GenericQueryPager( ReliableChannel ch, ClientOperation qryOp, ClientOperation pageQryOp, Consumer<PayloadOutputChannel> qryWriter ) { this(ch, qryOp, pageQryOp, qryWriter, 0, -1); } /** {@inheritDoc} */ @Override public Collection<T> next() throws ClientException { if (!hasNext) throw new IllegalStateException("No more query results"); return hasFirstPage ? queryPage() : part == -1 ? ch.service(qryOp, qryWriter, this::readResult) : ch.affinityService(cacheId, part, qryOp, qryWriter, this::readResult); } /** {@inheritDoc} */ @Override public void close() throws Exception {<FILL_FUNCTION_BODY>} /** {@inheritDoc} */ @Override public boolean hasNext() { return hasNext; } /** {@inheritDoc} */ @Override public boolean hasFirstPage() { return hasFirstPage; } /** {@inheritDoc} */ @Override public void reset() { hasFirstPage = false; hasNext = true; cursorId = null; clientCh = null; } /** * Override this method to read entries from the input stream. "Entries" means response data excluding heading * cursor ID and trailing "has next page" flag. * Use {@link this#hasFirstPage} flag to differentiate between the initial query and page query responses. */ abstract Collection<T> readEntries(PayloadInputChannel in); /** */ private Collection<T> readResult(PayloadInputChannel payloadCh) { if (!hasFirstPage) { long resCursorId = payloadCh.in().readLong(); if (cursorId != null) { if (cursorId != resCursorId) throw new ClientProtocolError( String.format("Expected cursor [%s] but received cursor [%s]", cursorId, resCursorId) ); } else { cursorId = resCursorId; clientCh = payloadCh.clientChannel(); } } Collection<T> res = readEntries(payloadCh); hasNext = payloadCh.in().readBoolean(); hasFirstPage = true; return res; } /** Get page. */ private Collection<T> queryPage() throws ClientException { return clientCh.service(pageQryOp, req -> req.out().writeLong(cursorId), this::readResult); } }
// Close cursor only if the server has more pages: the server closes cursor automatically on last page if (cursorId != null && hasNext && !clientCh.closed()) { try { clientCh.service(ClientOperation.RESOURCE_CLOSE, req -> req.out().writeLong(cursorId), null); } catch (ClientConnectionException | ClientReconnectedException ignored) { // Original connection was lost and cursor was closed by the server. } }
1,037
121
1,158
<no_super_class>
apache_ignite
ignite/modules/core/src/main/java/org/apache/ignite/internal/client/thin/PayloadOutputChannel.java
PayloadOutputChannel
close
class PayloadOutputChannel implements AutoCloseable { /** Initial output stream buffer capacity. */ private static final int INITIAL_BUFFER_CAPACITY = 1024; /** Client channel. */ private final ClientChannel ch; /** Output stream. */ private final BinaryHeapOutputStream out; /** Close guard. */ private final AtomicBoolean closed = new AtomicBoolean(); /** * Constructor. */ PayloadOutputChannel(ClientChannel ch) { // Disable AutoCloseable on the stream so that out callers don't release the pooled buffer before it is written to the socket. out = new BinaryHeapOutputStream(INITIAL_BUFFER_CAPACITY, BinaryMemoryAllocator.POOLED.chunk(), true); this.ch = ch; } /** * Gets client channel. */ public ClientChannel clientChannel() { return ch; } /** * Gets output stream. */ public BinaryOutputStream out() { return out; } /** {@inheritDoc} */ @Override public void close() {<FILL_FUNCTION_BODY>} }
// Pooled buffer is reusable and should be released once and only once. // Releasing more than once potentially "steals" it from another request. if (closed.compareAndSet(false, true)) out.release();
299
61
360
<no_super_class>
apache_ignite
ignite/modules/core/src/main/java/org/apache/ignite/internal/client/thin/TcpClientTransactions.java
TcpClientTransaction
endTx
class TcpClientTransaction implements ClientTransaction { /** Unique client-side transaction id. */ private final long txUid; /** Server-side transaction id. */ private final int txId; /** Client channel. */ private final ClientChannel clientCh; /** Transaction is closed. */ private volatile boolean closed; /** * @param id Transaction ID. * @param clientCh Client channel. */ private TcpClientTransaction(int id, ClientChannel clientCh) { txUid = txCnt.incrementAndGet(); txId = id; this.clientCh = clientCh; } /** {@inheritDoc} */ @Override public void commit() { Long threadTxUid; if (closed || (threadTxUid = threadLocTxUid.get()) == null) throw new ClientException("The transaction is already closed"); if (txUid != threadTxUid) throw new ClientException("You can commit transaction only from the thread it was started"); endTx(true); } /** {@inheritDoc} */ @Override public void rollback() { endTx(false); } /** {@inheritDoc} */ @Override public void close() { try { endTx(false); } catch (Exception ignore) { // No-op. } } /** * @param committed Committed. */ private void endTx(boolean committed) {<FILL_FUNCTION_BODY>} /** * Tx ID. */ int txId() { return txId; } /** * Client channel. */ ClientChannel clientChannel() { return clientCh; } /** * Is transaction closed. */ boolean isClosed() { return closed; } }
try { clientCh.service(ClientOperation.TX_END, req -> { req.out().writeInt(txId); req.out().writeBoolean(committed); }, null); } catch (ClientConnectionException e) { throw new ClientException("Transaction context has been lost due to connection errors", e); } finally { txMap.remove(txUid); closed = true; Long threadTxUid = threadLocTxUid.get(); if (threadTxUid != null && txUid == threadTxUid) threadLocTxUid.set(null); }
484
167
651
<no_super_class>
apache_ignite
ignite/modules/core/src/main/java/org/apache/ignite/internal/cluster/ClusterNodeLocalMapImpl.java
ClusterNodeLocalMapImpl
readResolve
class ClusterNodeLocalMapImpl<K, V> extends ConcurrentHashMap<K, V> implements ConcurrentMap<K, V>, Externalizable { /** */ private static final long serialVersionUID = 0L; /** */ private static final ThreadLocal<String> stash = new ThreadLocal<>(); /** */ private GridKernalContext ctx; /** * No-arg constructor is required by externalization. */ public ClusterNodeLocalMapImpl() { // No-op. } /** * * @param ctx Kernal context. */ ClusterNodeLocalMapImpl(GridKernalContext ctx) { assert ctx != null; this.ctx = ctx; } /** {@inheritDoc} */ @Override public void writeExternal(ObjectOutput out) throws IOException { U.writeString(out, ctx.igniteInstanceName()); } /** {@inheritDoc} */ @Override public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException { stash.set(U.readString(in)); } /** * Reconstructs object on unmarshalling. * * @return Reconstructed object. * @throws ObjectStreamException Thrown in case of unmarshalling error. */ protected Object readResolve() throws ObjectStreamException {<FILL_FUNCTION_BODY>} /** {@inheritDoc} */ @Override public String toString() { return S.toString(ClusterNodeLocalMapImpl.class, this); } }
try { return IgnitionEx.localIgnite().cluster().nodeLocalMap(); } catch (IllegalStateException e) { throw U.withCause(new InvalidObjectException(e.getMessage()), e); } finally { stash.remove(); }
401
75
476
<methods>public void <init>() ,public void <init>(int) ,public void <init>(Map<? extends K,? extends V>) ,public void <init>(int, float) ,public void <init>(int, float, int) ,public void clear() ,public V compute(K, BiFunction<? super K,? super V,? extends V>) ,public V computeIfAbsent(K, Function<? super K,? extends V>) ,public V computeIfPresent(K, BiFunction<? super K,? super V,? extends V>) ,public boolean contains(java.lang.Object) ,public boolean containsKey(java.lang.Object) ,public boolean containsValue(java.lang.Object) ,public Enumeration<V> elements() ,public Set<Entry<K,V>> entrySet() ,public boolean equals(java.lang.Object) ,public void forEach(BiConsumer<? super K,? super V>) ,public void forEach(long, BiConsumer<? super K,? super V>) ,public void forEach(long, BiFunction<? super K,? super V,? extends U>, Consumer<? super U>) ,public void forEachEntry(long, Consumer<? super Entry<K,V>>) ,public void forEachEntry(long, Function<Entry<K,V>,? extends U>, Consumer<? super U>) ,public void forEachKey(long, Consumer<? super K>) ,public void forEachKey(long, Function<? super K,? extends U>, Consumer<? super U>) ,public void forEachValue(long, Consumer<? super V>) ,public void forEachValue(long, Function<? super V,? extends U>, Consumer<? super U>) ,public V get(java.lang.Object) ,public V getOrDefault(java.lang.Object, V) ,public int hashCode() ,public boolean isEmpty() ,public KeySetView<K,V> keySet() ,public KeySetView<K,V> keySet(V) ,public Enumeration<K> keys() ,public long mappingCount() ,public V merge(K, V, BiFunction<? super V,? super V,? extends V>) ,public static KeySetView<K,java.lang.Boolean> newKeySet() ,public static KeySetView<K,java.lang.Boolean> newKeySet(int) ,public V put(K, V) ,public void putAll(Map<? extends K,? extends V>) ,public V putIfAbsent(K, V) ,public U reduce(long, BiFunction<? super K,? super V,? extends U>, BiFunction<? super U,? super U,? extends U>) ,public Entry<K,V> reduceEntries(long, BiFunction<Entry<K,V>,Entry<K,V>,? extends Entry<K,V>>) ,public U reduceEntries(long, Function<Entry<K,V>,? extends U>, BiFunction<? super U,? super U,? extends U>) ,public double reduceEntriesToDouble(long, ToDoubleFunction<Entry<K,V>>, double, java.util.function.DoubleBinaryOperator) ,public int reduceEntriesToInt(long, ToIntFunction<Entry<K,V>>, int, java.util.function.IntBinaryOperator) ,public long reduceEntriesToLong(long, ToLongFunction<Entry<K,V>>, long, java.util.function.LongBinaryOperator) ,public K reduceKeys(long, BiFunction<? super K,? super K,? extends K>) ,public U reduceKeys(long, Function<? super K,? extends U>, BiFunction<? super U,? super U,? extends U>) ,public double reduceKeysToDouble(long, ToDoubleFunction<? super K>, double, java.util.function.DoubleBinaryOperator) ,public int reduceKeysToInt(long, ToIntFunction<? super K>, int, java.util.function.IntBinaryOperator) ,public long reduceKeysToLong(long, ToLongFunction<? super K>, long, java.util.function.LongBinaryOperator) ,public double reduceToDouble(long, ToDoubleBiFunction<? super K,? super V>, double, java.util.function.DoubleBinaryOperator) ,public int reduceToInt(long, ToIntBiFunction<? super K,? super V>, int, java.util.function.IntBinaryOperator) ,public long reduceToLong(long, ToLongBiFunction<? super K,? super V>, long, java.util.function.LongBinaryOperator) ,public V reduceValues(long, BiFunction<? super V,? super V,? extends V>) ,public U reduceValues(long, Function<? super V,? extends U>, BiFunction<? super U,? super U,? extends U>) ,public double reduceValuesToDouble(long, ToDoubleFunction<? super V>, double, java.util.function.DoubleBinaryOperator) ,public int reduceValuesToInt(long, ToIntFunction<? super V>, int, java.util.function.IntBinaryOperator) ,public long reduceValuesToLong(long, ToLongFunction<? super V>, long, java.util.function.LongBinaryOperator) ,public V remove(java.lang.Object) ,public boolean remove(java.lang.Object, java.lang.Object) ,public V replace(K, V) ,public boolean replace(K, V, V) ,public void replaceAll(BiFunction<? super K,? super V,? extends V>) ,public U search(long, BiFunction<? super K,? super V,? extends U>) ,public U searchEntries(long, Function<Entry<K,V>,? extends U>) ,public U searchKeys(long, Function<? super K,? extends U>) ,public U searchValues(long, Function<? super V,? extends U>) ,public int size() ,public java.lang.String toString() ,public Collection<V> values() <variables>private static final int ABASE,private static final int ASHIFT,private static final long BASECOUNT,private static final long CELLSBUSY,private static final long CELLVALUE,private static final int DEFAULT_CAPACITY,private static final int DEFAULT_CONCURRENCY_LEVEL,static final int HASH_BITS,private static final float LOAD_FACTOR,private static final int MAXIMUM_CAPACITY,static final int MAX_ARRAY_SIZE,private static final int MAX_RESIZERS,private static final int MIN_TRANSFER_STRIDE,static final int MIN_TREEIFY_CAPACITY,static final int MOVED,static final int NCPU,static final int RESERVED,private static final int RESIZE_STAMP_BITS,private static final int RESIZE_STAMP_SHIFT,private static final long SIZECTL,private static final long TRANSFERINDEX,static final int TREEBIN,static final int TREEIFY_THRESHOLD,private static final jdk.internal.misc.Unsafe U,static final int UNTREEIFY_THRESHOLD,private volatile transient long baseCount,private volatile transient int cellsBusy,private volatile transient java.util.concurrent.ConcurrentHashMap.CounterCell[] counterCells,private transient EntrySetView<K,V> entrySet,private transient KeySetView<K,V> keySet,private volatile transient Node<K,V>[] nextTable,private static final java.io.ObjectStreamField[] serialPersistentFields,private static final long serialVersionUID,private volatile transient int sizeCtl,volatile transient Node<K,V>[] table,private volatile transient int transferIndex,private transient ValuesView<K,V> values
apache_ignite
ignite/modules/core/src/main/java/org/apache/ignite/internal/commandline/cache/distribution/CacheDistributionNode.java
CacheDistributionNode
readExternalData
class CacheDistributionNode extends VisorDataTransferObject { /** */ private static final long serialVersionUID = 0L; /** Node identifier. */ private UUID nodeId; /** Network addresses. */ private String addrs; /** User attribute in result. */ private Map<String, String> userAttrs; /** Information about groups. */ private List<CacheDistributionGroup> groups; /** Default constructor. */ public CacheDistributionNode() { } /** * @param nodeId Node identifier. * @param addrs Network addresses. * @param userAttrs Map node user attribute. * @param groups Information about groups. */ public CacheDistributionNode(UUID nodeId, String addrs, Map<String, String> userAttrs, List<CacheDistributionGroup> groups) { this.nodeId = nodeId; this.addrs = addrs; this.userAttrs = userAttrs; this.groups = groups; } /** */ public UUID getNodeId() { return nodeId; } /** */ public void setNodeId(UUID nodeId) { this.nodeId = nodeId; } /** */ public String getAddresses() { return addrs; } /** */ public void setAddresses(String addrs) { this.addrs = addrs; } /** * @return User attribute in result. */ public Map<String, String> getUserAttributes() { return userAttrs; } /** * @param userAttrs New user attribute in result. */ public void setUserAttributes(Map<String, String> userAttrs) { this.userAttrs = userAttrs; } /** */ public List<CacheDistributionGroup> getGroups() { return groups; } /** */ public void setGroups(List<CacheDistributionGroup> groups) { this.groups = groups; } /** {@inheritDoc} */ @Override protected void writeExternalData(ObjectOutput out) throws IOException { U.writeUuid(out, nodeId); U.writeString(out, addrs); U.writeMap(out, userAttrs); U.writeCollection(out, groups); } /** {@inheritDoc} */ @Override protected void readExternalData(byte protoVer, ObjectInput in) throws IOException, ClassNotFoundException {<FILL_FUNCTION_BODY>} }
nodeId = U.readUuid(in); addrs = U.readString(in); userAttrs = U.readMap(in); groups = U.readList(in);
651
52
703
<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,private static final long serialVersionUID
apache_ignite
ignite/modules/core/src/main/java/org/apache/ignite/internal/commandline/cache/distribution/CacheDistributionPartition.java
CacheDistributionPartition
readExternalData
class CacheDistributionPartition extends VisorDataTransferObject { /** */ private static final long serialVersionUID = 0L; /** Partition identifier. */ private int partId; /** Flag primary or backup partition. */ private boolean primary; /** Partition status. */ private GridDhtPartitionState state; /** Partition update counters. */ private long updateCntr; /** Number of entries in partition. */ private long size; /** Default constructor. */ public CacheDistributionPartition() { } /** * @param partId Partition identifier. * @param primary Flag primary or backup partition. * @param state Partition status. * @param updateCntr Partition update counters. * @param size Number of entries in partition. */ public CacheDistributionPartition(int partId, boolean primary, GridDhtPartitionState state, long updateCntr, long size) { this.partId = partId; this.primary = primary; this.state = state; this.updateCntr = updateCntr; this.size = size; } /** */ public int getPartition() { return partId; } /** */ public void setPartition(int partId) { this.partId = partId; } /** */ public boolean isPrimary() { return primary; } /** */ public void setPrimary(boolean primary) { this.primary = primary; } /** */ public GridDhtPartitionState getState() { return state; } /** */ public void setState(GridDhtPartitionState state) { this.state = state; } /** */ public long getUpdateCounter() { return updateCntr; } /** */ public void setUpdateCounter(long updateCntr) { this.updateCntr = updateCntr; } /** */ public long getSize() { return size; } /** */ public void setSize(long size) { this.size = size; } /** {@inheritDoc} */ @Override protected void writeExternalData(ObjectOutput out) throws IOException { out.writeInt(partId); out.writeBoolean(primary); U.writeEnum(out, state); out.writeLong(updateCntr); out.writeLong(size); } /** {@inheritDoc} */ @Override protected void readExternalData(byte protoVer, ObjectInput in) throws IOException {<FILL_FUNCTION_BODY>} }
partId = in.readInt(); primary = in.readBoolean(); state = GridDhtPartitionState.fromOrdinal(in.readByte()); updateCntr = in.readLong(); size = in.readLong();
684
63
747
<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,private static final long serialVersionUID
apache_ignite
ignite/modules/core/src/main/java/org/apache/ignite/internal/jdbc/thin/AffinityCache.java
AffinityCache
addCacheDistribution
class AffinityCache { /** Affinity topology version. */ private final AffinityTopologyVersion ver; /** Cache partitions distribution. */ private final GridBoundedLinkedHashMap<Integer, UUID[]> cachePartitionsDistribution; /** Sql cache. */ private final GridBoundedLinkedHashMap<QualifiedSQLQuery, JdbcThinPartitionResultDescriptor> sqlCache; /** * Constructor. * * @param ver Affinity topology version. */ public AffinityCache(AffinityTopologyVersion ver, int partitionAwarenessPartDistributionsCacheSize, int partitionAwarenessSQLCacheSize) { this.ver = ver; cachePartitionsDistribution = new GridBoundedLinkedHashMap<>(partitionAwarenessPartDistributionsCacheSize); sqlCache = new GridBoundedLinkedHashMap<>(partitionAwarenessSQLCacheSize); } /** * @return Version. */ public AffinityTopologyVersion version() { return ver; } /** * Adds cache distribution related to the cache with specified cache id. * * @param cacheId Cache Id. * @param distribution Cache partitions distribution, where partition id is an array index. */ void addCacheDistribution(Integer cacheId, UUID[] distribution) {<FILL_FUNCTION_BODY>} /** * Adds sql query with corresponding partition result descriptor. * * @param sql Qualified sql query. * @param partRes Partition result descriptor. */ void addSqlQuery(QualifiedSQLQuery sql, JdbcThinPartitionResultDescriptor partRes) { sqlCache.put(sql, partRes == null ? JdbcThinPartitionResultDescriptor.EMPTY_DESCRIPTOR : partRes); } /** * Retrieves partition result descriptor related to corresponding sql query. * * @param sqlQry Qualified sql query. * @return Partition result descriptor or null. */ public JdbcThinPartitionResultDescriptor partitionResult(QualifiedSQLQuery sqlQry) { return sqlCache.get(sqlQry); } /** * @param cacheId Cache Id. * @return Cache partition distribution for given cache Id or null. */ public UUID[] cacheDistribution(int cacheId) { return cachePartitionsDistribution.get(cacheId); } }
for (Map.Entry<Integer, UUID[]> entry : cachePartitionsDistribution.entrySet()) { if (Arrays.equals(entry.getValue(), distribution)) { // put link to already existing distribution instead of creating new one. cachePartitionsDistribution.put(cacheId, entry.getValue()); return; } } cachePartitionsDistribution.put(cacheId, distribution);
600
103
703
<no_super_class>
apache_ignite
ignite/modules/core/src/main/java/org/apache/ignite/internal/jdbc/thin/JdbcThinUtils.java
JdbcThinUtils
typeName
class JdbcThinUtils { /** URL prefix. */ public static final String URL_PREFIX = "jdbc:ignite:thin://"; /** Port number property name. */ public static final String PROP_PORT = PROP_PREFIX + "port"; /** Hostname property name. */ public static final String PROP_HOST = PROP_PREFIX + "host"; /** Byte representation of value "default" */ private static final byte BYTE_DEFAULT = 2; /** Byte representation of value "disabled". */ private static final byte BYTE_ENABLED = 1; /** Byte representation of value "disabled". */ private static final byte BYTE_DISABLED = 0; /** * Converts Java class name to type from {@link Types}. * * @param cls Java class name. * @return Type from {@link Types}. */ public static int type(String cls) { if (Boolean.class.getName().equals(cls) || boolean.class.getName().equals(cls)) return BOOLEAN; else if (Byte.class.getName().equals(cls) || byte.class.getName().equals(cls)) return TINYINT; else if (Short.class.getName().equals(cls) || short.class.getName().equals(cls)) return SMALLINT; else if (Integer.class.getName().equals(cls) || int.class.getName().equals(cls)) return INTEGER; else if (Long.class.getName().equals(cls) || long.class.getName().equals(cls)) return BIGINT; else if (Float.class.getName().equals(cls) || float.class.getName().equals(cls)) return FLOAT; else if (Double.class.getName().equals(cls) || double.class.getName().equals(cls)) return DOUBLE; else if (String.class.getName().equals(cls)) return VARCHAR; else if (byte[].class.getName().equals(cls)) return BINARY; else if (Time.class.getName().equals(cls)) return TIME; else if (Timestamp.class.getName().equals(cls)) return TIMESTAMP; else if (Date.class.getName().equals(cls) || java.sql.Date.class.getName().equals(cls)) return DATE; else if (BigDecimal.class.getName().equals(cls)) return DECIMAL; else return OTHER; } /** * Converts Java class name to SQL type name. * * @param cls Java class name. * @return SQL type name. */ public static String typeName(String cls) {<FILL_FUNCTION_BODY>} /** * @param type a value from <code>java.sql.Types</code>. * @return {@code true} if type is plain and supported by thin JDBC driver. */ public static boolean isPlainJdbcType(int type) { return type != Types.ARRAY && type != Types.BLOB && type != Types.CLOB && type != Types.DATALINK && type != Types.JAVA_OBJECT && type != Types.NCHAR && type != Types.NVARCHAR && type != Types.LONGNVARCHAR && type != Types.REF && type != Types.ROWID && type != Types.SQLXML; } /** * Determines whether type is nullable. * * @param name Column name. * @param cls Java class name. * @return {@code True} if nullable. */ public static boolean nullable(String name, String cls) { return !"_KEY".equalsIgnoreCase(name) && !"_VAL".equalsIgnoreCase(name) && !(boolean.class.getName().equals(cls) || byte.class.getName().equals(cls) || short.class.getName().equals(cls) || int.class.getName().equals(cls) || long.class.getName().equals(cls) || float.class.getName().equals(cls) || double.class.getName().equals(cls)); } /** * Converts raw byte value to the nullable Boolean. Useful for the deserialization in the handshake. * * @param raw byte value to convert to Boolean. * @return converted value. */ @Nullable public static Boolean nullableBooleanFromByte(byte raw) { switch (raw) { case BYTE_DEFAULT: return null; case BYTE_ENABLED: return Boolean.TRUE; case BYTE_DISABLED: return Boolean.FALSE; default: throw new NumberFormatException("Incorrect byte: " + raw + ". Impossible to read nullable Boolean from it."); } } /** * Converts nullable Boolean to the raw byte. Useful for the serialization in the handshake. * * @param val value to convert. * @return byte representation. */ public static byte nullableBooleanToByte(@Nullable Boolean val) { if (val == null) return BYTE_DEFAULT; return val ? BYTE_ENABLED : BYTE_DISABLED; } }
if (Boolean.class.getName().equals(cls) || boolean.class.getName().equals(cls)) return "BOOLEAN"; else if (Byte.class.getName().equals(cls) || byte.class.getName().equals(cls)) return "TINYINT"; else if (Short.class.getName().equals(cls) || short.class.getName().equals(cls)) return "SMALLINT"; else if (Integer.class.getName().equals(cls) || int.class.getName().equals(cls)) return "INTEGER"; else if (Long.class.getName().equals(cls) || long.class.getName().equals(cls)) return "BIGINT"; else if (Float.class.getName().equals(cls) || float.class.getName().equals(cls)) return "FLOAT"; else if (Double.class.getName().equals(cls) || double.class.getName().equals(cls)) return "DOUBLE"; else if (String.class.getName().equals(cls)) return "VARCHAR"; else if (byte[].class.getName().equals(cls)) return "BINARY"; else if (Time.class.getName().equals(cls)) return "TIME"; else if (Timestamp.class.getName().equals(cls)) return "TIMESTAMP"; else if (Date.class.getName().equals(cls) || java.sql.Date.class.getName().equals(cls)) return "DATE"; else if (BigDecimal.class.getName().equals(cls)) return "DECIMAL"; else return "OTHER";
1,367
404
1,771
<no_super_class>
apache_ignite
ignite/modules/core/src/main/java/org/apache/ignite/internal/jdbc/thin/QualifiedSQLQuery.java
QualifiedSQLQuery
equals
class QualifiedSQLQuery { /** Schema name. */ private final String schemaName; /** Sql Query. */ private final String sqlQry; /** * Constructor. * * @param schemaName Schema name. * @param sqlQry Sql Query. */ public QualifiedSQLQuery(String schemaName, String sqlQry) { this.schemaName = schemaName; this.sqlQry = sqlQry; } /** * @return Schema name. */ public String schemaName() { return schemaName; } /** * @return Sql query. */ public String sqlQuery() { return sqlQry; } /** {@inheritDoc} */ @Override public boolean equals(Object o) {<FILL_FUNCTION_BODY>} /** {@inheritDoc} */ @Override public int hashCode() { int res = schemaName != null ? schemaName.hashCode() : 0; res = 31 * res + (sqlQry != null ? sqlQry.hashCode() : 0); return res; } /** {@inheritDoc} */ @Override public String toString() { return S.toString(QualifiedSQLQuery.class, this); } }
if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; QualifiedSQLQuery qry = (QualifiedSQLQuery)o; return Objects.equals(schemaName, qry.schemaName) && Objects.equals(sqlQry, qry.sqlQry);
339
96
435
<no_super_class>
apache_ignite
ignite/modules/core/src/main/java/org/apache/ignite/internal/jdbc2/JdbcQueryMultipleStatementsTask.java
JdbcQueryMultipleStatementsTask
call
class JdbcQueryMultipleStatementsTask implements IgniteCallable<List<JdbcStatementResultInfo>> { /** Serial version uid. */ private static final long serialVersionUID = 0L; /** Ignite. */ @IgniteInstanceResource private Ignite ignite; /** Schema name. */ private final String schemaName; /** Sql. */ private final String sql; /** Operation type flag - query or not. */ private Boolean isQry; /** Args. */ private final Object[] args; /** Fetch size. */ private final int fetchSize; /** Local execution flag. */ private final boolean loc; /** Local query flag. */ private final boolean locQry; /** Collocated query flag. */ private final boolean collocatedQry; /** Distributed joins flag. */ private final boolean distributedJoins; /** Enforce join order flag. */ private final boolean enforceJoinOrder; /** Lazy query execution flag. */ private final boolean lazy; /** * @param ignite Ignite. * @param schemaName Schema name. * @param sql Sql query. * @param isQry Operation type flag - query or not - to enforce query type check. * @param loc Local execution flag. * @param args Args. * @param fetchSize Fetch size. * @param locQry Local query flag. * @param collocatedQry Collocated query flag. * @param distributedJoins Distributed joins flag. * @param enforceJoinOrder Enforce joins order falg. * @param lazy Lazy query execution flag. */ public JdbcQueryMultipleStatementsTask(Ignite ignite, String schemaName, String sql, Boolean isQry, boolean loc, Object[] args, int fetchSize, boolean locQry, boolean collocatedQry, boolean distributedJoins, boolean enforceJoinOrder, boolean lazy) { this.ignite = ignite; this.args = args; this.schemaName = schemaName; this.sql = sql; this.isQry = isQry; this.fetchSize = fetchSize; this.loc = loc; this.locQry = locQry; this.collocatedQry = collocatedQry; this.distributedJoins = distributedJoins; this.enforceJoinOrder = enforceJoinOrder; this.lazy = lazy; } /** {@inheritDoc} */ @Override public List<JdbcStatementResultInfo> call() throws Exception {<FILL_FUNCTION_BODY>} /** * @return {@code true} if query with multiple statements is allowed. */ protected boolean allowMultipleStatements() { return true; } /** * @return query initiator identifier. */ protected String queryInitiatorId() { return null; } }
SqlFieldsQuery qry = (isQry != null ? new SqlFieldsQueryEx(sql, isQry) : new SqlFieldsQuery(sql)) .setArgs(args); qry.setPageSize(fetchSize); qry.setLocal(locQry); qry.setCollocated(collocatedQry); qry.setDistributedJoins(distributedJoins); qry.setEnforceJoinOrder(enforceJoinOrder); qry.setLazy(lazy); qry.setSchema(schemaName); if (!F.isEmpty(queryInitiatorId())) qry.setQueryInitiatorId(queryInitiatorId()); GridKernalContext ctx = ((IgniteKernal)ignite).context(); List<FieldsQueryCursor<List<?>>> curs = ctx.query().querySqlFields( qry, true, !allowMultipleStatements()); List<JdbcStatementResultInfo> resultsInfo = new ArrayList<>(curs.size()); for (FieldsQueryCursor<List<?>> cur0 : curs) { if (cur0 instanceof BulkLoadContextCursor) { curs.forEach(QueryCursor::close); throw new SQLException("COPY command is currently supported only in thin JDBC driver."); } QueryCursorImpl<List<?>> cur = (QueryCursorImpl<List<?>>)cur0; long updCnt = -1; UUID qryId = null; if (!cur.isQuery()) { List<List<?>> items = cur.getAll(); assert items != null && items.size() == 1 && items.get(0).size() == 1 && items.get(0).get(0) instanceof Long : "Invalid result set for not-SELECT query. [qry=" + sql + ", res=" + S.toString(List.class, items) + ']'; updCnt = (Long)items.get(0).get(0); cur.close(); } else { qryId = UUID.randomUUID(); JdbcQueryTask.Cursor jdbcCur = new JdbcQueryTask.Cursor(cur, cur.iterator()); JdbcQueryTask.addCursor(qryId, jdbcCur); if (!loc) JdbcQueryTask.scheduleRemoval(qryId); } JdbcStatementResultInfo resInfo = new JdbcStatementResultInfo(cur.isQuery(), qryId, updCnt); resultsInfo.add(resInfo); } return resultsInfo;
747
651
1,398
<no_super_class>
apache_ignite
ignite/modules/core/src/main/java/org/apache/ignite/internal/jdbc2/JdbcQueryTaskV3.java
JdbcQueryTaskV3
createTask
class JdbcQueryTaskV3 extends JdbcQueryTaskV2 { /** Serial version uid. */ private static final long serialVersionUID = 0L; /** Update metadata on demand flag. */ private final boolean updateMeta; /** Update metadata on demand flag. */ private final boolean skipReducerOnUpdate; /** * @param ignite Ignite. * @param cacheName Cache name. * @param schemaName Schema name. * @param sql Sql query. * @param isQry Operation type flag - query or not - to enforce query type check. * @param loc Local execution flag. * @param args Args. * @param fetchSize Fetch size. * @param uuid UUID. * @param locQry Local query flag. * @param collocatedQry Collocated query flag. * @param distributedJoins Distributed joins flag. * @param enforceJoinOrder Enforce joins order flag. * @param lazy Lazy query execution flag. * @param updateMeta Update metadata on demand. * @param skipReducerOnUpdate Flkag to enable server side updates. */ public JdbcQueryTaskV3(Ignite ignite, String cacheName, String schemaName, String sql, Boolean isQry, boolean loc, Object[] args, int fetchSize, UUID uuid, boolean locQry, boolean collocatedQry, boolean distributedJoins, boolean enforceJoinOrder, boolean lazy, boolean updateMeta, boolean skipReducerOnUpdate) { super(ignite, cacheName, schemaName, sql, isQry, loc, args, fetchSize, uuid, locQry, collocatedQry, distributedJoins, enforceJoinOrder, lazy); this.updateMeta = updateMeta; this.skipReducerOnUpdate = skipReducerOnUpdate; } /** {@inheritDoc} */ @Override protected boolean updateMetadata() { return updateMeta; } /** {@inheritDoc} */ @Override protected boolean skipReducerOnUpdate() { return skipReducerOnUpdate; } /** * @param ignite Ignite. * @param cacheName Cache name. * @param schemaName Schema name. * @param sql Sql query. * @param isQry Operation type flag - query or not - to enforce query type check. * @param loc Local execution flag. * @param args Args. * @param fetchSize Fetch size. * @param uuid UUID. * @param locQry Local query flag. * @param collocatedQry Collocated query flag. * @param distributedJoins Distributed joins flag. * @param enforceJoinOrder Enforce joins order flag. * @param lazy Lazy query execution flag. * @param updateMeta Update metadata on demand. * @param skipReducerOnUpdate Update on server flag. * @return Appropriate task JdbcQueryTask or JdbcQueryTaskV2. */ public static JdbcQueryTask createTask(Ignite ignite, String cacheName, String schemaName, String sql, Boolean isQry, boolean loc, Object[] args, int fetchSize, UUID uuid, boolean locQry, boolean collocatedQry, boolean distributedJoins, boolean enforceJoinOrder, boolean lazy, boolean updateMeta, boolean skipReducerOnUpdate) {<FILL_FUNCTION_BODY>} }
if (updateMeta || skipReducerOnUpdate) return new JdbcQueryTaskV3(ignite, cacheName, schemaName, sql, isQry, loc, args, fetchSize, uuid, locQry, collocatedQry, distributedJoins, enforceJoinOrder, lazy, updateMeta, skipReducerOnUpdate); else return JdbcQueryTaskV2.createTask(ignite, cacheName, schemaName, sql, isQry, loc, args, fetchSize, uuid, locQry, collocatedQry, distributedJoins, enforceJoinOrder, lazy);
851
149
1,000
<methods>public void <init>(org.apache.ignite.Ignite, java.lang.String, java.lang.String, java.lang.String, java.lang.Boolean, boolean, java.lang.Object[], int, java.util.UUID, boolean, boolean, boolean, boolean, boolean) ,public static org.apache.ignite.internal.jdbc2.JdbcQueryTask createTask(org.apache.ignite.Ignite, java.lang.String, java.lang.String, java.lang.String, java.lang.Boolean, boolean, java.lang.Object[], int, java.util.UUID, boolean, boolean, boolean, boolean, boolean) <variables>private final non-sealed boolean enforceJoinOrder,private final non-sealed boolean lazy,private static final long serialVersionUID
apache_ignite
ignite/modules/core/src/main/java/org/apache/ignite/internal/management/ClusterChangeTagTaskResult.java
ClusterChangeTagTaskResult
readExternalData
class ClusterChangeTagTaskResult extends IgniteDataTransferObject { /** */ private static final long serialVersionUID = 0L; /** */ private String tag; /** */ private Boolean success; /** */ private String errResp; /** Default constructor. */ public ClusterChangeTagTaskResult() { // No-op. } /** * @param tag Cluster tag. * @param success Success of update tag operation. * @param errResp Error response returned if cluster tag update has failed. */ public ClusterChangeTagTaskResult(String tag, @Nullable Boolean success, @Nullable String errResp) { this.tag = tag; this.success = success; this.errResp = errResp; } /** {@inheritDoc} */ @Override protected void writeExternalData(ObjectOutput out) throws IOException { out.writeObject(success); out.writeObject(errResp); out.writeObject(tag); } /** {@inheritDoc} */ @Override protected void readExternalData(byte protoVer, ObjectInput in) throws IOException, ClassNotFoundException {<FILL_FUNCTION_BODY>} /** */ public String tag() { return tag; } /** */ public Boolean success() { return success; } /** */ public String errorMessage() { return errResp; } }
success = (Boolean)in.readObject(); errResp = (String)in.readObject(); tag = (String)in.readObject();
371
42
413
<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/management/ShutdownPolicyTask.java
ShutdownPolicyJob
run
class ShutdownPolicyJob extends VisorJob<ShutdownPolicyCommandArg, ShutdownPolicyTaskResult> { /** Serial version id. */ private static final long serialVersionUID = 0L; /** Logger. */ @LoggerResource private IgniteLogger log; /** * Constructor of job. * * @param arg Argumants. * @param debug True if debug mode enable. */ protected ShutdownPolicyJob(ShutdownPolicyCommandArg arg, boolean debug) { super(arg, debug); } /** {@inheritDoc} */ @Override protected ShutdownPolicyTaskResult run(ShutdownPolicyCommandArg arg) throws IgniteException {<FILL_FUNCTION_BODY>} }
ShutdownPolicyTaskResult res = new ShutdownPolicyTaskResult(); if (arg.shutdownPolicy() != null) ignite.cluster().shutdownPolicy(arg.shutdownPolicy()); res.setShutdown(ignite.cluster().shutdownPolicy()); return res;
184
75
259
<methods>public non-sealed void <init>() <variables>
apache_ignite
ignite/modules/core/src/main/java/org/apache/ignite/internal/management/baseline/AbstractBaselineCommand.java
AbstractBaselineCommand
printResult
class AbstractBaselineCommand implements ComputeCommand<BaselineTaskArg, BaselineTaskResult> { /** {@inheritDoc} */ @Override public Class<BaselineTask> taskClass() { return BaselineTask.class; } /** {@inheritDoc} */ @Override public Collection<GridClientNode> nodes(Collection<GridClientNode> nodes, BaselineTaskArg arg) { return coordinatorOrNull(nodes); } /** {@inheritDoc} */ @Override public void printResult( BaselineTaskArg arg, BaselineTaskResult res, Consumer<String> printer ) {<FILL_FUNCTION_BODY>} }
printer.accept("Cluster state: " + res.clusterState()); printer.accept("Current topology version: " + res.getTopologyVersion()); BaselineAutoAdjustSettings autoAdjustSettings = res.getAutoAdjustSettings(); if (autoAdjustSettings != null) { printer.accept("Baseline auto adjustment " + (TRUE.equals(autoAdjustSettings.getEnabled()) ? "enabled" : "disabled") + ": softTimeout=" + autoAdjustSettings.getSoftTimeout() ); } if (autoAdjustSettings.enabled) { if (res.isBaselineAdjustInProgress()) printer.accept("Baseline auto-adjust is in progress"); else if (res.getRemainingTimeToBaselineAdjust() < 0) printer.accept("Baseline auto-adjust are not scheduled"); else printer.accept("Baseline auto-adjust will happen in '" + res.getRemainingTimeToBaselineAdjust() + "' ms"); } printer.accept(""); Map<String, BaselineNode> baseline = res.getBaseline(); Map<String, BaselineNode> srvs = res.getServers(); // if task runs on a node with BaselineNode of old version (V1) we'll get order=null for all nodes. Function<BaselineNode, String> extractFormattedAddrs = node -> { Stream<String> sortedByIpHosts = Optional.ofNullable(node) .map(addrs -> node.getAddrs()) .orElse(Collections.emptyList()) .stream() .sorted(Comparator .comparing(resolvedAddr -> new VisorTaskUtils.SortableAddress(resolvedAddr.address()))) .map(resolvedAddr -> { if (!resolvedAddr.hostname().equals(resolvedAddr.address())) return resolvedAddr.hostname() + "/" + resolvedAddr.address(); else return resolvedAddr.address(); }); if (arg.verbose()) { String hosts = String.join(",", sortedByIpHosts.collect(Collectors.toList())); if (!hosts.isEmpty()) return ", Addresses=" + hosts; else return ""; } else return sortedByIpHosts.findFirst().map(ip -> ", Address=" + ip).orElse(""); }; String crdStr = srvs.values().stream() // check for not null .filter(node -> node.getOrder() != null) .min(Comparator.comparing(BaselineNode::getOrder)) // format .map(crd -> " (Coordinator: ConsistentId=" + crd.getConsistentId() + extractFormattedAddrs.apply(crd) + ", Order=" + crd.getOrder() + ")") .orElse(""); printer.accept("Current topology version: " + res.getTopologyVersion() + crdStr); printer.accept(""); if (F.isEmpty(baseline)) printer.accept("Baseline nodes not found."); else { printer.accept("Baseline nodes:"); for (BaselineNode node : baseline.values()) { BaselineNode srvNode = srvs.get(node.getConsistentId()); String state = ", State=" + (srvNode != null ? "ONLINE" : "OFFLINE"); String order = srvNode != null ? ", Order=" + srvNode.getOrder() : ""; printer.accept(DOUBLE_INDENT + "ConsistentId=" + node.getConsistentId() + extractFormattedAddrs.apply(srvNode) + state + order); } printer.accept(U.DELIM); printer.accept("Number of baseline nodes: " + baseline.size()); printer.accept(""); List<BaselineNode> others = new ArrayList<>(); for (BaselineNode node : srvs.values()) { if (!baseline.containsKey(node.getConsistentId())) others.add(node); } if (F.isEmpty(others)) printer.accept("Other nodes not found."); else { printer.accept("Other nodes:"); for (BaselineNode node : others) printer.accept(DOUBLE_INDENT + "ConsistentId=" + node.getConsistentId() + ", Order=" + node.getOrder()); printer.accept("Number of other nodes: " + others.size()); } }
167
1,151
1,318
<no_super_class>
apache_ignite
ignite/modules/core/src/main/java/org/apache/ignite/internal/management/baseline/BaselineAddCommand.java
BaselineAddCommand
confirmationPrompt
class BaselineAddCommand extends AbstractBaselineCommand { /** {@inheritDoc} */ @Override public String description() { return "Add nodes into baseline topology"; } /** {@inheritDoc} */ @Override public String confirmationPrompt(BaselineTaskArg arg) {<FILL_FUNCTION_BODY>} /** {@inheritDoc} */ @Override public Class<BaselineAddCommandArg> argClass() { return BaselineAddCommandArg.class; } }
return "Warning: the command will perform changes in baseline.";
122
18
140
<methods>public non-sealed void <init>() ,public Collection<org.apache.ignite.internal.client.GridClientNode> nodes(Collection<org.apache.ignite.internal.client.GridClientNode>, org.apache.ignite.internal.management.baseline.BaselineCommand.BaselineTaskArg) ,public void printResult(org.apache.ignite.internal.management.baseline.BaselineCommand.BaselineTaskArg, org.apache.ignite.internal.management.baseline.BaselineTaskResult, Consumer<java.lang.String>) ,public Class<org.apache.ignite.internal.management.baseline.BaselineTask> taskClass() <variables>
apache_ignite
ignite/modules/core/src/main/java/org/apache/ignite/internal/management/baseline/BaselineAutoAdjustCommand.java
BaselineAutoAdjustCommand
confirmationPrompt
class BaselineAutoAdjustCommand extends AbstractBaselineCommand { /** {@inheritDoc} */ @Override public String description() { return "Set baseline autoadjustment settings"; } /** {@inheritDoc} */ @Override public String confirmationPrompt(BaselineTaskArg arg) {<FILL_FUNCTION_BODY>} /** {@inheritDoc} */ @Override public Class<BaselineAutoAdjustCommandArg> argClass() { return BaselineAutoAdjustCommandArg.class; } }
return "Warning: the command will perform changes in baseline.";
130
18
148
<methods>public non-sealed void <init>() ,public Collection<org.apache.ignite.internal.client.GridClientNode> nodes(Collection<org.apache.ignite.internal.client.GridClientNode>, org.apache.ignite.internal.management.baseline.BaselineCommand.BaselineTaskArg) ,public void printResult(org.apache.ignite.internal.management.baseline.BaselineCommand.BaselineTaskArg, org.apache.ignite.internal.management.baseline.BaselineTaskResult, Consumer<java.lang.String>) ,public Class<org.apache.ignite.internal.management.baseline.BaselineTask> taskClass() <variables>
apache_ignite
ignite/modules/core/src/main/java/org/apache/ignite/internal/management/baseline/BaselineAutoAdjustCommandArg.java
BaselineAutoAdjustCommandArg
readExternalData
class BaselineAutoAdjustCommandArg extends BaselineTaskArg { /** */ private static final long serialVersionUID = 0; /** */ @Positional @Argument(optional = true) @EnumDescription( names = { "ENABLE", "DISABLE" }, descriptions = { "Enable baseline auto adjust", "Disable baseline auto adjust" } ) private Enabled enabled; /** */ @Argument(optional = true, example = "<timeoutMillis>", withoutPrefix = true) private Long timeout; /** */ public enum Enabled { /** */ DISABLE, /** */ ENABLE } /** {@inheritDoc} */ @Override protected void writeExternalData(ObjectOutput out) throws IOException { super.writeExternalData(out); U.writeEnum(out, enabled); out.writeObject(timeout); } /** {@inheritDoc} */ @Override protected void readExternalData(byte protoVer, ObjectInput in) throws IOException, ClassNotFoundException {<FILL_FUNCTION_BODY>} /** */ public Enabled enabled() { return enabled; } /** */ public void enabled(Enabled enabled) { this.enabled = enabled; } /** */ public Long timeout() { return timeout; } /** */ public void timeout(Long timeout) { this.timeout = timeout; } }
super.readExternalData(protoVer, in); enabled = U.readEnum(in, Enabled.class); timeout = (Long)in.readObject();
378
45
423
<methods>public non-sealed void <init>() ,public boolean verbose() ,public void verbose(boolean) <variables>private boolean verbose
apache_ignite
ignite/modules/core/src/main/java/org/apache/ignite/internal/management/baseline/BaselineCommand.java
BaselineCommand
printResult
class BaselineCommand extends CommandRegistryImpl<BaselineTaskArg, BaselineTaskResult> implements ComputeCommand<BaselineTaskArg, BaselineTaskResult> { /** {@inheritDoc} */ @Override public String description() { return "Print cluster baseline topology"; } /** */ public BaselineCommand() { super( new BaselineAddCommand(), new BaselineRemoveCommand(), new BaselineSetCommand(), new BaselineVersionCommand(), new BaselineAutoAdjustCommand() ); } /** {@inheritDoc} */ @Override public Class<BaselineCommandArg> argClass() { return BaselineCommandArg.class; } /** {@inheritDoc} */ @Override public Class<BaselineTask> taskClass() { return BaselineTask.class; } /** {@inheritDoc} */ @Override public Collection<GridClientNode> nodes(Collection<GridClientNode> nodes, BaselineTaskArg arg) { return coordinatorOrNull(nodes); } /** {@inheritDoc} */ @Override public void printResult(BaselineTaskArg arg, BaselineTaskResult res, Consumer<String> printer) {<FILL_FUNCTION_BODY>} /** */ public abstract static class BaselineTaskArg extends IgniteDataTransferObject { /** */ @Argument(optional = true, description = "Show the full list of node ips") private boolean verbose; /** {@inheritDoc} */ @Override protected void writeExternalData(ObjectOutput out) throws IOException { out.writeBoolean(verbose); } /** {@inheritDoc} */ @Override protected void readExternalData(byte protoVer, ObjectInput in) throws IOException, ClassNotFoundException { verbose = in.readBoolean(); } /** */ public boolean verbose() { return verbose; } /** */ public void verbose(boolean verbose) { this.verbose = verbose; } } }
new AbstractBaselineCommand() { @Override public String description() { return null; } @Override public Class<? extends BaselineTaskArg> argClass() { return null; } }.printResult(arg, res, printer);
504
69
573
<methods>public Command<?,?> command(java.lang.String) ,public Iterator<Entry<java.lang.String,Command<?,?>>> commands() <variables>private final Map<java.lang.String,Command<?,?>> commands
apache_ignite
ignite/modules/core/src/main/java/org/apache/ignite/internal/management/cache/CacheConfigurationCollectorTaskArg.java
CacheConfigurationCollectorTaskArg
readExternalData
class CacheConfigurationCollectorTaskArg extends VisorDataTransferObject { /** */ private static final long serialVersionUID = 0L; /** Collection of cache names. */ private Collection<String> cacheNames; /** Cache name regexp. */ private String regex; /** * Default constructor. */ public CacheConfigurationCollectorTaskArg() { // No-op. } /** * @param cacheNames Collection of cache names. */ public CacheConfigurationCollectorTaskArg(Collection<String> cacheNames) { this.cacheNames = cacheNames; } /** * @param regex Cache name regexp. */ public CacheConfigurationCollectorTaskArg(String regex) { // Checks, that regex is correct. Pattern.compile(regex); this.regex = regex; } /** * @return Collection of cache deployment IDs. */ public Collection<String> getCacheNames() { return cacheNames; } /** * @return Cache name regexp. */ public String getRegex() { return regex; } /** {@inheritDoc} */ @Override public byte getProtocolVersion() { return V2; } /** {@inheritDoc} */ @Override protected void writeExternalData(ObjectOutput out) throws IOException { U.writeCollection(out, cacheNames); U.writeString(out, regex); } /** {@inheritDoc} */ @Override protected void readExternalData(byte protoVer, ObjectInput in) throws IOException, ClassNotFoundException {<FILL_FUNCTION_BODY>} /** {@inheritDoc} */ @Override public String toString() { return S.toString(CacheConfigurationCollectorTaskArg.class, this); } }
cacheNames = U.readCollection(in); if (protoVer > V1) regex = U.readString(in);
460
37
497
<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,private static final long serialVersionUID
apache_ignite
ignite/modules/core/src/main/java/org/apache/ignite/internal/management/cache/CacheEvictionConfiguration.java
CacheEvictionConfiguration
readExternalData
class CacheEvictionConfiguration extends VisorDataTransferObject { /** */ private static final long serialVersionUID = 0L; /** Eviction policy. */ private String plc; /** Cache eviction policy max size. */ private Integer plcMaxSize; /** Eviction filter to specify which entries should not be evicted. */ private String filter; /** * Default constructor. */ public CacheEvictionConfiguration() { // No-op. } /** * Create data transfer object for eviction configuration properties. * @param ccfg Cache configuration. */ public CacheEvictionConfiguration(CacheConfiguration ccfg) { final Factory evictionPlc = ccfg.getEvictionPolicyFactory(); plc = compactClass(evictionPlc); plcMaxSize = evictionPolicyMaxSize(evictionPlc); filter = compactClass(ccfg.getEvictionFilter()); } /** * @return Eviction policy. */ @Nullable public String getPolicy() { return plc; } /** * @return Cache eviction policy max size. */ @Nullable public Integer getPolicyMaxSize() { return plcMaxSize; } /** * @return Eviction filter to specify which entries should not be evicted. */ @Nullable public String getFilter() { return filter; } /** {@inheritDoc} */ @Override protected void writeExternalData(ObjectOutput out) throws IOException { U.writeString(out, plc); out.writeObject(plcMaxSize); U.writeString(out, filter); } /** {@inheritDoc} */ @Override protected void readExternalData(byte protoVer, ObjectInput in) throws IOException, ClassNotFoundException {<FILL_FUNCTION_BODY>} /** {@inheritDoc} */ @Override public String toString() { return S.toString(CacheEvictionConfiguration.class, this); } }
plc = U.readString(in); plcMaxSize = (Integer)in.readObject(); filter = U.readString(in);
506
41
547
<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,private static final long serialVersionUID
apache_ignite
ignite/modules/core/src/main/java/org/apache/ignite/internal/management/cache/CacheFindGarbageCommand.java
CacheFindGarbageCommand
printResult
class CacheFindGarbageCommand implements ComputeCommand<CacheFindGarbageCommandArg, FindAndDeleteGarbageInPersistenceTaskResult> { /** {@inheritDoc} */ @Override public String description() { return "Find and optionally delete garbage from shared cache groups which could be left after cache destroy"; } /** {@inheritDoc} */ @Override public Class<CacheFindGarbageCommandArg> argClass() { return CacheFindGarbageCommandArg.class; } /** {@inheritDoc} */ @Override public Class<FindAndDeleteGarbageInPersistenceTask> taskClass() { return FindAndDeleteGarbageInPersistenceTask.class; } /** {@inheritDoc} */ @Override public void printResult( CacheFindGarbageCommandArg arg, FindAndDeleteGarbageInPersistenceTaskResult res, Consumer<String> printer ) {<FILL_FUNCTION_BODY>} }
CommandUtils.printErrors(res.exceptions(), "Scanning for garbage failed on nodes:", printer); for (Map.Entry<UUID, FindAndDeleteGarbageInPersistenceJobResult> nodeEntry : res.result().entrySet()) { if (!nodeEntry.getValue().hasGarbage()) { printer.accept("Node " + nodeEntry.getKey() + " - garbage not found."); continue; } printer.accept("Garbage found on node " + nodeEntry.getKey() + ":"); FindAndDeleteGarbageInPersistenceJobResult val = nodeEntry.getValue(); Map<Integer, Map<Integer, Long>> grpPartErrorsCnt = val.checkResult(); if (!grpPartErrorsCnt.isEmpty()) { for (Map.Entry<Integer, Map<Integer, Long>> entry : grpPartErrorsCnt.entrySet()) { for (Map.Entry<Integer, Long> e : entry.getValue().entrySet()) { printer.accept(INDENT + "Group=" + entry.getKey() + ", partition=" + e.getKey() + ", count of keys=" + e.getValue()); } } } printer.accept(""); }
242
310
552
<no_super_class>
apache_ignite
ignite/modules/core/src/main/java/org/apache/ignite/internal/management/cache/CacheIdleVerifyDumpCommand.java
CacheIdleVerifyDumpCommand
printResult
class CacheIdleVerifyDumpCommand implements ComputeCommand<CacheIdleVerifyCommandArg, String> { /** {@inheritDoc} */ @Override public String description() { return "Calculate partition hash and print into standard output"; } /** {@inheritDoc} */ @Override public Class<CacheIdleVerifyDumpCommandArg> argClass() { return CacheIdleVerifyDumpCommandArg.class; } /** {@inheritDoc} */ @Override public Class<IdleVerifyDumpTask> taskClass() { return IdleVerifyDumpTask.class; } /** {@inheritDoc} */ @Override public void printResult(CacheIdleVerifyCommandArg arg, String path, Consumer<String> printer) {<FILL_FUNCTION_BODY>} }
printer.accept("IdleVerifyDumpTask successfully written output to '" + path + "'"); logParsedArgs(arg, printer);
197
37
234
<no_super_class>
apache_ignite
ignite/modules/core/src/main/java/org/apache/ignite/internal/management/cache/CacheListCommandArg.java
CacheListCommandArg
writeExternalData
class CacheListCommandArg extends IgniteDataTransferObject { /** */ private static final long serialVersionUID = 0; /** */ @Positional @Argument(example = "regexPattern") private String regex; /** */ @Argument(description = "print all configuration parameters for each cache", optional = true) private boolean config; /** */ @Positional @Argument(optional = true, example = "nodeId") private UUID nodeId; /** */ @Argument(description = "print configuration parameters per line. " + "This option has effect only when used with --config and without [--groups|--seq]", example = "multi-line", optional = true) private String outputFormat; /** */ @Argument(description = "print information about groups") private boolean groups; /** */ @Argument(description = "print information about sequences") private boolean seq; /** {@inheritDoc} */ @Override protected void writeExternalData(ObjectOutput out) throws IOException {<FILL_FUNCTION_BODY>} /** {@inheritDoc} */ @Override protected void readExternalData(byte protoVer, ObjectInput in) throws IOException, ClassNotFoundException { regex = U.readString(in); config = in.readBoolean(); nodeId = U.readUuid(in); outputFormat = U.readString(in); groups = in.readBoolean(); seq = in.readBoolean(); } /** */ public String regex() { return regex; } /** */ public void regex(String regex) { this.regex = regex; } /** */ public boolean groups() { return groups; } /** */ public void groups(boolean groups) { this.groups = groups; } /** */ public boolean seq() { return seq; } /** */ public void seq(boolean seq) { this.seq = seq; } /** */ public String outputFormat() { return outputFormat; } /** */ public void outputFormat(String outputFormat) { this.outputFormat = outputFormat; } /** */ public boolean config() { return config; } /** */ public void config(boolean config) { this.config = config; } /** */ public UUID nodeId() { return nodeId; } /** */ public void nodeId(UUID nodeId) { this.nodeId = nodeId; } }
U.writeString(out, regex); out.writeBoolean(config); U.writeUuid(out, nodeId); U.writeString(out, outputFormat); out.writeBoolean(groups); out.writeBoolean(seq);
667
66
733
<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/management/cache/CacheRebalanceConfiguration.java
CacheRebalanceConfiguration
readExternalData
class CacheRebalanceConfiguration extends VisorDataTransferObject { /** */ private static final long serialVersionUID = 0L; /** Cache rebalance mode. */ private CacheRebalanceMode mode; /** Cache rebalance batch size. */ private int batchSize; /** Rebalance partitioned delay. */ private long partitionedDelay; /** Time in milliseconds to wait between rebalance messages. */ private long throttle; /** Rebalance timeout. */ private long timeout; /** Rebalance batches prefetch count. */ private long batchesPrefetchCnt; /** Cache rebalance order. */ private int rebalanceOrder; /** * Default constructor. */ public CacheRebalanceConfiguration() { // No-op. } /** * Create data transfer object for rebalance configuration properties. * @param ccfg Cache configuration. */ public CacheRebalanceConfiguration(CacheConfiguration ccfg) { mode = ccfg.getRebalanceMode(); batchSize = ccfg.getRebalanceBatchSize(); partitionedDelay = ccfg.getRebalanceDelay(); throttle = ccfg.getRebalanceThrottle(); timeout = ccfg.getRebalanceTimeout(); batchesPrefetchCnt = ccfg.getRebalanceBatchesPrefetchCount(); rebalanceOrder = ccfg.getRebalanceOrder(); } /** * @return Cache rebalance mode. */ public CacheRebalanceMode getMode() { return mode; } /** * @return Cache rebalance batch size. */ public int getBatchSize() { return batchSize; } /** * @return Rebalance partitioned delay. */ public long getPartitionedDelay() { return partitionedDelay; } /** * @return Time in milliseconds to wait between rebalance messages. */ public long getThrottle() { return throttle; } /** * @return Rebalance timeout. */ public long getTimeout() { return timeout; } /** * @return Batches count */ public long getBatchesPrefetchCnt() { return batchesPrefetchCnt; } /** * @return Cache rebalance order. */ public int getRebalanceOrder() { return rebalanceOrder; } /** {@inheritDoc} */ @Override protected void writeExternalData(ObjectOutput out) throws IOException { U.writeEnum(out, mode); out.writeInt(batchSize); out.writeLong(partitionedDelay); out.writeLong(throttle); out.writeLong(timeout); out.writeLong(batchesPrefetchCnt); out.writeInt(rebalanceOrder); } /** {@inheritDoc} */ @Override protected void readExternalData(byte protoVer, ObjectInput in) throws IOException, ClassNotFoundException {<FILL_FUNCTION_BODY>} /** {@inheritDoc} */ @Override public String toString() { return S.toString(CacheRebalanceConfiguration.class, this); } }
mode = CacheRebalanceMode.fromOrdinal(in.readByte()); batchSize = in.readInt(); partitionedDelay = in.readLong(); throttle = in.readLong(); timeout = in.readLong(); batchesPrefetchCnt = in.readLong(); rebalanceOrder = in.readInt();
812
88
900
<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,private static final long serialVersionUID
apache_ignite
ignite/modules/core/src/main/java/org/apache/ignite/internal/management/cache/CacheScanCommand.java
CacheScanCommand
printResult
class CacheScanCommand implements ComputeCommand<CacheScanCommandArg, CacheScanTaskResult> { /** {@inheritDoc} */ @Override public String description() { return "Show cache content"; } /** {@inheritDoc} */ @Override public Class<CacheScanCommandArg> argClass() { return CacheScanCommandArg.class; } /** {@inheritDoc} */ @Override public Class<CacheScanTask> taskClass() { return CacheScanTask.class; } /** {@inheritDoc} */ @Override public void printResult(CacheScanCommandArg arg, CacheScanTaskResult res, Consumer<String> printer) {<FILL_FUNCTION_BODY>} }
List<SystemViewTask.SimpleType> types = res.titles().stream() .map(x -> SystemViewTask.SimpleType.STRING).collect(Collectors.toList()); SystemViewCommand.printTable(res.titles(), types, res.entries(), printer); if (res.entries().size() == arg.limit()) printer.accept("Result limited to " + arg.limit() + " rows. Limit can be changed with '--limit' argument.");
175
120
295
<no_super_class>
apache_ignite
ignite/modules/core/src/main/java/org/apache/ignite/internal/management/cache/CacheScanTask.java
CacheScanJob
binaryToString
class CacheScanJob extends VisorJob<CacheScanCommandArg, CacheScanTaskResult> { /** */ private static final long serialVersionUID = 0L; /** * Create job. * * @param arg Task argument. * @param debug Debug flag. */ private CacheScanJob(CacheScanCommandArg arg, boolean debug) { super(arg, debug); } /** {@inheritDoc} */ @Override protected CacheScanTaskResult run(CacheScanCommandArg arg) { if (F.isEmpty(arg.cacheName())) throw new IllegalStateException("Cache name was not specified."); if (arg.limit() <= 0) throw new IllegalStateException("Invalid limit value."); IgniteCache<Object, Object> cache = ignite.cache(arg.cacheName()).withKeepBinary(); List<String> titles = Arrays.asList("Key Class", "Key", "Value Class", "Value"); int cnt = 0; List<List<?>> entries = new ArrayList<>(); ScanQuery<Object, Object> scanQry = new ScanQuery<>().setPageSize(min(arg.limit(), DFLT_PAGE_SIZE)); try (QueryCursor<Cache.Entry<Object, Object>> qry = cache.query(scanQry)) { Iterator<Cache.Entry<Object, Object>> iter = qry.iterator(); while (cnt++ < arg.limit() && iter.hasNext()) { Cache.Entry<Object, Object> next = iter.next(); Object k = next.getKey(); Object v = next.getValue(); entries.add(Arrays.asList(typeOf(k), valueOf(k), typeOf(v), valueOf(v))); } } return new CacheScanTaskResult(titles, entries); } /** {@inheritDoc} */ @Override public SecurityPermissionSet requiredPermissions() { // This task does nothing but delegates the call to the Ignite public API. // Therefore, it is safe to execute task without any additional permissions check. return NO_PERMISSIONS; } /** * @param o Source object. * @return String representation of object class. */ private static String typeOf(Object o) { if (o != null) { Class<?> clazz = o.getClass(); return clazz.isArray() ? IgniteUtils.compact(clazz.getComponentType().getName()) + "[]" : IgniteUtils.compact(o.getClass().getName()); } else return "n/a"; } /** * @param o Object. * @return String representation of value. */ private static String valueOf(Object o) { if (o == null) return "null"; if (o instanceof byte[]) return "size=" + ((byte[])o).length; if (o instanceof Byte[]) return "size=" + ((Byte[])o).length; if (o instanceof Object[]) { return "size=" + ((Object[])o).length + ", values=[" + S.joinToString(Arrays.asList((Object[])o), ", ", "...", 120, 0) + "]"; } if (o instanceof BinaryObject) return binaryToString((BinaryObject)o); return o.toString(); } /** * Convert Binary object to string. * * @param obj Binary object. * @return String representation of Binary object. */ public static String binaryToString(BinaryObject obj) {<FILL_FUNCTION_BODY>} /** {@inheritDoc} */ @Override public String toString() { return S.toString(CacheScanJob.class, this); } }
int hash = obj.hashCode(); if (obj instanceof BinaryObjectEx) { BinaryObjectEx objEx = (BinaryObjectEx)obj; BinaryType meta; try { meta = ((BinaryObjectEx)obj).rawType(); } catch (BinaryObjectException ignore) { meta = null; } if (meta != null) { if (meta.isEnum()) { try { return obj.deserialize().toString(); } catch (BinaryObjectException ignore) { // NO-op. } } SB buf = new SB(meta.typeName()); if (meta.fieldNames() != null) { buf.a(" [hash=").a(hash); for (String name : meta.fieldNames()) { Object val = objEx.field(name); buf.a(", ").a(name).a('=').a(val); } buf.a(']'); return buf.toString(); } } } return S.toString(obj.getClass().getSimpleName(), "hash", hash, false, "typeId", obj.type().typeId(), true);
965
316
1,281
<methods>public non-sealed void <init>() <variables>
apache_ignite
ignite/modules/core/src/main/java/org/apache/ignite/internal/management/cache/CacheScheduleIndexesRebuildCommand.java
CacheScheduleIndexesRebuildCommand
description
class CacheScheduleIndexesRebuildCommand implements ComputeCommand<CacheScheduleIndexesRebuildCommandArg, ScheduleIndexRebuildTaskRes> { /** */ public static final String PREF_INDEXES_NOT_FOUND = "WARNING: These indexes were not found:"; /** */ public static final String PREF_REBUILD_NOT_SCHEDULED = "WARNING: Indexes rebuild was not scheduled for any cache. " + "Check command input."; /** */ public static final String PREF_REBUILD_NOT_SCHEDULED_MULTI = "WARNING: Indexes rebuild was not scheduled for " + "any cache on the following nodes. Check command input:"; /** {@inheritDoc} */ @Override public String description() {<FILL_FUNCTION_BODY>} /** {@inheritDoc} */ @Override public Class<CacheScheduleIndexesRebuildCommandArg> argClass() { return CacheScheduleIndexesRebuildCommandArg.class; } /** {@inheritDoc} */ @Override public Class<ScheduleIndexRebuildTask> taskClass() { return ScheduleIndexRebuildTask.class; } /** {@inheritDoc} */ @Override public Collection<GridClientNode> nodes(Collection<GridClientNode> nodes, CacheScheduleIndexesRebuildCommandArg arg) { if (arg.allNodes() || F.isEmpty(arg.nodeIds()) && arg.nodeId() == null) return nodes; nodeOrAll(arg.nodeId(), nodes); return CommandUtils.nodes(arg.nodeId() == null ? arg.nodeIds() : new UUID[] {arg.nodeId()}, nodes); } /** {@inheritDoc} */ @Override public void printResult( CacheScheduleIndexesRebuildCommandArg arg, ScheduleIndexRebuildTaskRes results, Consumer<String> printer ) { if (arg.nodeId() != null) { printSingleResult(results, printer); return; } Map<String, Set<UUID>> missedCaches = new HashMap<>(); Map<String, Set<UUID>> missedGrps = new HashMap<>(); Map<String, Set<UUID>> notFoundIndexes = new HashMap<>(); Map<String, Set<UUID>> scheduled = new HashMap<>(); Set<UUID> notScheduled = new HashSet<>(); results.results().forEach((nodeId, res) -> { storeEntryToNodesResults(missedCaches, res.notFoundCacheNames(), nodeId); storeEntryToNodesResults(missedGrps, res.notFoundGroupNames(), nodeId); storeEntryToNodesResults(notFoundIndexes, extractCacheIndexNames(res.notFoundIndexes()), nodeId); if (hasAtLeastOneIndex(res.cacheToIndexes())) storeEntryToNodesResults(scheduled, extractCacheIndexNames(res.cacheToIndexes()), nodeId); else notScheduled.add(nodeId); }); SB b = new SB(); if (!F.isEmpty(missedCaches)) printBlock(b, PREF_CACHES_NOT_FOUND, missedCaches, GridStringBuilder::a); if (!F.isEmpty(missedGrps)) printBlock(b, PREF_GROUPS_NOT_FOUND, missedGrps, GridStringBuilder::a); if (!F.isEmpty(notFoundIndexes)) printBlock(b, PREF_INDEXES_NOT_FOUND, notFoundIndexes, GridStringBuilder::a); if (!F.isEmpty(notScheduled)) { printHeader(b, PREF_REBUILD_NOT_SCHEDULED_MULTI); printEntryNewLine(b); b.a(nodeIdsString(notScheduled)); } if (!F.isEmpty(scheduled)) printBlock(b, PREF_SCHEDULED, scheduled, GridStringBuilder::a); printer.accept(b.toString().trim()); } /** */ private static Collection<String> extractCacheIndexNames(Map<String, Set<String>> cacheIndexes) { return F.flatCollections(cacheIndexes.entrySet().stream().map(cIdxs -> cIdxs.getValue().stream() .map(idx -> indexAndCacheInfo(cIdxs.getKey(), idx)).collect(Collectors.toList())).collect(Collectors.toList())); } /** */ private static String indexAndCacheInfo(String cache, String index) { return '\'' + index + "' (of cache '" + cache + "')"; } /** */ private static void printSingleResult(ScheduleIndexRebuildTaskRes result, Consumer<String> printer) { result.results().forEach((nodeId, res) -> { printMissed(printer, PREF_CACHES_NOT_FOUND, res.notFoundCacheNames()); printMissed(printer, PREF_GROUPS_NOT_FOUND, res.notFoundGroupNames()); if (hasAtLeastOneIndex(res.notFoundIndexes())) { printer.accept(PREF_INDEXES_NOT_FOUND); printCachesAndIndexes(res.notFoundIndexes(), printer); } if (!F.isEmpty(res.cacheToIndexes()) && hasAtLeastOneIndex(res.cacheToIndexes())) { printer.accept(PREF_SCHEDULED); printCachesAndIndexes(res.cacheToIndexes(), printer); } else printer.accept(PREF_REBUILD_NOT_SCHEDULED); printer.accept(""); }); } /** * Prints missed caches' or cache groups' names. * * @param printer Printer. * @param message Message. * @param missed Missed caches or cache groups' names. */ private static void printMissed(Consumer<String> printer, String message, Set<String> missed) { if (F.isEmpty(missed)) return; printer.accept(message); missed.stream() .sorted() .forEach(name -> printer.accept(INDENT + name)); printer.accept(""); } /** * Prints caches and their indexes. * * @param cachesToIndexes Cache -> indexes map. * @param printer Printer. */ private static void printCachesAndIndexes(Map<String, Set<String>> cachesToIndexes, Consumer<String> printer) { cachesToIndexes.forEach((cacheName, indexes) -> { printer.accept(INDENT + cacheName + ":"); indexes.forEach(index -> printer.accept(INDENT + INDENT + index)); }); } /** * @param cacheToIndexes Cache name -> indexes map. * @return {@code true} if has at least one index in the map, {@code false} otherwise. */ private static boolean hasAtLeastOneIndex(Map<String, Set<String>> cacheToIndexes) { return !F.isEmpty(cacheToIndexes) && cacheToIndexes.values().stream() .anyMatch(indexes -> !indexes.isEmpty()); } /** */ static <T> void storeCacheAndIndexResults(Map<IgnitePair<T>, Set<UUID>> to, Map<T, Set<T>> values, UUID nodeId) { if (F.isEmpty(values)) return; values.forEach((cache, indexes) -> indexes.forEach(idx -> to.compute(new IgnitePair<>(cache, idx), (c0, idxs0) -> { if (idxs0 == null) idxs0 = new HashSet<>(); idxs0.add(nodeId); return idxs0; }))); } }
return "Schedules rebuild of the indexes for specified caches via the Maintenance Mode. " + "Schedules rebuild of specified caches and cache-groups";
1,996
40
2,036
<no_super_class>
apache_ignite
ignite/modules/core/src/main/java/org/apache/ignite/internal/management/cache/CacheValidateIndexesCommandArg.java
CacheValidateIndexesCommandArg
parse
class CacheValidateIndexesCommandArg extends IgniteDataTransferObject { /** */ private static final long serialVersionUID = 0; /** */ @Positional @Argument(example = "cacheName1,...,cacheNameN", optional = true) private String value; /** */ @Positional @Argument(example = "nodeId", optional = true) private String value2; /** */ private String[] caches; /** */ private UUID[] nodeIds; /** */ @Argument(example = "N", description = "validate only the first N keys", optional = true) private int checkFirst = -1; /** */ @Argument(example = "K", description = "validate every Kth key", optional = true) private int checkThrough = -1; /** */ @Argument(description = "check the CRC-sum of pages stored on disk", optional = true) private boolean checkCrc; /** */ @Argument(description = "check that index size and cache size are the same", optional = true) private boolean checkSizes; /** */ private static void ensurePositive(int numVal, String arg) { if (numVal <= 0) throw new IllegalArgumentException("Value for '" + arg + "' property should be positive."); } /** */ private void parse(String value) {<FILL_FUNCTION_BODY>} /** {@inheritDoc} */ @Override protected void writeExternalData(ObjectOutput out) throws IOException { U.writeString(out, value); U.writeString(out, value2); U.writeArray(out, caches); U.writeArray(out, nodeIds); out.writeInt(checkFirst); out.writeInt(checkThrough); out.writeBoolean(checkCrc); out.writeBoolean(checkSizes); } /** {@inheritDoc} */ @Override protected void readExternalData(byte protoVer, ObjectInput in) throws IOException, ClassNotFoundException { value = U.readString(in); value2 = U.readString(in); caches = U.readArray(in, String.class); nodeIds = U.readArray(in, UUID.class); checkFirst = in.readInt(); checkThrough = in.readInt(); checkCrc = in.readBoolean(); checkSizes = in.readBoolean(); } /** */ public String value2() { return value2; } /** */ public void value2(String value2) { this.value2 = value2; parse(value2); } /** */ public String value() { return value; } /** */ public void value(String value) { this.value = value; parse(value); } /** */ public UUID[] nodeIds() { return nodeIds; } /** */ public void nodeIds(UUID[] nodeIds) { this.nodeIds = nodeIds; } /** */ public String[] caches() { return caches; } /** */ public void caches(String[] caches) { this.caches = caches; } /** */ public int checkFirst() { return checkFirst; } /** */ public void checkFirst(int checkFirst) { if (this.checkFirst == checkFirst) return; ensurePositive(checkFirst, "--check-first"); this.checkFirst = checkFirst; } /** */ public int checkThrough() { return checkThrough; } /** */ public void checkThrough(int checkThrough) { if (this.checkThrough == checkThrough) return; ensurePositive(checkThrough, "--check-through"); this.checkThrough = checkThrough; } /** */ public boolean checkCrc() { return checkCrc; } /** */ public void checkCrc(boolean checkCrc) { this.checkCrc = checkCrc; } /** */ public boolean checkSizes() { return checkSizes; } /** */ public void checkSizes(boolean checkSizes) { this.checkSizes = checkSizes; } }
try { nodeIds = CommandUtils.parseVal(value, UUID[].class); return; } catch (IllegalArgumentException ignored) { //No-op. } caches = CommandUtils.parseVal(value, String[].class);
1,118
72
1,190
<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/management/cache/ContentionClosure.java
ContentionClosure
call
class ContentionClosure implements IgniteCallable<ContentionInfo> { /** Serial version uid. */ private static final long serialVersionUID = 0L; /** Ignite. */ @IgniteInstanceResource protected transient IgniteEx ignite; /** */ private int minQueueSize; /** */ private int maxPrint; /** * @param minQueueSize Min candidate queue size to account. * @param maxPrint Max entries to print. */ public ContentionClosure(int minQueueSize, int maxPrint) { this.minQueueSize = minQueueSize; this.maxPrint = maxPrint; } /** {@inheritDoc} */ @Override public ContentionInfo call() throws Exception {<FILL_FUNCTION_BODY>} }
final IgniteTxManager tm = ignite.context().cache().context().tm(); final Collection<IgniteInternalTx> activeTxs = tm.activeTransactions(); ContentionInfo ci = new ContentionInfo(); ci.setNode(ignite.localNode()); ci.setEntries(new ArrayList<>()); for (IgniteInternalTx tx : activeTxs) { if (ci.getEntries().size() == maxPrint) break; // Show only primary txs. if (tx.local()) { IgniteTxLocalAdapter tx0 = (IgniteTxLocalAdapter)tx; final IgniteTxLocalState state0 = tx0.txState(); if (!(state0 instanceof IgniteTxStateImpl)) continue; final IgniteTxStateImpl state = (IgniteTxStateImpl)state0; final Collection<IgniteTxEntry> entries = state.allEntriesCopy(); IgniteTxEntry bad = null; int qSize = 0; for (IgniteTxEntry entry : entries) { Collection<GridCacheMvccCandidate> locs; GridCacheEntryEx cached = entry.cached(); while (true) { try { locs = cached.localCandidates(); break; } catch (GridCacheEntryRemovedException ignored) { cached = entry.context().cache().entryEx(entry.key()); } } if (locs != null) qSize += locs.size(); final Collection<GridCacheMvccCandidate> rmts = cached.remoteMvccSnapshot(); if (rmts != null) qSize += rmts.size(); if (qSize >= minQueueSize) { bad = entry; break; } else qSize = 0; } if (bad != null) { StringBuilder b = new StringBuilder(); b.append("TxEntry [cacheId=").append(bad.cacheId()). append(", key=").append(bad.key()). append(", queue=").append(qSize). append(", op=").append(bad.op()). append(", val=").append(bad.value()). append(", tx=").append(CU.txString(tx)). append(", other=["); final IgniteTxState st = tx.txState(); if (st instanceof IgniteTxStateImpl) { IgniteTxStateImpl st0 = (IgniteTxStateImpl)st; final Collection<IgniteTxEntry> cp = st0.allEntriesCopy(); for (IgniteTxEntry entry : cp) { if (entry == bad) continue; b.append(entry.toString()).append('\n'); } } b.append("]]"); ci.getEntries().add(b.toString()); } } } return ci;
204
755
959
<no_super_class>
apache_ignite
ignite/modules/core/src/main/java/org/apache/ignite/internal/management/cache/FindAndDeleteGarbageInPersistenceTask.java
FindAndDeleteGarbageInPersistenceJob
run
class FindAndDeleteGarbageInPersistenceJob extends VisorJob<CacheFindGarbageCommandArg, FindAndDeleteGarbageInPersistenceJobResult> { /** */ private static final long serialVersionUID = 0L; /** * @param arg Argument. * @param debug Debug. */ protected FindAndDeleteGarbageInPersistenceJob(CacheFindGarbageCommandArg arg, boolean debug) { super(arg, debug); } /** {@inheritDoc} */ @Override protected FindAndDeleteGarbageInPersistenceJobResult run(CacheFindGarbageCommandArg arg) throws IgniteException {<FILL_FUNCTION_BODY>} /** {@inheritDoc} */ @Override public String toString() { return S.toString(FindAndDeleteGarbageInPersistenceJob.class, this); } }
try { FindAndDeleteGarbageInPersistenceClosure closure = new FindAndDeleteGarbageInPersistenceClosure(arg.groups(), arg.delete()); ignite.context().resource().injectGeneric(closure); return closure.call(); } catch (Exception e) { throw new IgniteException(e); }
221
95
316
<methods>public non-sealed void <init>() ,public Map<? extends org.apache.ignite.compute.ComputeJob,org.apache.ignite.cluster.ClusterNode> map(List<org.apache.ignite.cluster.ClusterNode>, VisorTaskArgument<org.apache.ignite.internal.management.cache.CacheFindGarbageCommandArg>) ,public final org.apache.ignite.internal.management.cache.FindAndDeleteGarbageInPersistenceTaskResult 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 boolean debug,protected transient org.apache.ignite.internal.IgniteEx ignite,protected long start,protected org.apache.ignite.internal.management.cache.CacheFindGarbageCommandArg taskArg
apache_ignite
ignite/modules/core/src/main/java/org/apache/ignite/internal/management/cache/IndexForceRebuildTask.java
IndexForceRebuildJob
run
class IndexForceRebuildJob extends VisorJob<CacheIndexesForceRebuildCommandArg, IndexForceRebuildTaskRes> { /** */ private static final long serialVersionUID = 0L; /** * Create job with specified argument. * * @param arg Job argument. * @param debug Flag indicating whether debug information should be printed into node log. */ protected IndexForceRebuildJob(CacheIndexesForceRebuildCommandArg arg, boolean debug) { super(arg, debug); } /** {@inheritDoc} */ @Override protected IndexForceRebuildTaskRes run(CacheIndexesForceRebuildCommandArg arg) throws IgniteException {<FILL_FUNCTION_BODY>} }
assert (arg.cacheNames() == null) ^ (arg.groupNames() == null) : "Either cacheNames or cacheGroups must be specified."; Set<GridCacheContext> cachesToRebuild = new HashSet<>(); Set<String> notFound = new HashSet<>(); final GridCacheProcessor cacheProc = ignite.context().cache(); if (arg.cacheNames() != null) { for (String cacheName : arg.cacheNames()) { IgniteInternalCache cache = cacheProc.cache(cacheName); if (cache != null) cachesToRebuild.add(cache.context()); else notFound.add(cacheName); } } else { for (String cacheGrpName : arg.groupNames()) { CacheGroupContext grpCtx = cacheProc.cacheGroup(CU.cacheId(cacheGrpName)); if (grpCtx != null) cachesToRebuild.addAll(grpCtx.caches()); else notFound.add(cacheGrpName); } } Collection<GridCacheContext> cachesCtxWithRebuildingInProgress = ignite.context().cache().context().database().forceRebuildIndexes(cachesToRebuild); Set<IndexRebuildStatusInfoContainer> cachesWithRebuildingInProgress = cachesCtxWithRebuildingInProgress.stream() .map(IndexRebuildStatusInfoContainer::new) .collect(Collectors.toSet()); Set<IndexRebuildStatusInfoContainer> cachesWithStartedRebuild = cachesToRebuild.stream() .map(IndexRebuildStatusInfoContainer::new) .filter(c -> !cachesWithRebuildingInProgress.contains(c)) .collect(Collectors.toSet()); return new IndexForceRebuildTaskRes( cachesWithStartedRebuild, cachesWithRebuildingInProgress, notFound );
179
501
680
<methods>public non-sealed void <init>() ,public Map<? extends org.apache.ignite.compute.ComputeJob,org.apache.ignite.cluster.ClusterNode> map(List<org.apache.ignite.cluster.ClusterNode>, VisorTaskArgument<org.apache.ignite.internal.management.cache.CacheIndexesForceRebuildCommandArg>) ,public final Map<java.util.UUID,org.apache.ignite.internal.management.cache.IndexForceRebuildTaskRes> 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 boolean debug,protected transient org.apache.ignite.internal.IgniteEx ignite,protected long start,protected org.apache.ignite.internal.management.cache.CacheIndexesForceRebuildCommandArg taskArg
apache_ignite
ignite/modules/core/src/main/java/org/apache/ignite/internal/management/cache/IndexListTask.java
IndexListJob
run
class IndexListJob extends VisorJob<CacheIndexesListCommandArg, Set<IndexListInfoContainer>> { /** */ private static final long serialVersionUID = 0L; /** * Create job with specified argument. * * @param arg Job argument. * @param debug Flag indicating whether debug information should be printed into node log. */ protected IndexListJob(@Nullable CacheIndexesListCommandArg arg, boolean debug) { super(arg, debug); } /** {@inheritDoc} */ @Override protected Set<IndexListInfoContainer> run(@Nullable CacheIndexesListCommandArg arg) throws IgniteException {<FILL_FUNCTION_BODY>} /** */ @Nullable private Pattern getPattern(String regex) { return regex == null ? null : Pattern.compile(regex.toLowerCase()); } /** */ private static IndexListInfoContainer constructContainer(GridCacheContext<?, ?> ctx, InlineIndexImpl idx) { return new IndexListInfoContainer( ctx, idx.indexDefinition().idxName().idxName(), idx.indexDefinition().indexKeyDefinitions().keySet(), idx.indexDefinition().idxName().tableName() ); } /** */ private static boolean isNameValid(Pattern pattern, String name) { if (pattern == null) return true; return pattern.matcher(name.toLowerCase()).find(); } }
if (arg == null) throw new IgniteException("CacheIndexesListCommandArg is null"); Pattern indexesPtrn = getPattern(arg.indexName()); Pattern grpsPtrn = getPattern(arg.groupName()); Pattern cachesPtrn = getPattern(arg.cacheName()); Set<IndexListInfoContainer> idxInfos = new HashSet<>(); for (GridCacheContext<?, ?> ctx : ignite.context().cache().context().cacheContexts()) { final String cacheName = ctx.name(); final String grpName = ctx.config().getGroupName(); final String grpNameToValidate = grpName == null ? EMPTY_GROUP_NAME : grpName; if (!isNameValid(grpsPtrn, grpNameToValidate)) continue; if (!isNameValid(cachesPtrn, cacheName)) continue; Collection<Index> idxs = ignite.context().indexProcessor().indexes(cacheName); for (Index idx : idxs) { if (!isNameValid(indexesPtrn, idx.name())) continue; InlineIndexImpl idx0 = idx.unwrap(InlineIndexImpl.class); if (idx0 != null) idxInfos.add(constructContainer(ctx, idx0)); } } return idxInfos;
361
348
709
<methods>public non-sealed void <init>() <variables>
apache_ignite
ignite/modules/core/src/main/java/org/apache/ignite/internal/management/cache/IndexRebuildStatusInfoContainer.java
IndexRebuildStatusInfoContainer
toString
class IndexRebuildStatusInfoContainer extends IgniteDataTransferObject { /** Empty group name. */ public static final String EMPTY_GROUP_NAME = "no_group"; /** */ private static final long serialVersionUID = 0L; /** Group name. */ private String groupName; /** Cache name. */ private String cacheName; /** */ private int indexBuildPartitionsLeftCount; /** Local partitions count. */ private int totalPartitionsCount; /** * Empty constructor required for Serializable. */ public IndexRebuildStatusInfoContainer() { // No-op. } /** */ public IndexRebuildStatusInfoContainer(GridCacheContext<?, ?> cctx) { assert cctx != null; CacheConfiguration<?, ?> cfg = cctx.config(); groupName = cfg.getGroupName() == null ? EMPTY_GROUP_NAME : cfg.getGroupName(); cacheName = cfg.getName(); indexBuildPartitionsLeftCount = cctx.cache().metrics0().getIndexBuildPartitionsLeftCount(); totalPartitionsCount = cctx.topology().localPartitions().size(); } /** {@inheritDoc} */ @Override protected void writeExternalData(ObjectOutput out) throws IOException { U.writeString(out, groupName); U.writeString(out, cacheName); out.writeInt(indexBuildPartitionsLeftCount); out.writeInt(totalPartitionsCount); } /** {@inheritDoc} */ @Override protected void readExternalData(byte protoVer, ObjectInput in) throws IOException, ClassNotFoundException { groupName = U.readString(in); cacheName = U.readString(in); indexBuildPartitionsLeftCount = in.readInt(); totalPartitionsCount = in.readInt(); } /** {@inheritDoc} */ @Override public boolean equals(Object o) { if (!(o instanceof IndexRebuildStatusInfoContainer)) return false; IndexRebuildStatusInfoContainer other = (IndexRebuildStatusInfoContainer)o; return cacheName.equals(other.cacheName) && groupName.equals(other.groupName); } /** {@inheritDoc} */ @Override public int hashCode() { return groupName.hashCode() * 17 + cacheName.hashCode() * 37; } /** * @return Group name. */ public String groupName() { return groupName; } /** * @return Cache name. */ public String cacheName() { return cacheName; } /** * @return Total local node partitions count. */ public int totalPartitionsCount() { return totalPartitionsCount; } /** * @return The number of local node partitions that remain to be processed to complete indexing. */ public int indexBuildPartitionsLeftCount() { return indexBuildPartitionsLeftCount; } /** * @return default string object representation without {@code IndexRebuildStatusInfoContainer} and brackets. */ @Override public String toString() {<FILL_FUNCTION_BODY>} /** * @return Custom comparator. */ public static Comparator<IndexRebuildStatusInfoContainer> comparator() { return Comparator.comparing(IndexRebuildStatusInfoContainer::groupName) .thenComparing(IndexRebuildStatusInfoContainer::cacheName); } }
float progress = (float)(totalPartitionsCount - indexBuildPartitionsLeftCount) / totalPartitionsCount; String dfltImpl = S.toString( IndexRebuildStatusInfoContainer.class, this, "progress", (int)(Math.max(0, progress) * 100) + "%" ); return dfltImpl.substring(IndexRebuildStatusInfoContainer.class.getSimpleName().length() + 2, dfltImpl.length() - 1);
891
130
1,021
<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/management/cache/IndexRebuildStatusTask.java
IndexRebuildStatusJob
run
class IndexRebuildStatusJob extends VisorJob<CacheIndexesRebuildStatusCommandArg, Set<IndexRebuildStatusInfoContainer>> { /** */ private static final long serialVersionUID = 0L; /** * Create job with specified argument. * * @param arg Job argument. * @param debug Flag indicating whether debug information should be printed into node log. */ protected IndexRebuildStatusJob(@Nullable CacheIndexesRebuildStatusCommandArg arg, boolean debug) { super(arg, debug); } /** {@inheritDoc} */ @Override protected Set<IndexRebuildStatusInfoContainer> run( @Nullable CacheIndexesRebuildStatusCommandArg arg ) throws IgniteException {<FILL_FUNCTION_BODY>} }
Set<IgniteCacheProxy<?, ?>> rebuildIdxCaches = ignite.context().cache().publicCaches().stream() .filter(c -> !c.indexReadyFuture().isDone()) .collect(Collectors.toSet()); Set<IndexRebuildStatusInfoContainer> res = new HashSet<>(); for (IgniteCacheProxy<?, ?> cache : rebuildIdxCaches) res.add(new IndexRebuildStatusInfoContainer(cache.context())); return res;
191
129
320
<methods>public non-sealed void <init>() ,public Map<? extends org.apache.ignite.compute.ComputeJob,org.apache.ignite.cluster.ClusterNode> map(List<org.apache.ignite.cluster.ClusterNode>, VisorTaskArgument<org.apache.ignite.internal.management.cache.CacheIndexesRebuildStatusCommandArg>) ,public final Map<java.util.UUID,Set<org.apache.ignite.internal.management.cache.IndexRebuildStatusInfoContainer>> 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 boolean debug,protected transient org.apache.ignite.internal.IgniteEx ignite,protected long start,protected org.apache.ignite.internal.management.cache.CacheIndexesRebuildStatusCommandArg taskArg
apache_ignite
ignite/modules/core/src/main/java/org/apache/ignite/internal/management/cache/QueryIndexField.java
QueryIndexField
list
class QueryIndexField extends VisorDataTransferObject { /** */ private static final long serialVersionUID = 0L; /** Index field name. */ private String name; /** Index field sort order. */ private boolean sort; /** * Create data transfer object for given cache type metadata. */ public QueryIndexField() { // No-op. } /** * Create data transfer object for index field. * * @param name Index field name. * @param sort Index field sort order. */ public QueryIndexField(String name, boolean sort) { this.name = name; this.sort = sort; } /** * @param idx Query entity index. * @return Data transfer object for query entity index fields. */ public static List<QueryIndexField> list(QueryIndex idx) {<FILL_FUNCTION_BODY>} /** * @return Index field name. */ public String getName() { return name; } /** * @return Index field sort order. */ public boolean getSortOrder() { return sort; } /** {@inheritDoc} */ @Override protected void writeExternalData(ObjectOutput out) throws IOException { U.writeString(out, name); out.writeBoolean(sort); } /** {@inheritDoc} */ @Override protected void readExternalData(byte protoVer, ObjectInput in) throws IOException, ClassNotFoundException { name = U.readString(in); sort = in.readBoolean(); } /** {@inheritDoc} */ @Override public String toString() { return S.toString(QueryIndexField.class, this); } }
List<QueryIndexField> res = new ArrayList<>(); for (Map.Entry<String, Boolean> field: idx.getFields().entrySet()) res.add(new QueryIndexField(field.getKey(), !field.getValue())); return res;
445
67
512
<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,private static final long serialVersionUID
apache_ignite
ignite/modules/core/src/main/java/org/apache/ignite/internal/management/cache/ScheduleIndexRebuildTask.java
ScheduleIndexRebuildJob
run
class ScheduleIndexRebuildJob extends VisorJob<CacheScheduleIndexesRebuildCommandArg, ScheduleIndexRebuildJobRes> { /** Serial version uid. */ private static final long serialVersionUID = 0L; /** * Create job with specified argument. * * @param arg Job argument. * @param debug Flag indicating whether debug information should be printed into node log. */ protected ScheduleIndexRebuildJob(CacheScheduleIndexesRebuildCommandArg arg, boolean debug) { super(arg, debug); } /** {@inheritDoc} */ @Override protected ScheduleIndexRebuildJobRes run(CacheScheduleIndexesRebuildCommandArg arg) throws IgniteException {<FILL_FUNCTION_BODY>} /** * @param cache Cache name. * @return Indexes of the cache. */ private Set<String> indexes(String cache) { return ignite.context().indexProcessor().treeIndexes(cache, false).stream() .map(Index::name) .collect(Collectors.toSet()); } }
Set<String> argCacheGrps = arg.groupNames() == null ? null : new HashSet<>(Arrays.asList(arg.groupNames())); assert (arg.cacheToIndexes() != null && !arg.cacheToIndexes().isEmpty()) || (argCacheGrps != null && !argCacheGrps.isEmpty()) : "Cache to indexes map or cache groups must be specified."; Map<String, Set<String>> argCacheToIndexes = arg.cacheToIndexes() != null ? arg.cacheToIndexes() : new HashMap<>(); Set<String> notFoundCaches = new HashSet<>(); Set<String> notFoundGrps = new HashSet<>(); GridCacheProcessor cacheProc = ignite.context().cache(); Map<String, Set<String>> cacheToIndexes = new HashMap<>(); Map<String, Set<String>> cacheToMissedIndexes = new HashMap<>(); if (argCacheGrps != null) { argCacheGrps.forEach(groupName -> { CacheGroupContext grpCtx = cacheProc.cacheGroup(CU.cacheId(groupName)); if (grpCtx == null) { notFoundGrps.add(groupName); return; } grpCtx.caches().stream().map(GridCacheContext::name).forEach(cache -> { argCacheToIndexes.put(cache, Collections.emptySet()); }); }); } for (Entry<String, Set<String>> indexesByCache : argCacheToIndexes.entrySet()) { String cache = indexesByCache.getKey(); Set<String> indexesArg = indexesByCache.getValue(); int cacheId = CU.cacheId(cache); GridCacheContext<?, ?> cacheCtx = cacheProc.context().cacheContext(cacheId); if (cacheCtx == null) { notFoundCaches.add(cache); continue; } Set<String> existingIndexes = indexes(cache); Set<String> indexesToRebuild = cacheToIndexes.computeIfAbsent(cache, s -> new HashSet<>()); Set<String> missedIndexes = cacheToMissedIndexes.computeIfAbsent(cache, s -> new HashSet<>()); if (indexesArg.isEmpty()) indexesToRebuild.addAll(existingIndexes); else { indexesArg.forEach(index -> { if (!existingIndexes.contains(index)) { missedIndexes.add(index); return; } indexesToRebuild.add(index); }); } } if (hasAtLeastOneIndex(cacheToIndexes)) { MaintenanceRegistry maintenanceRegistry = ignite.context().maintenanceRegistry(); MaintenanceTask task = toMaintenanceTask( cacheToIndexes.entrySet().stream().collect(Collectors.toMap( (e) -> CU.cacheId(e.getKey()), Entry::getValue )) ); try { maintenanceRegistry.registerMaintenanceTask( task, oldTask -> mergeTasks(oldTask, task) ); } catch (IgniteCheckedException e) { throw new RuntimeException(e); } } return new ScheduleIndexRebuildJobRes( cacheToIndexes, cacheToMissedIndexes, notFoundCaches, notFoundGrps );
275
880
1,155
<methods>public non-sealed void <init>() ,public Map<? extends org.apache.ignite.compute.ComputeJob,org.apache.ignite.cluster.ClusterNode> map(List<org.apache.ignite.cluster.ClusterNode>, VisorTaskArgument<org.apache.ignite.internal.management.cache.CacheScheduleIndexesRebuildCommandArg>) ,public final org.apache.ignite.internal.management.cache.ScheduleIndexRebuildTaskRes 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 boolean debug,protected transient org.apache.ignite.internal.IgniteEx ignite,protected long start,protected org.apache.ignite.internal.management.cache.CacheScheduleIndexesRebuildCommandArg taskArg
apache_ignite
ignite/modules/core/src/main/java/org/apache/ignite/internal/management/cache/ValidateIndexesCheckSizeIssue.java
ValidateIndexesCheckSizeIssue
readExternalData
class ValidateIndexesCheckSizeIssue extends IgniteDataTransferObject { /** Serial version uid. */ private static final long serialVersionUID = 0L; /** Index name. */ private String idxName; /** Index size. */ private long idxSize; /** Error. */ @GridToStringExclude private Throwable t; /** * Default constructor. */ public ValidateIndexesCheckSizeIssue() { //Default constructor required for Externalizable. } /** * Constructor. * * @param idxName Index name. * @param idxSize Index size. * @param t Error. */ public ValidateIndexesCheckSizeIssue(@Nullable String idxName, long idxSize, @Nullable Throwable t) { this.idxName = idxName; this.idxSize = idxSize; this.t = t; } /** {@inheritDoc} */ @Override protected void writeExternalData(ObjectOutput out) throws IOException { writeLongString(out, idxName); out.writeLong(idxSize); out.writeObject(t); } /** {@inheritDoc} */ @Override protected void readExternalData( byte protoVer, ObjectInput in ) throws IOException, ClassNotFoundException {<FILL_FUNCTION_BODY>} /** * Return index size. * * @return Index size. */ public long indexSize() { return idxSize; } /** * Return error. * * @return Error. */ public Throwable error() { return t; } /** {@inheritDoc} */ @Override public String toString() { return S.toString(ValidateIndexesCheckSizeIssue.class, this, "err", t); } }
idxName = readLongString(in); idxSize = in.readLong(); t = (Throwable)in.readObject();
481
37
518
<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/management/cache/ViewCacheClosure.java
ViewCacheClosure
call
class ViewCacheClosure implements IgniteCallable<List<CacheInfo>> { /** */ private static final long serialVersionUID = 0L; /** Regex. */ private String regex; /** {@code true} to skip cache destroying. */ private ViewCacheCmd cmd; /** */ @IgniteInstanceResource private Ignite ignite; /** * @param regex Regex name for stopping caches. * @param cmd Command. */ public ViewCacheClosure(String regex, ViewCacheCmd cmd) { this.regex = regex; this.cmd = cmd; } /** {@inheritDoc} */ @Override public List<CacheInfo> call() throws Exception {<FILL_FUNCTION_BODY>} /** * @param cacheName Cache name. */ private int mapped(String cacheName) { int mapped = 0; ClusterGroup srvs = ignite.cluster().forServers(); Collection<ClusterNode> nodes = srvs.forDataNodes(cacheName).nodes(); for (ClusterNode node : nodes) mapped += ignite.affinity(cacheName).primaryPartitions(node).length; return mapped; } /** * @param ctx Context. * @param compiled Compiled pattern. * @param cacheInfo Cache info. */ private void collectSequences(GridKernalContext ctx, Pattern compiled, List<CacheInfo> cacheInfo) throws IgniteCheckedException { String dsCacheName = DataStructuresProcessor.ATOMICS_CACHE_NAME + "@default-ds-group"; IgniteInternalCache<GridCacheInternalKey, AtomicDataStructureValue> cache0 = ctx.cache().cache(dsCacheName); final Iterator<Cache.Entry<GridCacheInternalKey, AtomicDataStructureValue>> iter = cache0.scanIterator(false, null); while (iter.hasNext()) { Cache.Entry<GridCacheInternalKey, AtomicDataStructureValue> entry = iter.next(); final AtomicDataStructureValue val = entry.getValue(); if (val.type() == DataStructureType.ATOMIC_SEQ) { final String name = entry.getKey().name(); if (compiled.matcher(name).find()) { CacheInfo ci = new CacheInfo(); ci.setSeqName(name); ci.setSeqVal(((GridCacheAtomicSequenceValue)val).get()); cacheInfo.add(ci); } } } } }
Pattern compiled = Pattern.compile(regex); List<CacheInfo> cacheInfo = new ArrayList<>(); IgniteKernal k = (IgniteKernal)ignite; if (cmd == null) cmd = ViewCacheCmd.CACHES; switch (cmd) { case SEQ: collectSequences(k.context(), compiled, cacheInfo); return cacheInfo; case GROUPS: Collection<CacheGroupContext> ctxs = k.context().cache().cacheGroups(); for (CacheGroupContext ctx : ctxs) { if (!ctx.userCache() || !compiled.matcher(ctx.cacheOrGroupName()).find()) continue; CacheInfo ci = new CacheInfo(); ci.setGrpName(ctx.cacheOrGroupName()); ci.setGrpId(ctx.groupId()); ci.setCachesCnt(ctx.caches().size()); ci.setPartitions(ctx.config().getAffinity().partitions()); ci.setBackupsCnt(ctx.config().getBackups()); ci.setAffinityClsName(ctx.config().getAffinity().getClass().getSimpleName()); ci.setMode(ctx.config().getCacheMode()); ci.setAtomicityMode(ctx.config().getAtomicityMode()); ci.setMapped(mapped(ctx.caches().iterator().next().name())); cacheInfo.add(ci); } return cacheInfo; default: Map<String, DynamicCacheDescriptor> descMap = k.context().cache().cacheDescriptors(); for (Map.Entry<String, DynamicCacheDescriptor> entry : descMap.entrySet()) { DynamicCacheDescriptor desc = entry.getValue(); if (!desc.cacheType().userCache() || !compiled.matcher(desc.cacheName()).find()) continue; CacheInfo ci = new CacheInfo(); ci.setCacheName(desc.cacheName()); ci.setCacheId(desc.cacheId()); ci.setGrpName(desc.groupDescriptor().groupName()); ci.setGrpId(desc.groupDescriptor().groupId()); ci.setPartitions(desc.cacheConfiguration().getAffinity().partitions()); ci.setBackupsCnt(desc.cacheConfiguration().getBackups()); ci.setAffinityClsName(desc.cacheConfiguration().getAffinity().getClass().getSimpleName()); ci.setMode(desc.cacheConfiguration().getCacheMode()); ci.setAtomicityMode(desc.cacheConfiguration().getAtomicityMode()); ci.setMapped(mapped(desc.cacheName())); cacheInfo.add(ci); } return cacheInfo; }
651
695
1,346
<no_super_class>
apache_ignite
ignite/modules/core/src/main/java/org/apache/ignite/internal/management/cdc/CdcDeleteLostSegmentsTask.java
CdcDeleteLostSegmentsJob
run
class CdcDeleteLostSegmentsJob extends VisorJob<CdcDeleteLostSegmentLinksCommandArg, Void> { /** */ private static final long serialVersionUID = 0L; /** Injected logger. */ @LoggerResource protected IgniteLogger log; /** * Create job with specified argument. * * @param arg Job argument. * @param debug Flag indicating whether debug information should be printed into node log. */ protected CdcDeleteLostSegmentsJob(CdcDeleteLostSegmentLinksCommandArg arg, boolean debug) { super(arg, debug); } /** {@inheritDoc} */ @Override protected Void run(CdcDeleteLostSegmentLinksCommandArg arg) throws IgniteException {<FILL_FUNCTION_BODY>} }
FileWriteAheadLogManager wal = (FileWriteAheadLogManager)ignite.context().cache().context().wal(true); File walCdcDir = wal.walCdcDirectory(); if (walCdcDir == null) throw new IgniteException("CDC is not configured."); CdcFileLockHolder lock = new CdcFileLockHolder(walCdcDir.getAbsolutePath(), "Delete lost segments job", log); try { lock.tryLock(1); try (Stream<Path> cdcFiles = Files.list(walCdcDir.toPath())) { Set<File> delete = new HashSet<>(); AtomicLong lastSgmnt = new AtomicLong(-1); cdcFiles .filter(p -> WAL_SEGMENT_FILE_FILTER.accept(p.toFile())) .sorted(Comparator.comparingLong(FileWriteAheadLogManager::segmentIndex) .reversed()) // Sort by segment index. .forEach(path -> { long idx = FileWriteAheadLogManager.segmentIndex(path); if (lastSgmnt.get() == -1 || lastSgmnt.get() - idx == 1) { lastSgmnt.set(idx); return; } delete.add(path.toFile()); }); if (delete.isEmpty()) { log.info("Lost segment CDC links were not found."); return null; } log.info("Found lost segment CDC links. The following links will be deleted: " + delete); delete.forEach(file -> { if (!file.delete()) { throw new IgniteException("Failed to delete lost segment CDC link [file=" + file.getAbsolutePath() + ']'); } log.info("Segment CDC link deleted [file=" + file.getAbsolutePath() + ']'); }); Path stateDir = walCdcDir.toPath().resolve(STATE_DIR); if (stateDir.toFile().exists()) { File walState = stateDir.resolve(WAL_STATE_FILE_NAME).toFile(); if (walState.exists() && !walState.delete()) { throw new IgniteException("Failed to delete wal state file [file=" + walState.getAbsolutePath() + ']'); } } } catch (IOException e) { throw new RuntimeException("Failed to delete lost segment CDC links.", e); } } catch (IgniteCheckedException e) { throw new RuntimeException("Failed to delete lost segment CDC links. " + "Unable to acquire lock to lock CDC folder. Make sure a CDC app is shut down " + "[dir=" + walCdcDir.getAbsolutePath() + ", reason=" + e.getMessage() + ']'); } finally { U.closeQuiet(lock); } return null;
206
754
960
<methods>public non-sealed void <init>() ,public Map<? extends org.apache.ignite.compute.ComputeJob,org.apache.ignite.cluster.ClusterNode> map(List<org.apache.ignite.cluster.ClusterNode>, VisorTaskArgument<org.apache.ignite.internal.management.cdc.CdcDeleteLostSegmentLinksCommandArg>) ,public final 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 boolean debug,protected transient org.apache.ignite.internal.IgniteEx ignite,protected long start,protected org.apache.ignite.internal.management.cdc.CdcDeleteLostSegmentLinksCommandArg taskArg
apache_ignite
ignite/modules/core/src/main/java/org/apache/ignite/internal/management/consistency/ConsistencyRepairCommand.java
ConsistencyRepairCommand
execute
class ConsistencyRepairCommand implements LocalCommand<ConsistencyRepairCommandArg, String> { /** {@inheritDoc} */ @Override public String description() { return "Check/Repair cache consistency using Read Repair approach"; } /** {@inheritDoc} */ @Override public Class<ConsistencyRepairCommandArg> argClass() { return ConsistencyRepairCommandArg.class; } /** {@inheritDoc} */ @Override public String execute( @Nullable GridClient cli, @Nullable Ignite ignite, ConsistencyRepairCommandArg arg, Consumer<String> printer ) throws GridClientException, IgniteException { StringBuilder sb = new StringBuilder(); boolean failed = false; if (arg.parallel()) failed = execute(cli, ignite, arg, nodes(cli, ignite), sb); else { Set<GridClientNode> nodes = nodes(cli, ignite).stream() .filter(node -> !node.isClient()) .collect(toSet()); for (GridClientNode node : nodes) { failed = execute(cli, ignite, arg, Collections.singleton(node), sb); if (failed) break; } } String res = sb.toString(); if (failed) throw new IgniteException(res); printer.accept(res); return res; } /** */ private boolean execute( @Nullable GridClient cli, @Nullable Ignite ignite, ConsistencyRepairCommandArg arg, Collection<GridClientNode> nodes, StringBuilder sb ) throws GridClientException {<FILL_FUNCTION_BODY>} }
boolean failed = false; ConsistencyTaskResult res = CommandUtils.execute( cli, ignite, ConsistencyRepairTask.class, arg, nodes ); if (res.cancelled()) { sb.append("Operation execution cancelled.\n\n"); failed = true; } if (res.failed()) { sb.append("Operation execution failed.\n\n"); failed = true; } if (failed) sb.append("[EXECUTION FAILED OR CANCELLED, RESULTS MAY BE INCOMPLETE OR INCONSISTENT]\n\n"); if (res.message() != null) sb.append(res.message()); else assert !arg.parallel(); return failed;
436
214
650
<no_super_class>
apache_ignite
ignite/modules/core/src/main/java/org/apache/ignite/internal/management/consistency/ConsistencyStatusCommand.java
ConsistencyStatusCommand
printResult
class ConsistencyStatusCommand implements ComputeCommand<NoArg, ConsistencyTaskResult> { /** {@inheritDoc} */ @Override public String description() { return "Cache consistency check/repair operations status"; } /** {@inheritDoc} */ @Override public Class<NoArg> argClass() { return NoArg.class; } /** {@inheritDoc} */ @Override public Class<ConsistencyStatusTask> taskClass() { return ConsistencyStatusTask.class; } /** {@inheritDoc} */ @Override public Collection<GridClientNode> nodes(Collection<GridClientNode> nodes, NoArg arg) { return servers(nodes); } /** {@inheritDoc} */ @Override public void printResult(NoArg arg, ConsistencyTaskResult res, Consumer<String> printer) {<FILL_FUNCTION_BODY>} }
if (res.cancelled()) printer.accept("Operation execution cancelled.\n\n"); if (res.failed()) printer.accept("Operation execution failed.\n\n"); if (res.cancelled() || res.failed()) printer.accept("[EXECUTION FAILED OR CANCELLED, RESULTS MAY BE INCOMPLETE OR INCONSISTENT]\n\n"); printer.accept(res.message());
225
118
343
<no_super_class>
apache_ignite
ignite/modules/core/src/main/java/org/apache/ignite/internal/management/consistency/ConsistencyStatusTask.java
ConsistencyStatusJob
run
class ConsistencyStatusJob extends VisorJob<NoArg, String> { /** Serial version uid. */ private static final long serialVersionUID = 0L; /** Injected logger. */ @LoggerResource protected IgniteLogger log; /** * @param arg Arguments. * @param debug Debug. */ protected ConsistencyStatusJob(NoArg arg, boolean debug) { super(arg, debug); } /** {@inheritDoc} */ @Override protected String run(NoArg arg) throws IgniteException {<FILL_FUNCTION_BODY>} }
if (MAP.isEmpty()) return null; StringBuilder sb = new StringBuilder(); for (Map.Entry<String, String> entry : MAP.entrySet()) { sb.append("\n Job: ").append(entry.getKey()).append("\n") .append(" Status: ").append(entry.getValue()).append("\n"); } return sb.toString();
155
103
258
<methods>public non-sealed void <init>() <variables>
apache_ignite
ignite/modules/core/src/main/java/org/apache/ignite/internal/management/defragmentation/DefragmentationScheduleCommand.java
DefragmentationScheduleCommand
nodes
class DefragmentationScheduleCommand implements ComputeCommand<DefragmentationStatusCommandArg, DefragmentationTaskResult> { /** {@inheritDoc} */ @Override public String description() { return "Schedule PDS defragmentation"; } /** {@inheritDoc} */ @Override public Class<DefragmentationScheduleCommandArg> argClass() { return DefragmentationScheduleCommandArg.class; } /** {@inheritDoc} */ @Override public Class<DefragmentationTask> taskClass() { return DefragmentationTask.class; } /** {@inheritDoc} */ @Override public void printResult( DefragmentationStatusCommandArg arg, DefragmentationTaskResult res, Consumer<String> printer ) { printer.accept(res.getMessage()); } /** {@inheritDoc} */ @Override public Collection<GridClientNode> nodes(Collection<GridClientNode> nodes, DefragmentationStatusCommandArg arg0) {<FILL_FUNCTION_BODY>} }
DefragmentationScheduleCommandArg arg = (DefragmentationScheduleCommandArg)arg0; if (F.isEmpty(arg.nodes())) return null; Set<String> nodesArg = new HashSet<>(Arrays.asList(arg.nodes())); return nodes.stream() .filter(n -> nodesArg.contains(Objects.toString(n.consistentId()))) .collect(Collectors.toList());
269
113
382
<no_super_class>
apache_ignite
ignite/modules/core/src/main/java/org/apache/ignite/internal/management/diagnostic/ConnectivityTask.java
ConnectivityJob
run
class ConnectivityJob extends VisorJob<DiagnosticConnectivityCommandArg, ConnectivityResult> { /** */ private static final long serialVersionUID = 0L; /** * @param arg Formal job argument. * @param debug Debug flag. */ private ConnectivityJob(DiagnosticConnectivityCommandArg arg, boolean debug) { super(arg, debug); } /** {@inheritDoc} */ @Override protected ConnectivityResult run(DiagnosticConnectivityCommandArg arg) {<FILL_FUNCTION_BODY>} /** {@inheritDoc} */ @Override public String toString() { return S.toString(ConnectivityJob.class, this); } }
List<UUID> ids = ignite.cluster().nodes().stream() .map(ClusterNode::id) .filter(uuid -> !Objects.equals(ignite.localNode().id(), uuid)) .collect(Collectors.toList()); List<ClusterNode> nodes = new ArrayList<>(ignite.cluster().forNodeIds(ids).nodes()); CommunicationSpi spi = ignite.configuration().getCommunicationSpi(); Map<ClusterNode, Boolean> statuses = new HashMap<>(); if (spi instanceof TcpCommunicationSpi) { BitSet set = ((TcpCommunicationSpi)spi).checkConnection(nodes).get(); for (int i = 0; i < nodes.size(); i++) { ClusterNode node = nodes.get(i); boolean success = set.get(i); statuses.put(node, success); } } return new ConnectivityResult(statuses);
177
249
426
<methods>public non-sealed void <init>() ,public Map<? extends org.apache.ignite.compute.ComputeJob,org.apache.ignite.cluster.ClusterNode> map(List<org.apache.ignite.cluster.ClusterNode>, VisorTaskArgument<org.apache.ignite.internal.management.diagnostic.DiagnosticConnectivityCommandArg>) ,public final Map<org.apache.ignite.cluster.ClusterNode,org.apache.ignite.internal.management.diagnostic.ConnectivityResult> 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 boolean debug,protected transient org.apache.ignite.internal.IgniteEx ignite,protected long start,protected org.apache.ignite.internal.management.diagnostic.DiagnosticConnectivityCommandArg taskArg
apache_ignite
ignite/modules/core/src/main/java/org/apache/ignite/internal/management/diagnostic/DiagnosticPagelocksCommand.java
DiagnosticPagelocksCommand
nodes
class DiagnosticPagelocksCommand implements ComputeCommand<DiagnosticPagelocksCommandArg, Map<ClusterNode, PageLocksResult>> { /** {@inheritDoc} */ @Override public String description() { return "View pages locks state information on the node or nodes"; } /** {@inheritDoc} */ @Override public Class<DiagnosticPagelocksCommandArg> argClass() { return DiagnosticPagelocksCommandArg.class; } /** {@inheritDoc} */ @Override public Class<PageLocksTask> taskClass() { return PageLocksTask.class; } /** {@inheritDoc} */ @Override public Collection<GridClientNode> nodes(Collection<GridClientNode> nodes, DiagnosticPagelocksCommandArg arg) {<FILL_FUNCTION_BODY>} /** {@inheritDoc} */ @Override public void printResult( DiagnosticPagelocksCommandArg arg, Map<ClusterNode, PageLocksResult> res, Consumer<String> printer ) { res.forEach((n, res0) -> printer.accept(n.id() + " (" + n.consistentId() + ") " + res0.result())); } }
if (arg.all()) return nodes; if (F.isEmpty(arg.nodes())) return null; Set<String> argNodes = new HashSet<>(Arrays.asList(arg.nodes())); return nodes.stream() .filter(entry -> argNodes.contains(entry.nodeId().toString()) || argNodes.contains(String.valueOf(entry.consistentId()))) .collect(Collectors.toList());
310
117
427
<no_super_class>
apache_ignite
ignite/modules/core/src/main/java/org/apache/ignite/internal/management/encryption/CacheGroupEncryptionCommand.java
CacheGroupEncryptionCommand
printResult
class CacheGroupEncryptionCommand<T> implements ComputeCommand<EncryptionCacheGroupArg, CacheGroupEncryptionTaskResult<T>> { /** {@inheritDoc} */ @Override public void printResult( EncryptionCacheGroupArg arg, CacheGroupEncryptionTaskResult<T> res, Consumer<String> printer ) {<FILL_FUNCTION_BODY>} /** {@inheritDoc} */ @Override public Collection<GridClientNode> nodes(Collection<GridClientNode> nodes, EncryptionCacheGroupArg arg) { return nodes; } /** * @param res Response. * @param grpName Cache group name. * @param printer Printer. */ protected abstract void printNodeResult(T res, String grpName, Consumer<String> printer); }
Map<UUID, IgniteException> exceptions = res.exceptions(); for (Map.Entry<UUID, IgniteException> entry : exceptions.entrySet()) { printer.accept(INDENT + "Node " + entry.getKey() + ":"); printer.accept(String.format("%sfailed to execute command for the cache group \"%s\": %s.", DOUBLE_INDENT, arg.cacheGroupName(), entry.getValue().getMessage())); } Map<UUID, T> results = res.results(); for (Map.Entry<UUID, T> entry : results.entrySet()) { printer.accept(INDENT + "Node " + entry.getKey() + ":"); printNodeResult(entry.getValue(), arg.cacheGroupName(), printer); }
204
195
399
<no_super_class>
apache_ignite
ignite/modules/core/src/main/java/org/apache/ignite/internal/management/encryption/EncryptionReencryptionStatusCommand.java
EncryptionReencryptionStatusCommand
printNodeResult
class EncryptionReencryptionStatusCommand extends CacheGroupEncryptionCommand<Long> { /** {@inheritDoc} */ @Override public String description() { return "Display re-encryption status of the cache group"; } /** {@inheritDoc} */ @Override public Class<EncryptionCacheGroupArg> argClass() { return EncryptionCacheGroupArg.class; } /** {@inheritDoc} */ @Override public Class<ReencryptionStatusTask> taskClass() { return ReencryptionStatusTask.class; } /** {@inheritDoc} */ @Override protected void printNodeResult(Long bytesLeft, String grpName, Consumer<String> printer) {<FILL_FUNCTION_BODY>} }
if (bytesLeft == -1) printer.accept(DOUBLE_INDENT + "re-encryption completed or not required"); else if (bytesLeft == 0) printer.accept(DOUBLE_INDENT + "re-encryption will be completed after the next checkpoint"); else printer.accept(String.format("%s%d KB of data left for re-encryption", DOUBLE_INDENT, bytesLeft / 1024));
184
115
299
<methods>public Collection<org.apache.ignite.internal.client.GridClientNode> nodes(Collection<org.apache.ignite.internal.client.GridClientNode>, org.apache.ignite.internal.management.encryption.EncryptionCacheGroupArg) ,public void printResult(org.apache.ignite.internal.management.encryption.EncryptionCacheGroupArg, CacheGroupEncryptionTaskResult<java.lang.Long>, Consumer<java.lang.String>) <variables>
apache_ignite
ignite/modules/core/src/main/java/org/apache/ignite/internal/management/kill/ClientConnectionDropTask.java
ClientConnectionDropTask
reduce0
class ClientConnectionDropTask extends VisorMultiNodeTask<KillClientCommandArg, Void, Boolean> { /** */ private static final long serialVersionUID = 0L; /** {@inheritDoc} */ @Override protected VisorJob<KillClientCommandArg, Boolean> job(KillClientCommandArg arg) { return new ClientConnectionDropJob(arg, debug); } /** {@inheritDoc} */ @Override protected Void reduce0(List<ComputeJobResult> results) throws IgniteException {<FILL_FUNCTION_BODY>} /** * Job to cancel client connection(s). */ private static class ClientConnectionDropJob extends VisorJob<KillClientCommandArg, Boolean> { /** */ private static final long serialVersionUID = 0L; /** * Create job with specified argument. * * @param arg Job argument. * @param debug Flag indicating whether debug information should be printed into node log. */ protected ClientConnectionDropJob(@Nullable KillClientCommandArg arg, boolean debug) { super(arg, debug); } /** {@inheritDoc} */ @Override protected Boolean run(@Nullable KillClientCommandArg arg) throws IgniteException { if (arg == null) return false; ClientProcessorMXBean bean = ignite.context().clientListener().mxBean(); if (!"ALL".equals(arg.connectionId())) return bean.dropConnection(Long.parseLong(arg.connectionId())); bean.dropAllConnections(); return true; } } }
boolean res = false; for (ComputeJobResult jobRes : results) { if (jobRes.getException() != null) throw jobRes.getException(); res |= jobRes.<Boolean>getData(); } if (!res) throw new IgniteException("No connection was dropped"); return null;
396
91
487
<methods>public non-sealed void <init>() ,public Map<? extends org.apache.ignite.compute.ComputeJob,org.apache.ignite.cluster.ClusterNode> map(List<org.apache.ignite.cluster.ClusterNode>, VisorTaskArgument<org.apache.ignite.internal.management.kill.KillClientCommandArg>) ,public final 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 boolean debug,protected transient org.apache.ignite.internal.IgniteEx ignite,protected long start,protected org.apache.ignite.internal.management.kill.KillClientCommandArg taskArg
apache_ignite
ignite/modules/core/src/main/java/org/apache/ignite/internal/management/meta/MetaRemoveCommandArg.java
MetaRemoveCommandArg
out
class MetaRemoveCommandArg extends MetaDetailsCommandArg { /** */ private static final long serialVersionUID = 0; /** */ @Argument(optional = true, example = "<fileName>") private String out; /** {@inheritDoc} */ @Override protected void writeExternalData(ObjectOutput out) throws IOException { super.writeExternalData(out); U.writeString(out, this.out); } /** {@inheritDoc} */ @Override protected void readExternalData(byte protoVer, ObjectInput in) throws IOException, ClassNotFoundException { super.readExternalData(protoVer, in); out = U.readString(in); } /** */ public String out() { return out; } /** */ public void out(String out) {<FILL_FUNCTION_BODY>} }
Path outFile = FileSystems.getDefault().getPath(out); try (OutputStream os = Files.newOutputStream(outFile)) { os.close(); Files.delete(outFile); } catch (IOException e) { throw new IllegalArgumentException("Cannot write to output file " + outFile + ". Error: " + e.toString(), e); } this.out = out;
222
107
329
<methods>public non-sealed void <init>() ,public java.lang.String toString() ,public int typeId() ,public void typeId(int) ,public java.lang.String typeName() ,public void typeName(java.lang.String) <variables>private static final long serialVersionUID,private int typeId,private java.lang.String typeName
apache_ignite
ignite/modules/core/src/main/java/org/apache/ignite/internal/management/meta/MetadataRemoveTask.java
MetadataRemoveJob
run
class MetadataRemoveJob extends VisorJob<MetaRemoveCommandArg, MetadataMarshalled> { /** */ private static final long serialVersionUID = 0L; /** Auto-inject job context. */ @JobContextResource private transient ComputeJobContext jobCtx; /** Metadata future. */ private transient IgniteInternalFuture<?> future; /** Job result: metadata info for removed type (used for job continuation). */ private transient MetadataMarshalled res; /** * @param arg Argument. * @param debug Debug. */ protected MetadataRemoveJob(@Nullable MetaRemoveCommandArg arg, boolean debug) { super(arg, debug); } /** {@inheritDoc} */ @Override public SecurityPermissionSet requiredPermissions() { return systemPermissions(ADMIN_METADATA_OPS); } /** {@inheritDoc} */ @Override protected MetadataMarshalled run(@Nullable MetaRemoveCommandArg arg) throws IgniteException {<FILL_FUNCTION_BODY>} }
try { if (future == null) { assert Objects.nonNull(arg); int typeId = typeId(ignite.context(), arg.typeId(), arg.typeName()); BinaryMetadata meta = ((CacheObjectBinaryProcessorImpl)ignite.context().cacheObjects()) .binaryMetadata(typeId); if (meta == null) return new MetadataMarshalled(null, null); byte[] marshalled = U.marshal(ignite.context(), meta); res = new MetadataMarshalled(marshalled, meta); ignite.context().cacheObjects().removeType(typeId); future = ignite.context().closure().runAsync( BROADCAST, new DropAllThinSessionsJob(), options(ignite.cluster().forServers().nodes()) ); jobCtx.holdcc(); future.listen(() -> { if (future.isDone()) jobCtx.callcc(); }); return null; } return res; } catch (IgniteCheckedException e) { throw new IgniteException(e); }
270
299
569
<methods>public non-sealed void <init>() ,public Map<? extends org.apache.ignite.compute.ComputeJob,org.apache.ignite.cluster.ClusterNode> map(List<org.apache.ignite.cluster.ClusterNode>, VisorTaskArgument<org.apache.ignite.internal.management.meta.MetaRemoveCommandArg>) ,public final org.apache.ignite.internal.management.meta.MetadataMarshalled 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 boolean debug,protected transient org.apache.ignite.internal.IgniteEx ignite,protected long start,protected org.apache.ignite.internal.management.meta.MetaRemoveCommandArg taskArg
apache_ignite
ignite/modules/core/src/main/java/org/apache/ignite/internal/management/metric/MetricCommand.java
MetricCommand
printResult
class MetricCommand extends CommandRegistryImpl<MetricCommandArg, Map<String, ?>> implements ComputeCommand<MetricCommandArg, Map<String, ?>> { /** */ public MetricCommand() { super( new MetricConfigureHistogramCommand(), new MetricConfigureHitrateCommand() ); } /** {@inheritDoc} */ @Override public String description() { return "Print metric value"; } /** {@inheritDoc} */ @Override public Class<MetricCommandArg> argClass() { return MetricCommandArg.class; } /** {@inheritDoc} */ @Override public Class<MetricTask> taskClass() { return MetricTask.class; } /** {@inheritDoc} */ @Override public Collection<GridClientNode> nodes(Collection<GridClientNode> nodes, MetricCommandArg arg) { return nodeOrNull(arg.nodeId(), nodes); } /** {@inheritDoc} */ @Override public void printResult(MetricCommandArg arg, Map<String, ?> res, Consumer<String> printer) {<FILL_FUNCTION_BODY>} }
if (res != null) { List<List<?>> data = res.entrySet().stream() .map(entry -> Arrays.asList(entry.getKey(), entry.getValue())) .collect(Collectors.toList()); printTable(asList("metric", "value"), asList(STRING, STRING), data, printer); } else printer.accept("No metric with specified name was found [name=" + arg.name() + "]");
295
122
417
<methods>public Command<?,?> command(java.lang.String) ,public Iterator<Entry<java.lang.String,Command<?,?>>> commands() <variables>private final Map<java.lang.String,Command<?,?>> commands
apache_ignite
ignite/modules/core/src/main/java/org/apache/ignite/internal/management/metric/MetricConfigureHistogramCommandArg.java
MetricConfigureHistogramCommandArg
newBounds
class MetricConfigureHistogramCommandArg extends MetricCommandArg { /** */ private static final long serialVersionUID = 0; /** */ @Argument(description = "Comma-separated list of longs to configure histogram", example = "newBounds") @Positional private long[] newBounds; /** {@inheritDoc} */ @Override protected void writeExternalData(ObjectOutput out) throws IOException { super.writeExternalData(out); U.writeLongArray(out, newBounds); } /** {@inheritDoc} */ @Override protected void readExternalData(byte protoVer, ObjectInput in) throws IOException, ClassNotFoundException { super.readExternalData(protoVer, in); newBounds = U.readLongArray(in); } /** */ public long[] newBounds() { return newBounds; } /** */ public void newBounds(long[] bounds) {<FILL_FUNCTION_BODY>} }
if (!F.isSorted(bounds)) throw new IllegalArgumentException("Bounds must be sorted"); this.newBounds = bounds;
249
38
287
<methods>public non-sealed void <init>() ,public java.lang.String name() ,public void name(java.lang.String) ,public java.util.UUID nodeId() ,public void nodeId(java.util.UUID) <variables>private java.lang.String name,private java.util.UUID nodeId,private static final long serialVersionUID
apache_ignite
ignite/modules/core/src/main/java/org/apache/ignite/internal/management/persistence/PersistenceCleanCorruptedCommand.java
PersistenceCleanCorruptedCommand
description
class PersistenceCleanCorruptedCommand extends PersistenceAbstractCommand { /** {@inheritDoc} */ @Override public String description() {<FILL_FUNCTION_BODY>} /** {@inheritDoc} */ @Override public Class<PersistenceCleanCorruptedTaskArg> argClass() { return PersistenceCleanCorruptedTaskArg.class; } }
return "Clean directories of caches with corrupted data files";
89
18
107
<methods>public non-sealed void <init>() ,public void printResult(org.apache.ignite.internal.management.persistence.PersistenceCommand.PersistenceTaskArg, org.apache.ignite.internal.management.persistence.PersistenceTaskResult, Consumer<java.lang.String>) ,public Class<org.apache.ignite.internal.management.persistence.PersistenceTask> taskClass() <variables>
apache_ignite
ignite/modules/core/src/main/java/org/apache/ignite/internal/management/persistence/PersistenceInfoCommand.java
PersistenceInfoCommand
description
class PersistenceInfoCommand extends PersistenceAbstractCommand { /** {@inheritDoc} */ @Override public String description() {<FILL_FUNCTION_BODY>} /** {@inheritDoc} */ @Override public Class<PersistenceInfoTaskArg> argClass() { return PersistenceInfoTaskArg.class; } }
return "The same information is printed when info subcommand is passed";
83
19
102
<methods>public non-sealed void <init>() ,public void printResult(org.apache.ignite.internal.management.persistence.PersistenceCommand.PersistenceTaskArg, org.apache.ignite.internal.management.persistence.PersistenceTaskResult, Consumer<java.lang.String>) ,public Class<org.apache.ignite.internal.management.persistence.PersistenceTask> taskClass() <variables>
apache_ignite
ignite/modules/core/src/main/java/org/apache/ignite/internal/management/persistence/PersistenceTaskResult.java
PersistenceTaskResult
readExternalData
class PersistenceTaskResult extends IgniteDataTransferObject { /** */ private static final long serialVersionUID = 0L; /** */ private boolean inMaintenanceMode; /** */ private boolean maintenanceTaskCompleted; /** */ private List<String> handledCaches; /** */ private List<String> failedToHandleCaches; /** */ private Map<String, IgniteBiTuple<Boolean, Boolean>> cachesInfo; /** */ public PersistenceTaskResult() { // No-op. } /** * */ public PersistenceTaskResult(boolean inMaintenanceMode) { this.inMaintenanceMode = inMaintenanceMode; } /** {@inheritDoc} */ @Override protected void writeExternalData(ObjectOutput out) throws IOException { out.writeBoolean(inMaintenanceMode); out.writeBoolean(maintenanceTaskCompleted); U.writeCollection(out, handledCaches); U.writeCollection(out, failedToHandleCaches); U.writeMap(out, cachesInfo); } /** {@inheritDoc} */ @Override protected void readExternalData(byte protoVer, ObjectInput in) throws IOException, ClassNotFoundException {<FILL_FUNCTION_BODY>} /** */ public boolean inMaintenanceMode() { return inMaintenanceMode; } /** */ public boolean maintenanceTaskCompleted() { return maintenanceTaskCompleted; } /** */ public void maintenanceTaskCompleted(boolean maintenanceTaskCompleted) { this.maintenanceTaskCompleted = maintenanceTaskCompleted; } /** */ public List<String> handledCaches() { return handledCaches; } /** */ public void handledCaches(List<String> handledCaches) { this.handledCaches = handledCaches; } /** */ public List<String> failedCaches() { return failedToHandleCaches; } /** */ public void failedCaches(List<String> failedToHandleCaches) { this.failedToHandleCaches = failedToHandleCaches; } /** */ public Map<String, IgniteBiTuple<Boolean, Boolean>> cachesInfo() { return cachesInfo; } /** */ public void cachesInfo(Map<String, IgniteBiTuple<Boolean, Boolean>> cachesInfo) { this.cachesInfo = cachesInfo; } }
inMaintenanceMode = in.readBoolean(); maintenanceTaskCompleted = in.readBoolean(); handledCaches = U.readList(in); failedToHandleCaches = U.readList(in); cachesInfo = U.readMap(in);
640
68
708
<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/management/snapshot/SnapshotCheckCommand.java
SnapshotCheckCommand
printResult
class SnapshotCheckCommand extends AbstractSnapshotCommand<SnapshotCheckCommandArg> { /** {@inheritDoc} */ @Override public String description() { return "Check snapshot"; } /** {@inheritDoc} */ @Override public Class<SnapshotCheckCommandArg> argClass() { return SnapshotCheckCommandArg.class; } /** {@inheritDoc} */ @Override public Class<SnapshotCheckTask> taskClass() { return SnapshotCheckTask.class; } /** {@inheritDoc} */ @Override public void printResult(SnapshotCheckCommandArg arg, SnapshotTaskResult res0, Consumer<String> printer) {<FILL_FUNCTION_BODY>} }
try { ((SnapshotPartitionsVerifyTaskResult)res0.result()).print(printer); } catch (Exception e) { throw new IgniteException(e); }
173
51
224
<methods>public non-sealed void <init>() ,public void printResult(org.apache.ignite.internal.management.snapshot.SnapshotCheckCommandArg, org.apache.ignite.internal.management.snapshot.SnapshotTaskResult, Consumer<java.lang.String>) <variables>
apache_ignite
ignite/modules/core/src/main/java/org/apache/ignite/internal/management/snapshot/SnapshotRestoreCommand.java
SnapshotRestoreCommand
deprecationMessage
class SnapshotRestoreCommand extends AbstractSnapshotCommand<SnapshotRestoreCommandArg> { /** {@inheritDoc} */ @Override public String description() { return "Restore snapshot"; } /** {@inheritDoc} */ @Override public @Nullable String deprecationMessage(SnapshotRestoreCommandArg arg) {<FILL_FUNCTION_BODY>} /** {@inheritDoc} */ @Override public Class<SnapshotRestoreCommandArg> argClass() { return SnapshotRestoreCommandArg.class; } /** {@inheritDoc} */ @Override public Class<SnapshotRestoreTask> taskClass() { return SnapshotRestoreTask.class; } /** {@inheritDoc} */ @Override public String confirmationPrompt(SnapshotRestoreCommandArg arg) { return arg.status() || arg.cancel() || arg.groups() != null ? null : "Warning: command will restore ALL USER-CREATED CACHE GROUPS from the snapshot " + arg.snapshotName() + '.'; } }
if (arg.start()) return "Command option '--start' is redundant and must be avoided."; else if (arg.cancel()) return "Command deprecated. Use '--snapshot cancel' instead."; else if (arg.status()) return "Command deprecated. Use '--snapshot status' instead."; return null;
261
90
351
<methods>public non-sealed void <init>() ,public void printResult(org.apache.ignite.internal.management.snapshot.SnapshotRestoreCommandArg, org.apache.ignite.internal.management.snapshot.SnapshotTaskResult, Consumer<java.lang.String>) <variables>
apache_ignite
ignite/modules/core/src/main/java/org/apache/ignite/internal/management/snapshot/SnapshotRestoreCommandArg.java
SnapshotRestoreCommandArg
writeExternalData
class SnapshotRestoreCommandArg extends IgniteDataTransferObject { /** */ private static final long serialVersionUID = 0; /** */ @Positional @Argument(description = "Snapshot name. " + "In the case of incremental snapshot (--incremental) full snapshot name must be provided") private String snapshotName; /** */ @Argument(optional = true, example = "incrementIndex", description = "Incremental snapshot index. " + "The command will restore snapshot and after that all its increments sequentially from 1 to the specified index") private int increment; /** */ @Argument(optional = true, description = "Cache group names", example = "group1,...groupN") private String[] groups; /** */ @Argument(example = "path", optional = true, description = "Path to the directory where the snapshot files are located. " + "If not specified, the default configured snapshot directory will be used") private String src; /** */ @Argument(optional = true, description = "Run the operation synchronously, " + "the command will wait for the entire operation to complete. " + "Otherwise, it will be performed in the background, and the command will immediately return control") private boolean sync; /** */ @Argument(optional = true, description = "Check snapshot data integrity before restore (slow!). Similar to the \"check\" command") private boolean check; /** */ @Argument(description = "Snapshot restore operation status (Command deprecated. Use '--snapshot status' instead)") private boolean status; /** */ @Argument(description = "Cancel snapshot restore operation (Command deprecated. Use '--snapshot cancel' instead)") private boolean cancel; /** */ @Argument(description = "Start snapshot restore operation (Default action)") private boolean start; /** */ public void ensureOptions() { if (!sync) return; if (cancel) throw new IllegalArgumentException("--sync and --cancel can't be used together"); if (status) throw new IllegalArgumentException("--sync and --status can't be used together"); } /** {@inheritDoc} */ @Override protected void writeExternalData(ObjectOutput out) throws IOException {<FILL_FUNCTION_BODY>} /** {@inheritDoc} */ @Override protected void readExternalData(byte protoVer, ObjectInput in) throws IOException, ClassNotFoundException { snapshotName = U.readString(in); increment = in.readInt(); groups = U.readArray(in, String.class); src = U.readString(in); sync = in.readBoolean(); check = in.readBoolean(); status = in.readBoolean(); cancel = in.readBoolean(); start = in.readBoolean(); } /** */ public boolean start() { return start; } /** */ public void start(boolean start) { this.start = start; ensureOptions(); } /** */ public boolean status() { return status; } /** */ public void status(boolean status) { this.status = status; ensureOptions(); } /** */ public boolean cancel() { return cancel; } /** */ public void cancel(boolean cancel) { this.cancel = cancel; ensureOptions(); } /** */ public String[] groups() { return groups; } /** */ public void groups(String[] groups) { this.groups = groups; } /** */ public String snapshotName() { return snapshotName; } /** */ public void snapshotName(String snapshotName) { this.snapshotName = snapshotName; } /** */ public int increment() { return increment; } /** */ public void increment(int increment) { this.increment = increment; } /** */ public String src() { return src; } /** */ public void src(String src) { this.src = src; } /** */ public boolean sync() { return sync; } /** */ public void sync(boolean sync) { this.sync = sync; ensureOptions(); } /** */ public boolean check() { return check; } /** */ public void check(boolean check) { this.check = check; } }
U.writeString(out, snapshotName); out.writeInt(increment); U.writeArray(out, groups); U.writeString(out, src); out.writeBoolean(sync); out.writeBoolean(check); out.writeBoolean(status); out.writeBoolean(cancel); out.writeBoolean(start);
1,151
92
1,243
<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/management/tracing/TracingConfigurationGetCommandArg.java
TracingConfigurationGetCommandArg
readExternalData
class TracingConfigurationGetCommandArg extends TracingConfigurationCommandArg { /** */ private static final long serialVersionUID = 0; /** */ @Argument(description = "Tracing span scope") @EnumDescription( names = { "DISCOVERY", "EXCHANGE", "COMMUNICATION", "TX", "SQL" }, descriptions = { "Discovery scope", "Exchange scope", "Communication scope", "Transactional scope", "SQL scope" } ) private Scope scope; /** */ @Argument(optional = true) private String label; /** {@inheritDoc} */ @Override protected void writeExternalData(ObjectOutput out) throws IOException { super.writeExternalData(out); U.writeEnum(out, scope); U.writeString(out, label); } /** {@inheritDoc} */ @Override protected void readExternalData(byte protoVer, ObjectInput in) throws IOException, ClassNotFoundException {<FILL_FUNCTION_BODY>} /** */ public Scope scope() { return scope; } /** */ public void scope(Scope scope) { this.scope = scope; } /** */ public String label() { return label; } /** */ public void label(String label) { this.label = label; } }
super.readExternalData(protoVer, in); scope = U.readEnum(in, Scope.class); label = U.readString(in);
371
44
415
<methods>public non-sealed void <init>() <variables>private static final long serialVersionUID
apache_ignite
ignite/modules/core/src/main/java/org/apache/ignite/internal/management/tracing/TracingConfigurationItem.java
TracingConfigurationItem
equals
class TracingConfigurationItem extends IgniteDataTransferObject { /** */ private static final long serialVersionUID = 0L; /** * Specifies the {@link Scope} of a trace's root span to which some specific tracing configuration will be applied. * It's a mandatory attribute. */ private Scope scope; /** * Specifies the label of a traced operation. It's an optional attribute. */ private String lb; /** * Number between 0 and 1 that more or less reflects the probability of sampling specific trace. 0 and 1 have * special meaning here, 0 means never 1 means always. Default value is 0 (never). */ private Double samplingRate; /** * Set of {@link Scope} that defines which sub-traces will be included in given trace. In other words, if child's * span scope is equals to parent's scope or it belongs to the parent's span included scopes, then given child span * will be attached to the current trace, otherwise it'll be skipped. See {@link * Span#isChainable(Scope)} for more details. */ private Set<Scope> includedScopes; /** * Default constructor. */ public TracingConfigurationItem() { // No-op. } /** * Constructor. * * @param scope Specifies the {@link Scope} of a trace's root span to which some specific tracing configuration will be applied. * @param lb Specifies the label of a traced operation. It's an optional attribute. * @param samplingRate Number between 0 and 1 that more or less reflects the probability of sampling specific trace. * 0 and 1 have special meaning here, 0 means never 1 means always. Default value is 0 (never). * @param includedScopes Set of {@link Scope} that defines which sub-traces will be included in given trace. * In other words, if child's span scope is equals to parent's scope * or it belongs to the parent's span included scopes, then given child span will be attached to the current trace, * otherwise it'll be skipped. * See {@link Span#isChainable(Scope)} for more details. */ public TracingConfigurationItem( Scope scope, String lb, Double samplingRate, Set<Scope> includedScopes ) { this.scope = scope; this.lb = lb; this.samplingRate = samplingRate; this.includedScopes = includedScopes; } /** * @return Specifies the of a trace's root span to which some specific tracing configuration will be applied. It's * a mandatory attribute. */ public Scope scope() { return scope; } /** * @return Specifies the label of a traced operation. It's an optional attribute. */ public String label() { return lb; } /** * @return Number between 0 and 1 that more or less reflects the probability of sampling specific trace. 0 and 1 * have special meaning here, 0 means never 1 means always. Default value is 0 (never). */ public Double samplingRate() { return samplingRate; } /** * @return Set of that defines which sub-traces will be included in given trace. In other words, if child's span * scope is equals to parent's scope or it belongs to the parent's span included scopes, then given child span will * be attached to the current trace, otherwise it'll be skipped. See for more details. */ public Set<Scope> includedScopes() { return includedScopes; } /** {@inheritDoc} */ @Override protected void writeExternalData(ObjectOutput out) throws IOException { out.writeBoolean(scope != null); if (scope != null) out.writeShort(scope.idx()); U.writeString(out, label()); out.writeObject(samplingRate); U.writeCollection(out, includedScopes); } /** {@inheritDoc} */ @Override protected void readExternalData(byte protoVer, ObjectInput in) throws IOException, ClassNotFoundException { if (in.readBoolean()) scope = Scope.fromIndex(in.readShort()); lb = U.readString(in); samplingRate = (Double)in.readObject(); includedScopes = U.readSet(in); } /** {@inheritDoc} */ @Override public String toString() { return S.toString(TracingConfigurationItem.class, this); } /** {@inheritDoc} */ @Override public boolean equals(Object o) {<FILL_FUNCTION_BODY>} }
if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; TracingConfigurationItem that = (TracingConfigurationItem)o; if (scope != that.scope) return false; if (lb != null ? !lb.equals(that.lb) : that.lb != null) return false; if (samplingRate != null ? !samplingRate.equals(that.samplingRate) : that.samplingRate != null) return false; return includedScopes != null ? includedScopes.equals(that.includedScopes) : that.includedScopes == null;
1,229
176
1,405
<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/management/tx/TxCommand.java
AbstractTxCommandArg
nodeDescription
class AbstractTxCommandArg extends IgniteDataTransferObject { // No-op. } /** * Provides text descrition of a cluster node. * * @param node Node. */ static String nodeDescription(ClusterNode node) {<FILL_FUNCTION_BODY>
return node.getClass().getSimpleName() + " [id=" + node.id() + ", addrs=" + node.addresses() + ", order=" + node.order() + ", ver=" + node.version() + ", isClient=" + node.isClient() + ", consistentId=" + node.consistentId() + "]";
78
98
176
<methods>public Command<?,?> command(java.lang.String) ,public Iterator<Entry<java.lang.String,Command<?,?>>> commands() <variables>private final Map<java.lang.String,Command<?,?>> commands
apache_ignite
ignite/modules/core/src/main/java/org/apache/ignite/internal/management/tx/TxVerboseInfo.java
TxVerboseInfo
readExternalData
class TxVerboseInfo extends IgniteDataTransferObject { /** */ private static final long serialVersionUID = 0L; /** Near xid version. */ private GridCacheVersion nearXidVer; /** Local node id. */ private UUID locNodeId; /** Local node consistent id. */ private Object locNodeConsistentId; /** Near node id. */ private UUID nearNodeId; /** Near node consistent id. */ private Object nearNodeConsistentId; /** Tx mapping type. */ private TxMappingType txMappingType; /** Dht node id. */ private UUID dhtNodeId; /** Dht node consistent id. */ private Object dhtNodeConsistentId; /** Used caches. */ private Map<Integer, String> usedCaches; /** Used cache groups. */ private Map<Integer, String> usedCacheGroups; /** Local tx keys. */ private List<TxVerboseKey> locTxKeys; /** Near only tx keys. */ private List<TxVerboseKey> nearOnlyTxKeys; /** {@inheritDoc} */ @Override protected void writeExternalData(ObjectOutput out) throws IOException { out.writeObject(nearXidVer); U.writeUuid(out, locNodeId); out.writeObject(locNodeConsistentId); U.writeUuid(out, nearNodeId); out.writeObject(nearNodeConsistentId); U.writeEnum(out, txMappingType); U.writeUuid(out, dhtNodeId); out.writeObject(dhtNodeConsistentId); U.writeMap(out, usedCaches); U.writeMap(out, usedCacheGroups); U.writeCollection(out, locTxKeys); U.writeCollection(out, nearOnlyTxKeys); } /** {@inheritDoc} */ @Override protected void readExternalData( byte protoVer, ObjectInput in ) throws IOException, ClassNotFoundException {<FILL_FUNCTION_BODY>} /** * @return Near xid version. */ public GridCacheVersion nearXidVersion() { return nearXidVer; } /** * @param nearXidVer New near xid version. */ public void nearXidVersion(GridCacheVersion nearXidVer) { this.nearXidVer = nearXidVer; } /** * @return Local node id. */ public UUID localNodeId() { return locNodeId; } /** * @param locNodeId New local node id. */ public void localNodeId(UUID locNodeId) { this.locNodeId = locNodeId; } /** * @return Local node consistent id. */ public Object localNodeConsistentId() { return locNodeConsistentId; } /** * @param locNodeConsistentId New local node consistent id. */ public void localNodeConsistentId(Object locNodeConsistentId) { this.locNodeConsistentId = locNodeConsistentId; } /** * @return Near node id. */ public UUID nearNodeId() { return nearNodeId; } /** * @param nearNodeId New near node id. */ public void nearNodeId(UUID nearNodeId) { this.nearNodeId = nearNodeId; } /** * @return Near node consistent id. */ public Object nearNodeConsistentId() { return nearNodeConsistentId; } /** * @param nearNodeConsistentId New near node consistent id. */ public void nearNodeConsistentId(Object nearNodeConsistentId) { this.nearNodeConsistentId = nearNodeConsistentId; } /** * @return Tx mapping type. */ public TxMappingType txMappingType() { return txMappingType; } /** * @param txMappingType New tx mapping type. */ public void txMappingType(TxMappingType txMappingType) { this.txMappingType = txMappingType; } /** * @return Dht node id. */ public UUID dhtNodeId() { return dhtNodeId; } /** * @param dhtNodeId New dht node id. */ public void dhtNodeId(UUID dhtNodeId) { this.dhtNodeId = dhtNodeId; } /** * @return Dht node consistent id. */ public Object dhtNodeConsistentId() { return dhtNodeConsistentId; } /** * @param dhtNodeConsistentId New dht node consistent id. */ public void dhtNodeConsistentId(Object dhtNodeConsistentId) { this.dhtNodeConsistentId = dhtNodeConsistentId; } /** * @return Used caches. */ public Map<Integer, String> usedCaches() { return usedCaches; } /** * @param usedCaches New used caches. */ public void usedCaches(Map<Integer, String> usedCaches) { this.usedCaches = usedCaches; } /** * @return Used cache groups. */ public Map<Integer, String> usedCacheGroups() { return usedCacheGroups; } /** * @param usedCacheGroups New used cache groups. */ public void usedCacheGroups(Map<Integer, String> usedCacheGroups) { this.usedCacheGroups = usedCacheGroups; } /** * @return Local tx keys. */ public List<TxVerboseKey> localTxKeys() { return locTxKeys; } /** * @param locTxKeys New local tx keys. */ public void localTxKeys(List<TxVerboseKey> locTxKeys) { this.locTxKeys = locTxKeys; } /** * @return Near only tx keys. */ public List<TxVerboseKey> nearOnlyTxKeys() { return nearOnlyTxKeys; } /** * @param nearOnlyTxKeys New near only tx keys. */ public void nearOnlyTxKeys(List<TxVerboseKey> nearOnlyTxKeys) { this.nearOnlyTxKeys = nearOnlyTxKeys; } /** {@inheritDoc} */ @Override public String toString() { return S.toString(TxVerboseInfo.class, this); } }
nearXidVer = (GridCacheVersion)in.readObject(); locNodeId = U.readUuid(in); locNodeConsistentId = in.readObject(); nearNodeId = U.readUuid(in); nearNodeConsistentId = in.readObject(); txMappingType = TxMappingType.fromOrdinal(in.readByte()); dhtNodeId = U.readUuid(in); dhtNodeConsistentId = in.readObject(); usedCaches = U.readHashMap(in); usedCacheGroups = U.readHashMap(in); locTxKeys = U.readList(in); nearOnlyTxKeys = U.readList(in);
1,704
178
1,882
<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/management/wal/WalTask.java
WalJob
run
class WalJob extends VisorJob<WalDeleteCommandArg, Collection<String>> { /** */ private static final long serialVersionUID = 0L; /** Auto injected logger */ @LoggerResource private transient IgniteLogger log; /** * @param arg WAL task argument. * @param debug Debug flag. */ public WalJob(WalDeleteCommandArg arg, boolean debug) { super(arg, debug); } /** {@inheritDoc} */ @Nullable @Override protected Collection<String> run(@Nullable WalDeleteCommandArg arg) throws IgniteException {<FILL_FUNCTION_BODY>} /** * Get unused wal segments. * * @param wal Database manager. * @return {@link Collection<String>} of absolute paths of unused WAL segments. * @throws IgniteCheckedException if failed. */ Collection<String> getUnusedWalSegments( GridCacheDatabaseSharedManager dbMgr, FileWriteAheadLogManager wal ) throws IgniteCheckedException { WALPointer lowBoundForTruncate = dbMgr.checkpointHistory().firstCheckpointPointer(); if (lowBoundForTruncate == null) return Collections.emptyList(); int maxIdx = resolveMaxReservedIndex(wal, lowBoundForTruncate); File[] walFiles = getWalArchiveDir().listFiles(WAL_ARCHIVE_FILE_FILTER); Collection<String> res = new ArrayList<>(walFiles != null && walFiles.length > 0 ? walFiles.length - 1 : 0); if (walFiles != null && walFiles.length > 0) { sortWalFiles(walFiles); // Obtain index of last archived WAL segment, it will not be deleted. long lastArchIdx = getIndex(walFiles[walFiles.length - 1]); for (File f : walFiles) { long fileIdx = getIndex(f); if (fileIdx < maxIdx && fileIdx < lastArchIdx) res.add(f.getAbsolutePath()); else break; } } return res; } /** * Delete unused wal segments. * * @param dbMgr Database manager. * @return {@link Collection<String>} of deleted WAL segment's files. * @throws IgniteCheckedException if failed. */ Collection<String> deleteUnusedWalSegments( GridCacheDatabaseSharedManager dbMgr, FileWriteAheadLogManager wal ) throws IgniteCheckedException { WALPointer lowBoundForTruncate = dbMgr.checkpointHistory().firstCheckpointPointer(); if (lowBoundForTruncate == null) return Collections.emptyList(); int maxIdx = resolveMaxReservedIndex(wal, lowBoundForTruncate); File[] walFiles = getWalArchiveDir().listFiles(WAL_ARCHIVE_FILE_FILTER); dbMgr.onWalTruncated(lowBoundForTruncate); int num = wal.truncate(lowBoundForTruncate); if (walFiles != null) { sortWalFiles(walFiles); Collection<String> res = new ArrayList<>(num); for (File walFile: walFiles) { if (getIndex(walFile) < maxIdx && num > 0) res.add(walFile.getAbsolutePath()); else break; num--; } return res; } else return Collections.emptyList(); } /** * */ private int resolveMaxReservedIndex(FileWriteAheadLogManager wal, WALPointer lowBoundForTruncate) { int resCnt = wal.reserved(null, lowBoundForTruncate); long highIdx = lowBoundForTruncate.index(); return (int)(highIdx - resCnt + 1); } /** * Get WAL archive directory from configuration. * * @return WAL archive directory. * @throws IgniteCheckedException if failed. */ private File getWalArchiveDir() throws IgniteCheckedException { IgniteConfiguration igCfg = ignite.context().config(); DataStorageConfiguration dsCfg = igCfg.getDataStorageConfiguration(); PdsFolderSettings resFldrs = ignite.context().pdsFolderResolver().resolveFolders(); String consId = resFldrs.folderName(); File dir; if (dsCfg.getWalArchivePath() != null) { File workDir0 = new File(dsCfg.getWalArchivePath()); dir = workDir0.isAbsolute() ? new File(workDir0, consId) : new File(U.resolveWorkDirectory(igCfg.getWorkDirectory(), dsCfg.getWalArchivePath(), false), consId); } else dir = new File(U.resolveWorkDirectory(igCfg.getWorkDirectory(), DataStorageConfiguration.DFLT_WAL_ARCHIVE_PATH, false), consId); if (!dir.exists()) throw new IgniteCheckedException("WAL archive directory does not exists" + dir.getAbsolutePath()); return dir; } /** * Sort WAL files according their indices. * * @param files Array of WAL segment files. */ private void sortWalFiles(File[] files) { Arrays.sort(files, new Comparator<File>() { @Override public int compare(File o1, File o2) { return Long.compare(getIndex(o1), getIndex(o2)); } }); } }
try { GridKernalContext cctx = ignite.context(); GridCacheDatabaseSharedManager dbMgr = (GridCacheDatabaseSharedManager)cctx.cache().context().database(); FileWriteAheadLogManager wal = (FileWriteAheadLogManager)cctx.cache().context().wal(); if (dbMgr == null || arg == null || wal == null) return null; if (arg instanceof WalPrintCommandArg) return getUnusedWalSegments(dbMgr, wal); else return deleteUnusedWalSegments(dbMgr, wal); } catch (IgniteCheckedException e) { U.error(log, "Failed to perform WAL task", e); throw new IgniteException("Failed to perform WAL task", e); }
1,487
204
1,691
<methods>public non-sealed void <init>() ,public Map<? extends org.apache.ignite.compute.ComputeJob,org.apache.ignite.cluster.ClusterNode> map(List<org.apache.ignite.cluster.ClusterNode>, VisorTaskArgument<org.apache.ignite.internal.management.wal.WalDeleteCommandArg>) ,public final org.apache.ignite.internal.management.wal.WalTaskResult 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 boolean debug,protected transient org.apache.ignite.internal.IgniteEx ignite,protected long start,protected org.apache.ignite.internal.management.wal.WalDeleteCommandArg taskArg
apache_ignite
ignite/modules/core/src/main/java/org/apache/ignite/internal/managers/collision/GridCollisionManager.java
GridCollisionManager
onCollision
class GridCollisionManager extends GridManagerAdapter<CollisionSpi> { /** Reference for external listener. */ private final AtomicReference<CollisionExternalListener> extLsnr = new AtomicReference<>(); /** * @param ctx Grid kernal context. */ public GridCollisionManager(GridKernalContext ctx) { super(ctx, ctx.config().getCollisionSpi()); } /** {@inheritDoc} */ @Override public void start() throws IgniteCheckedException { startSpi(); if (enabled()) { getSpi().setExternalCollisionListener(new CollisionExternalListener() { @Override public void onExternalCollision() { CollisionExternalListener lsnr = extLsnr.get(); if (lsnr != null) lsnr.onExternalCollision(); } }); } else log.info("Collision resolution is disabled (all jobs will be activated upon arrival)."); if (log.isDebugEnabled()) log.debug(startInfo()); } /** {@inheritDoc} */ @Override public void stop(boolean cancel) throws IgniteCheckedException { stopSpi(); // Unsubscribe. if (enabled()) getSpi().setExternalCollisionListener(null); if (log.isDebugEnabled()) log.debug(stopInfo()); } /** * Unsets external collision listener. */ public void unsetCollisionExternalListener() { if (enabled()) getSpi().setExternalCollisionListener(null); } /** * @param lsnr Listener to external collision events. */ public void setCollisionExternalListener(@Nullable CollisionExternalListener lsnr) { if (enabled()) { if (lsnr != null && !extLsnr.compareAndSet(null, lsnr)) assert false : "Collision external listener has already been set " + "(perhaps need to add support for multiple listeners)"; else if (log.isDebugEnabled()) log.debug("Successfully set external collision listener: " + lsnr); } } /** * Invoke collision SPI. * * @param waitJobs Collection of waiting jobs. * @param activeJobs Collection of active jobs. * @param heldJobs Collection of held jobs. */ public void onCollision( final Collection<CollisionJobContext> waitJobs, final Collection<CollisionJobContext> activeJobs, final Collection<CollisionJobContext> heldJobs ) {<FILL_FUNCTION_BODY>} }
if (enabled()) { if (log.isDebugEnabled()) log.debug("Resolving job collisions [waitJobs=" + waitJobs + ", activeJobs=" + activeJobs + ']'); getSpi().onCollision(new CollisionContext() { /** {@inheritDoc} */ @Override public Collection<CollisionJobContext> activeJobs() { return activeJobs; } /** {@inheritDoc} */ @Override public Collection<CollisionJobContext> waitingJobs() { return waitJobs; } /** {@inheritDoc} */ @Override public Collection<CollisionJobContext> heldJobs() { return heldJobs; } }); }
671
185
856
<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 boolean enabled() ,public void onAfterSpiStart() ,public void onBeforeSpiStart() ,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 final void onKernalStart(boolean) throws org.apache.ignite.IgniteCheckedException,public final void onKernalStop(boolean) ,public IgniteInternalFuture<?> onReconnected(boolean) throws org.apache.ignite.IgniteCheckedException,public void printMemoryStats() ,public final 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>protected final non-sealed org.apache.ignite.internal.GridKernalContext ctx,private final non-sealed boolean enabled,private boolean injected,protected final non-sealed org.apache.ignite.IgniteLogger log,private final Map<org.apache.ignite.spi.IgniteSpi,java.lang.Boolean> spiMap,private final non-sealed org.apache.ignite.spi.collision.CollisionSpi[] spis