proj_name
stringclasses 131
values | relative_path
stringlengths 30
228
| class_name
stringlengths 1
68
| func_name
stringlengths 1
48
| masked_class
stringlengths 78
9.82k
| func_body
stringlengths 46
9.61k
| len_input
int64 29
2.01k
| len_output
int64 14
1.94k
| total
int64 55
2.05k
| relevant_context
stringlengths 0
38.4k
|
|---|---|---|---|---|---|---|---|---|---|
apache_ignite
|
ignite/modules/core/src/main/java/org/apache/ignite/internal/processors/query/GridQueryCancel.java
|
GridQueryCancel
|
cancel
|
class GridQueryCancel {
/** */
private final List<QueryCancellable> cancelActions = new ArrayList<>(3);
/** */
private boolean canceled;
/**
* Adds a cancel action.
*
* @param clo Clo.
*/
public synchronized void add(QueryCancellable clo) throws QueryCancelledException {
assert clo != null;
if (canceled)
throw new QueryCancelledException();
cancelActions.add(clo);
}
/**
* Executes cancel closure.
*/
public synchronized void cancel() {<FILL_FUNCTION_BODY>}
/**
* Stops query execution if a user requested cancel.
*/
public synchronized void checkCancelled() throws QueryCancelledException {
if (canceled)
throw new QueryCancelledException();
}
/** */
public synchronized boolean isCanceled() {
return canceled;
}
}
|
if (canceled)
return;
canceled = true;
IgniteException ex = null;
// Run actions in the reverse order.
for (int i = cancelActions.size() - 1; i >= 0; i--) {
try {
QueryCancellable act = cancelActions.get(i);
act.doCancel();
}
catch (Exception e) {
if (ex == null)
ex = new IgniteException(e);
else
ex.addSuppressed(e);
}
}
if (ex != null)
throw ex;
| 252
| 158
| 410
|
<no_super_class>
|
apache_ignite
|
ignite/modules/core/src/main/java/org/apache/ignite/internal/processors/query/GridQueryRowDescriptorImpl.java
|
GridQueryRowDescriptorImpl
|
getAlternativeColumnId
|
class GridQueryRowDescriptorImpl implements GridQueryRowDescriptor {
/** Non existent column. */
public static final int COL_NOT_EXISTS = -1;
/** */
private final GridCacheContextInfo<?, ?> cacheInfo;
/** */
private final GridQueryTypeDescriptor type;
/** */
private volatile String[] fields;
/** */
private volatile GridQueryProperty[] props;
/** */
private volatile Set<String> rowKeyColumnNames;
/** Id of user-defined key column */
private volatile int keyAliasColId;
/** Id of user-defined value column */
private volatile int valAliasColId;
/**
* Constructor.
*
* @param cacheInfo Cache context.
* @param type Type descriptor.
*/
public GridQueryRowDescriptorImpl(GridCacheContextInfo<?, ?> cacheInfo, GridQueryTypeDescriptor type) {
assert type != null;
this.cacheInfo = cacheInfo;
this.type = type;
onMetadataUpdated();
}
/** {@inheritDoc} */
@SuppressWarnings({"WeakerAccess", "ToArrayCallWithZeroLengthArrayArgument"})
@Override public final void onMetadataUpdated() {
fields = type.fields().keySet().toArray(new String[type.fields().size()]);
props = new GridQueryProperty[fields.length];
for (int i = 0; i < fields.length; i++) {
GridQueryProperty p = type.property(fields[i]);
assert p != null : fields[i];
props[i] = p;
}
List<String> fieldsList = Arrays.asList(fields);
keyAliasColId = (type.keyFieldName() != null) ?
QueryUtils.DEFAULT_COLUMNS_COUNT + fieldsList.indexOf(type.keyFieldAlias()) : COL_NOT_EXISTS;
valAliasColId = (type.valueFieldName() != null) ?
QueryUtils.DEFAULT_COLUMNS_COUNT + fieldsList.indexOf(type.valueFieldAlias()) : COL_NOT_EXISTS;
rowKeyColumnNames = Arrays.stream(props).filter(GridQueryProperty::key)
.map(GridQueryProperty::name)
.collect(Collectors.toSet());
}
/** {@inheritDoc} */
@Override public GridQueryTypeDescriptor type() {
return type;
}
/** {@inheritDoc} */
@Override @Nullable public GridCacheContext<?, ?> context() {
return cacheInfo.cacheContext();
}
/** {@inheritDoc} */
@Override public int fieldsCount() {
return fields.length;
}
/** {@inheritDoc} */
@Override public Object getFieldValue(Object key, Object val, int fieldIdx) {
try {
return props[fieldIdx].value(key, val);
}
catch (IgniteCheckedException e) {
throw new IgniteException(e);
}
}
/** {@inheritDoc} */
@Override public void setFieldValue(Object key, Object val, Object fieldVal, int fieldIdx) {
try {
props[fieldIdx].setValue(key, val, fieldVal);
}
catch (IgniteCheckedException e) {
throw new IgniteException(e);
}
}
/** {@inheritDoc} */
@Override public boolean isFieldKeyProperty(int fieldIdx) {
return props[fieldIdx].key();
}
/** {@inheritDoc} */
@Override public boolean isKeyColumn(int colId) {
assert colId >= 0;
return colId == QueryUtils.KEY_COL || colId == keyAliasColId;
}
/** {@inheritDoc} */
@Override public boolean isValueColumn(int colId) {
assert colId >= 0;
return colId == QueryUtils.VAL_COL || colId == valAliasColId;
}
/** {@inheritDoc} */
@Override public int getAlternativeColumnId(int colId) {<FILL_FUNCTION_BODY>}
/** {@inheritDoc} */
@Override public Set<String> getRowKeyColumnNames() {
return new HashSet<>(rowKeyColumnNames);
}
}
|
if (keyAliasColId > 0) {
if (colId == QueryUtils.KEY_COL)
return keyAliasColId;
else if (colId == keyAliasColId)
return QueryUtils.KEY_COL;
}
if (valAliasColId > 0) {
if (colId == QueryUtils.VAL_COL)
return valAliasColId;
else if (colId == valAliasColId)
return QueryUtils.VAL_COL;
}
return colId;
| 1,086
| 136
| 1,222
|
<no_super_class>
|
apache_ignite
|
ignite/modules/core/src/main/java/org/apache/ignite/internal/processors/query/QueryEntityEx.java
|
QueryEntityEx
|
setAffinityKeyInlineSize
|
class QueryEntityEx extends QueryEntity {
/** */
private static final long serialVersionUID = 0L;
/** Fields that must have non-null value. */
private Set<String> notNullFields;
/** Whether to preserve order specified by {@link #getKeyFields()} or not. */
private boolean preserveKeysOrder;
/** Whether a primary key should be autocreated or not. */
private boolean implicitPk;
/** Whether absent PK parts should be filled with defaults or not. */
private boolean fillAbsentPKsWithDefaults;
/** INLINE_SIZE for PK index. */
private Integer pkInlineSize;
/** INLINE_SIZE for affinity field index. */
private Integer affKeyInlineSize;
/**
* Default constructor.
*/
public QueryEntityEx() {
// No-op.
}
/**
* Copying constructor.
*
* @param other Instance to copy.
*/
public QueryEntityEx(QueryEntity other) {
super(other);
if (other instanceof QueryEntityEx) {
QueryEntityEx other0 = (QueryEntityEx)other;
notNullFields = other0.notNullFields != null ? new HashSet<>(other0.notNullFields) : null;
preserveKeysOrder = other0.preserveKeysOrder;
implicitPk = other0.implicitPk;
fillAbsentPKsWithDefaults = other0.fillAbsentPKsWithDefaults;
pkInlineSize = other0.pkInlineSize != null ? other0.pkInlineSize : -1;
affKeyInlineSize = other0.affKeyInlineSize != null ? other0.affKeyInlineSize : -1;
}
}
/** {@inheritDoc} */
@Override @Nullable public Set<String> getNotNullFields() {
return notNullFields;
}
/** {@inheritDoc} */
@Override public QueryEntity setNotNullFields(@Nullable Set<String> notNullFields) {
this.notNullFields = notNullFields;
return this;
}
/**
* @return {@code true} if order should be preserved, {@code false} otherwise.
*/
public boolean isPreserveKeysOrder() {
return preserveKeysOrder;
}
/**
* @param preserveKeysOrder Whether the order should be preserved or not.
* @return {@code this} for chaining.
*/
public QueryEntity setPreserveKeysOrder(boolean preserveKeysOrder) {
this.preserveKeysOrder = preserveKeysOrder;
return this;
}
/** */
public boolean implicitPk() {
return implicitPk;
}
/** */
public QueryEntity implicitPk(boolean implicitPk) {
this.implicitPk = implicitPk;
return this;
}
/**
* @return {@code true} if absent PK parts should be filled with defaults, {@code false} otherwise.
*/
public boolean fillAbsentPKsWithDefaults() {
return fillAbsentPKsWithDefaults;
}
/**
* @param fillAbsentPKsWithDefaults Whether absent PK parts should be filled with defaults or not.
* @return {@code this} for chaining.
*/
public QueryEntity fillAbsentPKsWithDefaults(boolean fillAbsentPKsWithDefaults) {
this.fillAbsentPKsWithDefaults = fillAbsentPKsWithDefaults;
return this;
}
/**
* Returns INLINE_SIZE for PK index.
*
* @return INLINE_SIZE for PK index.
*/
public Integer getPrimaryKeyInlineSize() {
return pkInlineSize;
}
/**
* Sets INLINE_SIZE for PK index.
*
* @param pkInlineSize INLINE_SIZE for PK index, when {@code null} - inline size is calculated automativally.
* @return {@code this} for chaining.
*/
public QueryEntity setPrimaryKeyInlineSize(Integer pkInlineSize) {
if (pkInlineSize != null && pkInlineSize < 0) {
throw new CacheException("Inline size for sorted primary key cannot be negative. "
+ "[inlineSize=" + pkInlineSize + ']');
}
this.pkInlineSize = pkInlineSize;
return this;
}
/**
* Returns INLINE_SIZE for affinity field index.
*
* @return INLINE_SIZE for affinity field index.
*/
public Integer getAffinityKeyInlineSize() {
return affKeyInlineSize;
}
/**
* Sets INLINE_SIZE for AFFINITY_KEY index.
*
* @param affKeyInlineSize INLINE_SIZE for AFFINITY_KEY index, when {@code null} - inline size is calculated automativally.
* @return {@code this} for chaining.
*/
public QueryEntity setAffinityKeyInlineSize(Integer affKeyInlineSize) {<FILL_FUNCTION_BODY>}
/** {@inheritDoc} */
@Override public boolean equals(Object o) {
if (this == o)
return true;
if (o == null || getClass() != o.getClass())
return false;
QueryEntityEx entity = (QueryEntityEx)o;
return super.equals(entity) && F.eq(notNullFields, entity.notNullFields)
&& preserveKeysOrder == entity.preserveKeysOrder
&& implicitPk == entity.implicitPk
&& F.eq(pkInlineSize, entity.pkInlineSize)
&& F.eq(affKeyInlineSize, entity.affKeyInlineSize);
}
/** {@inheritDoc} */
@Override public int hashCode() {
int res = super.hashCode();
res = 31 * res + (notNullFields != null ? notNullFields.hashCode() : 0);
res = 31 * res + (preserveKeysOrder ? 1 : 0);
res = 31 * res + (implicitPk ? 1 : 0);
res = 31 * res + (pkInlineSize != null ? pkInlineSize.hashCode() : 0);
res = 31 * res + (affKeyInlineSize != null ? affKeyInlineSize.hashCode() : 0);
return res;
}
/** {@inheritDoc} */
@Override public String toString() {
return S.toString(QueryEntityEx.class, this);
}
}
|
if (affKeyInlineSize != null && affKeyInlineSize < 0) {
throw new CacheException("Inline size for affinity fieled index cannot be negative. "
+ "[inlineSize=" + affKeyInlineSize + ']');
}
this.affKeyInlineSize = affKeyInlineSize;
return this;
| 1,670
| 91
| 1,761
|
<methods>public void <init>() ,public void <init>(org.apache.ignite.cache.QueryEntity) ,public void <init>(java.lang.String, java.lang.String) ,public void <init>(Class<?>, Class<?>) ,public org.apache.ignite.cache.QueryEntity addQueryField(java.lang.String, java.lang.String, java.lang.String) ,public boolean equals(java.lang.Object) ,public java.lang.String findKeyType() ,public java.lang.String findValueType() ,public Map<java.lang.String,java.lang.String> getAliases() ,public Map<java.lang.String,java.lang.Object> getDefaultFieldValues() ,public LinkedHashMap<java.lang.String,java.lang.String> getFields() ,public Map<java.lang.String,java.lang.Integer> getFieldsPrecision() ,public Map<java.lang.String,java.lang.Integer> getFieldsScale() ,public Collection<org.apache.ignite.cache.QueryIndex> getIndexes() ,public java.lang.String getKeyFieldName() ,public Set<java.lang.String> getKeyFields() ,public java.lang.String getKeyType() ,public Set<java.lang.String> getNotNullFields() ,public java.lang.String getTableName() ,public java.lang.String getValueFieldName() ,public java.lang.String getValueType() ,public int hashCode() ,public org.apache.ignite.cache.QueryEntityPatch makePatch(org.apache.ignite.cache.QueryEntity) ,public org.apache.ignite.cache.QueryEntity setAliases(Map<java.lang.String,java.lang.String>) ,public org.apache.ignite.cache.QueryEntity setDefaultFieldValues(Map<java.lang.String,java.lang.Object>) ,public org.apache.ignite.cache.QueryEntity setFields(LinkedHashMap<java.lang.String,java.lang.String>) ,public org.apache.ignite.cache.QueryEntity setFieldsPrecision(Map<java.lang.String,java.lang.Integer>) ,public org.apache.ignite.cache.QueryEntity setFieldsScale(Map<java.lang.String,java.lang.Integer>) ,public org.apache.ignite.cache.QueryEntity setIndexes(Collection<org.apache.ignite.cache.QueryIndex>) ,public org.apache.ignite.cache.QueryEntity setKeyFieldName(java.lang.String) ,public org.apache.ignite.cache.QueryEntity setKeyFields(Set<java.lang.String>) ,public org.apache.ignite.cache.QueryEntity setKeyType(java.lang.String) ,public org.apache.ignite.cache.QueryEntity setNotNullFields(Set<java.lang.String>) ,public org.apache.ignite.cache.QueryEntity setTableName(java.lang.String) ,public org.apache.ignite.cache.QueryEntity setValueFieldName(java.lang.String) ,public org.apache.ignite.cache.QueryEntity setValueType(java.lang.String) ,public java.lang.String toString() <variables>private Set<java.lang.String> _notNullFields,private Map<java.lang.String,java.lang.String> aliases,private Map<java.lang.String,java.lang.Object> defaultFieldValues,private LinkedHashMap<java.lang.String,java.lang.String> fields,private Map<java.lang.String,java.lang.Integer> fieldsPrecision,private Map<java.lang.String,java.lang.Integer> fieldsScale,private Collection<org.apache.ignite.cache.QueryIndex> idxs,private java.lang.String keyFieldName,private Set<java.lang.String> keyFields,private java.lang.String keyType,private static final long serialVersionUID,private java.lang.String tableName,private java.lang.String valType,private java.lang.String valueFieldName
|
apache_ignite
|
ignite/modules/core/src/main/java/org/apache/ignite/internal/processors/query/QueryIndexDescriptorImpl.java
|
QueryIndexDescriptorImpl
|
addField
|
class QueryIndexDescriptorImpl implements GridQueryIndexDescriptor {
/** Fields sorted by order number. */
private final Collection<T2<String, Integer>> fields = new TreeSet<>(
new Comparator<T2<String, Integer>>() {
@Override public int compare(T2<String, Integer> o1, T2<String, Integer> o2) {
if (o1.get2().equals(o2.get2())) // Order is equal, compare field names to avoid replace in Set.
return o1.get1().compareTo(o2.get1());
return o1.get2() < o2.get2() ? -1 : 1;
}
});
/** Fields which should be indexed in descending order. */
private Collection<String> descendings;
/** Type descriptor. */
@GridToStringExclude
private final QueryTypeDescriptorImpl typDesc;
/** Index name. */
private final String name;
/** */
private final QueryIndexType type;
/** */
private final int inlineSize;
/**
* Constructor.
*
* @param typDesc Type descriptor.
* @param name Index name.
* @param type Type.
* @param inlineSize Inline size.
*/
public QueryIndexDescriptorImpl(QueryTypeDescriptorImpl typDesc, String name, QueryIndexType type, int inlineSize) {
assert type != null;
this.typDesc = typDesc;
this.name = name;
this.type = type;
this.inlineSize = inlineSize;
}
/**
* @return Type descriptor.
*/
public QueryTypeDescriptorImpl typeDescriptor() {
return typDesc;
}
/** {@inheritDoc} */
@Override public String name() {
return name;
}
/** {@inheritDoc} */
@Override public Collection<String> fields() {
Collection<String> res = new ArrayList<>(fields.size());
for (T2<String, Integer> t : fields)
res.add(t.get1());
return res;
}
/** {@inheritDoc} */
@Override public int inlineSize() {
return inlineSize;
}
/** {@inheritDoc} */
@Override public boolean descending(String field) {
return descendings != null && descendings.contains(field);
}
/**
* Adds field to this index.
*
* @param field Field name.
* @param orderNum Field order number in this index.
* @param descending Sort order.
* @return This instance for chaining.
* @throws IgniteCheckedException If failed.
*/
public QueryIndexDescriptorImpl addField(String field, int orderNum, boolean descending)
throws IgniteCheckedException {<FILL_FUNCTION_BODY>}
/** {@inheritDoc} */
@Override public QueryIndexType type() {
return type;
}
/** {@inheritDoc} */
@Override public String toString() {
return S.toString(QueryIndexDescriptorImpl.class, this);
}
}
|
if (!typDesc.hasField(field))
throw new IgniteCheckedException("Field not found: " + field);
fields.add(new T2<>(field, orderNum));
if (descending) {
if (descendings == null)
descendings = new HashSet<>();
descendings.add(field);
}
return this;
| 783
| 98
| 881
|
<no_super_class>
|
apache_ignite
|
ignite/modules/core/src/main/java/org/apache/ignite/internal/processors/query/QueryTypeNameKey.java
|
QueryTypeNameKey
|
equals
|
class QueryTypeNameKey {
/** */
private final String cacheName;
/** */
private final String typeName;
/**
* @param cacheName Cache name.
* @param typeName Type name.
*/
public QueryTypeNameKey(@Nullable String cacheName, String typeName) {
assert !F.isEmpty(typeName) : typeName;
this.cacheName = cacheName;
this.typeName = typeName;
}
/** {@inheritDoc} */
@Override public boolean equals(Object o) {<FILL_FUNCTION_BODY>}
/** {@inheritDoc} */
@Override public int hashCode() {
return 31 * (cacheName != null ? cacheName.hashCode() : 0) + typeName.hashCode();
}
/** {@inheritDoc} */
@Override public String toString() {
return S.toString(QueryTypeNameKey.class, this);
}
}
|
if (this == o)
return true;
if (o == null || getClass() != o.getClass())
return false;
QueryTypeNameKey other = (QueryTypeNameKey)o;
return (cacheName != null ? cacheName.equals(other.cacheName) : other.cacheName == null) &&
typeName.equals(other.typeName);
| 242
| 99
| 341
|
<no_super_class>
|
apache_ignite
|
ignite/modules/core/src/main/java/org/apache/ignite/internal/processors/query/messages/GridQueryKillResponse.java
|
GridQueryKillResponse
|
readFrom
|
class GridQueryKillResponse implements Message {
/** */
public static final short TYPE_CODE = 173;
/** */
private static final long serialVersionUID = 0L;
/** Error text. */
private String errMsg;
/** Request id.*/
private long reqId;
/**
* Default constructor.
*/
public GridQueryKillResponse() {
// No-op.
}
/**
* @param reqId Request id.
* @param errMsg Error message.
*/
public GridQueryKillResponse(long reqId, String errMsg) {
this.reqId = reqId;
this.errMsg = errMsg;
}
/**
* @return Request id.
*/
public long requestId() {
return reqId;
}
/**
* @return Error text or {@code null} if no error.
*/
public String error() {
return errMsg;
}
/** {@inheritDoc} */
@Override public void onAckReceived() {
// No-op.
}
/** {@inheritDoc} */
@Override public boolean writeTo(ByteBuffer buf, MessageWriter writer) {
writer.setBuffer(buf);
if (!writer.isHeaderWritten()) {
if (!writer.writeHeader(directType(), fieldsCount()))
return false;
writer.onHeaderWritten();
}
switch (writer.state()) {
case 0:
if (!writer.writeString("errMsg", errMsg))
return false;
writer.incrementState();
case 1:
if (!writer.writeLong("reqId", reqId))
return false;
writer.incrementState();
}
return true;
}
/** {@inheritDoc} */
@Override public boolean readFrom(ByteBuffer buf, MessageReader reader) {<FILL_FUNCTION_BODY>}
/** {@inheritDoc} */
@Override public short directType() {
return TYPE_CODE;
}
/** {@inheritDoc} */
@Override public byte fieldsCount() {
return 2;
}
/** {@inheritDoc} */
@Override public String toString() {
return S.toString(GridQueryKillResponse.class, this);
}
}
|
reader.setBuffer(buf);
if (!reader.beforeMessageRead())
return false;
switch (reader.state()) {
case 0:
errMsg = reader.readString("errMsg");
if (!reader.isLastRead())
return false;
reader.incrementState();
case 1:
reqId = reader.readLong("reqId");
if (!reader.isLastRead())
return false;
reader.incrementState();
}
return reader.afterMessageRead(GridQueryKillResponse.class);
| 594
| 149
| 743
|
<no_super_class>
|
apache_ignite
|
ignite/modules/core/src/main/java/org/apache/ignite/internal/processors/query/property/QueryReadOnlyMethodsAccessor.java
|
QueryReadOnlyMethodsAccessor
|
getValue
|
class QueryReadOnlyMethodsAccessor implements QueryPropertyAccessor {
/** */
private final Method getter;
/** */
private final String propName;
/**
* @param getter Getter method.
* @param propName Property name.
*/
public QueryReadOnlyMethodsAccessor(Method getter, String propName) {
getter.setAccessible(true);
this.getter = getter;
this.propName = propName;
}
/** {@inheritDoc} */
@Override public Object getValue(Object obj) throws IgniteCheckedException {<FILL_FUNCTION_BODY>}
/** {@inheritDoc} */
@Override public void setValue(Object obj, Object newVal) throws IgniteCheckedException {
throw new UnsupportedOperationException("Property is read-only [type=" + getType() +
", property=" + propName + ']');
}
/** {@inheritDoc} */
@Override public String getPropertyName() {
return propName;
}
/** {@inheritDoc} */
@Override public Class<?> getType() {
return getter.getReturnType();
}
}
|
try {
return getter.invoke(obj);
}
catch (Exception e) {
throw new IgniteCheckedException("Failed to invoke getter method " +
"[type=" + getType() + ", property=" + propName + ']', e);
}
| 298
| 73
| 371
|
<no_super_class>
|
apache_ignite
|
ignite/modules/core/src/main/java/org/apache/ignite/internal/processors/query/running/QueryHistoryTracker.java
|
QueryHistoryTracker
|
shrink
|
class QueryHistoryTracker {
/** Query history. */
private final ConcurrentHashMap<QueryHistoryKey, QueryHistory> qryHist;
/** Queue. */
private final ConcurrentLinkedDeque8<QueryHistory> evictionQueue = new ConcurrentLinkedDeque8<>();
/** History size. */
private final int histSz;
/**
* @param histSz History size.
*/
QueryHistoryTracker(int histSz) {
this.histSz = histSz;
qryHist = histSz > 0 ? new ConcurrentHashMap<>(histSz) : null;
}
/**
* @param failed {@code True} if query execution failed.
*/
void collectHistory(GridRunningQueryInfo runningQryInfo, boolean failed) {
if (histSz <= 0)
return;
String qry = runningQryInfo.query();
String schema = runningQryInfo.schemaName();
boolean loc = runningQryInfo.local();
long startTime = runningQryInfo.startTime();
long duration = U.currentTimeMillis() - startTime;
QueryHistory hist = new QueryHistory(qry, schema, loc, startTime, duration, failed);
QueryHistory mergedHist = qryHist.merge(hist.key(), hist, QueryHistory::aggregateWithNew);
if (touch(mergedHist) && qryHist.size() > histSz)
shrink();
}
/**
* @param entry Entry Which was updated
* @return {@code true} In case entry is new and has been added, {@code false} otherwise.
*/
private boolean touch(QueryHistory entry) {
Node<QueryHistory> node = entry.link();
// Entry has not been enqueued yet.
if (node == null) {
node = evictionQueue.offerLastx(entry);
if (!entry.replaceLink(null, node)) {
// Was concurrently added, need to clear it from queue.
removeLink(node);
return false;
}
if (node.item() == null) {
// Was concurrently shrinked.
entry.replaceLink(node, null);
return false;
}
return true;
}
else if (removeLink(node)) {
// Move node to tail.
Node<QueryHistory> newNode = evictionQueue.offerLastx(entry);
if (!entry.replaceLink(node, newNode)) {
// Was concurrently added, need to clear it from queue.
removeLink(newNode);
}
}
// Entry is already in queue.
return false;
}
/**
* Tries to remove one item from queue.
*/
private void shrink() {<FILL_FUNCTION_BODY>}
/**
* @param node Node which should be unlinked from eviction queue.
* @return {@code true} If node was unlinked.
*/
private boolean removeLink(Node<QueryHistory> node) {
return evictionQueue.unlinkx(node);
}
/**
* Gets SQL query history. Size of history could be configured via
* {@link SqlConfiguration#setSqlQueryHistorySize(int)}.
*
* @return SQL queries history aggregated by query text, schema and local flag.
*/
Map<QueryHistoryKey, QueryHistory> queryHistory() {
if (histSz <= 0)
return Collections.emptyMap();
return Collections.unmodifiableMap(qryHist);
}
}
|
while (true) {
QueryHistory entry = evictionQueue.poll();
if (entry == null)
return;
// History has been changed if we can't remove history entry.
// In this case eviction queue already offered by the entry and we don't put it back. Just try to do new
// attempt to remove oldest entry.
if (qryHist.remove(entry.key(), entry))
return;
}
| 900
| 113
| 1,013
|
<no_super_class>
|
apache_ignite
|
ignite/modules/core/src/main/java/org/apache/ignite/internal/processors/query/schema/SchemaIndexCacheCompoundFuture.java
|
SchemaIndexCacheCompoundFuture
|
error
|
class SchemaIndexCacheCompoundFuture extends GridCompoundFuture<SchemaIndexCacheStat, SchemaIndexCacheStat> {
/** Container for the first index rebuild error. */
private final AtomicReference<Throwable> errRef = new AtomicReference<>();
/** {@inheritDoc} */
@Override protected boolean ignoreFailure(Throwable err) {
errRef.compareAndSet(null, err);
return true;
}
/** {@inheritDoc} */
@Override public Throwable error() {<FILL_FUNCTION_BODY>}
}
|
Throwable err0 = super.error();
Throwable err1 = errRef.get();
if (err0 != null && err1 != null)
err0.addSuppressed(err1);
return err0 != null ? err0 : err1;
| 139
| 73
| 212
|
<methods>public void <init>() ,public void <init>(IgniteReducer<org.apache.ignite.internal.processors.query.schema.SchemaIndexCacheStat,org.apache.ignite.internal.processors.query.schema.SchemaIndexCacheStat>) ,public final GridCompoundFuture<org.apache.ignite.internal.processors.query.schema.SchemaIndexCacheStat,org.apache.ignite.internal.processors.query.schema.SchemaIndexCacheStat> add(IgniteInternalFuture<org.apache.ignite.internal.processors.query.schema.SchemaIndexCacheStat>) ,public final void apply(IgniteInternalFuture<org.apache.ignite.internal.processors.query.schema.SchemaIndexCacheStat>) ,public boolean cancel() throws org.apache.ignite.IgniteCheckedException,public final Collection<IgniteInternalFuture<org.apache.ignite.internal.processors.query.schema.SchemaIndexCacheStat>> futures() ,public final boolean initialized() ,public final GridCompoundFuture<org.apache.ignite.internal.processors.query.schema.SchemaIndexCacheStat,org.apache.ignite.internal.processors.query.schema.SchemaIndexCacheStat> markInitialized() ,public java.lang.String toString() <variables>private static final AtomicIntegerFieldUpdater<GridCompoundFuture#RAW> FLAGS_UPD,private static final int INIT_FLAG,private static final AtomicIntegerFieldUpdater<GridCompoundFuture#RAW> LSNR_CALLS_UPD,private final java.util.concurrent.locks.ReentrantReadWriteLock compoundsLock,private volatile java.lang.Object futs,private volatile int initFlag,private volatile int lsnrCalls,private final non-sealed IgniteReducer<org.apache.ignite.internal.processors.query.schema.SchemaIndexCacheStat,org.apache.ignite.internal.processors.query.schema.SchemaIndexCacheStat> rdc,private static final long serialVersionUID,private volatile int size
|
apache_ignite
|
ignite/modules/core/src/main/java/org/apache/ignite/internal/processors/query/schema/SchemaIndexCacheVisitorImpl.java
|
SchemaIndexCacheVisitorImpl
|
indexStatStr
|
class SchemaIndexCacheVisitorImpl implements SchemaIndexCacheVisitor {
/** Is extra index rebuild logging enabled. */
private final boolean collectStat = getBoolean(IGNITE_ENABLE_EXTRA_INDEX_REBUILD_LOGGING, false);
/** Cache context. */
private final GridCacheContext cctx;
/** Cancellation token. */
private final IndexRebuildCancelToken cancelTok;
/** Future for create/rebuild index. */
protected final GridFutureAdapter<Void> buildIdxFut;
/** Logger. */
protected final IgniteLogger log;
/**
* Constructor.
*
* @param cctx Cache context.
* @param cancelTok Cancellation token.
* @param buildIdxFut Future for create/rebuild index.
*/
public SchemaIndexCacheVisitorImpl(
GridCacheContext<?, ?> cctx,
IndexRebuildCancelToken cancelTok,
GridFutureAdapter<Void> buildIdxFut
) {
assert nonNull(cctx);
assert nonNull(buildIdxFut);
if (cctx.isNear())
cctx = ((GridNearCacheAdapter)cctx.cache()).dht().context();
this.cctx = cctx;
this.buildIdxFut = buildIdxFut;
this.cancelTok = cancelTok;
log = cctx.kernalContext().log(getClass());
}
/** {@inheritDoc} */
@Override public void visit(SchemaIndexCacheVisitorClosure clo) {
assert nonNull(clo);
List<GridDhtLocalPartition> locParts = cctx.topology().localPartitions();
if (locParts.isEmpty()) {
buildIdxFut.onDone();
return;
}
cctx.cache().metrics0().addIndexBuildPartitionsLeftCount(locParts.size());
cctx.cache().metrics0().resetIndexRebuildKeyProcessed();
beforeExecute();
AtomicInteger partsCnt = new AtomicInteger(locParts.size());
AtomicBoolean stop = new AtomicBoolean();
// To avoid a race between clearing pageMemory (on a cache stop ex. deactivation)
// and rebuilding indexes, which can lead to a fail of the node.
SchemaIndexCacheCompoundFuture buildIdxCompoundFut = new SchemaIndexCacheCompoundFuture();
for (GridDhtLocalPartition locPart : locParts) {
GridWorkerFuture<SchemaIndexCacheStat> workerFut = new GridWorkerFuture<>();
GridWorker worker =
new SchemaIndexCachePartitionWorker(cctx, locPart, stop, cancelTok, clo, workerFut, partsCnt);
workerFut.setWorker(worker);
buildIdxCompoundFut.add(workerFut);
cctx.kernalContext().pools().buildIndexExecutorService().execute(worker);
}
buildIdxCompoundFut.listen(() -> {
Throwable err = buildIdxCompoundFut.error();
if (isNull(err) && collectStat && log.isInfoEnabled()) {
try {
SchemaIndexCacheStat resStat = new SchemaIndexCacheStat();
buildIdxCompoundFut.futures().stream()
.map(IgniteInternalFuture::result)
.filter(Objects::nonNull)
.forEach(resStat::accumulate);
log.info(indexStatStr(resStat));
}
catch (Exception e) {
log.error("Error when trying to print index build/rebuild statistics [cacheName=" +
cctx.cache().name() + ", grpName=" + cctx.group().name() + "]", e);
}
}
buildIdxFut.onDone(err);
});
buildIdxCompoundFut.markInitialized();
}
/**
* Prints index cache stats to log.
*
* @param stat Index cache stats.
* @throws IgniteCheckedException if failed to get index size.
*/
private String indexStatStr(SchemaIndexCacheStat stat) throws IgniteCheckedException {<FILL_FUNCTION_BODY>}
/**
* This method is called before creating or rebuilding indexes.
* Used only for test.
*/
protected void beforeExecute(){
//no-op
}
/** {@inheritDoc} */
@Override public String toString() {
return S.toString(SchemaIndexCacheVisitorImpl.class, this);
}
}
|
SB res = new SB();
res.a("Details for cache rebuilding [name=" + cctx.cache().name() + ", grpName=" + cctx.group().name() + ']');
res.a(U.nl());
res.a(" Scanned rows " + stat.scannedKeys() + ", visited types " + stat.typeNames());
res.a(U.nl());
IndexProcessor idxProc = cctx.kernalContext().indexProcessor();
for (QueryTypeDescriptorImpl type : stat.types()) {
res.a(" Type name=" + type.name());
res.a(U.nl());
String pk = QueryUtils.PRIMARY_KEY_INDEX;
String tblName = type.tableName();
res.a(" Index: name=" + pk + ", size=" + idxProc.index(new IndexName(
cctx.cache().name(), type.schemaName(), tblName, pk)).unwrap(InlineIndex.class).totalCount());
res.a(U.nl());
for (GridQueryIndexDescriptor descriptor : type.indexes().values()) {
long size = idxProc.index(new IndexName(
cctx.cache().name(), type.schemaName(), tblName, pk)).unwrap(InlineIndex.class).totalCount();
res.a(" Index: name=" + descriptor.name() + ", size=" + size);
res.a(U.nl());
}
}
return res.toString();
| 1,144
| 388
| 1,532
|
<no_super_class>
|
apache_ignite
|
ignite/modules/core/src/main/java/org/apache/ignite/internal/processors/query/schema/management/AbstractIndexDescriptorFactory.java
|
AbstractIndexDescriptorFactory
|
keyDefinition
|
class AbstractIndexDescriptorFactory implements IndexDescriptorFactory {
/** */
protected static LinkedHashMap<String, IndexKeyDefinition> indexDescriptorToKeysDefinition(
GridQueryIndexDescriptor idxDesc,
GridQueryTypeDescriptor typeDesc
) {
LinkedHashMap<String, IndexKeyDefinition> keyDefs = new LinkedHashMap<>(idxDesc.fields().size());
for (String field : idxDesc.fields())
keyDefs.put(field, keyDefinition(typeDesc, field, !idxDesc.descending(field)));
return keyDefs;
}
/** */
protected static IndexKeyDefinition keyDefinition(GridQueryTypeDescriptor typeDesc, String field, boolean ascOrder) {<FILL_FUNCTION_BODY>}
}
|
Order order = new Order(ascOrder ? SortOrder.ASC : SortOrder.DESC, null);
GridQueryProperty prop = typeDesc.property(field);
// Try to find property by alternative key field name.
if (prop == null && F.eq(field, QueryUtils.KEY_FIELD_NAME) && !F.isEmpty(typeDesc.keyFieldName()))
prop = typeDesc.property(typeDesc.keyFieldName());
Class<?> fieldType = F.eq(field, QueryUtils.KEY_FIELD_NAME) ? typeDesc.keyClass() :
F.eq(field, QueryUtils.VAL_FIELD_NAME) ? typeDesc.valueClass() : prop.type();
int fieldPrecision = prop != null ? prop.precision() : -1;
return new IndexKeyDefinition(IndexKeyType.forClass(fieldType).code(), order, fieldPrecision);
| 180
| 220
| 400
|
<no_super_class>
|
apache_ignite
|
ignite/modules/core/src/main/java/org/apache/ignite/internal/processors/query/stat/Hasher.java
|
Hasher
|
fastHash
|
class Hasher {
/** */
private static final int SEED = 123456;
/** */
private static final int CHUNK_SIZE = 16;
/** */
private static final long C1 = 0x87c37b91114253d5L;
/** */
private static final long C2 = 0x4cf5ad432745937fL;
/** */
private long h1;
/** */
private long h2;
/** */
private int len;
/**
* Calculate hash by specified byte array.
*
* @param arr Array to calculate hash by.
* @return Hash value.
*/
public long fastHash(byte[] arr) {
return fastHash(arr, 0, arr.length);
}
/**
* Calculate hash by specified part of byte array.
*
* @param arr Array to calculate hash by.
* @param off Offset.
* @param len Length.
* @return Hash value.
*/
public long fastHash(byte[] arr, int off, int len) {<FILL_FUNCTION_BODY>}
/**
* Mix two long numbers.
*
* @param k1 The first number.
* @param k2 The second number.
*/
private void bmix64(long k1, long k2) {
h1 ^= mixK1(k1);
h1 = Long.rotateLeft(h1, 27);
h1 += h2;
h1 = h1 * 5 + 0x52dce729;
h2 ^= mixK2(k2);
h2 = Long.rotateLeft(h2, 31);
h2 += h1;
h2 = h2 * 5 + 0x38495ab5;
}
/**
* Process byte buffer to calculate hash by.
*
* @param bb Buffer to process.
*/
private void process(ByteBuffer bb) {
long k1 = bb.getLong();
long k2 = bb.getLong();
bmix64(k1, k2);
len += CHUNK_SIZE;
}
/**
* Get int.
*
* @param val Byte value
* @return Integer value
*/
private static int toInt(byte val) {
return val & 0xFF;
}
/**
* Process remaining bytes from byte buffer.
*
* @param bb Byte buffer to finish processing.
*/
private void processRemaining(ByteBuffer bb) {
long k1 = 0;
long k2 = 0;
len += bb.remaining();
switch (bb.remaining()) {
case 15:
k2 ^= (long)toInt(bb.get(14)) << 48; // fall through
case 14:
k2 ^= (long)toInt(bb.get(13)) << 40; // fall through
case 13:
k2 ^= (long)toInt(bb.get(12)) << 32; // fall through
case 12:
k2 ^= (long)toInt(bb.get(11)) << 24; // fall through
case 11:
k2 ^= (long)toInt(bb.get(10)) << 16; // fall through
case 10:
k2 ^= (long)toInt(bb.get(9)) << 8; // fall through
case 9:
k2 ^= (long)toInt(bb.get(8)); // fall through
case 8:
k1 ^= bb.getLong();
break;
case 7:
k1 ^= (long)toInt(bb.get(6)) << 48; // fall through
case 6:
k1 ^= (long)toInt(bb.get(5)) << 40; // fall through
case 5:
k1 ^= (long)toInt(bb.get(4)) << 32; // fall through
case 4:
k1 ^= (long)toInt(bb.get(3)) << 24; // fall through
case 3:
k1 ^= (long)toInt(bb.get(2)) << 16; // fall through
case 2:
k1 ^= (long)toInt(bb.get(1)) << 8; // fall through
case 1:
k1 ^= (long)toInt(bb.get(0));
break;
default:
throw new AssertionError("Should never get here.");
}
h1 ^= mixK1(k1);
h2 ^= mixK2(k2);
}
/**
* Make hash from internal state.
*
* @return Long hash value.
*/
private long makeHash() {
h1 ^= len;
h2 ^= len;
h1 += h2;
h2 += h1;
h1 = fmix64(h1);
h2 = fmix64(h2);
h1 += h2;
h2 += h1;
return h1;
}
/**
* Mix long value to prepare internal state for hash generation.
*
* @param k Long value.
* @return Hashed one.
*/
private static long fmix64(long k) {
k ^= k >>> 33;
k *= 0xff51afd7ed558ccdL;
k ^= k >>> 33;
k *= 0xc4ceb9fe1a85ec53L;
k ^= k >>> 33;
return k;
}
/**
* Mix value to update internal state h1.
*
* @param k1 Value to mix.
* @return New h1 value.
*/
private static long mixK1(long k1) {
k1 *= C1;
k1 = Long.rotateLeft(k1, 31);
k1 *= C2;
return k1;
}
/**
* Mix value to update internal state h2.
*
* @param k2 Value to mix.
* @return New h2 value.
*/
private static long mixK2(long k2) {
k2 *= C2;
k2 = Long.rotateLeft(k2, 33);
k2 *= C1;
return k2;
}
}
|
h1 = SEED;
h2 = SEED;
this.len = 0;
ByteBuffer bb = ByteBuffer.wrap(arr, off, len).order(ByteOrder.LITTLE_ENDIAN);
while (bb.remaining() >= CHUNK_SIZE)
process(bb);
if (bb.remaining() > 0)
processRemaining(bb);
return makeHash();
| 1,704
| 109
| 1,813
|
<no_super_class>
|
apache_ignite
|
ignite/modules/core/src/main/java/org/apache/ignite/internal/processors/query/stat/hll/serialization/BigEndianAscendingWordDeserializer.java
|
BigEndianAscendingWordDeserializer
|
readWord
|
class BigEndianAscendingWordDeserializer implements IWordDeserializer {
/** The number of bits per byte. */
private static final int BITS_PER_BYTE = 8;
/** long mask for the maximum value stored in a byte. */
private static final long BYTE_MASK = (1L << BITS_PER_BYTE) - 1L;
// ************************************************************************
/** The length in bits of the words to be read. */
private final int wordLength;
/** The byte array to which the words are serialized. */
private final byte[] bytes;
/** The number of leading padding bytes in 'bytes' to be ignored. */
private final int bytePadding;
/** The number of words that the byte array contains. */
private final int wordCount;
/** The current read state. */
private int currentWordIndex;
// ========================================================================
/**
* @param wordLength the length in bits of the words to be deserialized. Must
* be less than or equal to 64 and greater than or equal to 1.
* @param bytePadding the number of leading bytes that pad the serialized words.
* Must be greater than or equal to zero.
* @param bytes the byte array containing the serialized words. Cannot be
* <code>null</code>.
*/
public BigEndianAscendingWordDeserializer(final int wordLength, final int bytePadding, final byte[] bytes) {
if ((wordLength < 1) || (wordLength > 64))
throw new IllegalArgumentException("Word length must be >= 1 and <= 64. (was: " + wordLength + ")");
if (bytePadding < 0)
throw new IllegalArgumentException("Byte padding must be >= zero. (was: " + bytePadding + ")");
this.wordLength = wordLength;
this.bytes = bytes;
this.bytePadding = bytePadding;
final int dataBytes = (bytes.length - bytePadding);
final long dataBits = (dataBytes * BITS_PER_BYTE);
this.wordCount = (int)(dataBits / wordLength);
currentWordIndex = 0;
}
// ========================================================================
/* (non-Javadoc)
* @see net.agkn.hll.serialization.IWordDeserializer#readWord()
*/
@Override public long readWord() {
final long word = readWord(currentWordIndex);
currentWordIndex++;
return word;
}
// ------------------------------------------------------------------------
/**
* Reads the word at the specified sequence position (zero-indexed).
*
* @param position the zero-indexed position of the word to be read. This
* must be greater than or equal to zero.
* @return the value of the serialized word at the specified position.
*/
private long readWord(final int position) {<FILL_FUNCTION_BODY>}
/* (non-Javadoc)
* @see net.agkn.hll.serialization.IWordDeserializer#totalWordCount()
*/
@Override public int totalWordCount() {
return wordCount;
}
}
|
if (position < 0)
throw new ArrayIndexOutOfBoundsException(position);
// First bit of the word
final long firstBitIdx = (position * wordLength);
final int firstByteIdx = (bytePadding + (int)(firstBitIdx / BITS_PER_BYTE));
final int firstByteSkipBits = (int)(firstBitIdx % BITS_PER_BYTE);
// Last bit of the word
final long lastBitIdx = (firstBitIdx + wordLength - 1);
final int lastByteIdx = (bytePadding + (int)(lastBitIdx / BITS_PER_BYTE));
final int lastByteBitsToConsume;
final int bitsAfterByteBoundary = (int)((lastBitIdx + 1) % BITS_PER_BYTE);
// If the word terminates at the end of the last byte, consume the whole
// last byte.
if (bitsAfterByteBoundary == 0)
lastByteBitsToConsume = BITS_PER_BYTE;
else
// Otherwise, only consume what is necessary.
lastByteBitsToConsume = bitsAfterByteBoundary;
if (lastByteIdx >= bytes.length)
throw new ArrayIndexOutOfBoundsException("Word out of bounds of backing array.");
// Accumulator
long val = 0;
// --------------------------------------------------------------------
// First byte
final int bitsRemainingInFirstByte = (BITS_PER_BYTE - firstByteSkipBits);
final int bitsToConsumeInFirstByte = Math.min(bitsRemainingInFirstByte, wordLength);
long firstByte = (long)bytes[firstByteIdx];
// Mask off the bits to skip in the first byte.
final long firstByteMask = ((1L << bitsRemainingInFirstByte) - 1L);
firstByte &= firstByteMask;
// Right-align relevant bits of first byte.
firstByte >>>= (bitsRemainingInFirstByte - bitsToConsumeInFirstByte);
val |= firstByte;
// If the first byte contains the whole word, short-circuit.
if (firstByteIdx == lastByteIdx)
return val;
// --------------------------------------------------------------------
// Middle bytes
final int middleByteCnt = (lastByteIdx - firstByteIdx - 1);
for (int i = 0; i < middleByteCnt; i++) {
final long middleByte = (bytes[firstByteIdx + i + 1] & BYTE_MASK);
// Push middle byte onto accumulator.
val <<= BITS_PER_BYTE;
val |= middleByte;
}
// --------------------------------------------------------------------
// Last byte
long lastByte = (bytes[lastByteIdx] & BYTE_MASK);
lastByte >>= (BITS_PER_BYTE - lastByteBitsToConsume);
val <<= lastByteBitsToConsume;
val |= lastByte;
return val;
| 802
| 750
| 1,552
|
<no_super_class>
|
apache_ignite
|
ignite/modules/core/src/main/java/org/apache/ignite/internal/processors/query/stat/hll/serialization/HLLMetadata.java
|
HLLMetadata
|
toString
|
class HLLMetadata implements IHLLMetadata {
/** */
private final int schemaVersion;
/** */
private final HLLType type;
/** */
private final int registerCountLog2;
/** */
private final int registerWidth;
/** */
private final int log2ExplicitCutoff;
/** */
private final boolean explicitOff;
/** */
private final boolean explicitAuto;
/** */
private final boolean sparseEnabled;
/**
* @param schemaVersion the schema version number of the HLL. This must
* be greater than or equal to zero.
* @param type the {@link HLLType type} of the HLL. This cannot
* be <code>null</code>.
* @param registerCountLog2 the log-base-2 register count parameter for
* probabilistic HLLs. This must be greater than or equal to zero.
* @param registerWidth the register width parameter for probabilistic
* HLLs. This must be greater than or equal to zero.
* @param log2ExplicitCutoff the log-base-2 of the explicit cardinality cutoff,
* if it is explicitly defined. (If <code>explicitOff</code> or
* <code>explicitAuto</code> is <code>true</code> then this has no
* meaning.)
* @param explicitOff the flag for 'explicit off'-mode, where the
* {@link HLLType#EXPLICIT} representation is not used. Both this and
* <code>explicitAuto</code> cannot be <code>true</code> at the same
* time.
* @param explicitAuto the flag for 'explicit auto'-mode, where the
* {@link HLLType#EXPLICIT} representation's promotion cutoff is
* determined based on in-memory size automatically. Both this and
* <code>explicitOff</code> cannot be <code>true</code> at the same
* time.
* @param sparseEnabled the flag for 'sparse-enabled'-mode, where the
* {@link HLLType#SPARSE} representation is used.
*/
public HLLMetadata(final int schemaVersion,
final HLLType type,
final int registerCountLog2,
final int registerWidth,
final int log2ExplicitCutoff,
final boolean explicitOff,
final boolean explicitAuto,
final boolean sparseEnabled) {
this.schemaVersion = schemaVersion;
this.type = type;
this.registerCountLog2 = registerCountLog2;
this.registerWidth = registerWidth;
this.log2ExplicitCutoff = log2ExplicitCutoff;
this.explicitOff = explicitOff;
this.explicitAuto = explicitAuto;
this.sparseEnabled = sparseEnabled;
}
/* (non-Javadoc)
* @see net.agkn.hll.serialization.IHLLMetadata#schemaVersion()
*/
@Override public int schemaVersion() {
return schemaVersion;
}
/* (non-Javadoc)
* @see net.agkn.hll.serialization.IHLLMetadata#HLLType()
*/
@Override public HLLType HLLType() {
return type;
}
/* (non-Javadoc)
* @see net.agkn.hll.serialization.IHLLMetadata#registerCountLog2()
*/
@Override public int registerCountLog2() {
return registerCountLog2;
}
/* (non-Javadoc)
* @see net.agkn.hll.serialization.IHLLMetadata#registerWidth()
*/
@Override public int registerWidth() {
return registerWidth;
}
/* (non-Javadoc)
* @see net.agkn.hll.serialization.IHLLMetadata#log2ExplicitCutoff()
*/
@Override public int log2ExplicitCutoff() {
return log2ExplicitCutoff;
}
/* (non-Javadoc)
* @see net.agkn.hll.serialization.IHLLMetadata#explicitOff()
*/
@Override public boolean explicitOff() {
return explicitOff;
}
/* (non-Javadoc)
* @see net.agkn.hll.serialization.IHLLMetadata#explicitAuto()
* @see net.agkn.hll.serialization.IHLLMetadata#log2ExplicitCutoff()
*/
@Override public boolean explicitAuto() {
return explicitAuto;
}
/* (non-Javadoc)
* @see net.agkn.hll.serialization.IHLLMetadata#sparseEnabled()
*/
@Override public boolean sparseEnabled() {
return sparseEnabled;
}
/* (non-Javadoc)
* @see java.lang.Object#toString()
*/
@Override public String toString() {<FILL_FUNCTION_BODY>}
}
|
return "<HLLMetadata schemaVersion: " + this.schemaVersion + ", type: " + this.type.toString() +
", registerCountLog2: " + this.registerCountLog2 + ", registerWidth: " + this.registerWidth +
", log2ExplicitCutoff: " + this.log2ExplicitCutoff + ", explicitOff: " + this.explicitOff +
", explicitAuto: " + this.explicitAuto + ">";
| 1,271
| 111
| 1,382
|
<no_super_class>
|
apache_ignite
|
ignite/modules/core/src/main/java/org/apache/ignite/internal/processors/query/stat/hll/util/NumberUtil.java
|
NumberUtil
|
fromHex
|
class NumberUtil {
// loge(2) (log-base e of 2)
public static final double LOGE_2 = 0.6931471805599453;
// ************************************************************************
/**
* Computes the <code>log2</code> (log-base-two) of the specified value.
*
* @param value the <code>double</code> for which the <code>log2</code> is
* desired.
* @return the <code>log2</code> of the specified value
*/
public static double log2(final double value) {
// REF: http://en.wikipedia.org/wiki/Logarithmic_scale (conversion of bases)
return Math.log(value) / LOGE_2;
}
// ========================================================================
// the hex characters
private static final char[] HEX = { '0', '1', '2', '3', '4', '5', '6', '7',
'8', '9', 'A', 'B', 'C', 'D', 'E', 'F' };
// ------------------------------------------------------------------------
/**
* Converts the specified array of <code>byte</code>s into a string of
* hex characters (low <code>byte</code> first).
*
* @param bytes the array of <code>byte</code>s that are to be converted.
* This cannot be <code>null</code> though it may be empty.
* @param offset the offset in <code>bytes</code> at which the bytes will
* be taken. This cannot be negative and must be less than
* <code>bytes.length - 1</code>.
* @param cnt the number of bytes to be retrieved from the specified array.
* This cannot be negative. If greater than <code>bytes.length - offset</code>
* then that value is used.
* @return a string of at most <code>count</code> characters that represents
* the specified byte array in hex. This will never be <code>null</code>
* though it may be empty if <code>bytes</code> is empty or <code>count</code>
* is zero.
* @throws IllegalArgumentException if <code>offset</code> is greater than
* or equal to <code>bytes.length</code>.
* @see #fromHex(String, int, int)
*/
public static String toHex(final byte[] bytes, final int offset, final int cnt) {
if (offset >= bytes.length) throw new IllegalArgumentException("Offset is greater than the length (" + offset +
" >= " + bytes.length + ").")/*by contract*/;
final int byteCnt = Math.min( (bytes.length - offset), cnt);
final int upperBound = byteCnt + offset;
final char[] chars = new char[byteCnt * 2/*two chars per byte*/];
int charIdx = 0;
for (int i = offset; i < upperBound; i++) {
final byte val = bytes[i];
chars[charIdx++] = HEX[(val >>> 4) & 0x0F];
chars[charIdx++] = HEX[val & 0x0F];
}
return new String(chars);
}
/**
* Converts the specified array of hex characters into an array of <code>byte</code>s
* (low <code>byte</code> first).
*
* @param string the string of hex characters to be converted into <code>byte</code>s.
* This cannot be <code>null</code> though it may be blank.
* @param offset the offset in the string at which the characters will be
* taken. This cannot be negative and must be less than <code>string.length() - 1</code>.
* @param count the number of characters to be retrieved from the specified
* string. This cannot be negative and must be divisible by two
* (since there are two characters per <code>byte</code>).
* @return the array of <code>byte</code>s that were converted from the
* specified string (in the specified range). This will never be
* <code>null</code> though it may be empty if <code>string</code>
* is empty or <code>count</code> is zero.
* @throws IllegalArgumentException if <code>offset</code> is greater than
* or equal to <code>string.length()</code> or if <code>count</code>
* is not divisible by two.
* @see #toHex(byte[], int, int)
*/
public static byte[] fromHex(final String string, final int offset, final int count) {<FILL_FUNCTION_BODY>}
// ------------------------------------------------------------------------
/**
* @param character a hex character to be converted to a <code>byte</code>.
* This cannot be a character other than [a-fA-F0-9].
* @return the value of the specified character. This will be a value <code>0</code>
* through <code>15</code>.
* @throws IllegalArgumentException if the specified character is not in
* [a-fA-F0-9]
*/
private static final int digit(final char character) {
switch (character) {
case '0':
return 0;
case '1':
return 1;
case '2':
return 2;
case '3':
return 3;
case '4':
return 4;
case '5':
return 5;
case '6':
return 6;
case '7':
return 7;
case '8':
return 8;
case '9':
return 9;
case 'a':
case 'A':
return 10;
case 'b':
case 'B':
return 11;
case 'c':
case 'C':
return 12;
case 'd':
case 'D':
return 13;
case 'e':
case 'E':
return 14;
case 'f':
case 'F':
return 15;
default:
throw new IllegalArgumentException("Character is not in [a-fA-F0-9] ('" + character + "').");
}
}
}
|
if (offset >= string.length())
throw new IllegalArgumentException("Offset is greater than the length (" + offset + " >= " +
string.length() + ").")/*by contract*/;
if ( (count & 0x01) != 0)
throw new IllegalArgumentException("Count is not divisible by two (" + count + ").")/*by contract*/;
final int charCnt = Math.min((string.length() - offset), count);
final int upperBound = offset + charCnt;
final byte[] bytes = new byte[charCnt >>> 1/*aka /2*/];
int byteIdx = 0/*beginning*/;
for (int i = offset; i < upperBound; i += 2)
bytes[byteIdx++] = (byte)(( (digit(string.charAt(i)) << 4) | digit(string.charAt(i + 1))) & 0xFF);
return bytes;
| 1,684
| 236
| 1,920
|
<no_super_class>
|
apache_ignite
|
ignite/modules/core/src/main/java/org/apache/ignite/internal/processors/query/stat/messages/StatisticsDecimalMessage.java
|
StatisticsDecimalMessage
|
writeTo
|
class StatisticsDecimalMessage implements Message {
/** */
private static final long serialVersionUID = 0L;
/** */
public static final short TYPE_CODE = 184;
/** */
private int scale;
/** */
private byte[] b;
/**
*
*/
public StatisticsDecimalMessage() {
// No-op.
}
/**
* @param val Value.
*/
public StatisticsDecimalMessage(BigDecimal val) {
if (val == null) {
scale = 0;
b = null;
}
else {
scale = val.scale();
b = val.unscaledValue().toByteArray();
}
}
/**
* @return Decimal value.
*/
public BigDecimal value() {
if (b == null && scale == 0)
return null;
return new BigDecimal(new BigInteger(b), scale);
}
/** {@inheritDoc} */
@Override public boolean writeTo(ByteBuffer buf, MessageWriter writer) {<FILL_FUNCTION_BODY>}
/** {@inheritDoc} */
@Override public boolean readFrom(ByteBuffer buf, MessageReader reader) {
reader.setBuffer(buf);
if (!reader.beforeMessageRead())
return false;
switch (reader.state()) {
case 0:
b = reader.readByteArray("b");
if (!reader.isLastRead())
return false;
reader.incrementState();
case 1:
scale = reader.readInt("scale");
if (!reader.isLastRead())
return false;
reader.incrementState();
}
return reader.afterMessageRead(StatisticsDecimalMessage.class);
}
/** {@inheritDoc} */
@Override public short directType() {
return TYPE_CODE;
}
/** {@inheritDoc} */
@Override public byte fieldsCount() {
return 2;
}
/** {@inheritDoc} */
@Override public void onAckReceived() {
// No-op.
}
/** {@inheritDoc} */
@Override public String toString() {
return Objects.toString(value());
}
}
|
writer.setBuffer(buf);
if (!writer.isHeaderWritten()) {
if (!writer.writeHeader(directType(), fieldsCount()))
return false;
writer.onHeaderWritten();
}
switch (writer.state()) {
case 0:
if (!writer.writeByteArray("b", b))
return false;
writer.incrementState();
case 1:
if (!writer.writeInt("scale", scale))
return false;
writer.incrementState();
}
return true;
| 582
| 145
| 727
|
<no_super_class>
|
apache_ignite
|
ignite/modules/core/src/main/java/org/apache/ignite/internal/processors/query/stat/messages/StatisticsKeyMessage.java
|
StatisticsKeyMessage
|
readFrom
|
class StatisticsKeyMessage implements Message {
/** */
private static final long serialVersionUID = 0L;
/** */
public static final short TYPE_CODE = 183;
/** Object schema. */
private String schema;
/** Object name. */
private String obj;
/** Optional list of columns to collect statistics by. */
@GridDirectCollection(String.class)
private List<String> colNames;
/**
* {@link Externalizable} support.
*/
public StatisticsKeyMessage() {
// No-op.
}
/**
* Constructor.
*
* @param schema Schema name.
* @param obj Object name.
* @param colNames Column names.
*/
public StatisticsKeyMessage(String schema, String obj, List<String> colNames) {
this.schema = schema;
this.obj = obj;
this.colNames = colNames;
}
/**
* @return Schema name.
*/
public String schema() {
return schema;
}
/**
* @return Object name.
*/
public String obj() {
return obj;
}
/**
* @return Column names.
*/
public List<String> colNames() {
return colNames;
}
/** {@inheritDoc} */
@Override public boolean writeTo(ByteBuffer buf, MessageWriter writer) {
writer.setBuffer(buf);
if (!writer.isHeaderWritten()) {
if (!writer.writeHeader(directType(), fieldsCount()))
return false;
writer.onHeaderWritten();
}
switch (writer.state()) {
case 0:
if (!writer.writeCollection("colNames", colNames, MessageCollectionItemType.STRING))
return false;
writer.incrementState();
case 1:
if (!writer.writeString("obj", obj))
return false;
writer.incrementState();
case 2:
if (!writer.writeString("schema", schema))
return false;
writer.incrementState();
}
return true;
}
/** {@inheritDoc} */
@Override public boolean readFrom(ByteBuffer buf, MessageReader reader) {<FILL_FUNCTION_BODY>}
/** {@inheritDoc} */
@Override public short directType() {
return TYPE_CODE;
}
/** {@inheritDoc} */
@Override public byte fieldsCount() {
return 3;
}
/** {@inheritDoc} */
@Override public void onAckReceived() {
}
/** {@inheritDoc} */
@Override public String toString() {
return S.toString(StatisticsKeyMessage.class, this);
}
/** {@inheritDoc} */
@Override public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
StatisticsKeyMessage that = (StatisticsKeyMessage)o;
return Objects.equals(schema, that.schema) &&
Objects.equals(obj, that.obj) &&
Objects.equals(colNames, that.colNames);
}
/** {@inheritDoc} */
@Override public int hashCode() {
return Objects.hash(schema, obj, colNames);
}
}
|
reader.setBuffer(buf);
if (!reader.beforeMessageRead())
return false;
switch (reader.state()) {
case 0:
colNames = reader.readCollection("colNames", MessageCollectionItemType.STRING);
if (!reader.isLastRead())
return false;
reader.incrementState();
case 1:
obj = reader.readString("obj");
if (!reader.isLastRead())
return false;
reader.incrementState();
case 2:
schema = reader.readString("schema");
if (!reader.isLastRead())
return false;
reader.incrementState();
}
return reader.afterMessageRead(StatisticsKeyMessage.class);
| 867
| 196
| 1,063
|
<no_super_class>
|
apache_ignite
|
ignite/modules/core/src/main/java/org/apache/ignite/internal/processors/query/stat/messages/StatisticsObjectData.java
|
StatisticsObjectData
|
readFrom
|
class StatisticsObjectData implements Message {
/** */
private static final long serialVersionUID = 0L;
/** */
public static final short TYPE_CODE = 185;
/** Statistics key. */
private StatisticsKeyMessage key;
/** Total row count in current object. */
private long rowsCnt;
/** Type of statistics. */
private StatisticsType type;
/** Partition id if statistics was collected by partition. */
private int partId;
/** Update counter if statistics was collected by partition. */
private long updCnt;
/** Columns key to statistic map. */
@GridDirectMap(keyType = String.class, valueType = StatisticsColumnData.class)
private Map<String, StatisticsColumnData> data;
/**
* Constructor.
*
* @param key Statistics key.
* @param rowsCnt Total row count.
* @param type Statistics type.
* @param partId Partition id.
* @param updCnt Partition update counter.
* @param data Map of statistics column data.
*/
public StatisticsObjectData(
StatisticsKeyMessage key,
long rowsCnt,
StatisticsType type,
int partId,
long updCnt,
Map<String, StatisticsColumnData> data
) {
this.key = key;
this.rowsCnt = rowsCnt;
this.type = type;
this.partId = partId;
this.updCnt = updCnt;
this.data = data;
}
/**
* @return Statistics key.
*/
public StatisticsKeyMessage key() {
return key;
}
/**
* @return Total rows count.
*/
public long rowsCnt() {
return rowsCnt;
}
/**
* @return Statistics type.
*/
public StatisticsType type() {
return type;
}
/**
* @return Partition id.
*/
public int partId() {
return partId;
}
/**
* @return Partition update counter.
*/
public long updCnt() {
return updCnt;
}
/**
* @return Statistics column data.
*/
public Map<String, StatisticsColumnData> data() {
return data;
}
/**
* Default constructor.
*/
public StatisticsObjectData() {
// No-op.
}
/** {@inheritDoc} */
@Override public boolean writeTo(ByteBuffer buf, MessageWriter writer) {
writer.setBuffer(buf);
if (!writer.isHeaderWritten()) {
if (!writer.writeHeader(directType(), fieldsCount()))
return false;
writer.onHeaderWritten();
}
switch (writer.state()) {
case 0:
if (!writer.writeMap("data", data, MessageCollectionItemType.STRING, MessageCollectionItemType.MSG))
return false;
writer.incrementState();
case 1:
if (!writer.writeMessage("key", key))
return false;
writer.incrementState();
case 2:
if (!writer.writeInt("partId", partId))
return false;
writer.incrementState();
case 3:
if (!writer.writeLong("rowsCnt", rowsCnt))
return false;
writer.incrementState();
case 4:
if (!writer.writeByte("type", type != null ? (byte)type.ordinal() : -1))
return false;
writer.incrementState();
case 5:
if (!writer.writeLong("updCnt", updCnt))
return false;
writer.incrementState();
}
return true;
}
/** {@inheritDoc} */
@Override public boolean readFrom(ByteBuffer buf, MessageReader reader) {<FILL_FUNCTION_BODY>}
/** {@inheritDoc} */
@Override public short directType() {
return TYPE_CODE;
}
/** {@inheritDoc} */
@Override public byte fieldsCount() {
return 6;
}
/** {@inheritDoc} */
@Override public void onAckReceived() {
}
}
|
reader.setBuffer(buf);
if (!reader.beforeMessageRead())
return false;
switch (reader.state()) {
case 0:
data = reader.readMap("data", MessageCollectionItemType.STRING, MessageCollectionItemType.MSG, false);
if (!reader.isLastRead())
return false;
reader.incrementState();
case 1:
key = reader.readMessage("key");
if (!reader.isLastRead())
return false;
reader.incrementState();
case 2:
partId = reader.readInt("partId");
if (!reader.isLastRead())
return false;
reader.incrementState();
case 3:
rowsCnt = reader.readLong("rowsCnt");
if (!reader.isLastRead())
return false;
reader.incrementState();
case 4:
byte typeOrd;
typeOrd = reader.readByte("type");
if (!reader.isLastRead())
return false;
type = StatisticsType.fromOrdinal(typeOrd);
reader.incrementState();
case 5:
updCnt = reader.readLong("updCnt");
if (!reader.isLastRead())
return false;
reader.incrementState();
}
return reader.afterMessageRead(StatisticsObjectData.class);
| 1,116
| 372
| 1,488
|
<no_super_class>
|
apache_ignite
|
ignite/modules/core/src/main/java/org/apache/ignite/internal/processors/query/stat/messages/StatisticsRequest.java
|
StatisticsRequest
|
readFrom
|
class StatisticsRequest implements Message {
/** */
private static final long serialVersionUID = 0L;
/** */
public static final short TYPE_CODE = 187;
/** Gathering id. */
private UUID reqId;
/** Key to supply statistics by. */
private StatisticsKeyMessage key;
/** Type of required statistcs. */
private StatisticsType type;
/** For local statistics request - column config versions map: name to version. */
@GridDirectMap(keyType = String.class, valueType = Long.class)
private Map<String, Long> versions;
/** For local statistics request - version to gather statistics by. */
private AffinityTopologyVersion topVer;
/**
* Constructor.
*/
public StatisticsRequest() {
}
/**
* Constructor.
*
* @param reqId Request id.
* @param key Statistics key to get statistics by.
* @param type Required statistics type.
* @param topVer Topology version to get statistics by.
* @param versions Map of statistics version to column name to ensure actual statistics aquired.
*/
public StatisticsRequest(
UUID reqId,
StatisticsKeyMessage key,
StatisticsType type,
AffinityTopologyVersion topVer,
Map<String, Long> versions
) {
this.reqId = reqId;
this.key = key;
this.type = type;
this.topVer = topVer;
this.versions = versions;
}
/** Request id. */
public UUID reqId() {
return reqId;
}
/**
* @return Required statistics type.
*/
public StatisticsType type() {
return type;
}
/**
* @return Key for required statitics.
*/
public StatisticsKeyMessage key() {
return key;
}
/**
* @return Topology version.
*/
public AffinityTopologyVersion topVer() {
return topVer;
}
/**
* @return Column name to version map.
*/
public Map<String, Long> versions() {
return versions;
}
/** {@inheritDoc} */
@Override public String toString() {
return S.toString(StatisticsRequest.class, this);
}
/** {@inheritDoc} */
@Override public boolean writeTo(ByteBuffer buf, MessageWriter writer) {
writer.setBuffer(buf);
if (!writer.isHeaderWritten()) {
if (!writer.writeHeader(directType(), fieldsCount()))
return false;
writer.onHeaderWritten();
}
switch (writer.state()) {
case 0:
if (!writer.writeMessage("key", key))
return false;
writer.incrementState();
case 1:
if (!writer.writeUuid("reqId", reqId))
return false;
writer.incrementState();
case 2:
if (!writer.writeAffinityTopologyVersion("topVer", topVer))
return false;
writer.incrementState();
case 3:
if (!writer.writeByte("type", type != null ? (byte)type.ordinal() : -1))
return false;
writer.incrementState();
case 4:
if (!writer.writeMap("versions", versions, MessageCollectionItemType.STRING, MessageCollectionItemType.LONG))
return false;
writer.incrementState();
}
return true;
}
/** {@inheritDoc} */
@Override public boolean readFrom(ByteBuffer buf, MessageReader reader) {<FILL_FUNCTION_BODY>}
/** {@inheritDoc} */
@Override public short directType() {
return TYPE_CODE;
}
/** {@inheritDoc} */
@Override public byte fieldsCount() {
return 5;
}
/** {@inheritDoc} */
@Override public void onAckReceived() {
}
}
|
reader.setBuffer(buf);
if (!reader.beforeMessageRead())
return false;
switch (reader.state()) {
case 0:
key = reader.readMessage("key");
if (!reader.isLastRead())
return false;
reader.incrementState();
case 1:
reqId = reader.readUuid("reqId");
if (!reader.isLastRead())
return false;
reader.incrementState();
case 2:
topVer = reader.readAffinityTopologyVersion("topVer");
if (!reader.isLastRead())
return false;
reader.incrementState();
case 3:
byte typeOrd;
typeOrd = reader.readByte("type");
if (!reader.isLastRead())
return false;
type = StatisticsType.fromOrdinal(typeOrd);
reader.incrementState();
case 4:
versions = reader.readMap("versions", MessageCollectionItemType.STRING, MessageCollectionItemType.LONG, false);
if (!reader.isLastRead())
return false;
reader.incrementState();
}
return reader.afterMessageRead(StatisticsRequest.class);
| 1,032
| 327
| 1,359
|
<no_super_class>
|
apache_ignite
|
ignite/modules/core/src/main/java/org/apache/ignite/internal/processors/query/stat/messages/StatisticsResponse.java
|
StatisticsResponse
|
readFrom
|
class StatisticsResponse implements Message {
/** */
private static final long serialVersionUID = 0L;
/** */
public static final short TYPE_CODE = 188;
/** Request id. */
private UUID reqId;
/** Requested statistics. */
private StatisticsObjectData data;
/**
* Constructor.
*/
public StatisticsResponse() {
}
/**
* Constructor.
*
* @param reqId Request id
* @param data Statistics data.
*/
public StatisticsResponse(
UUID reqId,
StatisticsObjectData data
) {
this.reqId = reqId;
this.data = data;
}
/**
* @return Request id.
*/
public UUID reqId() {
return reqId;
}
/**
* @return Statitics data.
*/
public StatisticsObjectData data() {
return data;
}
/** {@inheritDoc} */
@Override public String toString() {
return S.toString(StatisticsResponse.class, this);
}
/** {@inheritDoc} */
@Override public boolean writeTo(ByteBuffer buf, MessageWriter writer) {
writer.setBuffer(buf);
if (!writer.isHeaderWritten()) {
if (!writer.writeHeader(directType(), fieldsCount()))
return false;
writer.onHeaderWritten();
}
switch (writer.state()) {
case 0:
if (!writer.writeMessage("data", data))
return false;
writer.incrementState();
case 1:
if (!writer.writeUuid("reqId", reqId))
return false;
writer.incrementState();
}
return true;
}
/** {@inheritDoc} */
@Override public boolean readFrom(ByteBuffer buf, MessageReader reader) {<FILL_FUNCTION_BODY>}
/** {@inheritDoc} */
@Override public short directType() {
return TYPE_CODE;
}
/** {@inheritDoc} */
@Override public byte fieldsCount() {
return 2;
}
/** {@inheritDoc} */
@Override public void onAckReceived() {
}
}
|
reader.setBuffer(buf);
if (!reader.beforeMessageRead())
return false;
switch (reader.state()) {
case 0:
data = reader.readMessage("data");
if (!reader.isLastRead())
return false;
reader.incrementState();
case 1:
reqId = reader.readUuid("reqId");
if (!reader.isLastRead())
return false;
reader.incrementState();
}
return reader.afterMessageRead(StatisticsResponse.class);
| 584
| 146
| 730
|
<no_super_class>
|
apache_ignite
|
ignite/modules/core/src/main/java/org/apache/ignite/internal/processors/query/stat/view/ColumnPartitionDataViewSupplier.java
|
ColumnPartitionDataViewSupplier
|
columnPartitionStatisticsViewSupplier
|
class ColumnPartitionDataViewSupplier {
/** Statistics store. */
private final IgniteStatisticsStore store;
/**
* Constructor.
*
* @param store Statistics store.
*/
public ColumnPartitionDataViewSupplier(IgniteStatisticsStore store) {
this.store = store;
}
/**
* Statistics column partition data view filterable supplier.
*
* @param filter Filter.
* @return Iterable with statistics column partition data views.
*/
public Iterable<StatisticsColumnPartitionDataView> columnPartitionStatisticsViewSupplier(
Map<String, Object> filter
) {<FILL_FUNCTION_BODY>}
}
|
String type = (String)filter.get(StatisticsColumnPartitionDataViewWalker.TYPE_FILTER);
if (type != null && !StatisticsColumnConfigurationView.TABLE_TYPE.equalsIgnoreCase(type))
return Collections.emptyList();
String schema = (String)filter.get(StatisticsColumnPartitionDataViewWalker.SCHEMA_FILTER);
String name = (String)filter.get(StatisticsColumnPartitionDataViewWalker.NAME_FILTER);
Integer partId = (Integer)filter.get(StatisticsColumnPartitionDataViewWalker.PARTITION_FILTER);
String column = (String)filter.get(StatisticsColumnPartitionDataViewWalker.COLUMN_FILTER);
Map<StatisticsKey, Collection<ObjectPartitionStatisticsImpl>> partsStatsMap;
if (!F.isEmpty(schema) && !F.isEmpty(name)) {
StatisticsKey key = new StatisticsKey(schema, name);
Collection<ObjectPartitionStatisticsImpl> keyStat;
if (partId == null)
keyStat = store.getLocalPartitionsStatistics(key);
else {
ObjectPartitionStatisticsImpl partStat = store.getLocalPartitionStatistics(key, partId);
keyStat = (partStat == null) ? Collections.emptyList() : Collections.singletonList(partStat);
}
partsStatsMap = Collections.singletonMap(key, keyStat);
}
else
partsStatsMap = store.getAllLocalPartitionsStatistics(schema);
List<StatisticsColumnPartitionDataView> res = new ArrayList<>();
for (Map.Entry<StatisticsKey, Collection<ObjectPartitionStatisticsImpl>> partsStatsEntry : partsStatsMap.entrySet()) {
StatisticsKey key = partsStatsEntry.getKey();
for (ObjectPartitionStatisticsImpl partStat : partsStatsEntry.getValue()) {
if (column == null) {
for (Map.Entry<String, ColumnStatistics> colStatEntry : partStat.columnsStatistics().entrySet())
res.add(new StatisticsColumnPartitionDataView(key, colStatEntry.getKey(), partStat));
}
else {
ColumnStatistics colStat = partStat.columnStatistics(column);
if (colStat != null)
res.add(new StatisticsColumnPartitionDataView(key, column, partStat));
}
}
}
return res;
| 176
| 598
| 774
|
<no_super_class>
|
apache_ignite
|
ignite/modules/core/src/main/java/org/apache/ignite/internal/processors/resource/GridResourceProxiedIgniteInjector.java
|
GridResourceProxiedIgniteInjector
|
ignite
|
class GridResourceProxiedIgniteInjector extends GridResourceBasicInjector<Ignite> {
/**
* @param rsrc Resource.
*/
public GridResourceProxiedIgniteInjector(Ignite rsrc) {
super(rsrc);
}
/** */
private Ignite ignite(Object target) {<FILL_FUNCTION_BODY>}
/** {@inheritDoc} */
@Override public void inject(GridResourceField field, Object target, Class<?> depCls, GridDeployment dep)
throws IgniteCheckedException {
GridResourceUtils.inject(field.getField(), target, ignite(target));
}
/** {@inheritDoc} */
@Override public void inject(GridResourceMethod mtd, Object target, Class<?> depCls, GridDeployment dep)
throws IgniteCheckedException {
GridResourceUtils.inject(mtd.getMethod(), target, ignite(target));
}
}
|
GridKernalContext ctx = ((IgniteEx)getResource()).context();
return ctx.security().sandbox().enabled() && !isSystemType(ctx, target, false)
? igniteProxy(getResource())
: getResource();
| 244
| 64
| 308
|
<methods>public org.apache.ignite.Ignite getResource() ,public void inject(org.apache.ignite.internal.processors.resource.GridResourceField, java.lang.Object, Class<?>, org.apache.ignite.internal.managers.deployment.GridDeployment) throws org.apache.ignite.IgniteCheckedException,public void inject(org.apache.ignite.internal.processors.resource.GridResourceMethod, java.lang.Object, Class<?>, org.apache.ignite.internal.managers.deployment.GridDeployment) throws org.apache.ignite.IgniteCheckedException,public java.lang.String toString() ,public void undeploy(org.apache.ignite.internal.managers.deployment.GridDeployment) <variables>private final non-sealed org.apache.ignite.Ignite rsrc
|
apache_ignite
|
ignite/modules/core/src/main/java/org/apache/ignite/internal/processors/rest/client/message/GridClientTaskResultBean.java
|
GridClientTaskResultBean
|
toString
|
class GridClientTaskResultBean implements Externalizable {
/** */
private static final long serialVersionUID = 0L;
/** Synthetic ID containing task ID and result holding node ID. */
private String id;
/** Execution finished flag. */
private boolean finished;
/** Result. */
private Object res;
/** Error if any occurs while execution. */
private String error;
/**
* @return Task ID.
*/
public String getId() {
return id;
}
/**
* @param id Task ID.
*/
public void setId(String id) {
this.id = id;
}
/**
* @return {@code true} if execution finished.
*/
public boolean isFinished() {
return finished;
}
/**
* @param finished {@code true} if execution finished.
*/
public void setFinished(boolean finished) {
this.finished = finished;
}
/**
* @return Task result.
*/
public <R> R getResult() {
return (R)res;
}
/**
* @param res Task result.
*/
public void setResult(Object res) {
this.res = res;
}
/**
* @return Error.
*/
public String getError() {
return error;
}
/**
* @param error Error.
*/
public void setError(String error) {
this.error = error;
}
/** {@inheritDoc} */
@Override public void writeExternal(ObjectOutput out) throws IOException {
U.writeString(out, id);
out.writeBoolean(finished);
out.writeObject(res);
U.writeString(out, error);
}
/** {@inheritDoc} */
@Override public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException {
id = U.readString(in);
finished = in.readBoolean();
res = in.readObject();
error = U.readString(in);
}
/** {@inheritDoc} */
@Override public String toString() {<FILL_FUNCTION_BODY>}
}
|
return getClass().getSimpleName() + " [res=" + res + ", error=" + error +
", finished=" + finished + ", id=" + id + "]";
| 565
| 48
| 613
|
<no_super_class>
|
apache_ignite
|
ignite/modules/core/src/main/java/org/apache/ignite/internal/processors/rest/client/message/GridClientTopologyRequest.java
|
GridClientTopologyRequest
|
equals
|
class GridClientTopologyRequest extends GridClientAbstractMessage {
/** */
private static final long serialVersionUID = 0L;
/** Id of requested node. */
private UUID nodeId;
/** IP address of requested node. */
private String nodeIp;
/** Include metrics flag. */
private boolean includeMetrics;
/** Include node attributes flag. */
private boolean includeAttrs;
/**
* @return Include metrics flag.
*/
public boolean includeMetrics() {
return includeMetrics;
}
/**
* @param includeMetrics Include metrics flag.
*/
public void includeMetrics(boolean includeMetrics) {
this.includeMetrics = includeMetrics;
}
/**
* @return Include node attributes flag.
*/
public boolean includeAttributes() {
return includeAttrs;
}
/**
* @param includeAttrs Include node attributes flag.
*/
public void includeAttributes(boolean includeAttrs) {
this.includeAttrs = includeAttrs;
}
/**
* @return Node identifier, if specified, {@code null} otherwise.
*/
public UUID nodeId() {
return nodeId;
}
/**
* @param nodeId Node identifier to lookup.
*/
public void nodeId(UUID nodeId) {
this.nodeId = nodeId;
}
/**
* @return Node ip address if specified, {@code null} otherwise.
*/
public String nodeIp() {
return nodeIp;
}
/**
* @param nodeIp Node ip address to lookup.
*/
public void nodeIp(String nodeIp) {
this.nodeIp = nodeIp;
}
/** {@inheritDoc} */
@Override public boolean equals(Object o) {<FILL_FUNCTION_BODY>}
/** {@inheritDoc} */
@Override public int hashCode() {
return 31 * (includeMetrics ? 1 : 0) +
(includeAttrs ? 1 : 0);
}
/** {@inheritDoc} */
@Override public void writeExternal(ObjectOutput out) throws IOException {
super.writeExternal(out);
U.writeUuid(out, nodeId);
U.writeString(out, nodeIp);
out.writeBoolean(includeMetrics);
out.writeBoolean(includeAttrs);
}
/** {@inheritDoc} */
@Override public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException {
super.readExternal(in);
nodeId = U.readUuid(in);
nodeIp = U.readString(in);
includeMetrics = in.readBoolean();
includeAttrs = in.readBoolean();
}
/** {@inheritDoc} */
@Override public String toString() {
return getClass().getSimpleName() + " [includeMetrics=" + includeMetrics +
", includeAttrs=" + includeAttrs + "]";
}
}
|
if (this == o)
return true;
if (o == null || getClass() != o.getClass())
return false;
GridClientTopologyRequest other = (GridClientTopologyRequest)o;
return includeAttrs == other.includeAttrs &&
includeMetrics == other.includeMetrics;
| 768
| 83
| 851
|
<methods>public non-sealed void <init>() ,public java.util.UUID clientId() ,public void clientId(java.util.UUID) ,public java.util.UUID destinationId() ,public void destinationId(java.util.UUID) ,public void readExternal(java.io.ObjectInput) throws java.io.IOException, java.lang.ClassNotFoundException,public long requestId() ,public void requestId(long) ,public byte[] sessionToken() ,public void sessionToken(byte[]) ,public java.lang.String toString() ,public void writeExternal(java.io.ObjectOutput) throws java.io.IOException<variables>private transient java.util.UUID destId,private transient java.util.UUID id,private transient long reqId,private static final long serialVersionUID,private byte[] sesTok
|
apache_ignite
|
ignite/modules/core/src/main/java/org/apache/ignite/internal/processors/rest/handlers/cache/GridCacheRestMetrics.java
|
GridCacheRestMetrics
|
map
|
class GridCacheRestMetrics {
/** Number of reads. */
private int reads;
/** Number of writes. */
private int writes;
/** Number of hits. */
private int hits;
/** Number of misses. */
private int misses;
/**
* Constructor.
*
* @param reads Reads.
* @param writes Writes.
* @param hits Hits.
* @param misses Misses.
*/
public GridCacheRestMetrics(int reads, int writes, int hits, int misses) {
this.reads = reads;
this.writes = writes;
this.hits = hits;
this.misses = misses;
}
/**
* Gets reads.
*
* @return Reads.
*/
public int getReads() {
return reads;
}
/**
* Sets reads.
*
* @param reads Reads.
*/
public void setReads(int reads) {
this.reads = reads;
}
/**
* Gets writes.
*
* @return Writes.
*/
public int getWrites() {
return writes;
}
/**
* Sets writes.
*
* @param writes Writes.
*/
public void setWrites(int writes) {
this.writes = writes;
}
/**
* Gets hits.
*
* @return Hits.
*/
public int getHits() {
return hits;
}
/**
* Sets hits.
*
* @param hits Hits.
*/
public void setHits(int hits) {
this.hits = hits;
}
/**
* Gets misses.
*
* @return Misses.
*/
public int getMisses() {
return misses;
}
/**
* Sets misses.
*
* @param misses Misses.
*/
public void setMisses(int misses) {
this.misses = misses;
}
/**
* Creates map with strings.
*
* @return Map.
*/
public Map<String, Long> map() {<FILL_FUNCTION_BODY>}
}
|
Map<String, Long> map = new GridLeanMap<>(4);
map.put("reads", (long)reads);
map.put("writes", (long)writes);
map.put("hits", (long)hits);
map.put("misses", (long)misses);
return map;
| 601
| 89
| 690
|
<no_super_class>
|
apache_ignite
|
ignite/modules/core/src/main/java/org/apache/ignite/internal/processors/rest/handlers/cluster/GridBaselineCommandHandler.java
|
GridBaselineCommandHandler
|
currentState
|
class GridBaselineCommandHandler extends GridRestCommandHandlerAdapter {
/** Supported commands. */
private static final Collection<GridRestCommand> SUPPORTED_COMMANDS = U.sealList(BASELINE_CURRENT_STATE,
BASELINE_SET, BASELINE_ADD, BASELINE_REMOVE);
/**
* @param ctx Context.
*/
public GridBaselineCommandHandler(GridKernalContext ctx) {
super(ctx);
}
/** {@inheritDoc} */
@Override public Collection<GridRestCommand> supportedCommands() {
return SUPPORTED_COMMANDS;
}
/** {@inheritDoc} */
@Override public IgniteInternalFuture<GridRestResponse> handleAsync(GridRestRequest req)
throws IgniteCheckedException {
assert req != null;
assert SUPPORTED_COMMANDS.contains(req.command());
assert req instanceof GridRestBaselineRequest : "Invalid type of baseline request.";
if (log.isDebugEnabled())
log.debug("Handling baseline REST request: " + req);
GridRestBaselineRequest req0 = (GridRestBaselineRequest)req;
IgniteClusterEx cluster = ctx.grid().cluster();
List<Object> consistentIds = req0.consistentIds();
switch (req0.command()) {
case BASELINE_CURRENT_STATE: {
// No-op.
break;
}
case BASELINE_SET: {
Long topVer = req0.topologyVersion();
if (topVer == null && consistentIds == null)
throw new IgniteCheckedException("Failed to handle request (either topVer or consistentIds should be specified).");
if (topVer != null)
cluster.setBaselineTopology(topVer);
else
cluster.setBaselineTopology(filterServerNodesByConsId(consistentIds));
break;
}
case BASELINE_ADD: {
if (consistentIds == null)
throw new IgniteCheckedException(missingParameter("consistentIds"));
Set<BaselineNode> baselineTop = new HashSet<>(currentBaseLine());
baselineTop.addAll(filterServerNodesByConsId(consistentIds));
cluster.setBaselineTopology(baselineTop);
break;
}
case BASELINE_REMOVE: {
if (consistentIds == null)
throw new IgniteCheckedException(missingParameter("consistentIds"));
Collection<BaselineNode> baseline = currentBaseLine();
Set<BaselineNode> baselineTop = new HashSet<>(baseline);
baselineTop.removeAll(filterNodesByConsId(baseline, consistentIds));
cluster.setBaselineTopology(baselineTop);
break;
}
default:
assert false : "Invalid command for baseline handler: " + req;
}
return new GridFinishedFuture<>(new GridRestResponse(currentState()));
}
/**
* @return Current baseline.
*/
private Collection<BaselineNode> currentBaseLine() {
Collection<BaselineNode> baselineNodes = ctx.grid().cluster().currentBaselineTopology();
return baselineNodes != null ? baselineNodes : Collections.emptyList();
}
/**
* Collect baseline topology command result.
*
* @return Baseline descriptor.
*/
private GridBaselineCommandResponse currentState() {<FILL_FUNCTION_BODY>}
/**
* Filter passed nodes by consistent IDs.
*
* @param nodes Collection of nodes.
* @param consistentIds Collection of consistent IDs.
* @throws IllegalStateException In case of some consistent ID not found in nodes collection.
*/
private Collection<BaselineNode> filterNodesByConsId(Collection<? extends BaselineNode> nodes, List<Object> consistentIds) {
Map<Object, BaselineNode> nodeMap =
nodes.stream().collect(toMap(n -> n.consistentId().toString(), identity()));
Collection<BaselineNode> filtered = new ArrayList<>(consistentIds.size());
for (Object consistentId : consistentIds) {
BaselineNode node = nodeMap.get(consistentId);
if (node == null)
throw new IllegalStateException("Node not found for consistent ID: " + consistentId);
filtered.add(node);
}
return filtered;
}
/**
* Filter server nodes by consistent IDs.
*
* @param consistentIds Collection of consistent IDs to add.
* @throws IllegalStateException In case of some consistent ID not found in nodes collection.
*/
private Collection<BaselineNode> filterServerNodesByConsId(List<Object> consistentIds) {
return filterNodesByConsId(ctx.grid().cluster().forServers().nodes(), consistentIds);
}
}
|
IgniteClusterEx cluster = ctx.grid().cluster();
Collection<? extends BaselineNode> srvrs = cluster.forServers().nodes();
return new GridBaselineCommandResponse(cluster.state().active(), cluster.topologyVersion(), currentBaseLine(), srvrs);
| 1,210
| 71
| 1,281
|
<methods><variables>protected final non-sealed org.apache.ignite.internal.GridKernalContext ctx,protected final non-sealed org.apache.ignite.IgniteLogger log
|
apache_ignite
|
ignite/modules/core/src/main/java/org/apache/ignite/internal/processors/rest/handlers/cluster/GridChangeClusterStateCommandHandler.java
|
GridChangeClusterStateCommandHandler
|
handleAsync
|
class GridChangeClusterStateCommandHandler extends GridRestCommandHandlerAdapter {
/** Commands. */
private static final Collection<GridRestCommand> COMMANDS = U.sealList(CLUSTER_SET_STATE, CLUSTER_STATE);
/**
* @param ctx Context.
*/
public GridChangeClusterStateCommandHandler(GridKernalContext ctx) {
super(ctx);
}
/** {@inheritDoc} */
@Override public Collection<GridRestCommand> supportedCommands() {
return COMMANDS;
}
/** {@inheritDoc} */
@Override public IgniteInternalFuture<GridRestResponse> handleAsync(GridRestRequest restReq)
throws IgniteCheckedException {<FILL_FUNCTION_BODY>}
}
|
GridRestClusterStateRequest req = (GridRestClusterStateRequest)restReq;
switch (req.command()) {
case CLUSTER_STATE:
assert req.isReqCurrentMode() : req;
return new GridFinishedFuture<>(new GridRestResponse(ctx.grid().cluster().state()));
default:
assert req.state() != null : req;
U.log(log, "Received cluster state change request to " + req.state() +
" state from client node with ID: " + req.clientId());
ctx.state().changeGlobalState(req.state(), req.forceDeactivation(),
ctx.cluster().get().forServers().nodes(), false).get();
return new GridFinishedFuture<>(new GridRestResponse(req.command().key() + " done"));
}
| 192
| 208
| 400
|
<methods><variables>protected final non-sealed org.apache.ignite.internal.GridKernalContext ctx,protected final non-sealed org.apache.ignite.IgniteLogger log
|
apache_ignite
|
ignite/modules/core/src/main/java/org/apache/ignite/internal/processors/rest/handlers/cluster/GridChangeStateCommandHandler.java
|
GridChangeStateCommandHandler
|
handleAsync
|
class GridChangeStateCommandHandler extends GridRestCommandHandlerAdapter {
/** Commands. */
private static final Collection<GridRestCommand> commands =
U.sealList(CLUSTER_ACTIVATE, CLUSTER_DEACTIVATE, CLUSTER_CURRENT_STATE, CLUSTER_ACTIVE, CLUSTER_INACTIVE);
/**
* @param ctx Context.
*/
public GridChangeStateCommandHandler(GridKernalContext ctx) {
super(ctx);
}
/** {@inheritDoc} */
@Override public Collection<GridRestCommand> supportedCommands() {
return commands;
}
/** {@inheritDoc} */
@Override public IgniteInternalFuture<GridRestResponse> handleAsync(GridRestRequest restRest)
throws IgniteCheckedException {<FILL_FUNCTION_BODY>}
}
|
GridRestChangeStateRequest req = (GridRestChangeStateRequest)restRest;
switch (req.command()) {
case CLUSTER_CURRENT_STATE:
Boolean curState = ctx.state().publicApiActiveState(false);
return new GridFinishedFuture<>(new GridRestResponse(curState));
case CLUSTER_ACTIVE:
case CLUSTER_INACTIVE:
log.warning(req.command().key() + " is deprecated. Use newer commands.");
default:
ctx.state().changeGlobalState(req.active() ? ACTIVE : INACTIVE, req.forceDeactivation(),
ctx.cluster().get().forServers().nodes(), false).get();
return new GridFinishedFuture<>(new GridRestResponse(req.command().key() + " started"));
}
| 212
| 204
| 416
|
<methods><variables>protected final non-sealed org.apache.ignite.internal.GridKernalContext ctx,protected final non-sealed org.apache.ignite.IgniteLogger log
|
apache_ignite
|
ignite/modules/core/src/main/java/org/apache/ignite/internal/processors/rest/handlers/memory/MemoryMetricsCommandHandler.java
|
MemoryMetricsCommandHandler
|
handleAsync
|
class MemoryMetricsCommandHandler extends GridRestCommandHandlerAdapter {
/**
* Supported commands.
*/
private static final Collection<GridRestCommand> SUPPORTED_COMMANDS = U.sealList(
DATA_REGION_METRICS);
/**
* @param ctx Context.
*/
public MemoryMetricsCommandHandler(GridKernalContext ctx) {
super(ctx);
}
/** {@inheritDoc} */
@Override public Collection<GridRestCommand> supportedCommands() {
return SUPPORTED_COMMANDS;
}
/** {@inheritDoc} */
@Override public IgniteInternalFuture<GridRestResponse> handleAsync(GridRestRequest req) {<FILL_FUNCTION_BODY>}
}
|
assert req != null;
if (log.isDebugEnabled())
log.debug("Handling " + req.command().key() + " REST request: " + req);
GridRestCommand cmd = req.command();
switch (cmd) {
case DATA_REGION_METRICS:
return new GridFinishedFuture<>(new GridRestResponse(ctx.grid().dataRegionMetrics()));
default:
return new GridFinishedFuture<>(new GridRestResponse(GridRestResponse.STATUS_FAILED, "Unknown command"));
}
| 189
| 142
| 331
|
<methods><variables>protected final non-sealed org.apache.ignite.internal.GridKernalContext ctx,protected final non-sealed org.apache.ignite.IgniteLogger log
|
apache_ignite
|
ignite/modules/core/src/main/java/org/apache/ignite/internal/processors/rest/handlers/redis/GridRedisRestCommandHandler.java
|
GridRedisRestCommandHandler
|
longValue
|
class GridRedisRestCommandHandler implements GridRedisCommandHandler {
/** Logger. */
protected final IgniteLogger log;
/** REST protocol handler. */
protected final GridRestProtocolHandler hnd;
/** Kernel context. */
protected final GridKernalContext ctx;
/**
* Constructor.
*
* @param log Logger.
* @param hnd REST protocol handler.
* @param ctx Kernal context.
*/
protected GridRedisRestCommandHandler(IgniteLogger log, GridRestProtocolHandler hnd, GridKernalContext ctx) {
this.log = log;
this.hnd = hnd;
this.ctx = ctx;
}
/** {@inheritDoc} */
@Override public IgniteInternalFuture<GridRedisMessage> handleAsync(final GridNioSession ses,
final GridRedisMessage msg) {
assert msg != null;
try {
return hnd.handleAsync(asRestRequest(msg))
.chain(new CX1<IgniteInternalFuture<GridRestResponse>, GridRedisMessage>() {
@Override public GridRedisMessage applyx(IgniteInternalFuture<GridRestResponse> f)
throws IgniteCheckedException {
GridRestResponse restRes = f.get();
if (restRes.getSuccessStatus() == GridRestResponse.STATUS_SUCCESS)
msg.setResponse(makeResponse(restRes, msg.auxMKeys()));
else
msg.setResponse(GridRedisProtocolParser.toGenericError("Operation error"));
return msg;
}
}, ctx.pools().getRestExecutorService());
}
catch (IgniteCheckedException e) {
if (e instanceof GridRedisTypeException)
msg.setResponse(GridRedisProtocolParser.toTypeError(e.getMessage()));
else
msg.setResponse(GridRedisProtocolParser.toGenericError(e.getMessage()));
return new GridFinishedFuture<>(msg);
}
}
/**
* Retrieves long value following the parameter name from parameters list.
*
* @param name Parameter name.
* @param params Parameters list.
* @return Long value from parameters list or null if not exists.
* @throws GridRedisGenericException If parsing failed.
*/
@Nullable protected Long longValue(String name, List<String> params) throws GridRedisGenericException {<FILL_FUNCTION_BODY>}
/**
* Converts {@link GridRedisMessage} to {@link GridRestRequest}.
*
* @param msg {@link GridRedisMessage}
* @return {@link GridRestRequest}
* @throws IgniteCheckedException If fails.
*/
public abstract GridRestRequest asRestRequest(GridRedisMessage msg) throws IgniteCheckedException;
/**
* Prepares a response according to the request.
*
* @param resp REST response.
* @param params Auxiliary parameters.
* @return Response for the command.
*/
public abstract ByteBuffer makeResponse(GridRestResponse resp, List<String> params);
}
|
assert name != null;
Iterator<String> it = params.iterator();
while (it.hasNext()) {
if (name.equalsIgnoreCase(it.next())) {
if (it.hasNext()) {
String val = it.next();
try {
return Long.valueOf(val);
}
catch (NumberFormatException ignore) {
throw new GridRedisGenericException("Failed to parse parameter of Long type [" + name + "=" + val + "]");
}
}
else
throw new GridRedisGenericException("Syntax error. Missing value for parameter: " + name);
}
}
return null;
| 779
| 172
| 951
|
<no_super_class>
|
apache_ignite
|
ignite/modules/core/src/main/java/org/apache/ignite/internal/processors/rest/handlers/redis/string/GridRedisAppendCommandHandler.java
|
GridRedisAppendCommandHandler
|
asRestRequest
|
class GridRedisAppendCommandHandler extends GridRedisRestCommandHandler {
/** Supported commands. */
private static final Collection<GridRedisCommand> SUPPORTED_COMMANDS = U.sealList(
APPEND
);
/** Position of the value. */
private static final int VAL_POS = 2;
/**
* Handler constructor.
*
* @param log Logger to use.
* @param hnd Rest handler.
* @param ctx Kernal context.
*/
public GridRedisAppendCommandHandler(IgniteLogger log, GridRestProtocolHandler hnd, GridKernalContext ctx) {
super(log, hnd, ctx);
}
/** {@inheritDoc} */
@Override public Collection<GridRedisCommand> supportedCommands() {
return SUPPORTED_COMMANDS;
}
/** {@inheritDoc} */
@Override public GridRestRequest asRestRequest(GridRedisMessage msg) throws IgniteCheckedException {<FILL_FUNCTION_BODY>}
/** {@inheritDoc} */
@Override public ByteBuffer makeResponse(final GridRestResponse restRes, List<String> params) {
if (restRes.getResponse() == null)
return GridRedisProtocolParser.nil();
if (restRes.getResponse() instanceof String) {
int resLen = ((String)restRes.getResponse()).length();
return GridRedisProtocolParser.toInteger(String.valueOf(resLen));
}
else
return GridRedisProtocolParser.toTypeError("Operation against a key holding the wrong kind of value");
}
}
|
assert msg != null;
if (msg.messageSize() < 3)
throw new GridRedisGenericException("Wrong syntax");
GridRestCacheRequest appendReq = new GridRestCacheRequest();
GridRestCacheRequest getReq = new GridRestCacheRequest();
String val = msg.aux(VAL_POS);
appendReq.clientId(msg.clientId());
appendReq.key(msg.key());
appendReq.value(val);
appendReq.command(CACHE_APPEND);
appendReq.cacheName(msg.cacheName());
Object resp = hnd.handle(appendReq).getResponse();
if (resp != null && !(boolean)resp) {
// append on non-existing key.
GridRestCacheRequest setReq = new GridRestCacheRequest();
setReq.clientId(msg.clientId());
setReq.key(msg.key());
setReq.value(val);
setReq.command(CACHE_PUT);
setReq.cacheName(msg.cacheName());
hnd.handle(setReq);
}
getReq.clientId(msg.clientId());
getReq.key(msg.key());
getReq.command(CACHE_GET);
getReq.cacheName(msg.cacheName());
return getReq;
| 404
| 355
| 759
|
<methods>public abstract org.apache.ignite.internal.processors.rest.request.GridRestRequest asRestRequest(org.apache.ignite.internal.processors.rest.protocols.tcp.redis.GridRedisMessage) throws org.apache.ignite.IgniteCheckedException,public IgniteInternalFuture<org.apache.ignite.internal.processors.rest.protocols.tcp.redis.GridRedisMessage> handleAsync(org.apache.ignite.internal.util.nio.GridNioSession, org.apache.ignite.internal.processors.rest.protocols.tcp.redis.GridRedisMessage) ,public abstract java.nio.ByteBuffer makeResponse(org.apache.ignite.internal.processors.rest.GridRestResponse, List<java.lang.String>) <variables>protected final non-sealed org.apache.ignite.internal.GridKernalContext ctx,protected final non-sealed org.apache.ignite.internal.processors.rest.GridRestProtocolHandler hnd,protected final non-sealed org.apache.ignite.IgniteLogger log
|
apache_ignite
|
ignite/modules/core/src/main/java/org/apache/ignite/internal/processors/rest/handlers/redis/string/GridRedisSetCommandHandler.java
|
GridRedisSetCommandHandler
|
asRestRequest
|
class GridRedisSetCommandHandler extends GridRedisRestCommandHandler {
/** Supported commands. */
private static final Collection<GridRedisCommand> SUPPORTED_COMMANDS = U.sealList(
SET
);
/** Value position in Redis message. */
private static final int VAL_POS = 2;
/**
* Handler constructor.
*
* @param log Logger to use.
* @param hnd Rest handler.
* @param ctx Kernal context.
*/
public GridRedisSetCommandHandler(IgniteLogger log, GridRestProtocolHandler hnd, GridKernalContext ctx) {
super(log, hnd, ctx);
}
/** {@inheritDoc} */
@Override public Collection<GridRedisCommand> supportedCommands() {
return SUPPORTED_COMMANDS;
}
/** {@inheritDoc} */
@Override public GridRestRequest asRestRequest(GridRedisMessage msg) throws IgniteCheckedException {<FILL_FUNCTION_BODY>}
/**
* Attempts to set expiration when EX or PX parameters are specified.
*
* @param restReq {@link GridRestCacheRequest}.
* @param params Command parameters.
* @throws GridRedisGenericException When parameters are not valid.
*/
private void setExpire(GridRestCacheRequest restReq, List<String> params) throws GridRedisGenericException {
Long px = longValue("px", params);
Long ex = longValue("ex", params);
if (px != null)
restReq.ttl(px);
else if (ex != null)
restReq.ttl(ex * 1000L);
}
/** {@inheritDoc} */
@Override public ByteBuffer makeResponse(final GridRestResponse restRes, List<String> params) {
Object resp = restRes.getResponse();
if (resp == null)
return GridRedisProtocolParser.nil();
return (!(boolean)resp ? GridRedisProtocolParser.nil() : GridRedisProtocolParser.oKString());
}
}
|
assert msg != null;
if (msg.messageSize() < 3)
throw new GridRedisGenericException("Wrong number of arguments");
// check if an atomic long with the key exists (related to incr/decr).
IgniteAtomicLong l = ctx.grid().atomicLong(msg.key(), 0, false);
if (l != null) {
try {
l.close();
}
catch (IgniteException ignored) {
U.warn(log, "Failed to remove atomic long for key: " + msg.key());
}
}
GridRestCacheRequest restReq = new GridRestCacheRequest();
restReq.clientId(msg.clientId());
restReq.key(msg.key());
restReq.command(CACHE_PUT);
restReq.cacheName(msg.cacheName());
restReq.value(msg.aux(VAL_POS));
if (msg.messageSize() >= 4) {
List<String> params = msg.aux();
// get rid of SET value.
params.remove(0);
if (U.containsStringCollection(params, "nx", true))
restReq.command(CACHE_PUT_IF_ABSENT);
else if (U.containsStringCollection(params, "xx", true))
restReq.command(CACHE_REPLACE);
setExpire(restReq, params);
}
return restReq;
| 532
| 381
| 913
|
<methods>public abstract org.apache.ignite.internal.processors.rest.request.GridRestRequest asRestRequest(org.apache.ignite.internal.processors.rest.protocols.tcp.redis.GridRedisMessage) throws org.apache.ignite.IgniteCheckedException,public IgniteInternalFuture<org.apache.ignite.internal.processors.rest.protocols.tcp.redis.GridRedisMessage> handleAsync(org.apache.ignite.internal.util.nio.GridNioSession, org.apache.ignite.internal.processors.rest.protocols.tcp.redis.GridRedisMessage) ,public abstract java.nio.ByteBuffer makeResponse(org.apache.ignite.internal.processors.rest.GridRestResponse, List<java.lang.String>) <variables>protected final non-sealed org.apache.ignite.internal.GridKernalContext ctx,protected final non-sealed org.apache.ignite.internal.processors.rest.GridRestProtocolHandler hnd,protected final non-sealed org.apache.ignite.IgniteLogger log
|
apache_ignite
|
ignite/modules/core/src/main/java/org/apache/ignite/internal/processors/rest/handlers/task/GridTaskResultRequest.java
|
GridTaskResultRequest
|
writeTo
|
class GridTaskResultRequest implements Message {
/** */
private static final long serialVersionUID = 0L;
/** Task ID. */
private IgniteUuid taskId;
/** Topic. */
@GridDirectTransient
private Object topic;
/** Serialized topic. */
private byte[] topicBytes;
/**
* Public no-arg constructor for {@link Externalizable} support.
*/
public GridTaskResultRequest() {
// No-op.
}
/**
* @param taskId Task ID.
* @param topic Topic.
* @param topicBytes Serialized topic.
*/
GridTaskResultRequest(IgniteUuid taskId, Object topic, byte[] topicBytes) {
this.taskId = taskId;
this.topic = topic;
this.topicBytes = topicBytes;
}
/**
* @return Task ID.
*/
public IgniteUuid taskId() {
return taskId;
}
/**
* @param taskId Task ID.
*/
public void taskId(IgniteUuid taskId) {
assert taskId != null;
this.taskId = taskId;
}
/**
* @return Topic.
*/
public Object topic() {
return topic;
}
/**
* @return Serialized topic.
*/
public byte[] topicBytes() {
return topicBytes;
}
/**
* @param topic Topic.
*/
public void topic(String topic) {
assert topic != null;
this.topic = topic;
}
/** {@inheritDoc} */
@Override public void onAckReceived() {
// No-op.
}
/** {@inheritDoc} */
@Override public boolean writeTo(ByteBuffer buf, MessageWriter writer) {<FILL_FUNCTION_BODY>}
/** {@inheritDoc} */
@Override public boolean readFrom(ByteBuffer buf, MessageReader reader) {
reader.setBuffer(buf);
if (!reader.beforeMessageRead())
return false;
switch (reader.state()) {
case 0:
taskId = reader.readIgniteUuid("taskId");
if (!reader.isLastRead())
return false;
reader.incrementState();
case 1:
topicBytes = reader.readByteArray("topicBytes");
if (!reader.isLastRead())
return false;
reader.incrementState();
}
return reader.afterMessageRead(GridTaskResultRequest.class);
}
/** {@inheritDoc} */
@Override public short directType() {
return 76;
}
/** {@inheritDoc} */
@Override public byte fieldsCount() {
return 2;
}
}
|
writer.setBuffer(buf);
if (!writer.isHeaderWritten()) {
if (!writer.writeHeader(directType(), fieldsCount()))
return false;
writer.onHeaderWritten();
}
switch (writer.state()) {
case 0:
if (!writer.writeIgniteUuid("taskId", taskId))
return false;
writer.incrementState();
case 1:
if (!writer.writeByteArray("topicBytes", topicBytes))
return false;
writer.incrementState();
}
return true;
| 725
| 153
| 878
|
<no_super_class>
|
apache_ignite
|
ignite/modules/core/src/main/java/org/apache/ignite/internal/processors/security/thread/SecurityAwareRunnable.java
|
SecurityAwareRunnable
|
of
|
class SecurityAwareRunnable implements Runnable {
/** */
private final Runnable delegate;
/** */
private final IgniteSecurity security;
/** */
private final SecurityContext secCtx;
/** */
private SecurityAwareRunnable(IgniteSecurity security, Runnable delegate) {
assert security.enabled();
assert delegate != null;
this.delegate = delegate;
this.security = security;
secCtx = security.securityContext();
}
/** {@inheritDoc} */
@Override public void run() {
try (OperationSecurityContext ignored = security.withContext(secCtx)) {
delegate.run();
}
}
/** */
static Runnable of(IgniteSecurity security, Runnable delegate) {<FILL_FUNCTION_BODY>}
}
|
if (delegate == null || security.isDefaultContext())
return delegate;
return new SecurityAwareRunnable(security, delegate);
| 216
| 40
| 256
|
<no_super_class>
|
apache_ignite
|
ignite/modules/core/src/main/java/org/apache/ignite/internal/processors/service/LazyServiceConfiguration.java
|
LazyServiceConfiguration
|
equalsIgnoreNodeFilter
|
class LazyServiceConfiguration extends ServiceConfiguration {
/** */
private static final long serialVersionUID = 0L;
/** Service instance. */
@GridToStringExclude
private transient Service srvc;
/** Service interceptors. */
@GridToStringExclude
private transient ServiceCallInterceptor[] interceptors;
/** */
private String srvcClsName;
/** */
private byte[] srvcBytes;
/** */
private byte[] interceptorsBytes;
/** Names of platform service methods to build service statistics. */
@GridToStringExclude
private String[] platformMtdNames;
/**
* Default constructor.
*/
public LazyServiceConfiguration() {
// No-op.
}
/**
* @param cfg Configuration.
* @param srvcBytes Marshalled service.
* @param interceptorsBytes Marshalled interceptors.
*/
public LazyServiceConfiguration(ServiceConfiguration cfg, byte[] srvcBytes, @Nullable byte[] interceptorsBytes) {
assert cfg.getService() != null : cfg;
assert srvcBytes != null;
name = cfg.getName();
totalCnt = cfg.getTotalCount();
maxPerNodeCnt = cfg.getMaxPerNodeCount();
cacheName = cfg.getCacheName();
affKey = cfg.getAffinityKey();
nodeFilter = cfg.getNodeFilter();
this.srvcBytes = srvcBytes;
srvc = cfg.getService();
srvcClsName = srvc.getClass().getName();
isStatisticsEnabled = cfg.isStatisticsEnabled();
interceptors = cfg.getInterceptors();
this.interceptorsBytes = interceptorsBytes;
}
/**
* @return Service bytes.
*/
public byte[] serviceBytes() {
return srvcBytes;
}
/**
* @return Service class name.
*/
public String serviceClassName() {
return srvcClsName;
}
/** {@inheritDoc} */
@Override public Service getService() {
assert srvc != null : this;
return srvc;
}
/** {@inheritDoc} */
@Override public ServiceCallInterceptor[] getInterceptors() {
return interceptors;
}
/**
* @return Interceptors bytes.
*/
public byte[] interceptorBytes() {
return interceptorsBytes;
}
/** {@inheritDoc} */
@SuppressWarnings("RedundantIfStatement")
@Override public boolean equalsIgnoreNodeFilter(Object o) {<FILL_FUNCTION_BODY>}
/** */
LazyServiceConfiguration platformMtdNames(String[] platformMtdNames) {
this.platformMtdNames = platformMtdNames;
return this;
}
/** @return Names of known service methods. */
String[] platformMtdNames() {
return platformMtdNames;
}
/** {@inheritDoc} */
@Override public String toString() {
String svcCls = srvc == null ? "" : srvc.getClass().getSimpleName();
String nodeFilterCls = nodeFilter == null ? "" : nodeFilter.getClass().getSimpleName();
return S.toString(LazyServiceConfiguration.class, this, "svcCls", svcCls, "nodeFilterCls", nodeFilterCls);
}
}
|
if (this == o)
return true;
if (o == null || getClass() != o.getClass())
return false;
LazyServiceConfiguration that = (LazyServiceConfiguration)o;
if (maxPerNodeCnt != that.getMaxPerNodeCount())
return false;
if (totalCnt != that.getTotalCount())
return false;
if (affKey != null ? !affKey.equals(that.getAffinityKey()) : that.getAffinityKey() != null)
return false;
if (cacheName != null ? !cacheName.equals(that.getCacheName()) : that.getCacheName() != null)
return false;
if (name != null ? !name.equals(that.getName()) : that.getName() != null)
return false;
if (!Arrays.equals(srvcBytes, that.srvcBytes))
return false;
if (!Arrays.equals(interceptorsBytes, that.interceptorsBytes))
return false;
return true;
| 897
| 276
| 1,173
|
<methods>public non-sealed void <init>() ,public boolean equals(java.lang.Object) ,public boolean equalsIgnoreNodeFilter(java.lang.Object) ,public java.lang.Object getAffinityKey() ,public java.lang.String getCacheName() ,public org.apache.ignite.services.ServiceCallInterceptor[] getInterceptors() ,public int getMaxPerNodeCount() ,public java.lang.String getName() ,public IgnitePredicate<org.apache.ignite.cluster.ClusterNode> getNodeFilter() ,public org.apache.ignite.services.Service getService() ,public int getTotalCount() ,public int hashCode() ,public boolean isStatisticsEnabled() ,public org.apache.ignite.services.ServiceConfiguration setAffinityKey(java.lang.Object) ,public org.apache.ignite.services.ServiceConfiguration setCacheName(java.lang.String) ,public transient org.apache.ignite.services.ServiceConfiguration setInterceptors(org.apache.ignite.services.ServiceCallInterceptor[]) ,public org.apache.ignite.services.ServiceConfiguration setMaxPerNodeCount(int) ,public org.apache.ignite.services.ServiceConfiguration setName(java.lang.String) ,public org.apache.ignite.services.ServiceConfiguration setNodeFilter(IgnitePredicate<org.apache.ignite.cluster.ClusterNode>) ,public org.apache.ignite.services.ServiceConfiguration setService(org.apache.ignite.services.Service) ,public org.apache.ignite.services.ServiceConfiguration setStatisticsEnabled(boolean) ,public org.apache.ignite.services.ServiceConfiguration setTotalCount(int) ,public java.lang.String toString() <variables>protected java.lang.Object affKey,protected java.lang.String cacheName,protected org.apache.ignite.services.ServiceCallInterceptor[] interceptors,protected boolean isStatisticsEnabled,protected int maxPerNodeCnt,protected java.lang.String name,protected IgnitePredicate<org.apache.ignite.cluster.ClusterNode> nodeFilter,private static final long serialVersionUID,private org.apache.ignite.services.Service svc,protected int totalCnt
|
apache_ignite
|
ignite/modules/core/src/main/java/org/apache/ignite/internal/processors/service/ServiceContextImpl.java
|
ServiceContextImpl
|
method
|
class ServiceContextImpl implements ServiceContext {
/** */
private static final long serialVersionUID = 0L;
/** Null method. */
private static final Method NULL_METHOD = ServiceContextImpl.class.getMethods()[0];
/** Service name. */
private final String name;
/** Execution ID. */
private final UUID execId;
/** Cache name. */
private final String cacheName;
/** Affinity key. */
@GridToStringInclude
private final Object affKey;
/** Executor service. */
@GridToStringExclude
private final ExecutorService exe;
/** Methods reflection cache. */
private final ConcurrentMap<GridServiceMethodReflectKey, Method> mtds = new ConcurrentHashMap<>();
/** Invocation metrics. */
private ReadOnlyMetricRegistry metrics;
/** Service. */
@GridToStringExclude
private volatile Service svc;
/** Service call interceptor. */
@GridToStringExclude
private volatile ServiceCallInterceptor interceptor;
/** Cancelled flag. */
private volatile boolean isCancelled;
/** Service statistics flag. */
private final boolean isStatisticsEnabled;
/**
* @param name Service name.
* @param execId Execution ID.
* @param cacheName Cache name.
* @param affKey Affinity key.
* @param exe Executor service.
* @param statisticsEnabled Service statistics flag.
*/
ServiceContextImpl(String name,
UUID execId,
String cacheName,
Object affKey,
ExecutorService exe,
boolean statisticsEnabled
) {
this.name = name;
this.execId = execId;
this.cacheName = cacheName;
this.affKey = affKey;
this.exe = exe;
this.isStatisticsEnabled = statisticsEnabled;
}
/** {@inheritDoc} */
@Override public String name() {
return name;
}
/** {@inheritDoc} */
@Override public UUID executionId() {
return execId;
}
/** {@inheritDoc} */
@Override public boolean isCancelled() {
return isCancelled;
}
/** {@inheritDoc} */
@Nullable @Override public String cacheName() {
return cacheName;
}
/** {@inheritDoc} */
@Nullable @Override public <K> K affinityKey() {
return (K)affKey;
}
/**
* @param svc Service instance.
*/
void service(Service svc) {
this.svc = svc;
}
/**
* @return Service instance or {@code null} if service initialization is not finished yet.
*/
@Nullable Service service() {
return svc;
}
/**
* @param interceptor Service call interceptor.
*/
void interceptor(ServiceCallInterceptor interceptor) {
this.interceptor = interceptor;
}
/**
* @return Service call interceptor.
*/
ServiceCallInterceptor interceptor() {
return interceptor;
}
/**
* @return Executor service.
*/
ExecutorService executor() {
return exe;
}
/**
* @return Invocation metrics.
*/
@Nullable ReadOnlyMetricRegistry metrics() {
return metrics;
}
/**
* Sets the invocation metrics.
*
* @return {@code this}.
*/
ServiceContextImpl metrics(ReadOnlyMetricRegistry metrics) {
this.metrics = metrics;
return this;
}
/** @return {@code True} if statistics is enabled for this service. {@code False} otherwise. */
boolean isStatisticsEnabled() {
return isStatisticsEnabled;
}
/**
* @param key Method key.
* @return Method.
*/
@Nullable Method method(GridServiceMethodReflectKey key) {<FILL_FUNCTION_BODY>}
/** {@inheritDoc} */
@Override public ServiceCallContext currentCallContext() {
return ServiceCallContextHolder.current();
}
/**
* @param isCancelled Cancelled flag.
*/
public void setCancelled(boolean isCancelled) {
this.isCancelled = isCancelled;
}
/** {@inheritDoc} */
@Override public String toString() {
return S.toString(ServiceContextImpl.class, this);
}
}
|
Method mtd = mtds.get(key);
if (mtd == null) {
try {
mtd = svc.getClass().getMethod(key.methodName(), key.argTypes());
mtd.setAccessible(true);
}
catch (NoSuchMethodException ignored) {
mtd = NULL_METHOD;
}
mtds.put(key, mtd);
}
return mtd == NULL_METHOD ? null : mtd;
| 1,163
| 127
| 1,290
|
<no_super_class>
|
apache_ignite
|
ignite/modules/core/src/main/java/org/apache/ignite/internal/processors/timeout/GridTimeoutProcessor.java
|
TimeoutWorker
|
body
|
class TimeoutWorker extends GridWorker {
/**
*
*/
TimeoutWorker() {
super(
ctx.config().getIgniteInstanceName(),
"grid-timeout-worker",
GridTimeoutProcessor.this.log,
ctx.workersRegistry()
);
}
/** {@inheritDoc} */
@Override protected void body() throws InterruptedException {<FILL_FUNCTION_BODY>}
}
|
Throwable err = null;
try {
while (!isCancelled()) {
updateHeartbeat();
long now = U.currentTimeMillis();
onIdle();
for (Iterator<GridTimeoutObject> iter = timeoutObjs.iterator(); iter.hasNext(); ) {
GridTimeoutObject timeoutObj = iter.next();
if (timeoutObj.endTime() <= now) {
try {
boolean rmvd = timeoutObjs.remove(timeoutObj);
if (log.isDebugEnabled())
log.debug("Timeout has occurred [obj=" + timeoutObj + ", process=" + rmvd + ']');
if (rmvd)
timeoutObj.onTimeout();
}
catch (Throwable e) {
if (isCancelled() && !(e instanceof Error)) {
if (log.isDebugEnabled())
log.debug("Error when executing timeout callback: " + timeoutObj);
return;
}
U.error(log, "Error when executing timeout callback: " + timeoutObj, e);
if (e instanceof Error)
throw e;
}
}
else
break;
}
synchronized (mux) {
while (!isCancelled()) {
// Access of the first element must be inside of
// synchronization block, so we don't miss out
// on thread notification events sent from
// 'addTimeoutObject(..)' method.
GridTimeoutObject first = timeoutObjs.firstx();
if (first != null) {
long waitTime = first.endTime() - U.currentTimeMillis();
if (waitTime > 0) {
blockingSectionBegin();
try {
mux.wait(waitTime);
}
finally {
blockingSectionEnd();
}
}
else
break;
}
else {
blockingSectionBegin();
try {
mux.wait(5000);
}
finally {
blockingSectionEnd();
}
}
}
}
}
}
catch (Throwable t) {
if (!(t instanceof InterruptedException))
err = t;
throw t;
}
finally {
if (err == null && !isCancelled.get())
err = new IllegalStateException("Thread " + name() + " is terminated unexpectedly.");
if (err instanceof OutOfMemoryError)
ctx.failure().process(new FailureContext(CRITICAL_ERROR, err));
else if (err != null)
ctx.failure().process(new FailureContext(SYSTEM_WORKER_TERMINATION, err));
}
| 114
| 682
| 796
|
<methods>public void collectGridNodeData(org.apache.ignite.spi.discovery.DiscoveryDataBag) ,public void collectJoiningNodeData(org.apache.ignite.spi.discovery.DiscoveryDataBag) ,public org.apache.ignite.internal.GridComponent.DiscoveryDataExchangeType discoveryDataType() ,public void onDisconnected(IgniteFuture<?>) throws org.apache.ignite.IgniteCheckedException,public void onGridDataReceived(org.apache.ignite.spi.discovery.DiscoveryDataBag.GridDiscoveryData) ,public void onJoiningNodeDataReceived(org.apache.ignite.spi.discovery.DiscoveryDataBag.JoiningNodeDiscoveryData) ,public void onKernalStart(boolean) throws org.apache.ignite.IgniteCheckedException,public void onKernalStop(boolean) ,public IgniteInternalFuture<?> onReconnected(boolean) throws org.apache.ignite.IgniteCheckedException,public void printMemoryStats() ,public void start() throws org.apache.ignite.IgniteCheckedException,public void stop(boolean) throws org.apache.ignite.IgniteCheckedException,public java.lang.String toString() ,public org.apache.ignite.spi.IgniteNodeValidationResult validateNode(org.apache.ignite.cluster.ClusterNode) ,public org.apache.ignite.spi.IgniteNodeValidationResult validateNode(org.apache.ignite.cluster.ClusterNode, org.apache.ignite.spi.discovery.DiscoveryDataBag.JoiningNodeDiscoveryData) <variables>private static final java.lang.String DIAGNOSTIC_LOG_CATEGORY,protected final non-sealed org.apache.ignite.internal.GridKernalContext ctx,protected final non-sealed org.apache.ignite.IgniteLogger diagnosticLog,protected final non-sealed org.apache.ignite.IgniteLogger log
|
apache_ignite
|
ignite/modules/core/src/main/java/org/apache/ignite/internal/processors/tracing/configuration/DistributedTracingConfiguration.java
|
DistributedTracingConfiguration
|
parse
|
class DistributedTracingConfiguration
extends SimpleDistributedProperty<HashMap<TracingConfigurationCoordinates, TracingConfigurationParameters>> {
/** */
private static final String TRACING_CONFIGURATION_DISTRIBUTED_METASTORE_KEY = "tr.config";
/**
* Constructor.
*/
public DistributedTracingConfiguration() {
super(TRACING_CONFIGURATION_DISTRIBUTED_METASTORE_KEY, null,
"The tracing configuration. Please use the '--tracing-configuration' command to modify.");
}
/**
* @return A new property that is detached from {@link DistributedConfigurationProcessor}.
* This means distributed updates are not accessible.
*/
public static DistributedTracingConfiguration detachedProperty() {
return new DistributedTracingConfiguration();
}
/** {@inheritDoc} */
@Override public HashMap<TracingConfigurationCoordinates, TracingConfigurationParameters> parse(String str) {<FILL_FUNCTION_BODY>}
}
|
throw new IgniteException("Please use the '--tracing-configuration' command to modify the tracing configuration");
| 258
| 29
| 287
|
<methods>public void <init>(java.lang.String, Function<java.lang.String,HashMap<org.apache.ignite.spi.tracing.TracingConfigurationCoordinates,org.apache.ignite.spi.tracing.TracingConfigurationParameters>>, java.lang.String) ,public void addListener(DistributePropertyListener<? super HashMap<org.apache.ignite.spi.tracing.TracingConfigurationCoordinates,org.apache.ignite.spi.tracing.TracingConfigurationParameters>>) ,public java.lang.String description() ,public HashMap<org.apache.ignite.spi.tracing.TracingConfigurationCoordinates,org.apache.ignite.spi.tracing.TracingConfigurationParameters> get() ,public java.lang.String getName() ,public HashMap<org.apache.ignite.spi.tracing.TracingConfigurationCoordinates,org.apache.ignite.spi.tracing.TracingConfigurationParameters> getOrDefault(HashMap<org.apache.ignite.spi.tracing.TracingConfigurationCoordinates,org.apache.ignite.spi.tracing.TracingConfigurationParameters>) ,public void localUpdate(java.io.Serializable) ,public void onAttached() ,public void onReadyForUpdate(org.apache.ignite.internal.processors.configuration.distributed.PropertyUpdateClosure) ,public HashMap<org.apache.ignite.spi.tracing.TracingConfigurationCoordinates,org.apache.ignite.spi.tracing.TracingConfigurationParameters> parse(java.lang.String) ,public static java.lang.Integer parseNonNegativeInteger(java.lang.String) ,public static java.lang.Long parseNonNegativeLong(java.lang.String) ,public static HashSet<java.lang.String> parseStringSet(java.lang.String) ,public boolean propagate(HashMap<org.apache.ignite.spi.tracing.TracingConfigurationCoordinates,org.apache.ignite.spi.tracing.TracingConfigurationParameters>) throws org.apache.ignite.IgniteCheckedException,public GridFutureAdapter<?> propagateAsync(HashMap<org.apache.ignite.spi.tracing.TracingConfigurationCoordinates,org.apache.ignite.spi.tracing.TracingConfigurationParameters>) throws org.apache.ignite.IgniteCheckedException,public GridFutureAdapter<?> propagateAsync(HashMap<org.apache.ignite.spi.tracing.TracingConfigurationCoordinates,org.apache.ignite.spi.tracing.TracingConfigurationParameters>, HashMap<org.apache.ignite.spi.tracing.TracingConfigurationCoordinates,org.apache.ignite.spi.tracing.TracingConfigurationParameters>) throws org.apache.ignite.IgniteCheckedException,public java.lang.String toString() <variables>private volatile boolean attached,private volatile org.apache.ignite.internal.processors.configuration.distributed.PropertyUpdateClosure clusterWideUpdater,private final non-sealed java.lang.String description,private final non-sealed java.lang.String name,private final non-sealed Function<java.lang.String,HashMap<org.apache.ignite.spi.tracing.TracingConfigurationCoordinates,org.apache.ignite.spi.tracing.TracingConfigurationParameters>> parser,private final ConcurrentLinkedQueue<DistributePropertyListener<? super HashMap<org.apache.ignite.spi.tracing.TracingConfigurationCoordinates,org.apache.ignite.spi.tracing.TracingConfigurationParameters>>> updateListeners,protected volatile HashMap<org.apache.ignite.spi.tracing.TracingConfigurationCoordinates,org.apache.ignite.spi.tracing.TracingConfigurationParameters> val
|
apache_ignite
|
ignite/modules/core/src/main/java/org/apache/ignite/internal/processors/tracing/messages/TraceableMessagesHandler.java
|
TraceableMessagesHandler
|
beforeSend
|
class TraceableMessagesHandler {
/** Span manager. */
private final SpanManager spanMgr;
/** Logger. */
private final IgniteLogger log;
/**
* @param spanMgr Span manager.
* @param log Logger.
*/
public TraceableMessagesHandler(SpanManager spanMgr, IgniteLogger log) {
this.spanMgr = spanMgr;
this.log = log;
}
/**
* Called when message is received.
* A span with name associated with given message will be created.
* from contained serialized span {@link SpanContainer#serializedSpanBytes()}
*
* @param msg Traceable message.
*/
public void afterReceive(TraceableMessage msg) {
if (log.isDebugEnabled())
log.debug("Received traceable message: " + msg);
if (msg.spanContainer().span() == NoopSpan.INSTANCE && msg.spanContainer().serializedSpanBytes() != null)
msg.spanContainer().span(
spanMgr.create(TraceableMessagesTable.traceName(msg.getClass()), msg.spanContainer().serializedSpanBytes())
.addLog(() -> "Received")
);
}
/**
* Called when message is going to be send.
* A serialized span will be created and attached to {@link TraceableMessage#spanContainer()}.
*
* @param msg Traceable message.
*/
public void beforeSend(TraceableMessage msg) {<FILL_FUNCTION_BODY>}
/**
* Injects a sub-span to {@code msg} as child span contained in given {@code parent}.
*
* @param msg Branched message.
* @param parent Parent message.
* @param <T> Traceable message type.
* @return Branched message with span context from parent message.
*/
public <T extends TraceableMessage> T branch(T msg, TraceableMessage parent) {
assert parent.spanContainer().span() != null : parent;
msg.spanContainer().serializedSpanBytes(
spanMgr.serialize(parent.spanContainer().span())
);
msg.spanContainer().span(
spanMgr.create(TraceableMessagesTable.traceName(msg.getClass()), parent.spanContainer().span())
.addLog(() -> "Created")
);
return msg;
}
/**
* @param msg Message.
*/
public void finishProcessing(TraceableMessage msg) {
if (log.isDebugEnabled())
log.debug("Processed traceable message: " + msg);
if (!msg.spanContainer().span().isEnded())
msg.spanContainer().span()
.addLog(() -> "Processed")
.end();
}
}
|
if (msg.spanContainer().span() != NoopSpan.INSTANCE && msg.spanContainer().serializedSpanBytes() == null)
msg.spanContainer().serializedSpanBytes(spanMgr.serialize(msg.spanContainer().span()));
| 717
| 62
| 779
|
<no_super_class>
|
apache_ignite
|
ignite/modules/core/src/main/java/org/apache/ignite/internal/sql/command/SqlDropIndexCommand.java
|
SqlDropIndexCommand
|
parse
|
class SqlDropIndexCommand implements SqlCommand {
/** Schema name. */
private String schemaName;
/** Index name. */
private String idxName;
/** IF EXISTS flag. */
private boolean ifExists;
/**
* Default constructor.
*/
public SqlDropIndexCommand() {
}
/**
* @param schemaName Schema name.
* @param idxName Index name.
* @param ifExists If exists clause.
*/
public SqlDropIndexCommand(String schemaName, String idxName, boolean ifExists) {
this.schemaName = schemaName;
this.idxName = idxName;
this.ifExists = ifExists;
}
/** {@inheritDoc} */
@Override public String schemaName() {
return schemaName;
}
/** {@inheritDoc} */
@Override public void schemaName(String schemaName) {
this.schemaName = schemaName;
}
/**
* @return Index name.
*/
public String indexName() {
return idxName;
}
/**
* @return IF EXISTS flag.
*/
public boolean ifExists() {
return ifExists;
}
/** {@inheritDoc} */
@Override public SqlCommand parse(SqlLexer lex) {<FILL_FUNCTION_BODY>}
/** {@inheritDoc} */
@Override public String toString() {
return S.toString(SqlDropIndexCommand.class, this);
}
}
|
ifExists = parseIfExists(lex);
SqlQualifiedName idxQName = parseQualifiedIdentifier(lex, IF);
schemaName = idxQName.schemaName();
idxName = idxQName.name();
return this;
| 383
| 66
| 449
|
<no_super_class>
|
apache_ignite
|
ignite/modules/core/src/main/java/org/apache/ignite/internal/sql/command/SqlStatisticsCommands.java
|
SqlStatisticsCommands
|
parseColumn
|
class SqlStatisticsCommands implements SqlCommand {
/** Schema name. */
private String schemaName;
/** Targets to process. */
protected List<StatisticsTarget> targets = new ArrayList<>();
/** */
protected SqlStatisticsCommands() {
// No-op.
}
/** */
protected SqlStatisticsCommands(Collection<StatisticsTarget> targets) {
this.targets = new ArrayList<>(targets);
}
/** {@inheritDoc} */
@Override public String schemaName() {
return schemaName;
}
/** {@inheritDoc} */
@Override public void schemaName(String schemaName) {
this.schemaName = schemaName;
}
/**
* @return Analyze targets.
*/
public Collection<StatisticsTarget> targets() {
return Collections.unmodifiableList(targets);
}
/** {@inheritDoc} */
@Override public SqlCommand parse(SqlLexer lex) {
while (true) {
SqlQualifiedName tblQName = parseQualifiedIdentifier(lex);
String[] cols = parseColumnList(lex, false);
targets.add(new StatisticsTarget(tblQName.schemaName(), tblQName.name(), cols));
if (tryEnd(lex))
return this;
}
}
/**
* Test if it is the end of command.
*
* @param lex Sql lexer.
* @return {@code true} if end of command found, {@code false} - otherwise.
*/
protected boolean tryEnd(SqlLexer lex) {
return !lex.shift() || lex.tokenType() == SqlLexerTokenType.SEMICOLON;
}
/**
* @param lex Lexer.
* @param allowParams If {@code true} - allow params instead columns list.
*/
protected String[] parseColumnList(SqlLexer lex, boolean allowParams) {
SqlLexerToken nextTok = lex.lookAhead();
if (nextTok.token() == null || nextTok.tokenType() == SqlLexerTokenType.SEMICOLON
|| nextTok.tokenType() == SqlLexerTokenType.COMMA)
return null;
if (allowParams && matchesKeyword(nextTok, SqlKeyword.WITH))
return null;
lex.shift();
if (lex.tokenType() != SqlLexerTokenType.PARENTHESIS_LEFT)
throw errorUnexpectedToken(lex, "(");
Set<String> res = new HashSet<>();
while (true) {
parseColumn(lex, res);
if (skipCommaOrRightParenthesis(lex))
break;
}
return (res.isEmpty()) ? null : res.toArray(new String[0]);
}
/**
* Parse column name.
*
* @param lex Lexer.
*/
private void parseColumn(SqlLexer lex, Set<String> cols) {<FILL_FUNCTION_BODY>}
}
|
String name = parseIdentifier(lex);
if (!cols.add(name))
throw error(lex, "Column " + name + " already defined.");
| 796
| 41
| 837
|
<no_super_class>
|
apache_ignite
|
ignite/modules/core/src/main/java/org/apache/ignite/internal/sql/optimizer/affinity/PartitionClientContext.java
|
PartitionClientContext
|
partition
|
class PartitionClientContext {
/** Number of partitions. */
private int parts;
/** Mask to use in calculation when partitions count is power of 2. */
private int mask;
/**
* Constructor.
*
* @param parts Partitions count.
*/
public PartitionClientContext(int parts) {
assert parts <= CacheConfiguration.MAX_PARTITIONS_COUNT;
assert parts > 0;
this.parts = parts;
mask = RendezvousAffinityFunction.calculateMask(parts);
}
/**
* Resolve partition.
*
* @param arg Argument.
* @param typ Type.
* @return Partition or {@code null} if cannot be resolved.
*/
@Nullable public Integer partition(Object arg, @Nullable PartitionParameterType typ) {<FILL_FUNCTION_BODY>}
}
|
if (typ == null)
return null;
Object key = PartitionDataTypeUtils.convert(arg, typ);
if (key == PartitionDataTypeUtils.CONVERTATION_FAILURE)
return null;
if (key == null)
return null;
return RendezvousAffinityFunction.calculatePartition(key, mask, parts);
| 227
| 99
| 326
|
<no_super_class>
|
apache_ignite
|
ignite/modules/core/src/main/java/org/apache/ignite/internal/sql/optimizer/affinity/PartitionJoinCondition.java
|
PartitionJoinCondition
|
equals
|
class PartitionJoinCondition {
/** Cross JOIN. */
public static final PartitionJoinCondition CROSS = new PartitionJoinCondition(null, null, null, null, true);
/** Left alias. */
private final String leftAlias;
/** Right alias. */
private final String rightAlias;
/** Left column name. */
private final String leftCol;
/** Right column name. */
private final String rightCol;
/** Whether this is a cross-join. */
private final boolean cross;
/**
* Constructor.
*
* @param leftAlias Left alias.
* @param rightAlias Right alias.
* @param leftCol Left column name.
* @param rightCol Right column name.
*/
public PartitionJoinCondition(String leftAlias, String rightAlias, String leftCol, String rightCol) {
this(leftAlias, rightAlias, leftCol, rightCol, false);
}
/**
* Constructor.
*
* @param leftAlias Left alias.
* @param rightAlias Right alias.
* @param leftCol Left column name.
* @param rightCol Right column name.
* @param cross Whether this is a cross-join.
*/
private PartitionJoinCondition(String leftAlias, String rightAlias, String leftCol, String rightCol,
boolean cross) {
this.leftAlias = leftAlias;
this.rightAlias = rightAlias;
this.leftCol = leftCol;
this.rightCol = rightCol;
this.cross = cross;
}
/**
* Left alias.
*/
public String leftAlias() {
return leftAlias;
}
/**
* Right alias.
*/
public String rightAlias() {
return rightAlias;
}
/**
* @return Left column.
*/
public String leftColumn() {
return leftCol;
}
/**
* @return Right column.
*/
public String rightColumn() {
return rightCol;
}
/**
* @return Wheter this is a cross-join.
*/
public boolean cross() {
return cross;
}
/** {@inheritDoc} */
@Override public int hashCode() {
int res = leftAlias.hashCode();
res = 31 * res + rightAlias.hashCode();
res = 31 * res + leftCol.hashCode();
res = 31 * res + rightCol.hashCode();
res = 31 * res + Boolean.hashCode(cross);
return res;
}
/** {@inheritDoc} */
@Override public boolean equals(Object obj) {<FILL_FUNCTION_BODY>}
}
|
if (obj instanceof PartitionJoinCondition) {
PartitionJoinCondition other = (PartitionJoinCondition)obj;
return F.eq(leftAlias, other.leftAlias) && F.eq(rightAlias, other.rightAlias) &&
F.eq(leftCol, other.leftCol) && F.eq(rightCol, other.rightCol) && F.eq(cross, other.cross);
}
return false;
| 704
| 111
| 815
|
<no_super_class>
|
apache_ignite
|
ignite/modules/core/src/main/java/org/apache/ignite/internal/sql/optimizer/affinity/PartitionParameterNode.java
|
PartitionParameterNode
|
applySingle
|
class PartitionParameterNode extends PartitionSingleNode {
/** Indexing. */
@GridToStringExclude
private final PartitionResolver partRslvr;
/** Index. */
private final int idx;
/** Parameter data type. */
private final int type;
/** Client parameter type. */
private final PartitionParameterType clientType;
/**
* Constructor.
*
* @param tbl Table descriptor.
* @param partRslvr Partition resolver.
* @param idx Parameter index.
* @param type Parameter data type.
* @param clientType Mapped parameter type to be used by thin clients.
*/
public PartitionParameterNode(PartitionTable tbl, PartitionResolver partRslvr, int idx, int type,
PartitionParameterType clientType) {
super(tbl);
this.partRslvr = partRslvr;
this.idx = idx;
this.type = type;
this.clientType = clientType;
}
/** {@inheritDoc} */
@Override public Integer applySingle(PartitionClientContext cliCtx, Object... args) throws IgniteCheckedException {<FILL_FUNCTION_BODY>}
/** {@inheritDoc} */
@Override public boolean constant() {
return false;
}
/** {@inheritDoc} */
@Override public int value() {
return idx;
}
/**
* @return Parameter data type.
*/
public int type() {
return type;
}
/**
* @return Client parameter type.
*/
public PartitionParameterType clientType() {
return clientType;
}
/** {@inheritDoc} */
@Override public String toString() {
return S.toString(PartitionParameterNode.class, this);
}
}
|
assert args != null;
assert idx < args.length;
Object arg = args[idx];
if (cliCtx != null)
return cliCtx.partition(arg, clientType);
else {
assert partRslvr != null;
return partRslvr.partition(
arg,
type,
tbl.cacheName()
);
}
| 463
| 105
| 568
|
<methods>public transient Collection<java.lang.Integer> apply(org.apache.ignite.internal.sql.optimizer.affinity.PartitionClientContext, java.lang.Object[]) throws org.apache.ignite.IgniteCheckedException,public transient abstract java.lang.Integer applySingle(org.apache.ignite.internal.sql.optimizer.affinity.PartitionClientContext, java.lang.Object[]) throws org.apache.ignite.IgniteCheckedException,public java.lang.String cacheName() ,public abstract boolean constant() ,public boolean equals(java.lang.Object) ,public int hashCode() ,public int joinGroup() ,public org.apache.ignite.internal.sql.optimizer.affinity.PartitionTable table() ,public abstract int value() <variables>protected final non-sealed org.apache.ignite.internal.sql.optimizer.affinity.PartitionTable tbl
|
apache_ignite
|
ignite/modules/core/src/main/java/org/apache/ignite/internal/sql/optimizer/affinity/PartitionResult.java
|
PartitionResult
|
calculatePartitions
|
class PartitionResult {
/** Tree. */
@GridToStringInclude
private final PartitionNode tree;
/** Affinity function. */
private final PartitionTableAffinityDescriptor aff;
/** Affinity topology version. Used within Jdbc thin partition awareness. */
private final AffinityTopologyVersion topVer;
/** Cache name. Used within Jdbc thin partition awareness. */
private final String cacheName;
/** Partitions count. Used within Jdbc thin partition awareness. */
private final int partsCnt;
/**
* Constructor.
*
* @param tree Tree.
* @param aff Affinity function.
*/
public PartitionResult(PartitionNode tree, PartitionTableAffinityDescriptor aff, AffinityTopologyVersion topVer) {
this.tree = tree;
this.aff = aff;
this.topVer = topVer;
cacheName = tree != null ? tree.cacheName() : null;
partsCnt = aff != null ? aff.parts() : 0;
}
/**
* Constructor.
*
* @param tree Tree.
* @param aff Affinity function.
*/
/**
* Constructor.
*
* @param tree Tree.
* @param topVer Affinity topology version.
* @param cacheName Cache name.
* @param partsCnt Partitions count.
*/
public PartitionResult(PartitionNode tree, AffinityTopologyVersion topVer, String cacheName, int partsCnt) {
this.tree = tree;
aff = null;
this.topVer = topVer;
this.cacheName = cacheName;
this.partsCnt = partsCnt;
}
/**
* Tree.
*/
public PartitionNode tree() {
return tree;
}
/**
* @return Affinity function.
*/
public PartitionTableAffinityDescriptor affinity() {
return aff;
}
/**
* Calculate partitions for the query.
*
* @param explicitParts Explicit partitions provided in SqlFieldsQuery.partitions property.
* @param derivedParts Derived partitions found during partition pruning.
* @param args Arguments.
* @return Calculated partitions or {@code null} if failed to calculate and there should be a broadcast.
*/
@SuppressWarnings("ZeroLengthArrayAllocation")
public static int[] calculatePartitions(int[] explicitParts, PartitionResult derivedParts, Object[] args) {<FILL_FUNCTION_BODY>}
/**
* @return Affinity topology version. This method is intended to be used within the Jdbc thin client.
*/
public AffinityTopologyVersion topologyVersion() {
return topVer;
}
/**
* @return Cache name. This method is intended to be used within the Jdbc thin client.
*/
public String cacheName() {
return cacheName;
}
/**
* @return Partitions count. This method is intended to be used within the Jdbc thin client.
*/
public int partitionsCount() {
return partsCnt;
}
/**
* @return True if applicable to jdbc thin client side partition awareness:
* 1. Rendezvous affinity function without map filters was used;
* 2. Partition result tree neither PartitoinAllNode nor PartitionNoneNode;
*/
public boolean isClientPartitionAwarenessApplicable() {
return aff != null && aff.isClientPartitionAwarenessApplicable() &&
!(tree instanceof PartitionNoneNode) && !(tree instanceof PartitionAllNode);
}
/** {@inheritDoc} */
@Override public String toString() {
return S.toString(PartitionResult.class, this);
}
}
|
if (!F.isEmpty(explicitParts))
return explicitParts;
else if (derivedParts != null) {
try {
Collection<Integer> realParts = derivedParts.tree().apply(null, args);
if (realParts == null)
return null;
else if (realParts.isEmpty())
return IgniteUtils.EMPTY_INTS;
else {
int[] realParts0 = new int[realParts.size()];
int i = 0;
for (Integer realPart : realParts)
realParts0[i++] = realPart;
return realParts0;
}
}
catch (IgniteCheckedException e) {
throw new CacheException("Failed to calculate derived partitions for query.", e);
}
}
return null;
| 951
| 218
| 1,169
|
<no_super_class>
|
apache_ignite
|
ignite/modules/core/src/main/java/org/apache/ignite/internal/sql/optimizer/affinity/PartitionTableAffinityDescriptor.java
|
PartitionTableAffinityDescriptor
|
isCompatible
|
class PartitionTableAffinityDescriptor {
/** Affinity function type. */
private final PartitionAffinityFunctionType affFunc;
/** Number of partitions. */
private final int parts;
/** Whether node filter is set. */
private final boolean hasNodeFilter;
/** Data region name. */
private final String dataRegion;
/**
* Constructor.
*
* @param affFunc Affinity function type.
* @param parts Number of partitions.
* @param hasNodeFilter Whether node filter is set.
* @param dataRegion Data region.
*/
public PartitionTableAffinityDescriptor(
PartitionAffinityFunctionType affFunc,
int parts,
boolean hasNodeFilter,
String dataRegion
) {
this.affFunc = affFunc;
this.parts = parts;
this.hasNodeFilter = hasNodeFilter;
this.dataRegion = dataRegion;
}
/**
* Check is provided descriptor is compatible with this instance (i.e. can be used in the same co-location group).
*
* @param other Other descriptor.
* @return {@code True} if compatible.
*/
@SuppressWarnings("BooleanMethodIsAlwaysInverted")
public boolean isCompatible(PartitionTableAffinityDescriptor other) {<FILL_FUNCTION_BODY>}
/**
*
* @return True if applicable to jdbc thin client side partition awareness.
*/
public boolean isClientPartitionAwarenessApplicable() {
return affFunc == PartitionAffinityFunctionType.RENDEZVOUS && !hasNodeFilter;
}
/**
* @return Number of partitions.
*/
public int parts() {
return parts;
}
/** {@inheritDoc} */
@Override public String toString() {
return S.toString(PartitionTableAffinityDescriptor.class, this);
}
}
|
if (other == null)
return false;
// Rendezvous affinity function is deterministic and doesn't depend on previous cluster view changes.
// In future other user affinity functions would be applicable as well if explicityl marked deterministic.
if (affFunc == PartitionAffinityFunctionType.RENDEZVOUS) {
// We cannot be sure that two caches are co-located if custom node filter is present.
// Nota that technically we may try to compare two filters. However, this adds unnecessary complexity
// and potential deserialization issues when SQL is called from client nodes or thin clients.
if (!hasNodeFilter) {
return
other.affFunc == PartitionAffinityFunctionType.RENDEZVOUS &&
!other.hasNodeFilter &&
other.parts == parts &&
F.eq(other.dataRegion, dataRegion);
}
}
return false;
| 484
| 229
| 713
|
<no_super_class>
|
apache_ignite
|
ignite/modules/core/src/main/java/org/apache/ignite/internal/util/GridArgumentCheck.java
|
GridArgumentCheck
|
notEmpty
|
class GridArgumentCheck {
/** Null pointer error message prefix. */
public static final String NULL_MSG_PREFIX = "Ouch! Argument cannot be null: ";
/** Invalid argument error message prefix. */
private static final String INVALID_ARG_MSG_PREFIX = "Ouch! Argument is invalid: ";
/** Not empty argument error message suffix. */
private static final String NOT_EMPTY_SUFFIX = " must not be empty.";
/** Not null or empty error message suffix. */
private static final String NOT_NULL_OR_EMPTY_SUFFIX = " must not be null or empty.";
/**
* Checks if given argument value is not {@code null}. Otherwise - throws {@link NullPointerException}.
*
* @param val Argument value to check.
* @param name Name of the argument in the code (used in error message).
*/
public static void notNull(@Nullable Object val, String name) {
if (val == null)
throw new NullPointerException(NULL_MSG_PREFIX + name);
}
/**
* Checks that none of the given values are {@code null}. Otherwise - throws {@link NullPointerException}.
*
* @param val1 1st argument value to check.
* @param name1 Name of the 1st argument in the code (used in error message).
* @param val2 2nd argument value to check.
* @param name2 Name of the 2nd argument in the code (used in error message).
*/
public static void notNull(Object val1, String name1, Object val2, String name2) {
notNull(val1, name1);
notNull(val2, name2);
}
/**
* Checks that none of the given values are {@code null}. Otherwise - throws {@link NullPointerException}.
*
* @param val1 1st argument value to check.
* @param name1 Name of the 1st argument in the code (used in error message).
* @param val2 2nd argument value to check.
* @param name2 Name of the 2nd argument in the code (used in error message).
* @param val3 3rd argument value to check.
* @param name3 Name of the 3rd argument in the code (used in error message).
*/
public static void notNull(Object val1, String name1, Object val2, String name2, Object val3, String name3) {
notNull(val1, name1);
notNull(val2, name2);
notNull(val3, name3);
}
/**
* Checks that none of the given values are {@code null}. Otherwise - throws {@link NullPointerException}.
*
* @param val1 1st argument value to check.
* @param name1 Name of the 1st argument in the code (used in error message).
* @param val2 2nd argument value to check.
* @param name2 Name of the 2nd argument in the code (used in error message).
* @param val3 3rd argument value to check.
* @param name3 Name of the 3rd argument in the code (used in error message).
* @param val4 4th argument value to check.
* @param name4 Name of the 4th argument in the code (used in error message).
*/
public static void notNull(Object val1, String name1, Object val2, String name2, Object val3, String name3,
Object val4, String name4) {
notNull(val1, name1);
notNull(val2, name2);
notNull(val3, name3);
notNull(val4, name4);
}
/**
* Checks if given argument's condition is equal to {@code true}, otherwise
* throws {@link IllegalArgumentException} exception.
*
* @param cond Argument's value condition to check.
* @param desc Description of the condition to be used in error message.
*/
public static void ensure(boolean cond, String desc) {
if (!cond)
throw new IllegalArgumentException(INVALID_ARG_MSG_PREFIX + desc);
}
/**
* Checks that given collection is not empty.
*
* @param c Collection.
* @param name Argument name.
*/
public static void notEmpty(Collection<?> c, String name) {
notNull(c, name);
if (c.isEmpty())
throw new IllegalArgumentException(INVALID_ARG_MSG_PREFIX + name + NOT_EMPTY_SUFFIX);
}
/**
* Checks that given array is not empty.
*
* @param arr Array.
* @param name Argument name.
*/
public static void notEmpty(Object[] arr, String name) {<FILL_FUNCTION_BODY>}
/**
* Checks that given array is not empty.
*
* @param arr Array.
* @param name Argument name.
*/
public static void notEmpty(int[] arr, String name) {
notNull(arr, name);
if (arr.length == 0)
throw new IllegalArgumentException(INVALID_ARG_MSG_PREFIX + name + NOT_EMPTY_SUFFIX);
}
/**
* Checks that given array is not empty.
*
* @param arr Array.
* @param name Argument name.
*/
public static void notEmpty(long[] arr, String name) {
notNull(arr, name);
if (arr.length == 0)
throw new IllegalArgumentException(INVALID_ARG_MSG_PREFIX + name + NOT_EMPTY_SUFFIX);
}
/**
* Checks that given array is not empty.
*
* @param arr Array.
* @param name Argument name.
*/
public static void notEmpty(double[] arr, String name) {
notNull(arr, name);
if (arr.length == 0)
throw new IllegalArgumentException(INVALID_ARG_MSG_PREFIX + name + NOT_EMPTY_SUFFIX);
}
/**
* Checks that given String is not empty.
*
* @param str String.
* @param name Argument name.
*/
public static void notEmpty(String str, String name) {
notNull(str, name);
if (str.isEmpty())
throw new IllegalArgumentException(INVALID_ARG_MSG_PREFIX + name + NOT_EMPTY_SUFFIX);
}
/**
* Checks that given String is nullable but not empty.
*
* @param str String.
* @param name Argument name.
*/
public static void nullableNotEmpty(String str, String name) {
if (str == null)
return;
if (str.isEmpty())
throw new IllegalArgumentException(INVALID_ARG_MSG_PREFIX + name + NOT_EMPTY_SUFFIX);
}
/**
* Checks that a String is not null or empty.
*
* @param value Value to check.
* @param name Argument name.
*/
public static void notNullOrEmpty(String value, String name) {
notNull(value, name);
if (value.trim().isEmpty())
throw new IllegalArgumentException(INVALID_ARG_MSG_PREFIX + name + NOT_NULL_OR_EMPTY_SUFFIX);
}
}
|
notNull(arr, name);
if (arr.length == 0)
throw new IllegalArgumentException(INVALID_ARG_MSG_PREFIX + name + NOT_EMPTY_SUFFIX);
| 1,881
| 53
| 1,934
|
<no_super_class>
|
apache_ignite
|
ignite/modules/core/src/main/java/org/apache/ignite/internal/util/GridAtomicInitializer.java
|
GridAtomicInitializer
|
init
|
class GridAtomicInitializer<T> {
/** */
private final Object mux = new Object();
/** */
private volatile boolean finished;
/** Don't use volatile because we write this field before 'finished' write and read after 'finished' read. */
@SuppressWarnings("FieldAccessedSynchronizedAndUnsynchronized")
private Exception e;
/** Don't use volatile because we write this field before 'finished' write and read after 'finished' read. */
@SuppressWarnings("FieldAccessedSynchronizedAndUnsynchronized")
private T res;
/**
* Executes initialization operation only once.
*
* @param c Initialization operation.
* @return Result of initialization.
* @throws IgniteCheckedException If failed.
*/
public T init(Callable<T> c) throws IgniteCheckedException {<FILL_FUNCTION_BODY>}
/**
* @return True, if initialization was already successfully completed.
*/
public boolean succeeded() {
return finished && e == null;
}
/**
* Should be called only if succeeded.
*
* @return Result.
*/
public T result() {
return res;
}
/**
* Await for completion.
*
* @return {@code true} If initialization was completed successfully.
* @throws IgniteInterruptedCheckedException If thread was interrupted.
*/
public boolean await() throws IgniteInterruptedCheckedException {
if (!finished) {
synchronized (mux) {
while (!finished)
U.wait(mux);
}
}
return e == null;
}
/** {@inheritDoc} */
@Override public String toString() {
return S.toString(GridAtomicInitializer.class, this);
}
}
|
if (!finished) {
synchronized (mux) {
if (!finished) {
try {
res = c.call();
}
catch (Exception e) {
this.e = e;
}
finally {
finished = true;
mux.notifyAll();
}
}
}
}
if (e != null)
throw e instanceof IgniteCheckedException ? (IgniteCheckedException)e : new IgniteCheckedException(e);
return res;
| 468
| 136
| 604
|
<no_super_class>
|
apache_ignite
|
ignite/modules/core/src/main/java/org/apache/ignite/internal/util/GridAtomicInteger.java
|
GridAtomicInteger
|
setIfNotEquals
|
class GridAtomicInteger extends AtomicInteger {
/** */
private static final long serialVersionUID = 0L;
/**
* Creates a new AtomicInteger with initial value {@code 0}.
*/
public GridAtomicInteger() {
// No-op.
}
/**
* Creates a new AtomicInteger with the given initial value.
*
* @param initVal the initial value
*/
public GridAtomicInteger(int initVal) {
super(initVal);
}
/**
* Atomically updates value only if {@code check} value is greater
* than current value.
*
* @param check Value to check against.
* @param update Value to set.
* @return {@code True} if value was set.
*/
public boolean greaterAndSet(int check, int update) {
while (true) {
int cur = get();
if (check > cur) {
if (compareAndSet(cur, update))
return true;
}
else
return false;
}
}
/**
* Atomically updates value only if {@code check} value is greater
* than or equal to current value.
*
* @param check Value to check against.
* @param update Value to set.
* @return {@code True} if value was set.
*/
public boolean greaterEqualsAndSet(int check, int update) {
while (true) {
int cur = get();
if (check >= cur) {
if (compareAndSet(cur, update))
return true;
}
else
return false;
}
}
/**
* Atomically updates value only if {@code check} value is less
* than current value.
*
* @param check Value to check against.
* @param update Value to set.
* @return {@code True} if value was set.
*/
public boolean lessAndSet(int check, int update) {
while (true) {
int cur = get();
if (check < cur) {
if (compareAndSet(cur, update))
return true;
}
else
return false;
}
}
/**
* Atomically updates value only if {@code check} value is less
* than current value.
*
* @param check Value to check against.
* @param update Value to set.
* @return {@code True} if value was set.
*/
public boolean lessEqualsAndSet(int check, int update) {
while (true) {
int cur = get();
if (check <= cur) {
if (compareAndSet(cur, update))
return true;
}
else
return false;
}
}
/**
* Sets value only if it is greater than current one.
*
* @param update Value to set.
* @return {@code True} if value was set.
*/
public boolean setIfGreater(int update) {
while (true) {
int cur = get();
if (update > cur) {
if (compareAndSet(cur, update))
return true;
}
else
return false;
}
}
/**
* Sets value only if it is greater than or equals to current one.
*
* @param update Value to set.
* @return {@code True} if value was set.
*/
public boolean setIfGreaterEquals(int update) {
while (true) {
int cur = get();
if (update >= cur) {
if (compareAndSet(cur, update))
return true;
}
else
return false;
}
}
/**
* Sets value only if it is less than current one.
*
* @param update Value to set.
* @return {@code True} if value was set.
*/
public boolean setIfLess(int update) {
while (true) {
int cur = get();
if (update < cur) {
if (compareAndSet(cur, update))
return true;
}
else
return false;
}
}
/**
* Sets value only if it is less than or equals to current one.
*
* @param update Value to set.
* @return {@code True} if value was set.
*/
public boolean setIfLessEquals(int update) {
while (true) {
int cur = get();
if (update <= cur) {
if (compareAndSet(cur, update))
return true;
}
else
return false;
}
}
/**
* Sets value only if it is not equals to current one.
*
* @param update Value to set.
* @return {@code True} if value was set.
*/
public boolean setIfNotEquals(int update) {<FILL_FUNCTION_BODY>}
/**
* Atomically updates value only if passed in predicate returns {@code true}.
*
* @param p Predicate to check.
* @param update Value to set.
* @return {@code True} if value was set.
*/
public boolean checkAndSet(IgnitePredicate<Integer> p, int update) {
while (true) {
int cur = get();
if (p.apply(cur)) {
if (compareAndSet(cur, update))
return true;
}
else
return false;
}
}
}
|
while (true) {
int cur = get();
if (update != cur) {
if (compareAndSet(cur, update))
return true;
}
else
return false;
}
| 1,408
| 59
| 1,467
|
<methods>public void <init>() ,public void <init>(int) ,public final int accumulateAndGet(int, java.util.function.IntBinaryOperator) ,public final int addAndGet(int) ,public final int compareAndExchange(int, int) ,public final int compareAndExchangeAcquire(int, int) ,public final int compareAndExchangeRelease(int, int) ,public final boolean compareAndSet(int, int) ,public final int decrementAndGet() ,public double doubleValue() ,public float floatValue() ,public final int get() ,public final int getAcquire() ,public final int getAndAccumulate(int, java.util.function.IntBinaryOperator) ,public final int getAndAdd(int) ,public final int getAndDecrement() ,public final int getAndIncrement() ,public final int getAndSet(int) ,public final int getAndUpdate(java.util.function.IntUnaryOperator) ,public final int getOpaque() ,public final int getPlain() ,public final int incrementAndGet() ,public int intValue() ,public final void lazySet(int) ,public long longValue() ,public final void set(int) ,public final void setOpaque(int) ,public final void setPlain(int) ,public final void setRelease(int) ,public java.lang.String toString() ,public final int updateAndGet(java.util.function.IntUnaryOperator) ,public final boolean weakCompareAndSet(int, int) ,public final boolean weakCompareAndSetAcquire(int, int) ,public final boolean weakCompareAndSetPlain(int, int) ,public final boolean weakCompareAndSetRelease(int, int) ,public final boolean weakCompareAndSetVolatile(int, int) <variables>private static final jdk.internal.misc.Unsafe U,private static final long VALUE,private static final long serialVersionUID,private volatile int value
|
apache_ignite
|
ignite/modules/core/src/main/java/org/apache/ignite/internal/util/GridCircularBuffer.java
|
Item
|
update
|
class Item<V> {
/** */
private long idx;
/** */
@GridToStringInclude
private V item;
/**
*
*/
Item() {
// No-op.
}
/**
* @return Item.
*/
synchronized V item() {
return item;
}
/**
* @param newIdx Index.
* @param newItem Item.
* @param maxIdxDiff Max difference in indexes.
* @return Evicted value on success or {@code null} if update failed.
* @throws InterruptedException If interrupted.
*/
@Nullable synchronized V update(long newIdx, V newItem, long maxIdxDiff) throws InterruptedException {
assert newIdx >= 0;
// Thread should wait and allow previous update to finish.
while (newIdx - idx > maxIdxDiff)
wait();
V old = item;
idx = newIdx;
item = newItem;
notifyAll();
return old;
}
/**
* @param newIdx Index.
* @param newItem Item.
* @param maxIdxDiff Max difference in indexes.
* @param c Closure applied on evicted object before eviction.
* @return Evicted value on success or {@code null} if update failed.
* @throws InterruptedException If interrupted.
* @throws IgniteCheckedException If closure throws exception.
*/
@Nullable synchronized V update(long newIdx, V newItem, long maxIdxDiff, @Nullable IgniteInClosureX<V> c)
throws InterruptedException, IgniteCheckedException {<FILL_FUNCTION_BODY>}
/**
* @return Item data and index.
*/
synchronized T2<V, Long> get() {
return new T2<>(item, idx);
}
/** {@inheritDoc} */
@Override public synchronized String toString() {
return S.toString(Item.class, this, "hash=" + System.identityHashCode(this));
}
}
|
assert newIdx >= 0;
// Thread should wait and allow previous update to finish.
while (newIdx - idx > maxIdxDiff)
wait();
idx = newIdx; // Index should be updated even if closure fails.
if (c != null && item != null)
c.applyx(item);
V old = item;
item = newItem;
notifyAll();
return old;
| 535
| 116
| 651
|
<no_super_class>
|
apache_ignite
|
ignite/modules/core/src/main/java/org/apache/ignite/internal/util/GridCloseableIteratorAdapterEx.java
|
GridCloseableIteratorAdapterEx
|
hasNextX
|
class GridCloseableIteratorAdapterEx<T> extends GridIteratorAdapter<T>
implements GridCloseableIterator<T> {
/** */
private static final long serialVersionUID = 0L;
/** Closed flag. */
private final AtomicBoolean closed = new AtomicBoolean();
/** {@inheritDoc} */
@Override public final T nextX() throws IgniteCheckedException {
if (closed.get())
return null;
try {
if (!onHasNext())
throw new NoSuchElementException();
return onNext();
}
catch (IgniteCheckedException e) {
if (closed.get())
return null;
else
throw e;
}
}
/**
* @return Next element.
* @throws IgniteCheckedException If failed.
* @throws NoSuchElementException If no element found.
*/
protected abstract T onNext() throws IgniteCheckedException;
/** {@inheritDoc} */
@Override public final boolean hasNextX() throws IgniteCheckedException {<FILL_FUNCTION_BODY>}
/**
* @return {@code True} if iterator has next element.
* @throws IgniteCheckedException If failed.
*/
protected abstract boolean onHasNext() throws IgniteCheckedException;
/** {@inheritDoc} */
@Override public final void removeX() throws IgniteCheckedException {
if (closed.get())
throw new NoSuchElementException("Iterator has been closed.");
try {
onRemove();
}
catch (IgniteCheckedException e) {
if (!closed.get())
throw e;
}
}
/**
* Called on remove from iterator.
*
* @throws IgniteCheckedException If failed.
*/
protected void onRemove() throws IgniteCheckedException {
throw new UnsupportedOperationException("Remove is not supported.");
}
/** {@inheritDoc} */
@Override public final void close() throws IgniteCheckedException {
if (closed.compareAndSet(false, true))
onClose();
}
/**
* Invoked on iterator close.
*
* @throws IgniteCheckedException If closing failed.
*/
protected void onClose() throws IgniteCheckedException {
// No-op.
}
/** {@inheritDoc} */
@Override public boolean isClosed() {
return closed.get();
}
}
|
if (closed.get())
return false;
try {
return onHasNext();
}
catch (IgniteCheckedException e) {
if (closed.get())
return false;
else
throw e;
}
| 621
| 67
| 688
|
<methods>public non-sealed void <init>() ,public final boolean hasNext() ,public final Iterator<T> iterator() ,public final T next() ,public final void remove() <variables>private static final long serialVersionUID
|
apache_ignite
|
ignite/modules/core/src/main/java/org/apache/ignite/internal/util/GridCollections.java
|
LockedCollection
|
remove
|
class LockedCollection<E> extends ReentrantLock implements Collection<E> {
/** */
private static final long serialVersionUID = 0L;
/** Delegating collection. */
protected final Collection<E> c;
/**
* @param c Delegating collection.
*/
private LockedCollection(Collection<E> c) {
this.c = c;
}
/** {@inheritDoc} */
@Override public boolean add(E e) {
lock();
try {
return c.add(e);
}
finally {
unlock();
}
}
/** {@inheritDoc} */
@Override public int size() {
lock();
try {
return c.size();
}
finally {
unlock();
}
}
/** {@inheritDoc} */
@Override public boolean isEmpty() {
lock();
try {
return c.isEmpty();
}
finally {
unlock();
}
}
/** {@inheritDoc} */
@Override public boolean contains(Object o) {
lock();
try {
return c.contains(o);
}
finally {
unlock();
}
}
/** {@inheritDoc} */
@Override public Iterator<E> iterator() {
return c.iterator(); // Must be manually synced by user.
}
/** {@inheritDoc} */
@Override public Object[] toArray() {
lock();
try {
return c.toArray();
}
finally {
unlock();
}
}
/** {@inheritDoc} */
@SuppressWarnings({"SuspiciousToArrayCall"})
@Override public <T> T[] toArray(T[] a) {
lock();
try {
return c.toArray(a);
}
finally {
unlock();
}
}
/** {@inheritDoc} */
@Override public boolean remove(Object o) {<FILL_FUNCTION_BODY>}
/** {@inheritDoc} */
@Override public boolean containsAll(Collection<?> c) {
lock();
try {
return this.c.containsAll(c);
}
finally {
unlock();
}
}
/** {@inheritDoc} */
@Override public boolean addAll(Collection<? extends E> c) {
lock();
try {
return this.c.addAll(c);
}
finally {
unlock();
}
}
/** {@inheritDoc} */
@Override public boolean removeAll(Collection<?> c) {
lock();
try {
return this.c.removeAll(c);
}
finally {
unlock();
}
}
/** {@inheritDoc} */
@Override public boolean retainAll(Collection<?> c) {
lock();
try {
return this.c.retainAll(c);
}
finally {
unlock();
}
}
/** {@inheritDoc} */
@Override public void clear() {
lock();
try {
c.clear();
}
finally {
unlock();
}
}
/** {@inheritDoc} */
@Override public int hashCode() {
lock();
try {
return c.hashCode();
}
finally {
unlock();
}
}
/** {@inheritDoc} */
@Override public boolean equals(Object o) {
lock();
try {
return c.equals(o);
}
finally {
unlock();
}
}
/** {@inheritDoc} */
@Override public String toString() {
lock();
try {
return c.toString();
}
finally {
unlock();
}
}
/**
* Overrides write object.
*
* @param s Object output stream.
* @throws IOException If failed.
*/
private void writeObject(ObjectOutputStream s) throws IOException {
lock();
try {
s.defaultWriteObject();
}
finally {
unlock();
}
}
}
|
lock();
try {
return c.remove(o);
}
finally {
unlock();
}
| 1,079
| 35
| 1,114
|
<no_super_class>
|
apache_ignite
|
ignite/modules/core/src/main/java/org/apache/ignite/internal/util/GridConcurrentMultiPairQueue.java
|
GridConcurrentMultiPairQueue
|
next
|
class GridConcurrentMultiPairQueue<K, V> {
/** */
public static final GridConcurrentMultiPairQueue EMPTY =
new GridConcurrentMultiPairQueue<>(Collections.emptyMap());
/** Inner holder. */
private final V[][] vals;
/** Storage for every array length. */
private final int[] lenSeq;
/** Current absolute position. */
private final AtomicInteger pos = new AtomicInteger();
/** Precalculated max position. */
private final int maxPos;
/** Keys array. */
private final K[] keysArr;
/** */
public GridConcurrentMultiPairQueue(Map<K, ? extends Collection<V>> items) {
int pairCnt = (int)items.entrySet().stream().map(Map.Entry::getValue).filter(k -> k.size() > 0).count();
vals = (V[][])new Object[pairCnt][];
keysArr = (K[])new Object[pairCnt];
lenSeq = new int[pairCnt];
int keyPos = 0;
int size = -1;
for (Map.Entry<K, ? extends Collection<V>> p : items.entrySet()) {
if (p.getValue().isEmpty())
continue;
keysArr[keyPos] = p.getKey();
lenSeq[keyPos] = size += p.getValue().size();
vals[keyPos++] = (V[])p.getValue().toArray();
}
maxPos = size + 1;
}
/** */
public GridConcurrentMultiPairQueue(Collection<T2<K, V[]>> items) {
int pairCnt = (int)items.stream().map(Map.Entry::getValue).filter(k -> k.length > 0).count();
vals = (V[][])new Object[pairCnt][];
keysArr = (K[])new Object[pairCnt];
lenSeq = new int[pairCnt];
int keyPos = 0;
int size = -1;
for (Map.Entry<K, V[]> p : items) {
if (p.getValue().length == 0)
continue;
keysArr[keyPos] = p.getKey();
lenSeq[keyPos] = size += p.getValue().length;
vals[keyPos++] = p.getValue();
}
maxPos = size + 1;
}
/**
* Retrieves and removes the head of this queue,
* or returns {@code false} if this queue is empty.
*
* @return {@code true} if {@link #next} return non empty result, or {@code false} if this queue is empty
*/
public boolean next(Result<K, V> res) {<FILL_FUNCTION_BODY>}
/**
* @return {@code true} if empty.
*/
public boolean isEmpty() {
return pos.get() >= maxPos;
}
/**
* @return Constant initialisation size.
*/
public int initialSize() {
return maxPos;
}
/** State holder. */
public static class Result<K, V> {
/** Current segment. */
private int segment;
/** Key holder. */
private K key;
/** Value holeder. */
private V val;
/** Current state setter. */
public void set(K k, V v, int seg) {
key = k;
val = v;
segment = seg;
}
/** Current segment. */
private int getSegment() {
return segment;
}
/** Current key. */
public K getKey() {
return key;
}
/** Current value. */
public V getValue() {
return val;
}
/** */
@Override public String toString() {
return S.toString(Result.class, this);
}
}
}
|
int absPos = pos.getAndIncrement();
if (absPos >= maxPos) {
res.set(null, null, 0);
return false;
}
int segment = res.getSegment();
if (absPos > lenSeq[segment]) {
segment = Arrays.binarySearch(lenSeq, segment, lenSeq.length - 1, absPos);
segment = segment < 0 ? -segment - 1 : segment;
}
int relPos = segment == 0 ? absPos : (absPos - lenSeq[segment - 1] - 1);
K key = keysArr[segment];
res.set(key, vals[segment][relPos], segment);
return true;
| 1,019
| 198
| 1,217
|
<no_super_class>
|
apache_ignite
|
ignite/modules/core/src/main/java/org/apache/ignite/internal/util/GridStripedSpinBusyLock.java
|
GridStripedSpinBusyLock
|
block
|
class GridStripedSpinBusyLock {
/** Writer mask. */
private static int WRITER_MASK = 1 << 30;
/** Default amount of stripes. */
private static final int DFLT_STRIPE_CNT = Runtime.getRuntime().availableProcessors() * 4;
/** Thread index. */
private static ThreadLocal<Integer> THREAD_IDX = new ThreadLocal<Integer>() {
@Override protected Integer initialValue() {
return new Random().nextInt(Integer.MAX_VALUE);
}
};
/** States; they are not subjects to false-sharing because actual values are located far from each other. */
private final AtomicInteger[] states;
/**
* Default constructor.
*/
public GridStripedSpinBusyLock() {
this(DFLT_STRIPE_CNT);
}
/**
* Constructor.
*
* @param stripeCnt Amount of stripes.
*/
public GridStripedSpinBusyLock(int stripeCnt) {
states = new AtomicInteger[stripeCnt];
for (int i = 0; i < stripeCnt; i++)
states[i] = new AtomicInteger();
}
/**
* Enter busy state.
*
* @return {@code True} if entered busy state.
*/
public boolean enterBusy() {
int val = state().incrementAndGet();
if ((val & WRITER_MASK) == WRITER_MASK) {
leaveBusy();
return false;
}
else
return true;
}
/**
* Leave busy state.
*/
public void leaveBusy() {
state().decrementAndGet();
}
/**
* Block.
*/
public void block() {<FILL_FUNCTION_BODY>}
/**
* Gets state of thread's stripe.
*
* @return State.
*/
private AtomicInteger state() {
return states[THREAD_IDX.get() % states.length];
}
}
|
// 1. CAS-loop to set a writer bit.
for (AtomicInteger state : states) {
while (true) {
int oldVal = state.get();
if (state.compareAndSet(oldVal, oldVal | WRITER_MASK))
break;
}
}
// 2. Wait until all readers are out.
boolean interrupt = false;
for (AtomicInteger state : states) {
while (state.get() != WRITER_MASK) {
try {
Thread.sleep(10);
}
catch (InterruptedException ignored) {
interrupt = true;
}
}
}
if (interrupt)
Thread.currentThread().interrupt();
| 549
| 193
| 742
|
<no_super_class>
|
apache_ignite
|
ignite/modules/core/src/main/java/org/apache/ignite/internal/util/IgniteCollectors.java
|
IgniteCollectors
|
toCompoundFuture
|
class IgniteCollectors {
/**
* Empty constructor.
*/
private IgniteCollectors() { }
/**
* Collector of {@link IgniteInternalFuture} inheritors stream to {@link GridCompoundFuture}.
*
* @param <T> Result type of inheritor {@link IgniteInternalFuture}.
* @param <R> Result type of {@link GridCompoundFuture}.
* @return Compound future that contains all stream futures
* and initialized with {@link GridCompoundFuture#markInitialized()}.
*/
public static <T, R> Collector<? super IgniteInternalFuture,
? super GridCompoundFuture<T, R>, GridCompoundFuture<T, R>> toCompoundFuture() {<FILL_FUNCTION_BODY>}
}
|
final GridCompoundFuture<T, R> res = new GridCompoundFuture<>();
return Collectors.collectingAndThen(
Collectors.reducing(
res,
res::add,
(a, b) -> a // No needs to merge compound futures.
),
GridCompoundFuture::markInitialized
);
| 199
| 89
| 288
|
<no_super_class>
|
apache_ignite
|
ignite/modules/core/src/main/java/org/apache/ignite/internal/util/IgniteExceptionRegistry.java
|
IgniteExceptionRegistry
|
onException
|
class IgniteExceptionRegistry {
/** */
public static final int DEFAULT_QUEUE_SIZE = 1000;
/** */
private static final IgniteExceptionRegistry instance = new IgniteExceptionRegistry();
/** */
private int maxSize = IgniteSystemProperties.getInteger(IGNITE_EXCEPTION_REGISTRY_MAX_SIZE, DEFAULT_QUEUE_SIZE);
/** */
private AtomicLong errCnt = new AtomicLong();
/** */
private final ConcurrentLinkedDeque<ExceptionInfo> q = new ConcurrentLinkedDeque<>();
/**
* @return Registry instance.
*/
public static IgniteExceptionRegistry get() {
return instance;
}
/**
*
*/
private IgniteExceptionRegistry() {
// No-op.
}
/**
* Puts exception into queue.
* Thread-safe.
*
* @param msg Message that describe reason why error was suppressed.
* @param e Exception.
*/
public void onException(String msg, Throwable e) {<FILL_FUNCTION_BODY>}
/**
* Gets suppressed errors.
*
* @param order Order number to filter errors.
* @return List of exceptions that happened after specified order.
*/
public List<ExceptionInfo> getErrors(long order) {
List<ExceptionInfo> errors = new ArrayList<>();
for (ExceptionInfo error : q) {
if (error.order > order)
errors.add(error);
}
return errors;
}
/**
* Sets max size. Default value {@link #DEFAULT_QUEUE_SIZE}
*
* @param maxSize Max size.
*/
public void setMaxSize(int maxSize) {
A.ensure(maxSize > 0, "Max queue size must be greater than 0.");
this.maxSize = maxSize;
}
/**
* Prints errors.
*
* @param log Logger.
*/
public void printErrors(IgniteLogger log) {
int size = q.size();
Iterator<ExceptionInfo> descIter = q.descendingIterator();
for (int i = 0; i < size && descIter.hasNext(); i++) {
ExceptionInfo error = descIter.next();
U.error(
log,
"Error: " + (i + 1) + U.nl() +
" Time: " + new Date(error.time()) + U.nl() +
" Error: " + error.message() + U.nl() +
" Thread ID: " + error.threadId() + U.nl() +
" Thread name: " + error.threadName(),
error.error()
);
}
}
/**
* Errors count.
*
* @return Errors count.
*/
public long errorCount() {
return errCnt.get();
}
/**
* Detailed info about suppressed error.
*/
@SuppressWarnings("PublicInnerClass")
public static class ExceptionInfo implements Serializable {
/** */
private static final long serialVersionUID = 0L;
/** */
private final long order;
/** */
@GridToStringExclude
private final Throwable error;
/** */
private final long threadId;
/** */
private final String threadName;
/** */
private final long time;
/** */
private String msg;
/**
* Constructor.
*
* @param order Locally unique ID that is atomically incremented for each new error.
* @param error Suppressed error.
* @param msg Message that describe reason why error was suppressed.
* @param threadId Thread ID.
* @param threadName Thread name.
* @param time Occurrence time.
*/
public ExceptionInfo(long order, Throwable error, String msg, long threadId, String threadName, long time) {
this.order = order;
this.error = error;
this.threadId = threadId;
this.threadName = threadName;
this.time = time;
this.msg = msg;
}
/**
* @return Locally unique ID that is atomically incremented for each new error.
*/
public long order() {
return order;
}
/**
* @return Gets message that describe reason why error was suppressed.
*/
public String message() {
return msg;
}
/**
* @return Suppressed error.
*/
public Throwable error() {
return error;
}
/**
* @return Gets thread ID.
*/
public long threadId() {
return threadId;
}
/**
* @return Gets thread name.
*/
public String threadName() {
return threadName;
}
/**
* @return Gets time.
*/
public long time() {
return time;
}
/** {@inheritDoc} */
@Override public String toString() {
return S.toString(ExceptionInfo.class, this);
}
}
}
|
q.offerFirst(
new ExceptionInfo(
errCnt.incrementAndGet(),
e,
msg,
Thread.currentThread().getId(),
Thread.currentThread().getName(),
U.currentTimeMillis()));
// Remove extra entries.
int delta = q.size() - maxSize;
for (int i = 0; i < delta && q.size() > maxSize; i++)
q.pollLast();
| 1,318
| 117
| 1,435
|
<no_super_class>
|
apache_ignite
|
ignite/modules/core/src/main/java/org/apache/ignite/internal/util/ReentrantReadWriteLockWithTracking.java
|
ReadLockWithTracking
|
dec
|
class ReadLockWithTracking extends ReentrantReadWriteLock.ReadLock {
/** */
private static final long serialVersionUID = 0L;
/** */
private static final ThreadLocal<T2<Integer, Long>> READ_LOCK_HOLDER_TS =
ThreadLocal.withInitial(() -> new T2<>(0, 0L));
/** */
private IgniteLogger log;
/** */
private long readLockThreshold;
/** */
protected ReadLockWithTracking(ReentrantReadWriteLock lock, @Nullable IgniteLogger log, long readLockThreshold) {
super(lock);
this.log = log;
this.readLockThreshold = readLockThreshold;
}
/** */
private void inc() {
T2<Integer, Long> val = READ_LOCK_HOLDER_TS.get();
int cntr = val.get1();
if (cntr == 0)
val.set2(U.currentTimeMillis());
val.set1(++cntr);
READ_LOCK_HOLDER_TS.set(val);
}
/** */
private void dec() {<FILL_FUNCTION_BODY>}
/** {@inheritDoc} */
@Override public void lock() {
super.lock();
inc();
}
/** {@inheritDoc} */
@Override public void lockInterruptibly() throws InterruptedException {
super.lockInterruptibly();
inc();
}
/** {@inheritDoc} */
@Override public boolean tryLock() {
if (super.tryLock()) {
inc();
return true;
}
else
return false;
}
/** {@inheritDoc} */
@Override public boolean tryLock(long timeout, TimeUnit unit) throws InterruptedException {
if (super.tryLock(timeout, unit)) {
inc();
return true;
}
else
return false;
}
/** {@inheritDoc} */
@Override public void unlock() {
super.unlock();
dec();
}
}
|
T2<Integer, Long> val = READ_LOCK_HOLDER_TS.get();
int cntr = val.get1();
if (--cntr == 0) {
long timeout = U.currentTimeMillis() - val.get2();
if (timeout > readLockThreshold) {
GridStringBuilder sb = new GridStringBuilder();
sb.a(LOCK_HOLD_MESSAGE + timeout + " ms." + nl());
U.printStackTrace(Thread.currentThread().getId(), sb);
U.warn(log, sb.toString());
}
}
val.set1(cntr);
READ_LOCK_HOLDER_TS.set(val);
| 542
| 186
| 728
|
<no_super_class>
|
apache_ignite
|
ignite/modules/core/src/main/java/org/apache/ignite/internal/util/UUIDCollectionMessage.java
|
UUIDCollectionMessage
|
readFrom
|
class UUIDCollectionMessage implements Message {
/** */
private static final long serialVersionUID = 0L;
/** */
@GridDirectCollection(UUID.class)
private Collection<UUID> uuids;
/**
* Empty constructor required for direct marshalling.
*/
public UUIDCollectionMessage() {
// No-op.
}
/**
* @param uuids UUIDs to wrap.
*/
public UUIDCollectionMessage(Collection<UUID> uuids) {
this.uuids = uuids;
}
/**
* @param uuids UUIDs.
* @return Message.
*/
public static UUIDCollectionMessage of(UUID... uuids) {
if (uuids == null || uuids.length == 0)
return null;
List<UUID> list = uuids.length == 1 ? Collections.singletonList(uuids[0]) : Arrays.asList(uuids);
return new UUIDCollectionMessage(list);
}
/**
* @return The collection of UUIDs that was wrapped.
*/
public Collection<UUID> uuids() {
return uuids;
}
/** {@inheritDoc} */
@Override public void onAckReceived() {
// No-op.
}
/** {@inheritDoc} */
@Override public boolean writeTo(ByteBuffer buf, MessageWriter writer) {
writer.setBuffer(buf);
if (!writer.isHeaderWritten()) {
if (!writer.writeHeader(directType(), fieldsCount()))
return false;
writer.onHeaderWritten();
}
switch (writer.state()) {
case 0:
if (!writer.writeCollection("uuids", uuids, MessageCollectionItemType.UUID))
return false;
writer.incrementState();
}
return true;
}
/** {@inheritDoc} */
@Override public boolean readFrom(ByteBuffer buf, MessageReader reader) {<FILL_FUNCTION_BODY>}
/** {@inheritDoc} */
@Override public short directType() {
return 115;
}
/** {@inheritDoc} */
@Override public byte fieldsCount() {
return 1;
}
/** {@inheritDoc} */
@Override public boolean equals(Object o) {
if (this == o)
return true;
if (o == null || getClass() != o.getClass())
return false;
UUIDCollectionMessage that = (UUIDCollectionMessage)o;
return uuids == that.uuids || (uuids != null && uuids.equals(that.uuids));
}
/** {@inheritDoc} */
@Override public int hashCode() {
return uuids != null ? uuids.hashCode() : 0;
}
/** {@inheritDoc} */
@Override public String toString() {
return S.toString(UUIDCollectionMessage.class, this, "uuidsSize", uuids == null ? null : uuids.size());
}
}
|
reader.setBuffer(buf);
if (!reader.beforeMessageRead())
return false;
switch (reader.state()) {
case 0:
uuids = reader.readCollection("uuids", MessageCollectionItemType.UUID);
if (!reader.isLastRead())
return false;
reader.incrementState();
}
return reader.afterMessageRead(UUIDCollectionMessage.class);
| 784
| 110
| 894
|
<no_super_class>
|
apache_ignite
|
ignite/modules/core/src/main/java/org/apache/ignite/internal/util/collection/IntRWHashMap.java
|
IntRWHashMap
|
putIfAbsent
|
class IntRWHashMap<V> implements IntMap<V> {
/** RW Lock. */
private final ReadWriteLock lock = new ReentrantReadWriteLock();
/** Map delegate. */
private final IntHashMap<V> delegate;
/** Default constructor. */
public IntRWHashMap() {
delegate = new IntHashMap<>();
}
/** {@inheritDoc} */
@Override public V get(int key) {
lock.readLock().lock();
try {
return delegate.get(key);
}
finally {
lock.readLock().unlock();
}
}
/** {@inheritDoc} */
@Override public V put(int key, V val) {
lock.writeLock().lock();
try {
return delegate.put(key, val);
}
finally {
lock.writeLock().unlock();
}
}
/** {@inheritDoc} */
@Override public V remove(int key) {
lock.writeLock().lock();
try {
return delegate.remove(key);
}
finally {
lock.writeLock().unlock();
}
}
/** {@inheritDoc} */
@Override public V putIfAbsent(int key, V val) {<FILL_FUNCTION_BODY>}
/** {@inheritDoc} */
@Override public <E extends Throwable> void forEach(EntryConsumer<V, E> act) throws E {
lock.readLock().lock();
try {
delegate.forEach(act);
}
finally {
lock.readLock().unlock();
}
}
/** {@inheritDoc} */
@Override public int size() {
lock.readLock().lock();
try {
return delegate.size();
}
finally {
lock.readLock().unlock();
}
}
/** {@inheritDoc} */
@Override public boolean isEmpty() {
return size() == 0;
}
/** {@inheritDoc} */
@Override public int[] keys() {
lock.readLock().lock();
try {
return delegate.keys();
}
finally {
lock.readLock().unlock();
}
}
/** {@inheritDoc} */
@Override public Collection<V> values() {
lock.readLock().lock();
try {
return delegate.values();
}
finally {
lock.readLock().unlock();
}
}
/** {@inheritDoc} */
@Override public boolean containsKey(int key) {
lock.readLock().lock();
try {
return delegate.containsKey(key);
}
finally {
lock.readLock().unlock();
}
}
/** {@inheritDoc} */
@Override public boolean containsValue(V val) {
lock.readLock().lock();
try {
return delegate.containsValue(val);
}
finally {
lock.readLock().unlock();
}
}
/** {@inheritDoc} */
@Override public void clear() {
lock.writeLock().lock();
try {
delegate.clear();
}
finally {
lock.writeLock().unlock();
}
}
/** {@inheritDoc} */
@Override public String toString() {
lock.readLock().lock();
try {
return delegate.toString();
}
finally {
lock.readLock().unlock();
}
}
}
|
lock.writeLock().lock();
try {
return delegate.putIfAbsent(key, val);
}
finally {
lock.writeLock().unlock();
}
| 882
| 49
| 931
|
<no_super_class>
|
apache_ignite
|
ignite/modules/core/src/main/java/org/apache/ignite/internal/util/future/CountDownFuture.java
|
CountDownFuture
|
addError
|
class CountDownFuture extends GridFutureAdapter<Void> {
/** */
private AtomicInteger remaining;
/** */
private AtomicReference<Exception> errCollector;
/**
* @param cnt Number of completing parties.
*/
public CountDownFuture(int cnt) {
remaining = new AtomicInteger(cnt);
errCollector = new AtomicReference<>();
}
/** {@inheritDoc} */
@Override public boolean onDone(@Nullable Void res, @Nullable Throwable err) {
if (err != null)
addError(err);
int left = remaining.decrementAndGet();
boolean done = left == 0 && super.onDone(res, errCollector.get());
if (done)
afterDone();
return done;
}
/**
*
*/
protected void afterDone() {
// No-op, to be overridden in subclasses.
}
/**
* @param err Error.
*/
private void addError(Throwable err) {<FILL_FUNCTION_BODY>}
}
|
Exception ex = errCollector.get();
if (ex == null) {
Exception compound = new IgniteCheckedException("Compound exception for CountDownFuture.");
ex = errCollector.compareAndSet(null, compound) ? compound : errCollector.get();
}
assert ex != null;
ex.addSuppressed(err);
| 285
| 93
| 378
|
<methods>public non-sealed void <init>() ,public boolean cancel() throws org.apache.ignite.IgniteCheckedException,public IgniteInternalFuture<T> chain(IgniteClosure<? super IgniteInternalFuture<java.lang.Void>,T>) ,public IgniteInternalFuture<T> chain(IgniteOutClosure<T>) ,public IgniteInternalFuture<T> chain(IgniteClosure<? super IgniteInternalFuture<java.lang.Void>,T>, java.util.concurrent.Executor) ,public IgniteInternalFuture<T> chain(IgniteOutClosure<T>, java.util.concurrent.Executor) ,public IgniteInternalFuture<T> chainCompose(IgniteClosure<? super IgniteInternalFuture<java.lang.Void>,IgniteInternalFuture<T>>) ,public IgniteInternalFuture<T> chainCompose(IgniteClosure<? super IgniteInternalFuture<java.lang.Void>,IgniteInternalFuture<T>>, java.util.concurrent.Executor) ,public java.lang.Throwable error() ,public java.lang.Void get() throws org.apache.ignite.IgniteCheckedException,public java.lang.Void get(long) throws org.apache.ignite.IgniteCheckedException,public java.lang.Void get(long, java.util.concurrent.TimeUnit) throws org.apache.ignite.IgniteCheckedException,public java.lang.Void getUninterruptibly() throws org.apache.ignite.IgniteCheckedException,public void ignoreInterrupts() ,public boolean isCancelled() ,public boolean isDone() ,public boolean isFailed() ,public void listen(IgniteInClosure<? super IgniteInternalFuture<java.lang.Void>>) ,public void listen(org.apache.ignite.lang.IgniteRunnable) ,public org.apache.ignite.IgniteLogger logger() ,public boolean onCancelled() ,public final boolean onDone() ,public final boolean onDone(java.lang.Void) ,public final boolean onDone(java.lang.Throwable) ,public boolean onDone(java.lang.Void, java.lang.Throwable) ,public void reset() ,public java.lang.Void 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/util/future/GridEmbeddedFuture.java
|
AsyncListener2
|
apply
|
class AsyncListener2 implements IgniteInClosure<IgniteInternalFuture<A>> {
/** */
private static final long serialVersionUID = 0L;
/** {@inheritDoc} */
@Override public final void apply(IgniteInternalFuture<A> f) {<FILL_FUNCTION_BODY>}
/**
* @param f Future.
* @throws Exception In case of error.
*/
protected abstract void applyx(IgniteInternalFuture<A> f) throws Exception;
}
|
try {
applyx(f);
}
catch (IgniteIllegalStateException ignore) {
U.warn(null, "Will not execute future listener (grid is stopping): " + this);
}
catch (Exception e) {
onDone(e);
}
catch (Error e) {
onDone(e);
throw e;
}
| 128
| 98
| 226
|
<methods>public non-sealed void <init>() ,public boolean cancel() throws org.apache.ignite.IgniteCheckedException,public IgniteInternalFuture<T> chain(IgniteClosure<? super IgniteInternalFuture<A>,T>) ,public IgniteInternalFuture<T> chain(IgniteOutClosure<T>) ,public IgniteInternalFuture<T> chain(IgniteClosure<? super IgniteInternalFuture<A>,T>, java.util.concurrent.Executor) ,public IgniteInternalFuture<T> chain(IgniteOutClosure<T>, java.util.concurrent.Executor) ,public IgniteInternalFuture<T> chainCompose(IgniteClosure<? super IgniteInternalFuture<A>,IgniteInternalFuture<T>>) ,public IgniteInternalFuture<T> chainCompose(IgniteClosure<? super IgniteInternalFuture<A>,IgniteInternalFuture<T>>, java.util.concurrent.Executor) ,public java.lang.Throwable error() ,public A get() throws org.apache.ignite.IgniteCheckedException,public A get(long) throws org.apache.ignite.IgniteCheckedException,public A get(long, java.util.concurrent.TimeUnit) throws org.apache.ignite.IgniteCheckedException,public A getUninterruptibly() throws org.apache.ignite.IgniteCheckedException,public void ignoreInterrupts() ,public boolean isCancelled() ,public boolean isDone() ,public boolean isFailed() ,public void listen(IgniteInClosure<? super IgniteInternalFuture<A>>) ,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(A) ,public final boolean onDone(java.lang.Throwable) ,public boolean onDone(A, java.lang.Throwable) ,public void reset() ,public A 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/util/future/IgniteFutureImpl.java
|
IgniteFutureImpl
|
get
|
class IgniteFutureImpl<V> implements IgniteFuture<V> {
/** */
protected final IgniteInternalFuture<V> fut;
/** */
protected final Executor defaultExecutor;
/**
* @param fut Future.
*/
public IgniteFutureImpl(IgniteInternalFuture<V> fut) {
this(fut, null);
}
/**
* @param fut Future.
* @param defaultExecutor Default executor.
*/
public IgniteFutureImpl(IgniteInternalFuture<V> fut, @Nullable Executor defaultExecutor) {
assert fut != null;
this.fut = fut;
this.defaultExecutor = defaultExecutor;
}
/**
* @return Internal future.
*/
public IgniteInternalFuture<V> internalFuture() {
return fut;
}
/** {@inheritDoc} */
@Override public boolean isCancelled() {
return fut.isCancelled();
}
/** {@inheritDoc} */
@Override public boolean isDone() {
return fut.isDone();
}
/** {@inheritDoc} */
@Override public void listen(IgniteInClosure<? super IgniteFuture<V>> lsnr) {
A.notNull(lsnr, "lsnr");
if (defaultExecutor != null && !isDone())
fut.listen(new InternalFutureListener(new AsyncFutureListener<>(lsnr, defaultExecutor)));
else
fut.listen(new InternalFutureListener(lsnr));
}
/** {@inheritDoc} */
@Override public void listenAsync(IgniteInClosure<? super IgniteFuture<V>> lsnr, Executor exec) {
A.notNull(lsnr, "lsnr");
A.notNull(exec, "exec");
fut.listen(new InternalFutureListener(new AsyncFutureListener<>(lsnr, exec)));
}
/** {@inheritDoc} */
@Override public <T> IgniteFuture<T> chain(final IgniteClosure<? super IgniteFuture<V>, T> doneCb) {
return new IgniteFutureImpl<>(chainInternal(doneCb, null), defaultExecutor);
}
/** {@inheritDoc} */
@Override public <T> IgniteFuture<T> chainAsync(final IgniteClosure<? super IgniteFuture<V>, T> doneCb,
Executor exec) {
A.notNull(doneCb, "doneCb");
A.notNull(exec, "exec");
return new IgniteFutureImpl<>(chainInternal(doneCb, exec), defaultExecutor);
}
/**
* @param doneCb Done callback.
* @return Internal future
*/
protected <T> IgniteInternalFuture<T> chainInternal(final IgniteClosure<? super IgniteFuture<V>, T> doneCb,
@Nullable Executor exec) {
C1<IgniteInternalFuture<V>, T> clos = new C1<IgniteInternalFuture<V>, T>() {
@Override public T apply(IgniteInternalFuture<V> fut) {
assert IgniteFutureImpl.this.fut == fut;
try {
return doneCb.apply(IgniteFutureImpl.this);
}
catch (Exception e) {
throw new GridClosureException(e);
}
}
};
if (exec != null)
return fut.chain(clos, exec);
if (defaultExecutor != null && !isDone())
return fut.chain(clos, defaultExecutor);
return fut.chain(clos);
}
/** {@inheritDoc} */
@Override public boolean cancel() throws IgniteException {
try {
return fut.cancel();
}
catch (IgniteCheckedException e) {
throw convertException(e);
}
}
/** {@inheritDoc} */
@Override public V get() {
try {
return fut.get();
}
catch (IgniteCheckedException e) {
throw convertException(e);
}
}
/** {@inheritDoc} */
@Override public V get(long timeout) {<FILL_FUNCTION_BODY>}
/** {@inheritDoc} */
@Override public V get(long timeout, TimeUnit unit) {
try {
return fut.get(timeout, unit);
}
catch (IgniteCheckedException e) {
throw convertException(e);
}
}
/**
* Convert internal exception to public exception.
*
* @param e Internal exception.
* @return Public excpetion.
*/
protected RuntimeException convertException(IgniteCheckedException e) {
return U.convertException(e);
}
/** {@inheritDoc} */
@Override public String toString() {
return "IgniteFuture [orig=" + fut + ']';
}
/**
*
*/
private class InternalFutureListener implements IgniteInClosure<IgniteInternalFuture<V>> {
/** */
private static final long serialVersionUID = 0L;
/** */
private final IgniteInClosure<? super IgniteFuture<V>> lsnr;
/**
* @param lsnr Wrapped listener.
*/
private InternalFutureListener(IgniteInClosure<? super IgniteFuture<V>> lsnr) {
assert lsnr != null;
this.lsnr = lsnr;
}
/** {@inheritDoc} */
@Override public int hashCode() {
return lsnr.hashCode();
}
/** {@inheritDoc} */
@Override public boolean equals(Object obj) {
if (obj == null || !obj.getClass().equals(InternalFutureListener.class))
return false;
InternalFutureListener lsnr0 = (InternalFutureListener)obj;
return lsnr.equals(lsnr0.lsnr);
}
/** {@inheritDoc} */
@Override public void apply(IgniteInternalFuture<V> fut) {
assert IgniteFutureImpl.this.fut == fut;
lsnr.apply(IgniteFutureImpl.this);
}
/** {@inheritDoc} */
@Override public String toString() {
return lsnr.toString();
}
}
}
|
try {
return fut.get(timeout);
}
catch (IgniteCheckedException e) {
throw convertException(e);
}
| 1,618
| 42
| 1,660
|
<no_super_class>
|
apache_ignite
|
ignite/modules/core/src/main/java/org/apache/ignite/internal/util/future/IgniteRemoteMapTask.java
|
IgniteRemoteMapTask
|
map
|
class IgniteRemoteMapTask<T, R> extends ComputeTaskAdapter<T, R> {
/** */
private static final long serialVersionUID = 0L;
/** */
private final ClusterNode node;
/** */
private final ComputeTask<T, R> remoteTask;
/**
* @param node Target node.
* @param remoteTask Delegate task.
*/
public IgniteRemoteMapTask(ClusterNode node, ComputeTask<T, R> remoteTask) {
this.node = node;
this.remoteTask = remoteTask;
}
/** {@inheritDoc} */
@NotNull @Override public Map<? extends ComputeJob, ClusterNode> map(List<ClusterNode> subgrid,
@Nullable T arg) throws IgniteException {<FILL_FUNCTION_BODY>}
/** {@inheritDoc} */
@Nullable @Override public R reduce(List<ComputeJobResult> results) throws IgniteException {
assert results.size() == 1;
return results.get(0).getData();
}
/**
*
*/
private static class Job<T, R> extends ComputeJobAdapter {
/** */
private static final long serialVersionUID = 0L;
/** Auto-inject job context. */
@JobContextResource
private ComputeJobContext jobCtx;
/** Auto-inject ignite instance. */
@IgniteInstanceResource
private Ignite ignite;
/** */
private final ComputeTask<T, R> remoteTask;
/** */
@Nullable private final T arg;
/** */
@Nullable private ComputeTaskFuture<R> future;
/**
* @param remoteTask Remote task.
* @param arg Argument.
*/
public Job(ComputeTask<T, R> remoteTask, @Nullable T arg) {
this.remoteTask = remoteTask;
this.arg = arg;
}
/** {@inheritDoc} */
@Override public Object execute() throws IgniteException {
if (future == null) {
IgniteCompute compute = ignite.compute().withAsync();
compute.execute(remoteTask, arg);
ComputeTaskFuture<R> fut = compute.future();
this.future = fut;
jobCtx.holdcc();
fut.listen(new IgniteInClosure<IgniteFuture<R>>() {
@Override public void apply(IgniteFuture<R> future) {
jobCtx.callcc();
}
});
return null;
}
else {
return future.get();
}
}
}
}
|
for (ClusterNode node : subgrid) {
if (node.equals(this.node))
return Collections.singletonMap(new Job<>(remoteTask, arg), node);
}
throw new IgniteException("Node " + node + " is not present in subgrid.");
| 673
| 74
| 747
|
<methods>public non-sealed void <init>() ,public org.apache.ignite.compute.ComputeJobResultPolicy result(org.apache.ignite.compute.ComputeJobResult, List<org.apache.ignite.compute.ComputeJobResult>) throws org.apache.ignite.IgniteException<variables>private static final long serialVersionUID
|
apache_ignite
|
ignite/modules/core/src/main/java/org/apache/ignite/internal/util/io/GridFileUtils.java
|
GridFileUtils
|
copy
|
class GridFileUtils {
/** Copy buffer size. */
private static final int COPY_BUFFER_SIZE = 1024 * 1024;
/**
* Copy file
*
* @param src Source.
* @param dst Dst.
* @param maxBytes Max bytes.
*/
public static void copy(FileIO src, FileIO dst, long maxBytes) throws IOException {
assert maxBytes >= 0;
long bytes = Math.min(src.size(), maxBytes);
byte[] buf = new byte[COPY_BUFFER_SIZE];
while (bytes > 0)
bytes -= dst.writeFully(buf, 0, src.readFully(buf, 0, (int)Math.min(COPY_BUFFER_SIZE, bytes)));
dst.force();
}
/**
* Copy file
*
* @param srcFactory Source factory.
* @param src Source.
* @param dstFactory Dst factory.
* @param dst Dst.
* @param maxBytes Max bytes.
*/
public static void copy(
FileIOFactory srcFactory,
File src,
FileIOFactory dstFactory,
File dst,
long maxBytes
) throws IOException {<FILL_FUNCTION_BODY>}
/**
* Checks that creating hard links between given paths is available.
*
* @param path1 The first path.
* @param path2 The second path.
* @throws IgniteCheckedException If creating hard links is not available.
*/
public static void ensureHardLinkAvailable(Path path1, Path path2) throws IgniteCheckedException {
try {
FileStore fs1 = Files.getFileStore(path1);
FileStore fs2 = Files.getFileStore(path2);
if (!F.eq(fs1.name(), fs2.name())) {
throw new IgniteCheckedException("Paths are not stored at the same device or partition. " +
"Creating hard links is not available. [path1=" + path1 + ", path2=" + path2 +
", fileStoreName1=" + fs1.name() + ", fileStoreName2=" + fs2.name() + ']');
}
}
catch (IOException e) {
throw new IgniteCheckedException("Unable to check file stores.", e);
}
}
}
|
boolean err = true;
try (FileIO dstIO = dstFactory.create(dst, CREATE, TRUNCATE_EXISTING, WRITE)) {
try (FileIO srcIO = srcFactory.create(src, READ)) {
copy(srcIO, dstIO, maxBytes);
err = false;
}
}
finally {
if (err)
dst.delete();
}
| 610
| 112
| 722
|
<no_super_class>
|
apache_ignite
|
ignite/modules/core/src/main/java/org/apache/ignite/internal/util/io/GridReversedLinesFileReader.java
|
FilePart
|
readLine
|
class FilePart {
/** */
private final long no;
/** */
private final byte[] data;
/** */
private byte[] leftOver;
/** */
private int currentLastBytePos;
/**
* ctor
* @param no the part number
* @param length its length
* @param leftOverOfLastFilePart remainder
* @throws IOException if there is a problem reading the file
*/
private FilePart(final long no, final int length, final byte[] leftOverOfLastFilePart) throws IOException {
this.no = no;
int dataLength = length + (leftOverOfLastFilePart != null ? leftOverOfLastFilePart.length : 0);
this.data = new byte[dataLength];
final long off = (no - 1) * blockSize;
// read data
if (no > 0 /* file not empty */) {
randomAccessFile.seek(off);
final int cntRead = randomAccessFile.read(data, 0, length);
if (cntRead != length) {
throw new IllegalStateException("Count of requested bytes and actually read bytes don't match");
}
}
// copy left over part into data arr
if (leftOverOfLastFilePart != null) {
System.arraycopy(leftOverOfLastFilePart, 0, data, length, leftOverOfLastFilePart.length);
}
this.currentLastBytePos = data.length - 1;
this.leftOver = null;
}
/**
* Handles block rollover
*
* @return the new FilePart or null
* @throws IOException if there was a problem reading the file
*/
private FilePart rollOver() throws IOException {
if (currentLastBytePos > -1) {
throw new IllegalStateException("Current currentLastCharPos unexpectedly positive... "
+ "last readLine() should have returned something! currentLastCharPos=" + currentLastBytePos);
}
if (no > 1) {
return new FilePart(no - 1, blockSize, leftOver);
}
else {
// NO 1 was the last FilePart, we're finished
if (leftOver != null) {
throw new IllegalStateException("Unexpected leftover of the last block: leftOverOfThisFilePart="
+ new String(leftOver, encoding));
}
return null;
}
}
/**
* Reads a line.
*
* @return the line or null
* @throws IOException if there is an error reading from the file
*/
private String readLine() throws IOException {<FILL_FUNCTION_BODY>}
/**
* Creates the buffer containing any left over bytes.
*/
private void createLeftOver() {
int lineLengthBytes = currentLastBytePos + 1;
if (lineLengthBytes > 0) {
// create left over for next block
leftOver = new byte[lineLengthBytes];
System.arraycopy(data, 0, leftOver, 0, lineLengthBytes);
}
else {
leftOver = null;
}
currentLastBytePos = -1;
}
/**
* Finds the new-line sequence and return its length.
*
* @param data buffer to scan
* @param i start offset in buffer
* @return length of newline sequence or 0 if none found
*/
private int getNewLineMatchByteCount(byte[] data, int i) {
for (byte[] newLineSeq : newLineSequences) {
boolean match = true;
for (int j = newLineSeq.length - 1; j >= 0; j--) {
int k = i + j - (newLineSeq.length - 1);
match &= k >= 0 && data[k] == newLineSeq[j];
}
if (match) {
return newLineSeq.length;
}
}
return 0;
}
}
|
String line = null;
int newLineMatchByteCnt;
boolean isLastFilePart = no == 1;
int i = currentLastBytePos;
while (i > -1) {
if (!isLastFilePart && i < avoidNewlineSplitBufferSize) {
// avoidNewlineSplitBuffer: for all except the last file part we
// take a few bytes to the next file part to avoid splitting of newlines
createLeftOver();
break; // skip last few bytes and leave it to the next file part
}
// --- check for newline ---
if ((newLineMatchByteCnt = getNewLineMatchByteCount(data, i)) > 0 /* found newline */) {
final int lineStart = i + 1;
int lineLengthBytes = currentLastBytePos - lineStart + 1;
if (lineLengthBytes < 0) {
throw new IllegalStateException("Unexpected negative line length=" + lineLengthBytes);
}
byte[] lineData = new byte[lineLengthBytes];
System.arraycopy(data, lineStart, lineData, 0, lineLengthBytes);
line = new String(lineData, encoding);
currentLastBytePos = i - newLineMatchByteCnt;
break; // found line
}
// --- move cursor ---
i -= byteDecrement;
// --- end of file part handling ---
if (i < 0) {
createLeftOver();
break; // end of file part
}
}
// --- last file part handling ---
if (isLastFilePart && leftOver != null) {
// there will be no line break anymore, this is the first line of the file
line = new String(leftOver, encoding);
leftOver = null;
}
return line;
| 1,009
| 449
| 1,458
|
<no_super_class>
|
apache_ignite
|
ignite/modules/core/src/main/java/org/apache/ignite/internal/util/lang/GridAbsClosureX.java
|
GridAbsClosureX
|
apply
|
class GridAbsClosureX extends GridAbsClosure {
/** */
private static final long serialVersionUID = 0L;
/** {@inheritDoc} */
@Override public void apply() {<FILL_FUNCTION_BODY>}
/**
* Closure body that can throw {@link IgniteCheckedException}.
*
* @throws IgniteCheckedException Thrown in case of any error condition inside of the closure.
*/
public abstract void applyx() throws IgniteCheckedException;
}
|
try {
applyx();
}
catch (IgniteCheckedException ex) {
throw F.wrap(ex);
}
| 130
| 39
| 169
|
<methods>public non-sealed void <init>() ,public abstract void apply() ,public final void run() <variables>private static final long serialVersionUID
|
apache_ignite
|
ignite/modules/core/src/main/java/org/apache/ignite/internal/util/lang/IgniteClosure2X.java
|
IgniteClosure2X
|
apply
|
class IgniteClosure2X<E1, E2, R> implements IgniteBiClosure<E1, E2, R> {
/** */
private static final long serialVersionUID = 0L;
/** {@inheritDoc} */
@Override public R apply(E1 e1, E2 e2) {<FILL_FUNCTION_BODY>}
/**
* Closure body that can throw {@link IgniteCheckedException}.
*
* @param e1 First bound free variable, i.e. the element the closure is called or closed on.
* @param e2 Second bound free variable, i.e. the element the closure is called or closed on.
* @return Optional return value.
* @throws IgniteCheckedException Thrown in case of any error condition inside of the closure.
*/
public abstract R applyx(E1 e1, E2 e2) throws IgniteCheckedException;
}
|
try {
return applyx(e1, e2);
}
catch (IgniteCheckedException e) {
throw F.wrap(e);
}
| 231
| 46
| 277
|
<no_super_class>
|
apache_ignite
|
ignite/modules/core/src/main/java/org/apache/ignite/internal/util/lang/IgniteInClosureX.java
|
IgniteInClosureX
|
apply
|
class IgniteInClosureX<T> implements IgniteInClosure<T> {
/** */
private static final long serialVersionUID = 0L;
/** {@inheritDoc} */
@Override public void apply(T t) {<FILL_FUNCTION_BODY>}
/**
* In-closure body that can throw {@link IgniteCheckedException}.
*
* @param t The variable the closure is called or closed on.
* @throws IgniteCheckedException Thrown in case of any error condition inside of the closure.
*/
public abstract void applyx(T t) throws IgniteCheckedException;
}
|
try {
applyx(t);
}
catch (IgniteCheckedException e) {
throw F.wrap(e);
}
| 160
| 41
| 201
|
<no_super_class>
|
apache_ignite
|
ignite/modules/core/src/main/java/org/apache/ignite/internal/util/lang/IgniteSingletonIterator.java
|
IgniteSingletonIterator
|
onNext
|
class IgniteSingletonIterator<T> extends GridCloseableIteratorAdapter<T> {
/** */
private static final long serialVersionUID = 0L;
/** */
private final T val;
/** */
private boolean hasNext = true;
/** */
public IgniteSingletonIterator(T val) {
this.val = val;
}
/** {@inheritDoc} */
@Override protected boolean onHasNext() throws IgniteCheckedException {
return hasNext;
}
/** {@inheritDoc} */
@Override protected T onNext() throws IgniteCheckedException {<FILL_FUNCTION_BODY>}
}
|
if (!hasNext)
throw new NoSuchElementException();
hasNext = false;
return val;
| 166
| 33
| 199
|
<methods>public non-sealed void <init>() ,public final void close() throws org.apache.ignite.IgniteCheckedException,public final boolean hasNextX() throws org.apache.ignite.IgniteCheckedException,public boolean isClosed() ,public final T nextX() throws org.apache.ignite.IgniteCheckedException,public final void removeX() throws org.apache.ignite.IgniteCheckedException<variables>private boolean closed,private static final long serialVersionUID
|
apache_ignite
|
ignite/modules/core/src/main/java/org/apache/ignite/internal/util/lang/gridfunc/FlatIterator.java
|
FlatIterator
|
hasNextX
|
class FlatIterator<T> extends GridIteratorAdapter<T> {
/** */
private static final long serialVersionUID = 0L;
/** */
private Iterator<?> iter;
/** */
private Iterator<T> next;
/** */
private boolean moved;
/** */
private boolean more;
/**
* @param iterable Input iterable of iterators.
*/
public FlatIterator(Iterable<?> iterable) {
iter = iterable.iterator();
moved = true;
}
/** {@inheritDoc} */
@SuppressWarnings("unchecked")
@Override public boolean hasNextX() {<FILL_FUNCTION_BODY>}
/** {@inheritDoc} */
@Override public T nextX() {
if (hasNext()) {
moved = true;
return next.next();
}
throw new NoSuchElementException();
}
/** {@inheritDoc} */
@Override public void removeX() {
assert next != null;
next.remove();
}
/** {@inheritDoc} */
@Override public String toString() {
return S.toString(FlatIterator.class, this);
}
}
|
if (!moved)
return more;
moved = false;
if (next != null && next.hasNext())
return more = true;
while (iter.hasNext()) {
Object obj = iter.next();
if (obj instanceof Iterable)
next = ((Iterable)obj).iterator();
else if (obj instanceof Iterator)
next = (Iterator)obj;
else
assert false : "Iterable or Iterator are expected";
if (next.hasNext())
return more = true;
}
return more = false;
| 315
| 150
| 465
|
<methods>public non-sealed void <init>() ,public final boolean hasNext() ,public final Iterator<T> iterator() ,public final T next() ,public final void remove() <variables>private static final long serialVersionUID
|
apache_ignite
|
ignite/modules/core/src/main/java/org/apache/ignite/internal/util/lang/gridfunc/PredicateMapView.java
|
PredicateMapView
|
entrySet
|
class PredicateMapView<K, V> extends GridSerializableMap<K, V> {
/** */
private static final long serialVersionUID = 5531745605372387948L;
/** */
private final Map<K, V> map;
/** */
private final IgnitePredicate<? super K>[] preds;
/** Entry predicate. */
private IgnitePredicate<Entry<K, V>> entryPred;
/**
* @param map Input map that serves as a base for the view.
* @param preds Optional predicates. If predicates are not provided - all will be in the view.
*/
@SuppressWarnings({"unchecked"})
public PredicateMapView(Map<K, V> map, IgnitePredicate<? super K>... preds) {
this.map = map;
this.preds = preds;
this.entryPred = new EntryByKeyEvaluationPredicate(preds);
}
/** {@inheritDoc} */
@NotNull @Override public Set<Entry<K, V>> entrySet() {<FILL_FUNCTION_BODY>}
/** {@inheritDoc} */
@Override public boolean isEmpty() {
return entrySet().isEmpty();
}
/** {@inheritDoc} */
@Nullable @Override public V get(Object key) {
return GridFunc.isAll((K)key, preds) ? map.get(key) : null;
}
/** {@inheritDoc} */
@Nullable @Override public V put(K key, V val) {
V oldVal = get(key);
if (GridFunc.isAll(key, preds))
map.put(key, val);
return oldVal;
}
/** {@inheritDoc} */
@Override public boolean containsKey(Object key) {
return GridFunc.isAll((K)key, preds) && map.containsKey(key);
}
}
|
return new GridSerializableSet<Entry<K, V>>() {
@NotNull
@Override public Iterator<Entry<K, V>> iterator() {
return GridFunc.iterator0(map.entrySet(), false, entryPred);
}
@Override public int size() {
return F.size(map.keySet(), preds);
}
@Override public boolean remove(Object o) {
return F.isAll((Entry<K, V>)o, entryPred) && map.entrySet().remove(o);
}
@Override public boolean contains(Object o) {
return F.isAll((Entry<K, V>)o, entryPred) && map.entrySet().contains(o);
}
@Override public boolean isEmpty() {
return !iterator().hasNext();
}
};
| 501
| 210
| 711
|
<methods>public non-sealed void <init>() <variables>private static final long serialVersionUID
|
apache_ignite
|
ignite/modules/core/src/main/java/org/apache/ignite/internal/util/lang/gridfunc/TransformMapView2.java
|
TransformMapView2
|
entrySet
|
class TransformMapView2<K, V, V1> extends GridSerializableMap<K, V1> {
/** */
private static final long serialVersionUID = 0L;
/** */
private final Map<K, V> map;
/** */
private final IgniteBiClosure<K, V, V1> clos;
/** */
private final IgnitePredicate<? super K>[] preds;
/** Entry predicate. */
private IgnitePredicate<Entry<K, V>> entryPred;
/**
* @param map Input map that serves as a base for the view.
* @param clos Transformer for map value transformation.
* @param preds Optional predicates. If predicates are not provided - all will be in the view.
*/
@SuppressWarnings({"unchecked"})
public TransformMapView2(Map<K, V> map, IgniteBiClosure<K, V, V1> clos,
IgnitePredicate<? super K>... preds) {
this.map = map;
this.clos = clos;
this.preds = preds;
entryPred = new EntryByKeyEvaluationPredicate(preds);
}
/** {@inheritDoc} */
@NotNull @Override public Set<Entry<K, V1>> entrySet() {<FILL_FUNCTION_BODY>}
/** {@inheritDoc} */
@Override public boolean isEmpty() {
return entrySet().isEmpty();
}
/** {@inheritDoc} */
@Nullable @Override public V1 get(Object key) {
if (GridFunc.isAll((K)key, preds)) {
V v = map.get(key);
if (v != null)
return clos.apply((K)key, v);
}
return null;
}
/** {@inheritDoc} */
@Nullable @Override public V1 put(K key, V1 val) {
throw new UnsupportedOperationException("Put is not supported for readonly map view.");
}
/** {@inheritDoc} */
@Override public V1 remove(Object key) {
throw new UnsupportedOperationException("Remove is not supported for readonly map view.");
}
/** {@inheritDoc} */
@Override public boolean containsKey(Object key) {
return GridFunc.isAll((K)key, preds) && map.containsKey(key);
}
/** {@inheritDoc} */
@Override public String toString() {
return S.toString(TransformMapView2.class, this);
}
}
|
return new GridSerializableSet<Entry<K, V1>>() {
@NotNull
@Override public Iterator<Entry<K, V1>> iterator() {
return new Iterator<Entry<K, V1>>() {
private Iterator<Entry<K, V>> it = GridFunc.iterator0(map.entrySet(), true, entryPred);
@Override public boolean hasNext() {
return it.hasNext();
}
@Override public Entry<K, V1> next() {
final Entry<K, V> e = it.next();
return new Entry<K, V1>() {
@Override public K getKey() {
return e.getKey();
}
@Override public V1 getValue() {
return clos.apply(e.getKey(), e.getValue());
}
@Override public V1 setValue(V1 val) {
throw new UnsupportedOperationException(
"Put is not supported for readonly map view.");
}
};
}
@Override public void remove() {
throw new UnsupportedOperationException("Remove is not support for readonly map view.");
}
};
}
@Override public int size() {
return F.size(map.keySet(), preds);
}
@Override public boolean remove(Object o) {
throw new UnsupportedOperationException("Remove is not support for readonly map view.");
}
@Override public boolean contains(Object o) {
return F.isAll((Entry<K, V>)o, entryPred) && map.entrySet().contains(o);
}
@Override public boolean isEmpty() {
return !iterator().hasNext();
}
};
| 646
| 426
| 1,072
|
<methods>public non-sealed void <init>() <variables>private static final long serialVersionUID
|
apache_ignite
|
ignite/modules/core/src/main/java/org/apache/ignite/internal/util/nio/GridConnectionBytesVerifyFilter.java
|
GridConnectionBytesVerifyFilter
|
onMessageReceived
|
class GridConnectionBytesVerifyFilter extends GridNioFilterAdapter {
/** */
private static final int MAGIC_META_KEY = GridNioSessionMetaKey.nextUniqueKey();
/** */
private static final int MAGIC_BUF_KEY = GridNioSessionMetaKey.nextUniqueKey();
/** */
private IgniteLogger log;
/**
* Creates a filter instance.
*
* @param log Logger.
*/
public GridConnectionBytesVerifyFilter(IgniteLogger log) {
super("GridConnectionBytesVerifyFilter");
this.log = log;
}
/** {@inheritDoc} */
@Override public void onSessionOpened(GridNioSession ses) throws IgniteCheckedException {
proceedSessionOpened(ses);
}
/** {@inheritDoc} */
@Override public void onSessionClosed(GridNioSession ses) throws IgniteCheckedException {
proceedSessionClosed(ses);
}
/** {@inheritDoc} */
@Override public void onExceptionCaught(
GridNioSession ses,
IgniteCheckedException ex
) throws IgniteCheckedException {
proceedExceptionCaught(ses, ex);
}
/** {@inheritDoc} */
@Override public GridNioFuture<?> onSessionWrite(
GridNioSession ses,
Object msg,
boolean fut,
IgniteInClosure<IgniteException> ackC
) throws IgniteCheckedException {
return proceedSessionWrite(ses, msg, fut, ackC);
}
/** {@inheritDoc} */
@Override public void onMessageReceived(GridNioSession ses, Object msg) throws IgniteCheckedException {<FILL_FUNCTION_BODY>}
/** {@inheritDoc} */
@Override public GridNioFuture<Boolean> onSessionClose(GridNioSession ses) throws IgniteCheckedException {
return proceedSessionClose(ses);
}
/** {@inheritDoc} */
@Override public void onSessionIdleTimeout(GridNioSession ses) throws IgniteCheckedException {
proceedSessionIdleTimeout(ses);
}
/** {@inheritDoc} */
@Override public void onSessionWriteTimeout(GridNioSession ses) throws IgniteCheckedException {
proceedSessionWriteTimeout(ses);
}
}
|
// Verify only incoming connections.
if (!ses.accepted()) {
proceedMessageReceived(ses, msg);
return;
}
if (!(msg instanceof ByteBuffer))
throw new GridNioException("Failed to decode incoming message (message should be a byte buffer, is " +
"filter properly placed?): " + msg.getClass());
ByteBuffer buf = (ByteBuffer)msg;
Integer magic = ses.meta(MAGIC_META_KEY);
if (magic == null || magic < U.IGNITE_HEADER.length) {
byte[] magicBuf = ses.meta(MAGIC_BUF_KEY);
if (magicBuf == null)
magicBuf = new byte[U.IGNITE_HEADER.length];
int magicRead = magic == null ? 0 : magic;
int cnt = buf.remaining();
buf.get(magicBuf, magicRead, Math.min(U.IGNITE_HEADER.length - magicRead, cnt));
if (cnt + magicRead < U.IGNITE_HEADER.length) {
// Magic bytes are not fully read.
ses.addMeta(MAGIC_META_KEY, cnt + magicRead);
ses.addMeta(MAGIC_BUF_KEY, magicBuf);
}
else if (U.bytesEqual(magicBuf, 0, U.IGNITE_HEADER, 0, U.IGNITE_HEADER.length)) {
// Magic bytes read and equal to IGNITE_HEADER.
ses.removeMeta(MAGIC_BUF_KEY);
ses.addMeta(MAGIC_META_KEY, U.IGNITE_HEADER.length);
proceedMessageReceived(ses, buf);
}
else {
ses.close();
LT.warn(log, "Unknown connection detected (is some other software connecting to this " +
"Ignite port?) [rmtAddr=" + ses.remoteAddress() + ", locAddr=" + ses.localAddress() + ']');
}
}
else
proceedMessageReceived(ses, buf);
| 586
| 536
| 1,122
|
<methods>public org.apache.ignite.internal.util.nio.GridNioFilter nextFilter() ,public void nextFilter(org.apache.ignite.internal.util.nio.GridNioFilter) ,public GridNioFuture<?> onPauseReads(org.apache.ignite.internal.util.nio.GridNioSession) throws org.apache.ignite.IgniteCheckedException,public GridNioFuture<?> onResumeReads(org.apache.ignite.internal.util.nio.GridNioSession) throws org.apache.ignite.IgniteCheckedException,public org.apache.ignite.internal.util.nio.GridNioFilter previousFilter() ,public void previousFilter(org.apache.ignite.internal.util.nio.GridNioFilter) ,public void proceedExceptionCaught(org.apache.ignite.internal.util.nio.GridNioSession, org.apache.ignite.IgniteCheckedException) throws org.apache.ignite.IgniteCheckedException,public void proceedMessageReceived(org.apache.ignite.internal.util.nio.GridNioSession, java.lang.Object) throws org.apache.ignite.IgniteCheckedException,public GridNioFuture<?> proceedPauseReads(org.apache.ignite.internal.util.nio.GridNioSession) throws org.apache.ignite.IgniteCheckedException,public GridNioFuture<?> proceedResumeReads(org.apache.ignite.internal.util.nio.GridNioSession) throws org.apache.ignite.IgniteCheckedException,public GridNioFuture<java.lang.Boolean> proceedSessionClose(org.apache.ignite.internal.util.nio.GridNioSession) throws org.apache.ignite.IgniteCheckedException,public void proceedSessionClosed(org.apache.ignite.internal.util.nio.GridNioSession) throws org.apache.ignite.IgniteCheckedException,public void proceedSessionIdleTimeout(org.apache.ignite.internal.util.nio.GridNioSession) throws org.apache.ignite.IgniteCheckedException,public void proceedSessionOpened(org.apache.ignite.internal.util.nio.GridNioSession) throws org.apache.ignite.IgniteCheckedException,public GridNioFuture<?> proceedSessionWrite(org.apache.ignite.internal.util.nio.GridNioSession, java.lang.Object, boolean, IgniteInClosure<org.apache.ignite.IgniteException>) throws org.apache.ignite.IgniteCheckedException,public void proceedSessionWriteTimeout(org.apache.ignite.internal.util.nio.GridNioSession) throws org.apache.ignite.IgniteCheckedException,public void start() ,public void stop() ,public java.lang.String toString() <variables>private java.lang.String name,protected org.apache.ignite.internal.util.nio.GridNioFilter nextFilter,protected org.apache.ignite.internal.util.nio.GridNioFilter prevFilter
|
apache_ignite
|
ignite/modules/core/src/main/java/org/apache/ignite/internal/util/nio/GridDelimitedParser.java
|
GridDelimitedParser
|
decode
|
class GridDelimitedParser implements GridNioParser {
/** Buffer metadata key. */
private static final int BUF_META_KEY = GridNioSessionMetaKey.nextUniqueKey();
/** Delimiter. */
private final byte[] delim;
/** Direct buffer. */
private final boolean directBuf;
/**
* @param delim Delimiter.
* @param directBuf Direct buffer.
*/
public GridDelimitedParser(byte[] delim, boolean directBuf) {
this.delim = delim;
this.directBuf = directBuf;
}
/** {@inheritDoc} */
@Override public byte[] decode(GridNioSession ses, ByteBuffer buf) throws IOException, IgniteCheckedException {<FILL_FUNCTION_BODY>}
/** {@inheritDoc} */
@Override public ByteBuffer encode(GridNioSession ses, Object msg) throws IOException, IgniteCheckedException {
byte[] msg0 = (byte[])msg;
int cap = msg0.length + delim.length;
ByteBuffer res = directBuf ? ByteBuffer.allocateDirect(cap) : ByteBuffer.allocate(cap);
res.put(msg0);
res.put(delim);
res.flip();
return res;
}
/** {@inheritDoc} */
@Override public String toString() {
return this.getClass().getSimpleName();
}
}
|
GridNioDelimitedBuffer nioBuf = ses.meta(BUF_META_KEY);
// Decode for a given session is called per one thread, so there should not be any concurrency issues.
// However, we make some additional checks.
if (nioBuf == null) {
nioBuf = new GridNioDelimitedBuffer(delim);
GridNioDelimitedBuffer old = ses.addMeta(BUF_META_KEY, nioBuf);
assert old == null;
}
return nioBuf.read(buf);
| 366
| 146
| 512
|
<no_super_class>
|
apache_ignite
|
ignite/modules/core/src/main/java/org/apache/ignite/internal/util/nio/GridDirectParser.java
|
GridDirectParser
|
decode
|
class GridDirectParser implements GridNioParser {
/** Message metadata key. */
static final int MSG_META_KEY = GridNioSessionMetaKey.nextUniqueKey();
/** Reader metadata key. */
static final int READER_META_KEY = GridNioSessionMetaKey.nextUniqueKey();
/** */
private final IgniteLogger log;
/** */
private final MessageFactory msgFactory;
/** */
private final GridNioMessageReaderFactory readerFactory;
/**
* @param log Logger.
* @param msgFactory Message factory.
* @param readerFactory Message reader factory.
*/
public GridDirectParser(IgniteLogger log, MessageFactory msgFactory, GridNioMessageReaderFactory readerFactory) {
assert msgFactory != null;
assert readerFactory != null;
this.log = log;
this.msgFactory = msgFactory;
this.readerFactory = readerFactory;
}
/** {@inheritDoc} */
@Nullable @Override public Object decode(GridNioSession ses, ByteBuffer buf)
throws IOException, IgniteCheckedException {<FILL_FUNCTION_BODY>}
/** {@inheritDoc} */
@Override public ByteBuffer encode(GridNioSession ses, Object msg) throws IOException, IgniteCheckedException {
// No encoding needed for direct messages.
throw new UnsupportedEncodingException();
}
}
|
MessageReader reader = ses.meta(READER_META_KEY);
if (reader == null)
ses.addMeta(READER_META_KEY, reader = readerFactory.reader(ses, msgFactory));
Message msg = ses.removeMeta(MSG_META_KEY);
try {
if (msg == null && buf.remaining() >= Message.DIRECT_TYPE_SIZE) {
byte b0 = buf.get();
byte b1 = buf.get();
msg = msgFactory.create(makeMessageType(b0, b1));
}
boolean finished = false;
if (msg != null && buf.hasRemaining()) {
if (reader != null)
reader.setCurrentReadClass(msg.getClass());
finished = msg.readFrom(buf, reader);
}
if (finished) {
if (reader != null)
reader.reset();
return msg;
}
else {
ses.addMeta(MSG_META_KEY, msg);
return null;
}
}
catch (Throwable e) {
U.error(log, "Failed to read message [msg=" + msg +
", buf=" + buf +
", reader=" + reader +
", ses=" + ses + "]",
e);
throw e;
}
| 351
| 350
| 701
|
<no_super_class>
|
apache_ignite
|
ignite/modules/core/src/main/java/org/apache/ignite/internal/util/nio/SelectedSelectionKeySet.java
|
SelectedSelectionKeySet
|
doubleCapacityB
|
class SelectedSelectionKeySet extends AbstractSet<SelectionKey> {
/** */
private SelectionKey[] keysA;
/** */
private int keysASize;
/** */
private SelectionKey[] keysB;
/** */
private int keysBSize;
/** */
private boolean isA = true;
/**
*
*/
SelectedSelectionKeySet() {
keysA = new SelectionKey[1024];
keysB = keysA.clone();
}
/** {@inheritDoc} */
@Override public boolean add(SelectionKey o) {
if (o == null)
return false;
if (isA) {
int size = keysASize;
keysA[size++] = o;
keysASize = size;
if (size == keysA.length)
doubleCapacityA();
}
else {
int size = keysBSize;
keysB[size++] = o;
keysBSize = size;
if (size == keysB.length)
doubleCapacityB();
}
return true;
}
/**
*
*/
private void doubleCapacityA() {
SelectionKey[] newKeysA = new SelectionKey[keysA.length << 1];
System.arraycopy(keysA, 0, newKeysA, 0, keysASize);
keysA = newKeysA;
}
/**
*
*/
private void doubleCapacityB() {<FILL_FUNCTION_BODY>}
/**
* @return Selection keys.
*/
SelectionKey[] flip() {
if (isA) {
isA = false;
keysA[keysASize] = null;
keysBSize = 0;
return keysA;
}
else {
isA = true;
keysB[keysBSize] = null;
keysASize = 0;
return keysB;
}
}
/** {@inheritDoc} */
@Override public int size() {
if (isA)
return keysASize;
else
return keysBSize;
}
/** {@inheritDoc} */
@Override public boolean remove(Object o) {
return false;
}
/** {@inheritDoc} */
@Override public boolean contains(Object o) {
return false;
}
/** {@inheritDoc} */
@Override public Iterator<SelectionKey> iterator() {
throw new UnsupportedOperationException();
}
}
|
SelectionKey[] newKeysB = new SelectionKey[keysB.length << 1];
System.arraycopy(keysB, 0, newKeysB, 0, keysBSize);
keysB = newKeysB;
| 649
| 58
| 707
|
<methods>public boolean equals(java.lang.Object) ,public int hashCode() ,public boolean removeAll(Collection<?>) <variables>
|
apache_ignite
|
ignite/modules/core/src/main/java/org/apache/ignite/internal/util/nodestart/IgniteRemoteStartSpecification.java
|
IgniteRemoteStartSpecification
|
hashCode
|
class IgniteRemoteStartSpecification {
/** Hostname. */
private final String host;
/** Port number. */
private final int port;
/** Username. */
private final String uname;
/** Password. */
private final String passwd;
/** Private key file. */
private final File key;
/** Private key filename. */
private final String keyName;
/** Number of nodes to start. */
private final int nodes;
/** Ignite installation folder. */
private String igniteHome;
/** Configuration path. */
private String cfg;
/** Configuration filename. */
private String cfgName;
/** Script path. */
private String script;
/** Custom logger. */
private IgniteLogger logger;
/** Valid flag */
private boolean valid;
/**
* @param host Hostname.
* @param port Port number.
* @param uname Username.
* @param passwd Password (can be {@code null} if private key authentication is used).
* @param key Private key file path.
* @param nodes Number of nodes to start.
* @param igniteHome Ignite installation folder.
* @param cfg Configuration path.
* @param script Script path.
*/
public IgniteRemoteStartSpecification(@Nullable String host, int port, @Nullable String uname,
@Nullable String passwd, @Nullable File key, int nodes, @Nullable String igniteHome,
@Nullable String cfg, @Nullable String script) {
this(host, port, uname, passwd, key, nodes, igniteHome, cfg, script, null);
}
/**
* @param host Hostname.
* @param port Port number.
* @param uname Username.
* @param passwd Password (can be {@code null} if private key authentication is used).
* @param key Private key file path.
* @param nodes Number of nodes to start.
* @param igniteHome Ignite installation folder.
* @param cfg Configuration path.
* @param script Script path.
* @param logger Custom logger.
*/
public IgniteRemoteStartSpecification(@Nullable String host, int port, @Nullable String uname,
@Nullable String passwd, @Nullable File key, int nodes, @Nullable String igniteHome,
@Nullable String cfg, @Nullable String script, @Nullable IgniteLogger logger) {
assert port > 0;
assert nodes > 0;
this.host = !F.isEmpty(host) ? host : null;
this.port = port;
this.uname = !F.isEmpty(uname) ? uname : null;
this.passwd = !F.isEmpty(passwd) ? passwd : null;
this.key = key;
this.nodes = nodes;
this.igniteHome = !F.isEmpty(igniteHome) ? igniteHome : null;
this.cfg = !F.isEmpty(cfg) ? cfg : null;
cfgName = cfg == null ? null : shorten(cfg);
keyName = key == null ? "" : shorten(key.getAbsolutePath());
this.script = !F.isEmpty(script) ? script : null;
this.logger = logger;
}
/** {@inheritDoc} */
@Override public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof IgniteRemoteStartSpecification)) return false;
IgniteRemoteStartSpecification that = (IgniteRemoteStartSpecification)o;
return (host == null ? that.host == null : host.equals(that.host)) &&
(uname == null ? that.uname == null : uname.equals(that.uname)) &&
(passwd == null ? that.passwd == null : passwd.equals(that.passwd)) &&
(key == null ? that.key == null : key.equals(that.key)) &&
(igniteHome == null ? that.igniteHome == null : igniteHome.equals(that.igniteHome)) &&
(cfg == null ? that.cfg == null : cfg.equals(that.cfg)) &&
(script == null ? that.script == null : script.equals(that.script)) &&
port == that.port && nodes == that.nodes;
}
/** {@inheritDoc} */
@Override public int hashCode() {<FILL_FUNCTION_BODY>}
/**
* Get filename from path.
*
* @param path Path.
* @return Filename.
*/
private static String shorten(String path) {
int idx1 = path.lastIndexOf('/');
int idx2 = path.lastIndexOf('\\');
int idx = Math.max(idx1, idx2);
return idx == -1 ? path : path.substring(idx + 1);
}
/**
* @return Hostname.
*/
public String host() {
return host;
}
/**
* @return Port number.
*/
public int port() {
return port;
}
/**
* @return Username.
*/
public String username() {
return uname;
}
/**
* @return Password.
*/
public String password() {
return passwd;
}
/**
* @return Private key file path.
*/
public File key() {
return key;
}
/**
* @return Private key file name.
*/
public String keyName() {
return keyName;
}
/**
* @return Number of nodes to start.
*/
public int nodes() {
return nodes;
}
/**
* @return Ignite installation folder.
*/
public String igniteHome() {
return igniteHome;
}
/**
* @return Configuration full path.
*/
public String configuration() {
return cfg;
}
/**
* @return Configuration path short version - just file name.
*/
public String configurationName() {
return cfgName;
}
/**
* @return Script path.
*/
public String script() {
return script;
}
/**
* @return Custom logger.
*/
public IgniteLogger logger() {
return logger;
}
/**
* @return Valid flag.
*/
public boolean valid() {
return valid;
}
/**
* @param valid Valid flag.
*/
public void valid(boolean valid) {
this.valid = valid;
}
/**
* Sets correct separator in paths.
*
* @param separator Separator.
*/
public void fixPaths(char separator) {
if (igniteHome != null)
igniteHome = igniteHome.replace('\\', separator).replace('/', separator);
if (script != null)
script = script.replace('\\', separator).replace('/', separator);
if (cfg != null)
cfg = cfg.replace('\\', separator).replace('/', separator);
}
}
|
int res = host == null ? 0 : host.hashCode();
res = 31 * res + (uname == null ? 0 : uname.hashCode());
res = 31 * res + (passwd == null ? 0 : passwd.hashCode());
res = 31 * res + (key == null ? 0 : key.hashCode());
res = 31 * res + (igniteHome == null ? 0 : igniteHome.hashCode());
res = 31 * res + (cfg == null ? 0 : cfg.hashCode());
res = 31 * res + (script == null ? 0 : script.hashCode());
res = 31 * res + port;
res = 31 * res + nodes;
return res;
| 1,820
| 190
| 2,010
|
<no_super_class>
|
apache_ignite
|
ignite/modules/core/src/main/java/org/apache/ignite/internal/util/worker/CycleThread.java
|
CycleThread
|
run
|
class CycleThread extends Thread {
/** Sleep interval before each iteration. */
private final long sleepInterval;
/**
* Creates new cycle thread with given parameters.
*
* @param name thread name
* @param sleepInterval sleep interval before each iteration
*/
protected CycleThread(@NotNull String name, long sleepInterval) {
super(name);
this.sleepInterval = sleepInterval;
}
/** {@inheritDoc} */
@SuppressWarnings("BusyWait")
@Override public final void run() {<FILL_FUNCTION_BODY>}
/**
* Called on each iteration.
*
* @throws InterruptedException Еhrows if no specific handling required.
*/
public abstract void iteration() throws InterruptedException;
}
|
try {
while (!isInterrupted()) {
Thread.sleep(sleepInterval);
iteration();
}
}
catch (InterruptedException e) {
// No-op
}
| 199
| 55
| 254
|
<methods>public void <init>() ,public void <init>(java.lang.Runnable) ,public void <init>(java.lang.String) ,public void <init>(java.lang.ThreadGroup, java.lang.Runnable) ,public void <init>(java.lang.ThreadGroup, java.lang.String) ,public void <init>(java.lang.Runnable, java.lang.String) ,public void <init>(java.lang.ThreadGroup, java.lang.Runnable, java.lang.String) ,public void <init>(java.lang.ThreadGroup, java.lang.Runnable, java.lang.String, long) ,public void <init>(java.lang.ThreadGroup, java.lang.Runnable, java.lang.String, long, boolean) ,public static int activeCount() ,public final void checkAccess() ,public int countStackFrames() ,public static native java.lang.Thread currentThread() ,public static void dumpStack() ,public static int enumerate(java.lang.Thread[]) ,public static Map<java.lang.Thread,java.lang.StackTraceElement[]> getAllStackTraces() ,public java.lang.ClassLoader getContextClassLoader() ,public static java.lang.Thread.UncaughtExceptionHandler getDefaultUncaughtExceptionHandler() ,public long getId() ,public final java.lang.String getName() ,public final int getPriority() ,public java.lang.StackTraceElement[] getStackTrace() ,public java.lang.Thread.State getState() ,public final java.lang.ThreadGroup getThreadGroup() ,public java.lang.Thread.UncaughtExceptionHandler getUncaughtExceptionHandler() ,public static native boolean holdsLock(java.lang.Object) ,public void interrupt() ,public static boolean interrupted() ,public final boolean isAlive() ,public final boolean isDaemon() ,public boolean isInterrupted() ,public final void join() throws java.lang.InterruptedException,public final synchronized void join(long) throws java.lang.InterruptedException,public final synchronized void join(long, int) throws java.lang.InterruptedException,public static void onSpinWait() ,public final void resume() ,public void run() ,public void setContextClassLoader(java.lang.ClassLoader) ,public final void setDaemon(boolean) ,public static void setDefaultUncaughtExceptionHandler(java.lang.Thread.UncaughtExceptionHandler) ,public final synchronized void setName(java.lang.String) ,public final void setPriority(int) ,public void setUncaughtExceptionHandler(java.lang.Thread.UncaughtExceptionHandler) ,public static native void sleep(long) throws java.lang.InterruptedException,public static void sleep(long, int) throws java.lang.InterruptedException,public synchronized void start() ,public final void stop() ,public final void suspend() ,public java.lang.String toString() ,public static native void yield() <variables>private static final java.lang.StackTraceElement[] EMPTY_STACK_TRACE,public static final int MAX_PRIORITY,public static final int MIN_PRIORITY,public static final int NORM_PRIORITY,private volatile sun.nio.ch.Interruptible blocker,private final java.lang.Object blockerLock,private java.lang.ClassLoader contextClassLoader,private boolean daemon,private static volatile java.lang.Thread.UncaughtExceptionHandler defaultUncaughtExceptionHandler,private volatile long eetop,private java.lang.ThreadGroup group,java.lang.ThreadLocal.ThreadLocalMap inheritableThreadLocals,private java.security.AccessControlContext inheritedAccessControlContext,private volatile boolean interrupted,private volatile java.lang.String name,volatile java.lang.Object parkBlocker,private int priority,private final long stackSize,private boolean stillborn,private java.lang.Runnable target,private static int threadInitNumber,int threadLocalRandomProbe,int threadLocalRandomSecondarySeed,long threadLocalRandomSeed,java.lang.ThreadLocal.ThreadLocalMap threadLocals,private static long threadSeqNumber,private volatile int threadStatus,private final long tid,private volatile java.lang.Thread.UncaughtExceptionHandler uncaughtExceptionHandler
|
apache_ignite
|
ignite/modules/core/src/main/java/org/apache/ignite/internal/visor/VisorDataTransferObject.java
|
VisorDataTransferObject
|
readExternal
|
class VisorDataTransferObject implements Externalizable {
/** */
private static final long serialVersionUID = 6920203681702514010L;
/** Magic number to detect correct transfer objects. */
private static final int MAGIC = 0x42BEEF00;
/** Version 1. */
protected static final byte V1 = 1;
/** Version 2. */
protected static final byte V2 = 2;
/** Version 3. */
protected static final byte V3 = 3;
/** Version 4. */
protected static final byte V4 = 4;
/** Version 5. */
protected static final byte V5 = 5;
/**
* @param col Source collection.
* @param <T> Collection type.
* @return List based on passed collection.
*/
@Nullable protected static <T> List<T> toList(Collection<T> col) {
if (col instanceof List)
return (List<T>)col;
if (col != null)
return new ArrayList<>(col);
return null;
}
/**
* @param col Source collection.
* @param <T> Collection type.
* @return List based on passed collection.
*/
@Nullable protected static <T> Set<T> toSet(Collection<T> col) {
if (col != null)
return new LinkedHashSet<>(col);
return null;
}
/**
* @return Transfer object version.
*/
public byte getProtocolVersion() {
return V1;
}
/**
* Save object's specific data content.
*
* @param out Output object to write data content.
* @throws IOException If I/O errors occur.
*/
protected abstract void writeExternalData(ObjectOutput out) throws IOException;
/** {@inheritDoc} */
@Override public void writeExternal(ObjectOutput out) throws IOException {
int hdr = MAGIC + getProtocolVersion();
out.writeInt(hdr);
try (VisorDataTransferObjectOutput dtout = new VisorDataTransferObjectOutput(out)) {
writeExternalData(dtout);
}
}
/**
* Load object's specific data content.
*
* @param protoVer Input object version.
* @param in Input object to load data content.
* @throws IOException If I/O errors occur.
* @throws ClassNotFoundException If the class for an object being restored cannot be found.
*/
protected abstract void readExternalData(byte protoVer, ObjectInput in) throws IOException, ClassNotFoundException;
/** {@inheritDoc} */
@Override public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException {<FILL_FUNCTION_BODY>}
}
|
int hdr = in.readInt();
if ((hdr & MAGIC) != MAGIC)
throw new IOException("Unexpected VisorDataTransferObject header " +
"[actual=" + Integer.toHexString(hdr) + ", expected=" + Integer.toHexString(MAGIC) + "]");
byte ver = (byte)(hdr & 0xFF);
try (VisorDataTransferObjectInput dtin = new VisorDataTransferObjectInput(in)) {
readExternalData(ver, dtin);
}
| 713
| 146
| 859
|
<no_super_class>
|
apache_ignite
|
ignite/modules/core/src/main/java/org/apache/ignite/internal/visor/VisorTaskArgument.java
|
VisorTaskArgument
|
readExternalData
|
class VisorTaskArgument<A> extends VisorDataTransferObject {
/** */
private static final long serialVersionUID = 0L;
/** Node IDs task should be mapped to. */
private List<UUID> nodes;
/** Task argument. */
private A arg;
/** Debug flag. */
private boolean debug;
/**
* Default constructor.
*/
public VisorTaskArgument() {
// No-op.
}
/**
* Create Visor task argument.
*
* @param nodes Node IDs task should be mapped to.
* @param arg Task argument.
* @param debug Debug flag.
*/
public VisorTaskArgument(Collection<UUID> nodes, A arg, boolean debug) {
assert nodes != null;
assert !nodes.isEmpty();
this.nodes = toList(nodes);
this.arg = arg;
this.debug = debug;
}
/**
* Create Visor task argument with nodes, but without actual argument.
*
* @param nodes Node IDs task should be mapped to.
* @param debug Debug flag.
*/
public VisorTaskArgument(Collection<UUID> nodes, boolean debug) {
this(nodes, null, debug);
}
/**
* Create Visor task argument.
*
* @param node Node ID task should be mapped to.
* @param arg Task argument.
* @param debug Debug flag.
*/
public VisorTaskArgument(UUID node, A arg, boolean debug) {
this(Collections.singletonList(node), arg, debug);
}
/**
* Create Visor task argument with nodes, but without actual argument.
*
* @param node Node ID task should be mapped to.
* @param debug Debug flag.
*/
public VisorTaskArgument(UUID node, boolean debug) {
this(node, null, debug);
}
/**
* @return Node IDs task should be mapped to.
*/
public List<UUID> getNodes() {
return nodes;
}
/**
* @return Task argument.
*/
public A getArgument() {
return arg;
}
/**
* @return Debug flag.
*/
public boolean isDebug() {
return debug;
}
/** {@inheritDoc} */
@Override protected void writeExternalData(ObjectOutput out) throws IOException {
U.writeCollection(out, nodes);
out.writeObject(arg);
out.writeBoolean(debug);
}
/** {@inheritDoc} */
@Override protected void readExternalData(byte protoVer, ObjectInput in) throws IOException, ClassNotFoundException {<FILL_FUNCTION_BODY>}
/** {@inheritDoc} */
@Override public String toString() {
return S.toString(VisorTaskArgument.class, this);
}
}
|
nodes = U.readList(in);
arg = (A)in.readObject();
debug = in.readBoolean();
| 729
| 35
| 764
|
<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/lang/IgniteUuid.java
|
IgniteUuid
|
compareTo
|
class IgniteUuid implements Comparable<IgniteUuid>, Iterable<IgniteUuid>, Cloneable, Externalizable, Binarylizable {
/** */
private static final long serialVersionUID = 0L;
/** VM ID. */
public static final UUID VM_ID = UUID.randomUUID();
/** */
private static final AtomicLong cntGen = new AtomicLong(U.currentTimeMillis());
/** */
private UUID gid;
/** */
private long locId;
/**
* Empty constructor required for {@link Externalizable}.
*/
public IgniteUuid() {
// No-op.
}
/**
* Constructs {@code IgniteUuid} from a global and local identifiers.
*
* @param gid UUID.
* @param locId Counter.
*/
public IgniteUuid(UUID gid, long locId) {
assert gid != null;
this.gid = gid;
this.locId = locId;
}
/**
* Gets {@link UUID} associated with local VM.
*
* @return {@link UUID} associated with local VM.
*/
public static UUID vmId() {
return VM_ID;
}
/**
* Gets last generated local ID.
*
* @return Last generated local ID.
*/
public static long lastLocalId() {
return cntGen.get();
}
/**
* Creates new pseudo-random ID.
*
* @return Newly created pseudo-random ID.
*/
public static IgniteUuid randomUuid() {
return new IgniteUuid(VM_ID, cntGen.incrementAndGet());
}
/**
* Constructs new {@code IgniteUuid} based on global and local ID portions.
*
* @param id UUID instance.
* @return Newly created pseudo-random ID.
*/
public static IgniteUuid fromUuid(UUID id) {
A.notNull(id, "id");
return new IgniteUuid(id, cntGen.getAndIncrement());
}
/**
* Converts string into {@code IgniteUuid}. The String must be in the format generated
* by {@link IgniteUuid#toString()} method.
*
* @param s String to convert to {@code IgniteUuid}.
* @return {@code IgniteUuid} instance representing given string.
*/
public static IgniteUuid fromString(String s) {
int firstDash = s.indexOf('-');
return new IgniteUuid(
UUID.fromString(s.substring(firstDash + 1)),
Long.valueOf(new StringBuilder(s.substring(0, firstDash)).reverse().toString(), 16)
);
}
/**
* Gets a short string version of this ID. Use it only for UI where full version is
* available to the application.
*
* @return Short string version of this ID.
*/
public String shortString() {
return new StringBuilder(Long.toHexString(locId)).reverse().toString();
}
/**
* Gets global ID portion of this {@code IgniteUuid}.
*
* @return Global ID portion of this {@code IgniteUuid}.
*/
public UUID globalId() {
return gid;
}
/**
* Gets local ID portion of this {@code IgniteUuid}.
*
* @return Local ID portion of this {@code IgniteUuid}.
*/
public long localId() {
return locId;
}
/** {@inheritDoc} */
@Override public void writeExternal(ObjectOutput out) throws IOException {
U.writeUuid(out, gid);
out.writeLong(locId);
}
/** {@inheritDoc} */
@Override public void readExternal(ObjectInput in) throws IOException {
gid = U.readUuid(in);
locId = in.readLong();
}
/** {@inheritDoc} */
@Override public int compareTo(IgniteUuid o) {<FILL_FUNCTION_BODY>}
/** {@inheritDoc} */
@Override public GridIterator<IgniteUuid> iterator() {
return F.iterator(Collections.singleton(this), F.<IgniteUuid>identity(), true);
}
/** {@inheritDoc} */
@Override public boolean equals(Object obj) {
if (obj == this)
return true;
if (!(obj instanceof IgniteUuid))
return false;
IgniteUuid that = (IgniteUuid)obj;
return that.locId == locId && that.gid.equals(gid);
}
/** {@inheritDoc} */
@Override public void writeBinary(BinaryWriter writer) throws BinaryObjectException {
BinaryRawWriter out = writer.rawWriter();
out.writeLong(locId);
out.writeLong(gid.getMostSignificantBits());
out.writeLong(gid.getLeastSignificantBits());
}
/** {@inheritDoc} */
@Override public void readBinary(BinaryReader reader) throws BinaryObjectException {
BinaryRawReader in = reader.rawReader();
locId = in.readLong();
gid = new UUID(in.readLong(), in.readLong());
}
/** {@inheritDoc} */
@Override public int hashCode() {
return 31 * gid.hashCode() + (int)(locId ^ (locId >>> 32));
}
/** {@inheritDoc} */
@Override public Object clone() throws CloneNotSupportedException {
return super.clone();
}
/** {@inheritDoc} */
@Override public String toString() {
return shortString() + '-' + gid.toString();
}
}
|
if (o == this)
return 0;
if (o == null)
return 1;
int res = Long.compare(locId, o.locId);
if (res == 0)
res = gid.compareTo(o.globalId());
return res;
| 1,514
| 80
| 1,594
|
<no_super_class>
|
apache_ignite
|
ignite/modules/core/src/main/java/org/apache/ignite/logger/java/JavaLoggerFileHandler.java
|
JavaLoggerFileHandler
|
getIntProperty
|
class JavaLoggerFileHandler extends StreamHandler {
/** Log manager. */
private static final LogManager manager = LogManager.getLogManager();
/** Handler delegate. */
private volatile FileHandler delegate;
/** {@inheritDoc} */
@SuppressWarnings("NonSynchronizedMethodOverridesSynchronizedMethod")
@Override public void publish(LogRecord record) {
FileHandler delegate0 = delegate;
if (delegate0 != null)
delegate0.publish(record);
}
/** {@inheritDoc} */
@SuppressWarnings("NonSynchronizedMethodOverridesSynchronizedMethod")
@Override public void flush() {
FileHandler delegate0 = delegate;
if (delegate0 != null)
delegate0.flush();
}
/** {@inheritDoc} */
@SuppressWarnings("NonSynchronizedMethodOverridesSynchronizedMethod")
@Override public void close() throws SecurityException {
FileHandler delegate0 = delegate;
if (delegate0 != null)
delegate0.close();
}
/** {@inheritDoc} */
@Override public boolean isLoggable(LogRecord record) {
FileHandler delegate0 = delegate;
return delegate0 != null && delegate0.isLoggable(record);
}
/**
* Sets Node id and instantiates {@link FileHandler} delegate.
*
* @param nodeId Node id.
* @param workDir param.
*/
public void nodeId(UUID nodeId, String workDir) throws IgniteCheckedException, IOException {
nodeId(null, nodeId, workDir);
}
/**
* Sets Node id and instantiates {@link FileHandler} delegate.
*
* @param app Application name.
* @param nodeId Node id.
* @param workDir Path to the work directory.
*/
public void nodeId(@Nullable String app, @Nullable UUID nodeId, String workDir) throws IgniteCheckedException, IOException {
if (delegate != null)
return;
String clsName = getClass().getName();
String ptrn = manager.getProperty(clsName + ".pattern");
if (ptrn == null)
ptrn = "%{app}%{id8}.%g.log";
String fileName = ptrn
.replace("%{app}", app != null ? app : "ignite")
.replace("%{id8}", nodeId != null ? ("-" + U.id8(nodeId)) : "");
ptrn = new File(logDirectory(workDir), fileName).getAbsolutePath();
int limit = getIntProperty(clsName + ".limit", 0);
if (limit < 0)
limit = 0;
int cnt = getIntProperty(clsName + ".count", 1);
if (cnt <= 0)
cnt = 1;
boolean append = getBooleanProperty(clsName + ".append", false);
FileHandler delegate0;
synchronized (this) {
if (delegate != null)
return;
delegate = delegate0 = new FileHandler(ptrn, limit, cnt, append);
}
delegate0.setLevel(getLevel());
delegate0.setFormatter(getFormatter());
delegate0.setEncoding(getEncoding());
delegate0.setFilter(getFilter());
delegate0.setErrorManager(getErrorManager());
}
/**
* Returns current log file.
*
* @return Pattern or {@code null} if node id has not been set yet.
*/
@Nullable public String fileName() {
return JavaLogger.fileName(delegate);
}
/**
* Resolves logging directory.
*
* @param workDir Work directory.
* @return Logging directory.
*/
public static File logDirectory(String workDir) throws IgniteCheckedException {
return !F.isEmpty(U.IGNITE_LOG_DIR) ? new File(U.IGNITE_LOG_DIR) :
U.resolveWorkDirectory(workDir, "log", false);
}
/**
* Returns integer property from logging configuration.
*
* @param name Property name.
* @param dfltVal Default value.
* @return Parsed property value if it is set and valid or default value otherwise.
*/
private int getIntProperty(String name, int dfltVal) {<FILL_FUNCTION_BODY>}
/**
* Returns boolean property from logging configuration.
*
* @param name Property name.
* @param dfltVal Default value.
* @return Parsed property value if it is set and valid or default value otherwise.
*/
@SuppressWarnings("SimplifiableIfStatement")
private boolean getBooleanProperty(String name, boolean dfltVal) {
String val = manager.getProperty(name);
if (val == null)
return dfltVal;
val = val.toLowerCase();
if ("true".equals(val) || "1".equals(val))
return true;
if ("false".equals(val) || "0".equals(val))
return false;
return dfltVal;
}
/** {@inheritDoc} */
@Override public String toString() {
return S.toString(JavaLoggerFileHandler.class, this);
}
}
|
String val = manager.getProperty(name);
if (val == null)
return dfltVal;
try {
return Integer.parseInt(val.trim());
}
catch (Exception ex) {
ex.printStackTrace();
return dfltVal;
}
| 1,376
| 80
| 1,456
|
<methods>public void <init>() ,public void <init>(java.io.OutputStream, java.util.logging.Formatter) ,public synchronized void close() throws java.lang.SecurityException,public synchronized void flush() ,public boolean isLoggable(java.util.logging.LogRecord) ,public synchronized void publish(java.util.logging.LogRecord) ,public synchronized void setEncoding(java.lang.String) throws java.lang.SecurityException, java.io.UnsupportedEncodingException<variables>private boolean doneHeader,private java.io.OutputStream output,private volatile java.io.Writer writer
|
apache_ignite
|
ignite/modules/core/src/main/java/org/apache/ignite/platform/dotnet/PlatformDotNetCacheStoreFactory.java
|
PlatformDotNetCacheStoreFactory
|
create
|
class PlatformDotNetCacheStoreFactory implements Factory<PlatformDotNetCacheStore> {
/** */
private static final long serialVersionUID = 0L;
/** .Net type name. */
private String typName;
/** Properties. */
private Map<String, ?> props;
/** Instance. */
private transient PlatformDotNetCacheStore instance;
/**
* Gets .NET type name.
*
* @return .NET type name.
*/
public String getTypeName() {
return typName;
}
/**
* Sets .NET type name.
*
* @param typName .NET type name.
*/
public void setTypeName(String typName) {
this.typName = typName;
}
/**
* Get properties.
*
* @return Properties.
*/
public Map<String, ?> getProperties() {
return props;
}
/**
* Set properties.
*
* @param props Properties.
*/
public void setProperties(Map<String, ?> props) {
this.props = props;
}
/** {@inheritDoc} */
@SuppressWarnings("unchecked")
@Override public PlatformDotNetCacheStore create() {<FILL_FUNCTION_BODY>}
}
|
synchronized (this) {
if (instance == null) {
instance = new PlatformDotNetCacheStore();
instance.setTypeName(typName);
instance.setProperties(props);
}
return instance;
}
| 340
| 65
| 405
|
<no_super_class>
|
apache_ignite
|
ignite/modules/core/src/main/java/org/apache/ignite/plugin/security/SecurityBasicPermissionSet.java
|
SecurityBasicPermissionSet
|
equals
|
class SecurityBasicPermissionSet implements SecurityPermissionSet {
/** Serial version uid. */
private static final long serialVersionUID = 0L;
/** Cache permissions. */
@GridToStringInclude
private Map<String, Collection<SecurityPermission>> cachePermissions = new HashMap<>();
/** Task permissions. */
@GridToStringInclude
private Map<String, Collection<SecurityPermission>> taskPermissions = new HashMap<>();
/** Service permissions. */
@GridToStringInclude
private transient Map<String, Collection<SecurityPermission>> servicePermissions = isSecurityCompatibilityMode()
? compatibleServicePermissions()
: new HashMap<String, Collection<SecurityPermission>>();
/** System permissions. */
@GridToStringInclude
private Collection<SecurityPermission> systemPermissions;
/** Default allow all. */
private boolean dfltAllowAll;
/**
* Setter for set cache permission map.
*
* @param cachePermissions Cache permissions.
*/
public void setCachePermissions(Map<String, Collection<SecurityPermission>> cachePermissions) {
A.notNull(cachePermissions, "cachePermissions");
this.cachePermissions = cachePermissions;
}
/**
* Setter for set task permission map.
*
* @param taskPermissions Task permissions.
*/
public void setTaskPermissions(Map<String, Collection<SecurityPermission>> taskPermissions) {
A.notNull(taskPermissions, "taskPermissions");
this.taskPermissions = taskPermissions;
}
/**
* Setter for set service permission map.
*
* @param servicePermissions Service permissions.
*/
public void setServicePermissions(Map<String, Collection<SecurityPermission>> servicePermissions) {
A.notNull(taskPermissions, "servicePermissions");
this.servicePermissions = servicePermissions;
}
/**
* Setter for set collection system permission.
*
* @param systemPermissions System permissions.
*/
public void setSystemPermissions(Collection<SecurityPermission> systemPermissions) {
this.systemPermissions = systemPermissions;
}
/**
* Setter for set default allow all.
*
* @param dfltAllowAll Default allow all.
*/
public void setDefaultAllowAll(boolean dfltAllowAll) {
this.dfltAllowAll = dfltAllowAll;
}
/** {@inheritDoc} */
@Override public Map<String, Collection<SecurityPermission>> cachePermissions() {
return cachePermissions;
}
/** {@inheritDoc} */
@Override public Map<String, Collection<SecurityPermission>> taskPermissions() {
return taskPermissions;
}
/** {@inheritDoc} */
@Override public Map<String, Collection<SecurityPermission>> servicePermissions() {
return servicePermissions;
}
/** {@inheritDoc} */
@Nullable @Override public Collection<SecurityPermission> systemPermissions() {
return systemPermissions;
}
/** {@inheritDoc} */
@Override public boolean defaultAllowAll() {
return dfltAllowAll;
}
/** {@inheritDoc} */
@Override public boolean equals(Object o) {<FILL_FUNCTION_BODY>}
/** {@inheritDoc} */
@Override public int hashCode() {
int res = (dfltAllowAll ? 1 : 0);
res = 31 * res + (cachePermissions != null ? cachePermissions.hashCode() : 0);
res = 31 * res + (taskPermissions != null ? taskPermissions.hashCode() : 0);
res = 31 * res + (servicePermissions != null ? servicePermissions.hashCode() : 0);
res = 31 * res + (systemPermissions != null ? systemPermissions.hashCode() : 0);
return res;
}
/**
* @param out Out.
*/
private void writeObject(ObjectOutputStream out) throws IOException {
out.defaultWriteObject();
if (serializeVersion() >= 2)
U.writeMap(out, servicePermissions);
}
/**
* @param in In.
*/
private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException {
in.defaultReadObject();
if (serializeVersion() >= 2)
servicePermissions = U.readMap(in);
if (servicePermissions == null) {
// Allow all for compatibility mode
if (serializeVersion() < 2)
servicePermissions = compatibleServicePermissions();
else
servicePermissions = Collections.emptyMap();
}
}
/** {@inheritDoc} */
@Override public String toString() {
return S.toString(SecurityBasicPermissionSet.class, this);
}
}
|
if (this == o)
return true;
if (!(o instanceof SecurityBasicPermissionSet))
return false;
SecurityBasicPermissionSet other = (SecurityBasicPermissionSet)o;
return dfltAllowAll == other.dfltAllowAll &&
F.eq(cachePermissions, other.cachePermissions) &&
F.eq(taskPermissions, other.taskPermissions) &&
F.eq(servicePermissions, other.servicePermissions) &&
F.eq(systemPermissions, other.systemPermissions);
| 1,218
| 136
| 1,354
|
<no_super_class>
|
apache_ignite
|
ignite/modules/core/src/main/java/org/apache/ignite/spi/IgniteSpiMBeanAdapter.java
|
IgniteSpiMBeanAdapter
|
getUpTime
|
class IgniteSpiMBeanAdapter implements IgniteSpiManagementMBean {
/** */
protected IgniteSpiAdapter spiAdapter;
/**
* Constructor
*
* @param spiAdapter Spi implementation.
*/
public IgniteSpiMBeanAdapter(IgniteSpiAdapter spiAdapter) {
this.spiAdapter = spiAdapter;
}
/** {@inheritDoc} */
@Override public final String getStartTimestampFormatted() {
return DateFormat.getDateTimeInstance().format(new Date(spiAdapter.getStartTstamp()));
}
/** {@inheritDoc} */
@Override public final String getUpTimeFormatted() {
return X.timeSpan2DHMSM(getUpTime());
}
/** {@inheritDoc} */
@Override public final long getStartTimestamp() {
return spiAdapter.getStartTstamp();
}
/** {@inheritDoc} */
@Override public final long getUpTime() {<FILL_FUNCTION_BODY>}
/** {@inheritDoc} */
@Override public UUID getLocalNodeId() {
return spiAdapter.ignite.cluster().localNode().id();
}
/** {@inheritDoc} */
@Override public final String getIgniteHome() {
return spiAdapter.ignite.configuration().getIgniteHome();
}
/** {@inheritDoc} */
@Override public String getName() {
return spiAdapter.getName();
}
}
|
final long startTstamp = spiAdapter.getStartTstamp();
return startTstamp == 0 ? 0 : U.currentTimeMillis() - startTstamp;
| 377
| 49
| 426
|
<no_super_class>
|
apache_ignite
|
ignite/modules/core/src/main/java/org/apache/ignite/spi/communication/tcp/internal/ClusterStateProvider.java
|
ClusterStateProvider
|
safeLocalNodeId
|
class ClusterStateProvider {
/** Ignite. */
private final Ignite ignite;
/** Local node supplier. */
private final Supplier<ClusterNode> locNodeSupplier;
/** Tcp communication spi. */
private final TcpCommunicationSpi tcpCommSpi;
/** Stopped supplier. */
private final Supplier<Boolean> stoppedSupplier;
/** Spi context without latch supplier. */
private final Supplier<IgniteSpiContext> spiCtxWithoutLatchSupplier;
/** Logger. */
private final IgniteLogger log;
/** Ignite ex supplier. */
private final Supplier<Ignite> igniteExSupplier;
/**
* @param ignite Ignite.
* @param locNodeSupplier Local node supplier.
* @param tcpCommSpi Tcp communication spi.
* @param stoppedSupplier Stopped supplier.
* @param spiCtxWithoutLatchSupplier Spi context without latch
* @param log Logger.
* @param igniteExSupplier Returns already exists instance from spi.
*/
public ClusterStateProvider(
Ignite ignite,
Supplier<ClusterNode> locNodeSupplier,
TcpCommunicationSpi tcpCommSpi,
Supplier<Boolean> stoppedSupplier,
Supplier<IgniteSpiContext> spiCtxWithoutLatchSupplier,
IgniteLogger log,
Supplier<Ignite> igniteExSupplier
) {
this.ignite = ignite;
this.locNodeSupplier = locNodeSupplier;
this.tcpCommSpi = tcpCommSpi;
this.stoppedSupplier = stoppedSupplier;
this.spiCtxWithoutLatchSupplier = spiCtxWithoutLatchSupplier;
this.log = log;
this.igniteExSupplier = igniteExSupplier;
}
/**
* @return {@code True} if local node in disconnected state.
*/
public boolean isLocalNodeDisconnected() {
boolean disconnected = false;
if (ignite instanceof IgniteKernal)
disconnected = ((IgniteEx)ignite).context().clientDisconnected();
return disconnected;
}
/**
* @return {@code True} if ssl enabled.
*/
public boolean isSslEnabled() {
return ignite.configuration().getSslContextFactory() != null;
}
/**
* @return {@link SSLEngine} for ssl connections.
*/
public SSLEngine createSSLEngine() {
return ignite.configuration().getSslContextFactory().create().createSSLEngine();
}
/**
* @return {@code true} if {@link TcpCommunicationSpi} stopped.
*/
public boolean isStopping() {
return stoppedSupplier.get();
}
/**
* Returns client failure detection timeout set to use for network related operations.
*
* @return client failure detection timeout in milliseconds or {@code 0} if the timeout is disabled.
*/
public long clientFailureDetectionTimeout() {
return tcpCommSpi.clientFailureDetectionTimeout();
}
/**
* @return {@link IgniteSpiContext} of {@link TcpCommunicationSpi}.
*/
public IgniteSpiContext getSpiContext() {
return tcpCommSpi.getSpiContext();
}
/**
* @return {@link IgniteSpiContext} of {@link TcpCommunicationSpi}.
*/
public IgniteSpiContext getSpiContextWithoutInitialLatch() {
return spiCtxWithoutLatchSupplier.get();
}
/**
* @return Outbound messages queue size.
*/
public int getOutboundMessagesQueueSize() {
return tcpCommSpi.getOutboundMessagesQueueSize();
}
/**
* Makes dump of {@link TcpCommunicationSpi} stats.
*/
public void dumpStats() {
tcpCommSpi.dumpStats();
}
/**
* Checks whether remote nodes support {@link HandshakeWaitMessage}.
*
* @return {@code True} if remote nodes support {@link HandshakeWaitMessage}.
*/
public boolean isHandshakeWaitSupported() {
DiscoverySpi discoSpi = ignite.configuration().getDiscoverySpi();
if (discoSpi instanceof IgniteDiscoverySpi)
return ((IgniteDiscoverySpi)discoSpi).allNodesSupport(IgniteFeatures.TCP_COMMUNICATION_SPI_HANDSHAKE_WAIT_MESSAGE);
else {
Collection<ClusterNode> nodes = discoSpi.getRemoteNodes();
return IgniteFeatures.allNodesSupports(nodes, IgniteFeatures.TCP_COMMUNICATION_SPI_HANDSHAKE_WAIT_MESSAGE);
}
}
/**
* @return Node ID message.
*/
public NodeIdMessage nodeIdMessage() {
final UUID locNodeId = (ignite != null && ignite instanceof IgniteKernal) ? ((IgniteEx)ignite).context().localNodeId() :
safeLocalNodeId();
return new NodeIdMessage(locNodeId);
}
/**
* @return Local node ID.
*/
private UUID safeLocalNodeId() {<FILL_FUNCTION_BODY>}
}
|
ClusterNode locNode = locNodeSupplier.get();
UUID id;
if (locNode == null) {
U.warn(log, "Local node is not started or fully initialized [isStopping=" +
isStopping() + ']');
id = new UUID(0, 0);
}
else
id = locNode.id();
return id;
| 1,383
| 103
| 1,486
|
<no_super_class>
|
apache_ignite
|
ignite/modules/core/src/main/java/org/apache/ignite/spi/communication/tcp/internal/HandshakeTimeoutObject.java
|
HandshakeTimeoutObject
|
run
|
class HandshakeTimeoutObject implements Runnable {
/** Object which used for connection. */
private final Object connectionObj;
/** Done. */
private final AtomicBoolean done = new AtomicBoolean();
/**
* @param connectionObj Client.
*/
public HandshakeTimeoutObject(Object connectionObj) {
assert connectionObj != null;
assert connectionObj instanceof GridCommunicationClient || connectionObj instanceof SelectableChannel;
this.connectionObj = connectionObj;
}
/**
* @return {@code True} if object has not yet been timed out.
*/
public boolean cancel() {
return done.compareAndSet(false, true);
}
/** {@inheritDoc} */
@Override public String toString() {
return S.toString(HandshakeTimeoutObject.class, this);
}
/** {@inheritDoc} */
@Override public void run() {<FILL_FUNCTION_BODY>}
}
|
if (done.compareAndSet(false, true)) {
// Close socket - timeout occurred.
if (connectionObj instanceof GridCommunicationClient)
((GridCommunicationClient)connectionObj).forceClose();
else
U.closeQuiet((AutoCloseable)connectionObj);
}
| 243
| 76
| 319
|
<no_super_class>
|
apache_ignite
|
ignite/modules/core/src/main/java/org/apache/ignite/spi/communication/tcp/messages/HandshakeMessage2.java
|
HandshakeMessage2
|
readFrom
|
class HandshakeMessage2 extends HandshakeMessage {
/** */
private static final long serialVersionUID = 0L;
/** Message size in bytes including {@link HandshakeMessage} fields. */
public static final int HANDSHAKE2_MESSAGE_SIZE = MESSAGE_FULL_SIZE + 4;
/** */
private int connIdx;
/**
*
*/
public HandshakeMessage2() {
// No-op.
}
/**
* @param nodeId Node ID.
* @param connectCnt Connect count.
* @param rcvCnt Number of received messages.
* @param connIdx Connection index.
*/
public HandshakeMessage2(UUID nodeId, long connectCnt, long rcvCnt, int connIdx) {
super(nodeId, connectCnt, rcvCnt);
this.connIdx = connIdx;
}
/** {@inheritDoc} */
@Override public short directType() {
return -44;
}
/** {@inheritDoc} */
@Override public int connectionIndex() {
return connIdx;
}
/** {@inheritDoc} */
@Override public int getMessageSize() {
return HANDSHAKE2_MESSAGE_SIZE;
}
/** {@inheritDoc} */
@Override public boolean writeTo(ByteBuffer buf, MessageWriter writer) {
if (!super.writeTo(buf, writer))
return false;
if (buf.remaining() < 4)
return false;
buf.putInt(connIdx);
return true;
}
/** {@inheritDoc} */
@Override public boolean readFrom(ByteBuffer buf, MessageReader reader) {<FILL_FUNCTION_BODY>}
/** {@inheritDoc} */
@Override public String toString() {
return S.toString(HandshakeMessage2.class, this, super.toString());
}
}
|
if (!super.readFrom(buf, reader))
return false;
if (buf.remaining() < 4)
return false;
connIdx = buf.getInt();
return true;
| 502
| 57
| 559
|
<methods>public void <init>() ,public void <init>(java.util.UUID, long, long) ,public long connectCount() ,public int connectionIndex() ,public short directType() ,public byte fieldsCount() ,public int getMessageSize() ,public java.util.UUID nodeId() ,public void onAckReceived() ,public boolean readFrom(java.nio.ByteBuffer, org.apache.ignite.plugin.extensions.communication.MessageReader) ,public long received() ,public java.lang.String toString() ,public boolean writeTo(java.nio.ByteBuffer, org.apache.ignite.plugin.extensions.communication.MessageWriter) <variables>public static final int MESSAGE_FULL_SIZE,private static final int MESSAGE_SIZE,private long connectCnt,private java.util.UUID nodeId,private long rcvCnt,private static final long serialVersionUID
|
apache_ignite
|
ignite/modules/core/src/main/java/org/apache/ignite/spi/communication/tcp/messages/NodeIdMessage.java
|
NodeIdMessage
|
nodeIdBytesWithType
|
class NodeIdMessage implements Message {
/** */
private static final long serialVersionUID = 0L;
/** Message body size (with message type) in bytes. */
static final int MESSAGE_SIZE = 16;
/** Full message size (with message type) in bytes. */
public static final int MESSAGE_FULL_SIZE = MESSAGE_SIZE + DIRECT_TYPE_SIZE;
/** */
private byte[] nodeIdBytes;
/** */
public NodeIdMessage() {
// No-op.
}
/**
* @param nodeId Node ID.
*/
public NodeIdMessage(UUID nodeId) {
assert nodeId != null;
nodeIdBytes = U.uuidToBytes(nodeId);
assert nodeIdBytes.length == MESSAGE_SIZE : "Node ID size must be " + MESSAGE_SIZE;
}
/**
* @return Node ID bytes.
*/
public byte[] nodeIdBytes() {
return nodeIdBytes;
}
/**
* @param nodeId Node ID.
* @return Marshalled node ID bytes with direct message type.
*/
public static byte[] nodeIdBytesWithType(UUID nodeId) {<FILL_FUNCTION_BODY>}
/** {@inheritDoc} */
@Override public void onAckReceived() {
// No-op.
}
/** {@inheritDoc} */
@Override public boolean writeTo(ByteBuffer buf, MessageWriter writer) {
assert nodeIdBytes.length == MESSAGE_SIZE;
if (buf.remaining() < MESSAGE_FULL_SIZE)
return false;
TcpCommunicationSpi.writeMessageType(buf, directType());
buf.put(nodeIdBytes);
return true;
}
/** {@inheritDoc} */
@Override public boolean readFrom(ByteBuffer buf, MessageReader reader) {
if (buf.remaining() < MESSAGE_SIZE)
return false;
nodeIdBytes = new byte[MESSAGE_SIZE];
buf.get(nodeIdBytes);
return true;
}
/** {@inheritDoc} */
@Override public short directType() {
return TcpCommunicationSpi.NODE_ID_MSG_TYPE;
}
/** {@inheritDoc} */
@Override public byte fieldsCount() {
return 0;
}
/** {@inheritDoc} */
@Override public String toString() {
return S.toString(NodeIdMessage.class, this);
}
}
|
byte[] nodeIdBytesWithType = new byte[MESSAGE_FULL_SIZE];
nodeIdBytesWithType[0] = (byte)(TcpCommunicationSpi.NODE_ID_MSG_TYPE & 0xFF);
nodeIdBytesWithType[1] = (byte)((TcpCommunicationSpi.NODE_ID_MSG_TYPE >> 8) & 0xFF);
U.uuidToBytes(nodeId, nodeIdBytesWithType, 2);
return nodeIdBytesWithType;
| 652
| 134
| 786
|
<no_super_class>
|
apache_ignite
|
ignite/modules/core/src/main/java/org/apache/ignite/spi/communication/tcp/messages/RecoveryLastReceivedMessage.java
|
RecoveryLastReceivedMessage
|
writeTo
|
class RecoveryLastReceivedMessage implements Message {
/** */
private static final long serialVersionUID = 0L;
/** */
public static final long ALREADY_CONNECTED = -1;
/** */
public static final long NODE_STOPPING = -2;
/** Need wait. */
public static final long NEED_WAIT = -3;
/** Initiator node is not in current topogy. */
public static final long UNKNOWN_NODE = -4;
/** Message body size in bytes. */
private static final int MESSAGE_SIZE = 8;
/** Full message size (with message type) in bytes. */
public static final int MESSAGE_FULL_SIZE = MESSAGE_SIZE + DIRECT_TYPE_SIZE;
/** */
private long rcvCnt;
/**
* Default constructor required by {@link Message}.
*/
public RecoveryLastReceivedMessage() {
// No-op.
}
/**
* @param rcvCnt Number of received messages.
*/
public RecoveryLastReceivedMessage(long rcvCnt) {
this.rcvCnt = rcvCnt;
}
/**
* @return Number of received messages.
*/
public long received() {
return rcvCnt;
}
/** {@inheritDoc} */
@Override public void onAckReceived() {
// No-op.
}
/** {@inheritDoc} */
@Override public boolean writeTo(ByteBuffer buf, MessageWriter writer) {<FILL_FUNCTION_BODY>}
/** {@inheritDoc} */
@Override public boolean readFrom(ByteBuffer buf, MessageReader reader) {
if (buf.remaining() < MESSAGE_SIZE)
return false;
rcvCnt = buf.getLong();
return true;
}
/** {@inheritDoc} */
@Override public short directType() {
return TcpCommunicationSpi.RECOVERY_LAST_ID_MSG_TYPE;
}
/** {@inheritDoc} */
@Override public byte fieldsCount() {
return 0;
}
/** {@inheritDoc} */
@Override public String toString() {
return S.toString(RecoveryLastReceivedMessage.class, this);
}
}
|
if (buf.remaining() < MESSAGE_FULL_SIZE)
return false;
TcpCommunicationSpi.writeMessageType(buf, directType());
buf.putLong(rcvCnt);
return true;
| 596
| 66
| 662
|
<no_super_class>
|
apache_ignite
|
ignite/modules/core/src/main/java/org/apache/ignite/spi/discovery/isolated/IsolatedDiscoverySpi.java
|
IsolatedDiscoverySpi
|
consistentId
|
class IsolatedDiscoverySpi extends IgniteSpiAdapter implements IgniteDiscoverySpi {
/** */
private Serializable consistentId;
/** */
private final long startTime = System.currentTimeMillis();
/** */
private IsolatedNode locNode;
/** */
private DiscoverySpiListener lsnr;
/** */
private ExecutorService exec = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());
/** */
private DiscoverySpiNodeAuthenticator nodeAuth;
/** */
private Marshaller marsh;
/** {@inheritDoc} */
@Override public Serializable consistentId() throws IgniteSpiException {<FILL_FUNCTION_BODY>}
/** {@inheritDoc} */
@Override public Collection<ClusterNode> getRemoteNodes() {
return emptyList();
}
/** {@inheritDoc} */
@Override public ClusterNode getLocalNode() {
return locNode;
}
/** {@inheritDoc} */
@Override public ClusterNode getNode(UUID nodeId) {
return locNode.id().equals(nodeId) ? locNode : null;
}
/** {@inheritDoc} */
@Override public boolean pingNode(UUID nodeId) {
return locNode.id().equals(nodeId);
}
/** {@inheritDoc} */
@Override public void setNodeAttributes(Map<String, Object> attrs, IgniteProductVersion ver) {
locNode = new IsolatedNode(ignite.configuration().getNodeId(), attrs, ver);
}
/** {@inheritDoc} */
@Override public void setListener(@Nullable DiscoverySpiListener lsnr) {
this.lsnr = lsnr;
}
/** {@inheritDoc} */
@Override public void setDataExchange(DiscoverySpiDataExchange exchange) {
// No-op.
}
/** {@inheritDoc} */
@Override public void setMetricsProvider(DiscoveryMetricsProvider metricsProvider) {
// No-op.
}
/** {@inheritDoc} */
@Override public void disconnect() throws IgniteSpiException {
// No-op.
}
/** {@inheritDoc} */
@Override public void setAuthenticator(DiscoverySpiNodeAuthenticator auth) {
nodeAuth = auth;
}
/** {@inheritDoc} */
@Override public long getGridStartTime() {
return startTime;
}
/** {@inheritDoc} */
@Override public void sendCustomEvent(DiscoverySpiCustomMessage msg) throws IgniteException {
exec.execute(() -> {
IgniteFuture<?> fut = lsnr.onDiscovery(new DiscoveryNotification(
EVT_DISCOVERY_CUSTOM_EVT,
1,
locNode,
singleton(locNode),
null,
msg,
null));
// Acknowledge message must be send after initial message processed.
fut.listen((f) -> {
DiscoverySpiCustomMessage ack = msg.ackMessage();
if (ack != null) {
exec.execute(() -> lsnr.onDiscovery(new DiscoveryNotification(
EVT_DISCOVERY_CUSTOM_EVT,
1,
locNode,
singleton(locNode),
null,
ack,
null))
);
}
});
});
}
/** {@inheritDoc} */
@Override public void failNode(UUID nodeId, @Nullable String warning) {
// No-op.
}
/** {@inheritDoc} */
@Override public boolean isClientMode() throws IllegalStateException {
return false;
}
/** {@inheritDoc} */
@Override public void spiStart(@Nullable String igniteInstanceName) throws IgniteSpiException {
if (nodeAuth != null) {
try {
SecurityCredentials locSecCred = (SecurityCredentials)locNode.attributes().get(ATTR_SECURITY_CREDENTIALS);
Map<String, Object> attrs = withSecurityContext(
authenticateLocalNode(locNode, locSecCred, nodeAuth), locNode.attributes(), marsh);
attrs.remove(ATTR_SECURITY_CREDENTIALS);
locNode.setAttributes(attrs);
}
catch (IgniteCheckedException e) {
throw new IgniteSpiException("Failed to authenticate local node (will shutdown local node).", e);
}
}
exec.execute(() -> {
lsnr.onLocalNodeInitialized(locNode);
lsnr.onDiscovery(new DiscoveryNotification(
EVT_NODE_JOINED,
1,
locNode,
singleton(locNode))
);
});
}
/** {@inheritDoc} */
@Override public void spiStop() throws IgniteSpiException {
exec.shutdownNow();
}
/** {@inheritDoc} */
@Override protected void onContextInitialized0(final IgniteSpiContext spiCtx) throws IgniteSpiException {
// No-op.
}
/** {@inheritDoc} */
@Override public boolean knownNode(UUID nodeId) {
return getNode(nodeId) != null;
}
/** {@inheritDoc} */
@Override public boolean clientReconnectSupported() {
return false;
}
/** {@inheritDoc} */
@Override public void clientReconnect() {
// No-op.
}
/** {@inheritDoc} */
@Override protected void injectResources(Ignite ignite) {
if (ignite instanceof IgniteKernal)
marsh = ((IgniteEx)ignite).context().marshallerContext().jdkMarshaller();
super.injectResources(ignite);
}
/** {@inheritDoc} */
@Override public boolean allNodesSupport(IgniteFeatures feature) {
if (locNode == null)
return false;
return allNodesSupports(singleton(locNode), feature);
}
/** {@inheritDoc} */
@Override public void simulateNodeFailure() {
// No-op.
}
/** {@inheritDoc} */
@Override public void setInternalListener(IgniteDiscoverySpiInternalListener lsnr) {
// No-op.
}
/** {@inheritDoc} */
@Override public boolean supportsCommunicationFailureResolve() {
return false;
}
/** {@inheritDoc} */
@Override public void resolveCommunicationFailure(ClusterNode node, Exception err) {
// No-op.
}
}
|
if (consistentId == null) {
IgniteConfiguration cfg = ignite.configuration();
final Serializable cfgId = cfg.getConsistentId();
consistentId = cfgId != null ? cfgId : UUID.randomUUID();
}
return consistentId;
| 1,687
| 76
| 1,763
|
<methods>public long clientFailureDetectionTimeout() ,public long failureDetectionTimeout() ,public void failureDetectionTimeoutEnabled(boolean) ,public boolean failureDetectionTimeoutEnabled() ,public org.apache.ignite.internal.util.IgniteExceptionRegistry getExceptionRegistry() ,public java.lang.String getName() ,public Map<java.lang.String,java.lang.Object> getNodeAttributes() throws org.apache.ignite.spi.IgniteSpiException,public org.apache.ignite.spi.IgniteSpiContext getSpiContext() ,public org.apache.ignite.Ignite ignite() ,public Collection<java.lang.Object> injectables() ,public final void onBeforeStart() ,public void onClientDisconnected(IgniteFuture<?>) ,public void onClientReconnected(boolean) ,public final void onContextDestroyed() ,public final void onContextInitialized(org.apache.ignite.spi.IgniteSpiContext) throws org.apache.ignite.spi.IgniteSpiException,public org.apache.ignite.spi.IgniteSpiAdapter setName(java.lang.String) ,public final boolean started() <variables>private long clientFailureDetectionTimeout,private long failureDetectionTimeout,private boolean failureDetectionTimeoutEnabled,protected org.apache.ignite.Ignite ignite,protected java.lang.String igniteInstanceName,private org.apache.ignite.cluster.ClusterNode locNode,protected org.apache.ignite.IgniteLogger log,private java.lang.String name,private org.apache.ignite.internal.managers.eventstorage.GridLocalEventListener paramsLsnr,private volatile org.apache.ignite.spi.IgniteSpiContext spiCtx,private javax.management.ObjectName spiMBean,private long startTstamp,private final java.util.concurrent.atomic.AtomicBoolean startedFlag
|
apache_ignite
|
ignite/modules/core/src/main/java/org/apache/ignite/spi/discovery/tcp/messages/TcpDiscoveryAbstractMessage.java
|
TcpDiscoveryAbstractMessage
|
equals
|
class TcpDiscoveryAbstractMessage implements Serializable {
/** */
private static final long serialVersionUID = 0L;
/** */
protected static final int CLIENT_FLAG_POS = 0;
/** */
protected static final int RESPONDED_FLAG_POS = 1;
/** */
protected static final int CLIENT_RECON_SUCCESS_FLAG_POS = 2;
/** */
protected static final int CHANGE_TOPOLOGY_FLAG_POS = 3;
/** */
protected static final int CLIENT_ACK_FLAG_POS = 4;
/** */
protected static final int FORCE_FAIL_FLAG_POS = 8;
/** */
protected static final int COMPRESS_DATA_PACKET = 9;
/** Sender of the message (transient). */
private transient UUID sndNodeId;
/** Message ID. */
private IgniteUuid id;
/**
* Verifier node ID.
* Node can mark the messages as verified for rest of nodes to apply the
* changes this message is issued for, i.e. node added message, node failed or
* left message are processed by other nodes only after coordinator
* verification.
*/
private UUID verifierNodeId;
/** Topology version. */
private long topVer;
/** Flags. */
@GridToStringExclude
private int flags;
/** Pending message index. */
private short pendingIdx;
/** */
@GridToStringInclude
private Set<UUID> failedNodes;
/**
* Default no-arg constructor for {@link Externalizable} interface.
*/
protected TcpDiscoveryAbstractMessage() {
// No-op.
}
/**
* Constructor.
*
* @param creatorNodeId Creator node ID.
*/
protected TcpDiscoveryAbstractMessage(UUID creatorNodeId) {
id = IgniteUuid.fromUuid(creatorNodeId);
}
/**
* @param msg Message.
*/
protected TcpDiscoveryAbstractMessage(TcpDiscoveryAbstractMessage msg) {
this.id = msg.id;
this.verifierNodeId = msg.verifierNodeId;
this.topVer = msg.topVer;
this.flags = msg.flags;
this.pendingIdx = msg.pendingIdx;
}
/**
* @return {@code True} if need use trace logging for this message (to reduce amount of logging with debug level).
*/
public boolean traceLogLevel() {
return false;
}
/**
* Gets creator node.
*
* @return Creator node ID.
*/
public UUID creatorNodeId() {
return id.globalId();
}
/**
* Gets message ID.
*
* @return Message ID.
*/
public IgniteUuid id() {
return id;
}
/**
* Gets sender node ID.
*
* @return Sender node ID.
*/
public UUID senderNodeId() {
return sndNodeId;
}
/**
* Sets sender node ID.
*
* @param sndNodeId Sender node ID.
*/
public void senderNodeId(UUID sndNodeId) {
this.sndNodeId = sndNodeId;
}
/**
* Checks whether message is verified.
*
* @return {@code true} if message was verified.
*/
public boolean verified() {
return verifierNodeId != null;
}
/**
* Gets verifier node ID.
*
* @return verifier node ID.
*/
public UUID verifierNodeId() {
return verifierNodeId;
}
/**
* Verifies the message and stores verifier ID.
*
* @param verifierNodeId Verifier node ID.
*/
public void verify(UUID verifierNodeId) {
this.verifierNodeId = verifierNodeId;
}
/**
* Gets topology version.
*
* @return Topology version.
*/
public long topologyVersion() {
return topVer;
}
/**
* Sets topology version.
*
* @param topVer Topology version.
*/
public void topologyVersion(long topVer) {
this.topVer = topVer;
}
/**
* Get client node flag.
*
* @return Client node flag.
*/
public boolean client() {
return getFlag(CLIENT_FLAG_POS);
}
/**
* Sets client node flag.
*
* @param client Client node flag.
*/
public void client(boolean client) {
setFlag(CLIENT_FLAG_POS, client);
}
/**
* Get force fail node flag.
*
* @return Force fail node flag.
*/
public boolean force() {
return getFlag(FORCE_FAIL_FLAG_POS);
}
/**
* Sets force fail node flag.
*
* @param force Force fail node flag.
*/
public void force(boolean force) {
setFlag(FORCE_FAIL_FLAG_POS, force);
}
/**
* @return Pending message index.
*/
public short pendingIndex() {
return pendingIdx;
}
/**
* @param pendingIdx Pending message index.
*/
public void pendingIndex(short pendingIdx) {
this.pendingIdx = pendingIdx;
}
/**
* @param pos Flag position.
* @return Flag value.
*/
protected boolean getFlag(int pos) {
assert pos >= 0 && pos < 32;
int mask = 1 << pos;
return (flags & mask) == mask;
}
/**
* @param pos Flag position.
* @param val Flag value.
*/
protected void setFlag(int pos, boolean val) {
assert pos >= 0 && pos < 32;
int mask = 1 << pos;
if (val)
flags |= mask;
else
flags &= ~mask;
}
/**
* @return {@code true} if message must be added to head of queue.
*/
public boolean highPriority() {
return false;
}
/**
* Adds node ID to the failed nodes list.
*
* @param nodeId Node ID.
*/
public void addFailedNode(UUID nodeId) {
assert nodeId != null;
if (failedNodes == null)
failedNodes = new HashSet<>();
failedNodes.add(nodeId);
}
/**
* @param failedNodes Failed nodes.
*/
public void failedNodes(@Nullable Set<UUID> failedNodes) {
this.failedNodes = failedNodes;
}
/**
* @return Failed nodes IDs.
*/
@Nullable public Collection<UUID> failedNodes() {
return failedNodes;
}
/** {@inheritDoc} */
@Override public boolean equals(Object obj) {<FILL_FUNCTION_BODY>}
/** {@inheritDoc} */
@Override public final int hashCode() {
return id.hashCode();
}
/** {@inheritDoc} */
@Override public String toString() {
return S.toString(TcpDiscoveryAbstractMessage.class, this, "isClient", getFlag(CLIENT_FLAG_POS));
}
}
|
if (this == obj)
return true;
else if (obj instanceof TcpDiscoveryAbstractMessage)
return id.equals(((TcpDiscoveryAbstractMessage)obj).id);
return false;
| 1,924
| 55
| 1,979
|
<no_super_class>
|
apache_ignite
|
ignite/modules/core/src/main/java/org/apache/ignite/spi/discovery/tcp/messages/TcpDiscoveryAbstractTraceableMessage.java
|
TcpDiscoveryAbstractTraceableMessage
|
readResolve
|
class TcpDiscoveryAbstractTraceableMessage extends TcpDiscoveryAbstractMessage implements TraceableMessage {
/** Container. */
private SpanContainer spanContainer = new SpanContainer();
/**
* Default no-arg constructor for {@link Externalizable} interface.
*/
protected TcpDiscoveryAbstractTraceableMessage() {
// No-op.
}
/**
* Constructor.
*
* @param creatorNodeId Creator node ID.
*/
protected TcpDiscoveryAbstractTraceableMessage(UUID creatorNodeId) {
super(creatorNodeId);
}
/**
* @param msg Message.
*/
protected TcpDiscoveryAbstractTraceableMessage(TcpDiscoveryAbstractTraceableMessage msg) {
super(msg);
this.spanContainer = msg.spanContainer;
}
/**
* Restores spanContainer field to non-null value after deserialization.
* This is needed for compatibility between nodes having Tracing SPI and not.
*
* @return Deserialized instance os the current class.
*/
public Object readResolve() {<FILL_FUNCTION_BODY>}
/** {@inheritDoc} */
@Override public SpanContainer spanContainer() {
return spanContainer;
}
}
|
if (spanContainer == null)
spanContainer = new SpanContainer();
return this;
| 324
| 28
| 352
|
<methods>public void addFailedNode(java.util.UUID) ,public boolean client() ,public void client(boolean) ,public java.util.UUID creatorNodeId() ,public boolean equals(java.lang.Object) ,public void failedNodes(Set<java.util.UUID>) ,public Collection<java.util.UUID> failedNodes() ,public boolean force() ,public void force(boolean) ,public final int hashCode() ,public boolean highPriority() ,public org.apache.ignite.lang.IgniteUuid id() ,public short pendingIndex() ,public void pendingIndex(short) ,public java.util.UUID senderNodeId() ,public void senderNodeId(java.util.UUID) ,public java.lang.String toString() ,public long topologyVersion() ,public void topologyVersion(long) ,public boolean traceLogLevel() ,public boolean verified() ,public java.util.UUID verifierNodeId() ,public void verify(java.util.UUID) <variables>protected static final int CHANGE_TOPOLOGY_FLAG_POS,protected static final int CLIENT_ACK_FLAG_POS,protected static final int CLIENT_FLAG_POS,protected static final int CLIENT_RECON_SUCCESS_FLAG_POS,protected static final int COMPRESS_DATA_PACKET,protected static final int FORCE_FAIL_FLAG_POS,protected static final int RESPONDED_FLAG_POS,private Set<java.util.UUID> failedNodes,private int flags,private org.apache.ignite.lang.IgniteUuid id,private short pendingIdx,private static final long serialVersionUID,private transient java.util.UUID sndNodeId,private long topVer,private java.util.UUID verifierNodeId
|
apache_ignite
|
ignite/modules/core/src/main/java/org/apache/ignite/spi/discovery/tcp/messages/TcpDiscoveryClientReconnectMessage.java
|
TcpDiscoveryClientReconnectMessage
|
equals
|
class TcpDiscoveryClientReconnectMessage extends TcpDiscoveryAbstractMessage {
/** */
private static final long serialVersionUID = 0L;
/** New router nodeID. */
private final UUID routerNodeId;
/** Last message ID. */
private final IgniteUuid lastMsgId;
/** Pending messages. */
@GridToStringExclude
private Collection<TcpDiscoveryAbstractMessage> msgs;
/**
* @param creatorNodeId Creator node ID.
* @param routerNodeId New router node ID.
* @param lastMsgId Last message ID.
*/
public TcpDiscoveryClientReconnectMessage(UUID creatorNodeId, UUID routerNodeId, IgniteUuid lastMsgId) {
super(creatorNodeId);
this.routerNodeId = routerNodeId;
this.lastMsgId = lastMsgId;
}
/**
* @return New router node ID.
*/
public UUID routerNodeId() {
return routerNodeId;
}
/**
* @return Last message ID.
*/
public IgniteUuid lastMessageId() {
return lastMsgId;
}
/**
* @param msgs Pending messages.
*/
public void pendingMessages(Collection<TcpDiscoveryAbstractMessage> msgs) {
this.msgs = msgs;
}
/**
* @return Pending messages.
*/
public Collection<TcpDiscoveryAbstractMessage> pendingMessages() {
return msgs;
}
/**
* @param success Success flag.
*/
public void success(boolean success) {
setFlag(CLIENT_RECON_SUCCESS_FLAG_POS, success);
}
/**
* @return Success flag.
*/
public boolean success() {
return getFlag(CLIENT_RECON_SUCCESS_FLAG_POS);
}
/** {@inheritDoc} */
@Override public boolean equals(Object obj) {<FILL_FUNCTION_BODY>}
/** {@inheritDoc} */
@Override public String toString() {
return S.toString(TcpDiscoveryClientReconnectMessage.class, this, "super", super.toString());
}
}
|
// NOTE!
// Do not call super. As IDs will differ, but we can ignore this.
if (!(obj instanceof TcpDiscoveryClientReconnectMessage))
return false;
TcpDiscoveryClientReconnectMessage other = (TcpDiscoveryClientReconnectMessage)obj;
return F.eq(creatorNodeId(), other.creatorNodeId()) &&
F.eq(routerNodeId, other.routerNodeId) &&
F.eq(lastMsgId, other.lastMsgId);
| 566
| 130
| 696
|
<methods>public void addFailedNode(java.util.UUID) ,public boolean client() ,public void client(boolean) ,public java.util.UUID creatorNodeId() ,public boolean equals(java.lang.Object) ,public void failedNodes(Set<java.util.UUID>) ,public Collection<java.util.UUID> failedNodes() ,public boolean force() ,public void force(boolean) ,public final int hashCode() ,public boolean highPriority() ,public org.apache.ignite.lang.IgniteUuid id() ,public short pendingIndex() ,public void pendingIndex(short) ,public java.util.UUID senderNodeId() ,public void senderNodeId(java.util.UUID) ,public java.lang.String toString() ,public long topologyVersion() ,public void topologyVersion(long) ,public boolean traceLogLevel() ,public boolean verified() ,public java.util.UUID verifierNodeId() ,public void verify(java.util.UUID) <variables>protected static final int CHANGE_TOPOLOGY_FLAG_POS,protected static final int CLIENT_ACK_FLAG_POS,protected static final int CLIENT_FLAG_POS,protected static final int CLIENT_RECON_SUCCESS_FLAG_POS,protected static final int COMPRESS_DATA_PACKET,protected static final int FORCE_FAIL_FLAG_POS,protected static final int RESPONDED_FLAG_POS,private Set<java.util.UUID> failedNodes,private int flags,private org.apache.ignite.lang.IgniteUuid id,private short pendingIdx,private static final long serialVersionUID,private transient java.util.UUID sndNodeId,private long topVer,private java.util.UUID verifierNodeId
|
apache_ignite
|
ignite/modules/core/src/main/java/org/apache/ignite/spi/discovery/tcp/messages/TcpDiscoveryConnectionCheckMessage.java
|
TcpDiscoveryConnectionCheckMessage
|
writeExternal
|
class TcpDiscoveryConnectionCheckMessage extends TcpDiscoveryAbstractMessage implements Externalizable {
/** */
private static final long serialVersionUID = 0L;
/**
* Default no-arg constructor for {@link Externalizable} interface.
*/
public TcpDiscoveryConnectionCheckMessage() {
// No-op.
}
/**
* Constructor.
*
* @param creatorNode Node created this message.
*/
public TcpDiscoveryConnectionCheckMessage(TcpDiscoveryNode creatorNode) {
super(creatorNode.id());
}
/** {@inheritDoc} */
@Override public boolean traceLogLevel() {
return true;
}
/** {@inheritDoc} */
@Override public void writeExternal(ObjectOutput out) throws IOException {<FILL_FUNCTION_BODY>}
/** {@inheritDoc} */
@Override public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException {
// This method has been left empty intentionally to keep message size at min.
}
/** {@inheritDoc} */
@Override public String toString() {
return S.toString(TcpDiscoveryConnectionCheckMessage.class, this, "super", super.toString());
}
}
|
// This method has been left empty intentionally to keep message size at min.
| 312
| 21
| 333
|
<methods>public void addFailedNode(java.util.UUID) ,public boolean client() ,public void client(boolean) ,public java.util.UUID creatorNodeId() ,public boolean equals(java.lang.Object) ,public void failedNodes(Set<java.util.UUID>) ,public Collection<java.util.UUID> failedNodes() ,public boolean force() ,public void force(boolean) ,public final int hashCode() ,public boolean highPriority() ,public org.apache.ignite.lang.IgniteUuid id() ,public short pendingIndex() ,public void pendingIndex(short) ,public java.util.UUID senderNodeId() ,public void senderNodeId(java.util.UUID) ,public java.lang.String toString() ,public long topologyVersion() ,public void topologyVersion(long) ,public boolean traceLogLevel() ,public boolean verified() ,public java.util.UUID verifierNodeId() ,public void verify(java.util.UUID) <variables>protected static final int CHANGE_TOPOLOGY_FLAG_POS,protected static final int CLIENT_ACK_FLAG_POS,protected static final int CLIENT_FLAG_POS,protected static final int CLIENT_RECON_SUCCESS_FLAG_POS,protected static final int COMPRESS_DATA_PACKET,protected static final int FORCE_FAIL_FLAG_POS,protected static final int RESPONDED_FLAG_POS,private Set<java.util.UUID> failedNodes,private int flags,private org.apache.ignite.lang.IgniteUuid id,private short pendingIdx,private static final long serialVersionUID,private transient java.util.UUID sndNodeId,private long topVer,private java.util.UUID verifierNodeId
|
apache_ignite
|
ignite/modules/core/src/main/java/org/apache/ignite/spi/discovery/tcp/messages/TcpDiscoveryNodeAddFinishedMessage.java
|
TcpDiscoveryNodeAddFinishedMessage
|
clientDiscoData
|
class TcpDiscoveryNodeAddFinishedMessage extends TcpDiscoveryAbstractTraceableMessage {
/** */
private static final long serialVersionUID = 0L;
/** Added node ID. */
private final UUID nodeId;
/**
* Client node can not get discovery data from TcpDiscoveryNodeAddedMessage, we have to pass discovery data in
* TcpDiscoveryNodeAddFinishedMessage
*/
@GridToStringExclude
private DiscoveryDataPacket clientDiscoData;
/** */
@GridToStringExclude
private Map<String, Object> clientNodeAttrs;
/**
* Constructor.
*
* @param creatorNodeId ID of the creator node (coordinator).
* @param nodeId Added node ID.
*/
public TcpDiscoveryNodeAddFinishedMessage(UUID creatorNodeId, UUID nodeId) {
super(creatorNodeId);
this.nodeId = nodeId;
}
/**
* @param msg Message.
*/
public TcpDiscoveryNodeAddFinishedMessage(TcpDiscoveryNodeAddFinishedMessage msg) {
super(msg);
nodeId = msg.nodeId;
clientDiscoData = msg.clientDiscoData;
clientNodeAttrs = msg.clientNodeAttrs;
}
/**
* Gets ID of the node added.
*
* @return ID of the node added.
*/
public UUID nodeId() {
return nodeId;
}
/**
* @return Discovery data for joined client.
*/
public DiscoveryDataPacket clientDiscoData() {
return clientDiscoData;
}
/**
* @param clientDiscoData Discovery data for joined client.
*/
public void clientDiscoData(DiscoveryDataPacket clientDiscoData) {<FILL_FUNCTION_BODY>}
/**
* @return Client node attributes.
*/
public Map<String, Object> clientNodeAttributes() {
return clientNodeAttrs;
}
/**
* @param clientNodeAttrs New client node attributes.
*/
public void clientNodeAttributes(Map<String, Object> clientNodeAttrs) {
this.clientNodeAttrs = clientNodeAttrs;
}
/** {@inheritDoc} */
@Override public String toString() {
return S.toString(TcpDiscoveryNodeAddFinishedMessage.class, this, "super", super.toString());
}
}
|
this.clientDiscoData = clientDiscoData;
assert clientDiscoData == null || !clientDiscoData.hasDataFromNode(nodeId);
| 626
| 42
| 668
|
<methods>public java.lang.Object readResolve() ,public org.apache.ignite.internal.processors.tracing.messages.SpanContainer spanContainer() <variables>private org.apache.ignite.internal.processors.tracing.messages.SpanContainer spanContainer
|
apache_ignite
|
ignite/modules/core/src/main/java/org/apache/ignite/spi/discovery/tcp/messages/TcpDiscoveryNodeAddedMessage.java
|
TcpDiscoveryNodeAddedMessage
|
clientTopology
|
class TcpDiscoveryNodeAddedMessage extends TcpDiscoveryAbstractTraceableMessage {
/** */
private static final long serialVersionUID = 0L;
/** Added node. */
private final TcpDiscoveryNode node;
/** */
private DiscoveryDataPacket dataPacket;
/** Pending messages from previous node. */
private Collection<TcpDiscoveryAbstractMessage> msgs;
/** Discarded message ID. */
private IgniteUuid discardMsgId;
/** Discarded message ID. */
private IgniteUuid discardCustomMsgId;
/** Current topology. Initialized by coordinator. */
@GridToStringInclude
private Collection<TcpDiscoveryNode> top;
/** */
@GridToStringInclude
private transient Collection<TcpDiscoveryNode> clientTop;
/** Topology snapshots history. */
private Map<Long, Collection<ClusterNode>> topHist;
/** Start time of the first grid node. */
private final long gridStartTime;
/**
* Constructor.
*
* @param creatorNodeId Creator node ID.
* @param node Node to add to topology.
* @param dataPacket container for collecting discovery data across the cluster.
* @param gridStartTime Start time of the first grid node.
*/
public TcpDiscoveryNodeAddedMessage(UUID creatorNodeId,
TcpDiscoveryNode node,
DiscoveryDataPacket dataPacket,
long gridStartTime
) {
super(creatorNodeId);
assert node != null;
assert gridStartTime > 0;
this.node = node;
this.dataPacket = dataPacket;
this.gridStartTime = gridStartTime;
}
/**
* @param msg Message.
*/
public TcpDiscoveryNodeAddedMessage(TcpDiscoveryNodeAddedMessage msg) {
super(msg);
this.node = msg.node;
this.msgs = msg.msgs;
this.discardMsgId = msg.discardMsgId;
this.discardCustomMsgId = msg.discardCustomMsgId;
this.top = msg.top;
this.clientTop = msg.clientTop;
this.topHist = msg.topHist;
this.dataPacket = msg.dataPacket;
this.gridStartTime = msg.gridStartTime;
}
/**
* Gets newly added node.
*
* @return New node.
*/
public TcpDiscoveryNode node() {
return node;
}
/**
* Gets pending messages sent to new node by its previous.
*
* @return Pending messages from previous node.
*/
@Nullable public Collection<TcpDiscoveryAbstractMessage> messages() {
return msgs;
}
/**
* Gets discarded message ID.
*
* @return Discarded message ID.
*/
@Nullable public IgniteUuid discardedMessageId() {
return discardMsgId;
}
/**
* Gets discarded custom message ID.
*
* @return Discarded message ID.
*/
@Nullable public IgniteUuid discardedCustomMessageId() {
return discardCustomMsgId;
}
/**
* Sets pending messages to send to new node.
*
* @param msgs Pending messages to send to new node.
* @param discardMsgId Discarded message ID.
* @param discardCustomMsgId Discarded custom message ID.
*/
public void messages(
@Nullable Collection<TcpDiscoveryAbstractMessage> msgs,
@Nullable IgniteUuid discardMsgId,
@Nullable IgniteUuid discardCustomMsgId
) {
this.msgs = msgs;
this.discardMsgId = discardMsgId;
this.discardCustomMsgId = discardCustomMsgId;
}
/**
* Gets topology.
*
* @return Current topology.
*/
@Nullable public Collection<TcpDiscoveryNode> topology() {
return top;
}
/**
* Sets topology.
*
* @param top Current topology.
*/
public void topology(@Nullable Collection<TcpDiscoveryNode> top) {
this.top = top;
}
/**
* @param top Topology at the moment when client joined.
*/
public void clientTopology(Collection<TcpDiscoveryNode> top) {<FILL_FUNCTION_BODY>}
/**
* @return Topology at the moment when client joined.
*/
public Collection<TcpDiscoveryNode> clientTopology() {
return clientTop;
}
/**
* Gets topology snapshots history.
*
* @return Map with topology snapshots history.
*/
public Map<Long, Collection<ClusterNode>> topologyHistory() {
return topHist;
}
/**
* Sets topology snapshots history.
*
* @param topHist Map with topology snapshots history.
*/
public void topologyHistory(@Nullable Map<Long, Collection<ClusterNode>> topHist) {
this.topHist = topHist;
}
/**
* @return {@link DiscoveryDataPacket} carried by this message.
*/
public DiscoveryDataPacket gridDiscoveryData() {
return dataPacket;
}
/**
* Clears discovery data to minimize message size.
*/
public void clearDiscoveryData() {
dataPacket = null;
}
/**
* Clears unmarshalled discovery data to minimize message size.
* These data are used only on "collect" stage and are not part of persistent state.
*/
public void clearUnmarshalledDiscoveryData() {
if (dataPacket != null)
dataPacket.clearUnmarshalledJoiningNodeData();
}
/**
* @return First grid node start time.
*/
public long gridStartTime() {
return gridStartTime;
}
/** {@inheritDoc} */
@Override public String toString() {
return S.toString(TcpDiscoveryNodeAddedMessage.class, this, "super", super.toString());
}
}
|
assert top != null && !top.isEmpty() : top;
this.clientTop = top;
| 1,573
| 29
| 1,602
|
<methods>public java.lang.Object readResolve() ,public org.apache.ignite.internal.processors.tracing.messages.SpanContainer spanContainer() <variables>private org.apache.ignite.internal.processors.tracing.messages.SpanContainer spanContainer
|
apache_ignite
|
ignite/modules/core/src/main/java/org/apache/ignite/spi/indexing/noop/NoopIndexingSpi.java
|
NoopIndexingSpi
|
query
|
class NoopIndexingSpi extends IgniteSpiAdapter implements IndexingSpi {
/** {@inheritDoc} */
@Override public Iterator<Cache.Entry<?, ?>> query(@Nullable String cacheName, Collection<Object> params,
@Nullable IndexingQueryFilter filters) throws IgniteSpiException {<FILL_FUNCTION_BODY>}
/** {@inheritDoc} */
@Override public void store(@Nullable String cacheName, Object key, Object val, long expirationTime)
throws IgniteSpiException {
assert false;
}
/** {@inheritDoc} */
@Override public void remove(@Nullable String cacheName, Object key) throws IgniteSpiException {
assert false;
}
/** {@inheritDoc} */
@Override public void spiStart(@Nullable String igniteInstanceName) throws IgniteSpiException {
// No-op.
}
/** {@inheritDoc} */
@Override public void spiStop() throws IgniteSpiException {
// No-op.
}
/** {@inheritDoc} */
@Override public NoopIndexingSpi setName(String name) {
super.setName(name);
return this;
}
}
|
throw new IgniteSpiException("You have to configure custom GridIndexingSpi implementation.");
| 301
| 25
| 326
|
<methods>public long clientFailureDetectionTimeout() ,public long failureDetectionTimeout() ,public void failureDetectionTimeoutEnabled(boolean) ,public boolean failureDetectionTimeoutEnabled() ,public org.apache.ignite.internal.util.IgniteExceptionRegistry getExceptionRegistry() ,public java.lang.String getName() ,public Map<java.lang.String,java.lang.Object> getNodeAttributes() throws org.apache.ignite.spi.IgniteSpiException,public org.apache.ignite.spi.IgniteSpiContext getSpiContext() ,public org.apache.ignite.Ignite ignite() ,public Collection<java.lang.Object> injectables() ,public final void onBeforeStart() ,public void onClientDisconnected(IgniteFuture<?>) ,public void onClientReconnected(boolean) ,public final void onContextDestroyed() ,public final void onContextInitialized(org.apache.ignite.spi.IgniteSpiContext) throws org.apache.ignite.spi.IgniteSpiException,public org.apache.ignite.spi.IgniteSpiAdapter setName(java.lang.String) ,public final boolean started() <variables>private long clientFailureDetectionTimeout,private long failureDetectionTimeout,private boolean failureDetectionTimeoutEnabled,protected org.apache.ignite.Ignite ignite,protected java.lang.String igniteInstanceName,private org.apache.ignite.cluster.ClusterNode locNode,protected org.apache.ignite.IgniteLogger log,private java.lang.String name,private org.apache.ignite.internal.managers.eventstorage.GridLocalEventListener paramsLsnr,private volatile org.apache.ignite.spi.IgniteSpiContext spiCtx,private javax.management.ObjectName spiMBean,private long startTstamp,private final java.util.concurrent.atomic.AtomicBoolean startedFlag
|
apache_ignite
|
ignite/modules/core/src/main/java/org/apache/ignite/spi/metric/jmx/MetricRegistryMBean.java
|
MetricRegistryMBean
|
searchHistogram
|
class MetricRegistryMBean extends ReadOnlyDynamicMBean {
/** Metric registry. */
ReadOnlyMetricRegistry mreg;
/**
* @param mreg Metric registry.
*/
public MetricRegistryMBean(ReadOnlyMetricRegistry mreg) {
this.mreg = mreg;
}
/** {@inheritDoc} */
@Override public Object getAttribute(String attr) {
if (attr.equals("MBeanInfo"))
return getMBeanInfo();
Metric metric = mreg.findMetric(attr);
if (metric == null)
return searchHistogram(attr, mreg);
if (metric instanceof BooleanMetric)
return ((BooleanMetric)metric).value();
else if (metric instanceof DoubleMetric)
return ((DoubleMetric)metric).value();
else if (metric instanceof IntMetric)
return ((IntMetric)metric).value();
else if (metric instanceof LongMetric)
return ((LongMetric)metric).value();
else if (metric instanceof ObjectMetric)
return ((ObjectMetric)metric).value();
throw new IllegalArgumentException("Unknown metric class. " + metric.getClass());
}
/** {@inheritDoc} */
@Override public MBeanInfo getMBeanInfo() {
Iterator<Metric> iter = mreg.iterator();
List<MBeanAttributeInfo> attrs = new ArrayList<>();
iter.forEachRemaining(metric -> {
if (metric instanceof HistogramMetric) {
String[] names = histogramBucketNames((HistogramMetric)metric);
assert names.length == ((HistogramMetric)metric).value().length;
for (String name : names) {
String n = name.substring(mreg.name().length() + 1);
attrs.add(new MBeanAttributeInfo(
n,
Long.class.getName(),
metric.description() != null ? metric.description() : n,
true,
false,
false));
}
}
else {
attrs.add(new MBeanAttributeInfo(
metric.name().substring(mreg.name().length() + 1),
metricClass(metric),
metric.description() != null ? metric.description() : metric.name(),
true,
false,
false));
}
});
return new MBeanInfo(
ReadOnlyMetricManager.class.getName(),
mreg.name(),
attrs.toArray(new MBeanAttributeInfo[attrs.size()]),
null,
null,
null);
}
/**
* @param metric Metric.
* @return Class of metric value.
*/
private String metricClass(Metric metric) {
if (metric instanceof BooleanMetric)
return Boolean.class.getName();
else if (metric instanceof DoubleMetric)
return Double.class.getName();
else if (metric instanceof IntMetric)
return Integer.class.getName();
else if (metric instanceof LongMetric)
return Long.class.getName();
else if (metric instanceof ObjectMetric)
return ((ObjectMetric)metric).type().getName();
throw new IllegalArgumentException("Unknown metric class. " + metric.getClass());
}
/**
* Parse attribute name for a histogram and search it's value.
*
* @param name Attribute name.
* @param mreg Metric registry to search histogram in.
* @return Specific bucket value or {@code null} if not found.
* @see MetricUtils#histogramBucketNames(HistogramMetric)
*/
public static Long searchHistogram(String name, ReadOnlyMetricRegistry mreg) {<FILL_FUNCTION_BODY>}
}
|
int highBoundIdx;
boolean isInf = name.endsWith(INF);
if (isInf)
highBoundIdx = name.length() - 4;
else {
highBoundIdx = name.lastIndexOf(HISTOGRAM_NAME_DIVIDER);
if (highBoundIdx == -1)
return null;
}
int lowBoundIdx = name.lastIndexOf(HISTOGRAM_NAME_DIVIDER, highBoundIdx - 1);
if (lowBoundIdx == -1)
return null;
Metric m = mreg.findMetric(name.substring(0, lowBoundIdx));
if (!(m instanceof HistogramMetric))
return null;
HistogramMetric h = (HistogramMetric)m;
long[] bounds = h.bounds();
long[] values = h.value();
long lowBound;
try {
lowBound = Long.parseLong(name.substring(lowBoundIdx + 1, highBoundIdx));
}
catch (NumberFormatException e) {
return null;
}
if (isInf) {
if (bounds[bounds.length - 1] == lowBound)
return values[values.length - 1];
return null;
}
long highBound;
try {
highBound = Long.parseLong(name.substring(highBoundIdx + 1));
}
catch (NumberFormatException e) {
return null;
}
int idx = binarySearch(bounds, highBound);
if (idx < 0)
return null;
if ((idx == 0 && lowBound != 0) || (idx != 0 && bounds[idx - 1] != lowBound))
return null;
return values[idx];
| 944
| 477
| 1,421
|
<methods>public non-sealed void <init>() ,public javax.management.AttributeList getAttributes(java.lang.String[]) ,public java.lang.Object invoke(java.lang.String, java.lang.Object[], java.lang.String[]) throws javax.management.MBeanException, javax.management.ReflectionException,public void setAttribute(javax.management.Attribute) ,public javax.management.AttributeList setAttributes(javax.management.AttributeList) <variables>
|
apache_ignite
|
ignite/modules/core/src/main/java/org/apache/ignite/spi/systemview/view/BinaryMetadataView.java
|
BinaryMetadataView
|
schemasIds
|
class BinaryMetadataView {
/** Meta. */
private final BinaryMetadata meta;
/** @param meta Meta. */
public BinaryMetadataView(BinaryMetadata meta) {
this.meta = meta;
}
/** @return Type id. */
@Order
public int typeId() {
return meta.typeId();
}
/** @return Type name. */
@Order(1)
public String typeName() {
return meta.typeName();
}
/** @return Affinity key field name. */
@Order(2)
public String affKeyFieldName() {
return meta.affinityKeyFieldName();
}
/** @return Fields count. */
@Order(3)
public int fieldsCount() {
return meta.fields().size();
}
/** @return Fields. */
@Order(4)
public String fields() {
return U.toStringSafe(meta.fields());
}
/** @return Schema IDs registered for this type. */
@Order(5)
public String schemasIds() {<FILL_FUNCTION_BODY>}
/** @return {@code True} if this is enum type. */
@Order(6)
public boolean isEnum() {
return meta.isEnum();
}
}
|
List<Integer> ids = new ArrayList<>(meta.schemas().size());
for (BinarySchema schema : meta.schemas())
ids.add(schema.schemaId());
return U.toStringSafe(ids);
| 337
| 58
| 395
|
<no_super_class>
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.