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/spi/systemview/view/sql/SqlIndexView.java
|
SqlIndexView
|
columns
|
class SqlIndexView {
/** Table. */
private final TableDescriptor tbl;
/** Index. */
private final IndexDescriptor idx;
/**
* @param tbl Table information.
* @param idx Index information.
*/
public SqlIndexView(TableDescriptor tbl, IndexDescriptor idx) {
this.tbl = tbl;
this.idx = idx;
}
/**
* Returns cache group ID.
*
* @return Cache group ID.
*/
@Order()
public int cacheGroupId() {
return tbl.cacheInfo().groupId();
}
/**
* Returns Cache group name.
*
* @return Cache group name.
*/
@Order(1)
public String cacheGroupName() {
return tbl.cacheInfo().groupName();
}
/**
* Returns cache ID.
* @return Cache ID.
*/
@Order(2)
public int cacheId() {
return tbl.cacheInfo().cacheId();
}
/**
* Returns cache name.
*
* @return Cache name.
*/
@Order(3)
public String cacheName() {
return tbl.cacheInfo().name();
}
/**
* Returns schema name.
*
* @return Schema name.
*/
@Order(4)
public String schemaName() {
return tbl.type().schemaName();
}
/**
* Returns table name.
*
* @return Table name.
*/
@Order(5)
public String tableName() {
return tbl.type().tableName();
}
/**
* Returns index name.
*
* @return Index name.
*/
@Order(6)
public String indexName() {
return idx.name();
}
/**
* Returns index type.
*
* @return Index type.
*/
@Order(7)
public String indexType() {
return idx.type().name();
}
/**
* Returns all columns on which index is built.
*
* @return Coma separated indexed columns.
*/
@Order(8)
public String columns() {<FILL_FUNCTION_BODY>}
/**
* Returns boolean value which indicates whether this index is for primary key or not.
*
* @return {@code True} if primary key index, {@code false} otherwise.
*/
@Order(9)
public boolean isPk() {
return idx.isPk();
}
/**
* Returns boolean value which indicates whether this index is unique or not.
*
* @return {@code True} if unique index, {@code false} otherwise.
*/
@Order(10)
public boolean isUnique() {
return idx.isPk() || (idx.isProxy() && idx.targetIdx().isPk());
}
/**
* Returns inline size in bytes.
*
* @return Inline size.
*/
@Order(11)
public Integer inlineSize() {
return idx.inlineSize();
}
}
|
return idx.keyDefinitions().entrySet().stream()
.map(fld -> '"' + fld.getKey() + '"' +
(fld.getValue().order().sortOrder() == SortOrder.DESC ? " DESC" : " ASC"))
.collect(Collectors.joining(", "));
| 814
| 82
| 896
|
<no_super_class>
|
apache_ignite
|
ignite/modules/core/src/main/java/org/apache/ignite/spi/systemview/view/sql/SqlTableColumnView.java
|
SqlTableColumnView
|
affinityColumn
|
class SqlTableColumnView {
/** Table. */
private final TableDescriptor tbl;
/** Query property. */
private final GridQueryProperty prop;
/**
* @param tbl Table.
* @param prop Column.
*/
public SqlTableColumnView(TableDescriptor tbl, GridQueryProperty prop) {
this.tbl = tbl;
this.prop = prop;
}
/** @return Column name. */
@Order
public String columnName() {
return prop.name();
}
/** @return Schema name. */
@Order(2)
public String schemaName() {
return tbl.type().schemaName();
}
/** @return Table name. */
@Order(1)
public String tableName() {
return tbl.type().tableName();
}
/** @return Field data type. */
public Class<?> type() {
return prop.type();
}
/** @return Field default. */
public String defaultValue() {
return prop.defaultValue() == null ? null : prop.defaultValue().toString();
}
/** @return Precision. */
public int precision() {
return prop.precision();
}
/** @return Scale. */
public int scale() {
return prop.scale();
}
/** @return {@code True} if nullable field. */
public boolean nullable() {
return !prop.notNull();
}
/** @return {@code True} if primary key. */
public boolean pk() {
return F.eq(prop.name(), tbl.type().keyFieldName()) || prop.key();
}
/** @return {@code True} if autoincremented field. */
public boolean autoIncrement() {
return false;
}
/** @return {@code True} if affinity column. */
public boolean affinityColumn() {<FILL_FUNCTION_BODY>}
}
|
return !tbl.type().customAffinityKeyMapper() &&
(F.eq(prop.name(), tbl.type().affinityKey()) || (F.isEmpty(tbl.type().affinityKey()) && pk()));
| 503
| 57
| 560
|
<no_super_class>
|
apache_ignite
|
ignite/modules/core/src/main/java/org/apache/ignite/ssl/AbstractSslContextFactory.java
|
AbstractSslContextFactory
|
createSslContext
|
class AbstractSslContextFactory implements Factory<SSLContext> {
/** */
private static final long serialVersionUID = 0L;
/** Default SSL protocol. */
public static final String DFLT_SSL_PROTOCOL = "TLS";
/** SSL protocol. */
protected String proto = DFLT_SSL_PROTOCOL;
/** Enabled cipher suites. */
protected String[] cipherSuites;
/** Enabled protocols. */
protected String[] protocols;
/** Cached instance of an {@link SSLContext}. */
protected final AtomicReference<SSLContext> sslCtx = new AtomicReference<>();
/**
* Gets protocol for secure transport.
*
* @return SSL protocol name.
*/
public String getProtocol() {
return proto;
}
/**
* Sets protocol for secure transport. If not specified, {@link #DFLT_SSL_PROTOCOL} will be used.
*
* @param proto SSL protocol name.
*/
public void setProtocol(String proto) {
A.notNull(proto, "proto");
this.proto = proto;
}
/**
* Sets enabled cipher suites.
*
* @param cipherSuites enabled cipher suites.
*/
public void setCipherSuites(String... cipherSuites) {
this.cipherSuites = cipherSuites;
}
/**
* Gets enabled cipher suites.
*
* @return enabled cipher suites
*/
public String[] getCipherSuites() {
return cipherSuites;
}
/**
* Gets enabled protocols.
*
* @return Enabled protocols.
*/
public String[] getProtocols() {
return protocols;
}
/**
* Sets enabled protocols.
*
* @param protocols Enabled protocols.
*/
public void setProtocols(String... protocols) {
this.protocols = protocols;
}
/**
* Creates SSL context based on factory settings.
*
* @return Initialized SSL context.
* @throws SSLException If SSL context could not be created.
*/
private SSLContext createSslContext() throws SSLException {<FILL_FUNCTION_BODY>}
/**
* @param param Value.
* @param name Name.
* @throws SSLException If {@code null}.
*/
protected void checkNullParameter(Object param, String name) throws SSLException {
if (param == null)
throw new SSLException("Failed to initialize SSL context (parameter cannot be null): " + name);
}
/**
* Checks that all required parameters are set.
*
* @throws SSLException If any of required parameters is missing.
*/
protected abstract void checkParameters() throws SSLException;
/**
* @return Created Key Managers.
* @throws SSLException If Key Managers could not be created.
*/
protected abstract KeyManager[] createKeyManagers() throws SSLException;
/**
* @return Created Trust Managers.
* @throws SSLException If Trust Managers could not be created.
*/
protected abstract TrustManager[] createTrustManagers() throws SSLException;
/** {@inheritDoc} */
@Override public SSLContext create() {
SSLContext ctx = sslCtx.get();
if (ctx == null) {
try {
ctx = createSslContext();
if (!sslCtx.compareAndSet(null, ctx))
ctx = sslCtx.get();
}
catch (SSLException e) {
throw new IgniteException(e);
}
}
return ctx;
}
}
|
checkParameters();
KeyManager[] keyMgrs = createKeyManagers();
TrustManager[] trustMgrs = createTrustManagers();
try {
SSLContext ctx = SSLContext.getInstance(proto);
if (cipherSuites != null || protocols != null) {
SSLParameters sslParameters = new SSLParameters();
if (cipherSuites != null)
sslParameters.setCipherSuites(cipherSuites);
if (protocols != null)
sslParameters.setProtocols(protocols);
ctx = new SSLContextWrapper(ctx, sslParameters);
}
ctx.init(keyMgrs, trustMgrs, null);
return ctx;
}
catch (NoSuchAlgorithmException e) {
throw new SSLException("Unsupported SSL protocol: " + proto, e);
}
catch (KeyManagementException e) {
throw new SSLException("Failed to initialized SSL context.", e);
}
| 948
| 259
| 1,207
|
<no_super_class>
|
apache_ignite
|
ignite/modules/core/src/main/java/org/apache/ignite/stream/StreamTransformer.java
|
EntryProcessorWrapper
|
classLoader
|
class EntryProcessorWrapper<K, V> extends StreamTransformer<K, V> implements GridPeerDeployAware {
/** */
private static final long serialVersionUID = 0L;
/** */
private CacheEntryProcessor<K, V, Object> ep;
/** */
private transient ClassLoader ldr;
/**
* @param ep Entry processor.
*/
EntryProcessorWrapper(CacheEntryProcessor<K, V, Object> ep) {
this.ep = ep;
}
/** {@inheritDoc} */
@Override public Object process(MutableEntry<K, V> entry, Object... args) throws EntryProcessorException {
return ep.process(entry, args);
}
/** {@inheritDoc} */
@Override public Class<?> deployClass() {
return ep.getClass();
}
/** {@inheritDoc} */
@Override public ClassLoader classLoader() {<FILL_FUNCTION_BODY>}
}
|
if (ldr == null)
ldr = U.detectClassLoader(deployClass());
return ldr;
| 243
| 35
| 278
|
<no_super_class>
|
apache_ignite
|
ignite/modules/core/src/main/java/org/apache/ignite/thread/IgniteThreadFactory.java
|
IgniteThreadFactory
|
newThread
|
class IgniteThreadFactory implements ThreadFactory {
/** Ignite instance name. */
private final String igniteInstanceName;
/** Thread name. */
private final String threadName;
/** Index generator for threads. */
private final AtomicInteger idxGen = new AtomicInteger();
/** */
private final byte plc;
/** Exception handler. */
private final UncaughtExceptionHandler eHnd;
/**
* Constructs new thread factory for given grid. All threads will belong
* to the same default thread group.
*
* @param igniteInstanceName Ignite instance name.
* @param threadName Thread name.
*/
public IgniteThreadFactory(String igniteInstanceName, String threadName) {
this(igniteInstanceName, threadName, null);
}
/**
* Constructs new thread factory for given grid. All threads will belong
* to the same default thread group.
*
* @param igniteInstanceName Ignite instance name.
* @param threadName Thread name.
* @param eHnd Uncaught exception handler.
*/
public IgniteThreadFactory(String igniteInstanceName, String threadName, UncaughtExceptionHandler eHnd) {
this(igniteInstanceName, threadName, GridIoPolicy.UNDEFINED, eHnd);
}
/**
* Constructs new thread factory for given grid. All threads will belong
* to the same default thread group.
*
* @param igniteInstanceName Ignite instance name.
* @param threadName Thread name.
* @param plc {@link GridIoPolicy} for thread pool.
* @param eHnd Uncaught exception handler.
*/
public IgniteThreadFactory(String igniteInstanceName, String threadName, byte plc, UncaughtExceptionHandler eHnd) {
this.igniteInstanceName = igniteInstanceName;
this.threadName = threadName;
this.plc = plc;
this.eHnd = eHnd;
}
/** {@inheritDoc} */
@Override public Thread newThread(@NotNull Runnable r) {<FILL_FUNCTION_BODY>}
/** {@inheritDoc} */
@Override public String toString() {
return S.toString(IgniteThreadFactory.class, this, super.toString());
}
}
|
Thread thread = new IgniteThread(igniteInstanceName, threadName, r, idxGen.incrementAndGet(), -1, plc);
if (eHnd != null)
thread.setUncaughtExceptionHandler(eHnd);
return thread;
| 585
| 70
| 655
|
<no_super_class>
|
apache_ignite
|
ignite/modules/core/src/main/java/org/apache/ignite/util/AttributeNodeFilter.java
|
AttributeNodeFilter
|
apply
|
class AttributeNodeFilter implements IgnitePredicate<ClusterNode> {
/** */
private static final long serialVersionUID = 0L;
/** Attributes. */
private final Map<String, Object> attrs;
/**
* Creates new node filter with a single attribute value.
*
* @param attrName Attribute name.
* @param attrVal Attribute value.
*/
public AttributeNodeFilter(String attrName, @Nullable Object attrVal) {
A.notNull(attrName, "attrName");
attrs = Collections.singletonMap(attrName, attrVal);
}
/**
* Creates new node filter with a set of attributes.
*
* @param attrs Attributes.
*/
public AttributeNodeFilter(Map<String, Object> attrs) {
A.notNull(attrs, "attrs");
this.attrs = attrs;
}
/** {@inheritDoc} */
@Override public boolean apply(ClusterNode node) {<FILL_FUNCTION_BODY>}
/**
* Gets attributes.
*
* @return Attributes collection.
*/
public Map<String, Object> getAttrs() {
return new HashMap<>(attrs);
}
}
|
Map<String, Object> nodeAttrs = node.attributes();
for (Map.Entry<String, Object> attr : attrs.entrySet()) {
if (!F.eq(nodeAttrs.get(attr.getKey()), attr.getValue()))
return false;
}
return true;
| 324
| 78
| 402
|
<no_super_class>
|
apache_ignite
|
ignite/modules/core/src/main/java/org/apache/ignite/util/deque/FastSizeDeque.java
|
Iter
|
pollFirst
|
class Iter implements Iterator<E> {
/** */
private final Iterator<E> iter;
/** */
private Iter(Iterator<E> iter) {
this.iter = iter;
}
/** {@inheritDoc} */
@Override public boolean hasNext() {
return iter.hasNext();
}
/** {@inheritDoc} */
@Override public E next() {
return iter.next();
}
/** {@inheritDoc} */
@Override public void remove() {
iter.remove();
adder.decrement();
}
/** {@inheritDoc} */
@Override public void forEachRemaining(Consumer<? super E> consumer) {
iter.forEachRemaining(consumer);
}
}
/** Underlying deque. */
private final Deque<E> deque;
/** Size. */
private final LongAdder adder = new LongAdder();
/** Creates a decorator.
*
* @param deque Deque being decorated.
*/
public FastSizeDeque(Deque<E> deque) {
this.deque = Objects.requireNonNull(deque);
}
/**
* Fast size getter.
*
* @return Deque size.
*/
public int sizex() {
return adder.intValue();
}
/**
* Tests this deque for emptiness.; equivalent to {@code sizex() == 0}.
*
* @return {@code True} if this deque is empty.
*/
public boolean isEmptyx() {
return adder.intValue() == 0;
}
/** {@inheritDoc} */
@Override public void addFirst(E e) {
deque.addFirst(e);
adder.increment();
}
/** {@inheritDoc} */
@Override public void addLast(E e) {
deque.addLast(e);
adder.increment();
}
/** {@inheritDoc} */
@Override public boolean offerFirst(E e) {
boolean res = deque.offerFirst(e);
if (res)
adder.increment();
return res;
}
/** {@inheritDoc} */
@Override public boolean offerLast(E e) {
boolean res = deque.offerLast(e);
if (res)
adder.increment();
return res;
}
/** {@inheritDoc} */
@Override public E removeFirst() {
E res = deque.removeFirst();
adder.decrement();
return res;
}
/** {@inheritDoc} */
@Override public E removeLast() {
E res = deque.removeLast();
adder.decrement();
return res;
}
/** {@inheritDoc} */
@Override public E pollFirst() {<FILL_FUNCTION_BODY>
|
E res = deque.pollFirst();
if (res != null)
adder.decrement();
return res;
| 766
| 40
| 806
|
<no_super_class>
|
apache_ignite
|
ignite/modules/core/src/main/java/org/jsr166/ConcurrentHashMap8.java
|
ConcurrentHashMap8
|
readObject
|
class ConcurrentHashMap8<K, V> implements Serializable {
private static final long serialVersionUID = 7249069246763182397L;
private Map<K, V> actualMap;
/**
* Reconstitutes the instance from a stream (that is, deserializes it).
*
* @param s the stream
*/
@SuppressWarnings("unchecked") private void readObject(java.io.ObjectInputStream s)
throws java.io.IOException, ClassNotFoundException {<FILL_FUNCTION_BODY>}
/**
* @return ConcurrentHashMap instead ConcurrentHashMap8 for using in code.
*/
Object readResolve() throws ObjectStreamException {
return actualMap;
}
}
|
s.defaultReadObject();
actualMap = new ConcurrentHashMap<>();
for (; ; ) {
K k = (K)s.readObject();
V v = (V)s.readObject();
if (k != null && v != null) {
actualMap.put(k, v);
}
else
break;
}
| 199
| 97
| 296
|
<no_super_class>
|
apache_ignite
|
ignite/modules/dev-utils/src/main/java/org/apache/ignite/development/utils/DataEntryWrapper.java
|
DataEntryWrapper
|
toString
|
class DataEntryWrapper extends DataEntry {
/**
* Source DataEntry.
*/
private final DataEntry source;
/** Strategy for the processing of sensitive data. */
private final ProcessSensitiveData sensitiveData;
/**
* Constructor.
*
* @param dataEntry Instance of {@link DataEntry}.
* @param sensitiveData Strategy for the processing of sensitive data.
*/
public DataEntryWrapper(
DataEntry dataEntry,
ProcessSensitiveData sensitiveData
) {
super(
dataEntry.cacheId(),
dataEntry.key(),
dataEntry.value(),
dataEntry.op(),
dataEntry.nearXidVersion(),
dataEntry.writeVersion(),
dataEntry.expireTime(),
dataEntry.partitionId(),
dataEntry.partitionCounter(),
dataEntry.flags()
);
this.source = dataEntry;
this.sensitiveData = sensitiveData;
}
/** {@inheritDoc} */
@Override public String toString() {
final String keyStr;
final String valStr;
if (source instanceof UnwrapDataEntry) {
final UnwrapDataEntry unwrappedDataEntry = (UnwrapDataEntry)this.source;
keyStr = toString(unwrappedDataEntry.unwrappedKey(), this.source.key());
valStr = toString(unwrappedDataEntry.unwrappedValue(), this.source.value());
}
else if (source instanceof RecordDataV1Serializer.EncryptedDataEntry) {
keyStr = "<encrypted>";
valStr = "<encrypted>";
}
else {
keyStr = toString(null, this.source.key());
valStr = toString(null, this.source.value());
}
return new SB(this.source.getClass().getSimpleName())
.a("[k = ").a(keyStr)
.a(", v = [").a(valStr).a("]")
.a(", super = [").a(S.toString(DataEntry.class, source)).a("]]")
.toString();
}
/**
* Returns a string representation of the entry key or entry value.
*
* @param value unwrappedKey or unwrappedValue
* @param co key or value
* @return String presentation of the entry key or entry value depends on {@code isValue}.
*/
public String toString(Object value, CacheObject co) {<FILL_FUNCTION_BODY>}
/**
* Produces auto-generated output of string presentation for given object (given the whole hierarchy).
*
* @param cls Declaration class of the object.
* @param obj Object to get a string presentation for.
* @return String presentation of the given object.
*/
public static String toStringRecursive(Class cls, Object obj) {
String result = null;
if (cls != Object.class)
result = S.toString(cls, obj, toStringRecursive(cls.getSuperclass(), obj));
return result;
}
}
|
String str;
if (sensitiveData == HIDE)
return "";
if (sensitiveData == HASH)
if (value != null)
return Integer.toString(value.hashCode());
else
return Integer.toString(co.hashCode());
if (value instanceof String)
str = (String)value;
else if (value instanceof BinaryObject)
str = value.toString();
else if (value != null)
str = toStringRecursive(value.getClass(), value);
else if (co instanceof BinaryObject)
str = co.toString();
else
str = null;
if (str == null || str.isEmpty()) {
try {
CacheObjectValueContext ctx = null;
try {
ctx = IgniteUtils.field(source, "cacheObjValCtx");
}
catch (Exception e) {
throw new IgniteException(e);
}
str = Base64.getEncoder().encodeToString(co.valueBytes(ctx));
}
catch (IgniteCheckedException e) {
throw new IgniteException(e);
}
}
if (sensitiveData == MD5)
str = ProcessSensitiveDataUtils.md5(str);
return str;
| 781
| 325
| 1,106
|
<methods>public void <init>(int, org.apache.ignite.internal.processors.cache.KeyCacheObject, org.apache.ignite.internal.processors.cache.CacheObject, org.apache.ignite.internal.processors.cache.GridCacheOperation, org.apache.ignite.internal.processors.cache.version.GridCacheVersion, org.apache.ignite.internal.processors.cache.version.GridCacheVersion, long, int, long, byte) ,public int cacheId() ,public long expireTime() ,public static byte flags(boolean) ,public static byte flags(boolean, boolean, boolean) ,public byte flags() ,public org.apache.ignite.internal.processors.cache.KeyCacheObject key() ,public org.apache.ignite.internal.processors.cache.version.GridCacheVersion nearXidVersion() ,public org.apache.ignite.internal.processors.cache.GridCacheOperation op() ,public long partitionCounter() ,public org.apache.ignite.internal.pagemem.wal.record.DataEntry partitionCounter(long) ,public int partitionId() ,public java.lang.String toString() ,public org.apache.ignite.internal.processors.cache.CacheObject value() ,public org.apache.ignite.internal.processors.cache.version.GridCacheVersion writeVersion() <variables>public static final byte EMPTY_FLAGS,public static final byte FROM_STORE_FLAG,public static final byte PRELOAD_FLAG,public static final byte PRIMARY_FLAG,protected int cacheId,protected long expireTime,protected byte flags,protected org.apache.ignite.internal.processors.cache.KeyCacheObject key,protected org.apache.ignite.internal.processors.cache.version.GridCacheVersion nearXidVer,protected org.apache.ignite.internal.processors.cache.GridCacheOperation op,protected long partCnt,protected int partId,protected org.apache.ignite.internal.processors.cache.CacheObject val,protected org.apache.ignite.internal.processors.cache.version.GridCacheVersion writeVer
|
apache_ignite
|
ignite/modules/dev-utils/src/main/java/org/apache/ignite/development/utils/IgniteWalConverter.java
|
IgniteWalConverter
|
getCurrentWalFilePath
|
class IgniteWalConverter {
/**
* @param args Args.
* @throws Exception If failed.
*/
public static void main(String[] args) {
final IgniteWalConverterArguments parameters = IgniteWalConverterArguments.parse(System.out, args);
if (parameters != null)
convert(System.out, parameters);
}
/**
* Write to out WAL log data in human-readable form.
*
* @param out Receiver of result.
* @param params Parameters.
*/
public static void convert(final PrintStream out, final IgniteWalConverterArguments params) {
System.setProperty(IgniteSystemProperties.IGNITE_TO_STRING_INCLUDE_SENSITIVE,
Boolean.toString(params.getProcessSensitiveData() == ProcessSensitiveData.HIDE));
System.setProperty(IgniteSystemProperties.IGNITE_PDS_SKIP_CRC, Boolean.toString(params.isSkipCrc()));
RecordV1Serializer.skipCrc = params.isSkipCrc();
System.setProperty(IgniteSystemProperties.IGNITE_TO_STRING_MAX_LENGTH, String.valueOf(Integer.MAX_VALUE));
final WalStat stat = params.isPrintStat() ? new WalStat() : null;
IgniteWalIteratorFactory.IteratorParametersBuilder iterParametersBuilder =
new IgniteWalIteratorFactory.IteratorParametersBuilder()
.pageSize(params.getPageSize())
.binaryMetadataFileStoreDir(params.getBinaryMetadataFileStoreDir())
.marshallerMappingFileStoreDir(params.getMarshallerMappingFileStoreDir())
.keepBinary(params.isKeepBinary());
if (params.getWalDir() != null)
iterParametersBuilder.filesOrDirs(params.getWalDir());
if (params.getWalArchiveDir() != null)
iterParametersBuilder.filesOrDirs(params.getWalArchiveDir());
final IgniteWalIteratorFactory factory = new IgniteWalIteratorFactory();
boolean printAlways = F.isEmpty(params.getRecordTypes());
try (WALIterator stIt = walIterator(factory.iterator(iterParametersBuilder), params.getPages())) {
String curWalPath = null;
while (stIt.hasNextX()) {
final String curRecordWalPath = getCurrentWalFilePath(stIt);
if (curWalPath == null || !curWalPath.equals(curRecordWalPath)) {
out.println("File: " + curRecordWalPath);
curWalPath = curRecordWalPath;
}
IgniteBiTuple<WALPointer, WALRecord> next = stIt.nextX();
final WALPointer pointer = next.get1();
final WALRecord record = next.get2();
if (stat != null)
stat.registerRecord(record, pointer, true);
if (printAlways || params.getRecordTypes().contains(record.type())) {
boolean print = true;
if (record instanceof TimeStampRecord)
print = withinTimeRange((TimeStampRecord)record, params.getFromTime(), params.getToTime());
final String recordStr = toString(record, params.getProcessSensitiveData());
if (print && (F.isEmpty(params.getRecordContainsText()) || recordStr.contains(params.getRecordContainsText())))
out.println(recordStr);
}
}
}
catch (Exception e) {
e.printStackTrace(out);
}
if (stat != null)
out.println("Statistic collected:\n" + stat.toString());
}
/**
* Checks if provided TimeStampRecord is within time range.
*
* @param rec Record.
* @param fromTime Lower bound for timestamp.
* @param toTime Upper bound for timestamp;
* @return {@code True} if timestamp is within range.
*/
private static boolean withinTimeRange(TimeStampRecord rec, Long fromTime, Long toTime) {
if (fromTime != null && rec.timestamp() < fromTime)
return false;
if (toTime != null && rec.timestamp() > toTime)
return false;
return true;
}
/**
* Get current wal file path, used in {@code WALIterator}.
*
* @param it WALIterator.
* @return Current wal file path.
*/
private static String getCurrentWalFilePath(WALIterator it) {<FILL_FUNCTION_BODY>}
/**
* Converting {@link WALRecord} to a string with sensitive data.
*
* @param walRecord Instance of {@link WALRecord}.
* @param sensitiveData Strategy for processing of sensitive data.
* @return String representation of {@link WALRecord}.
*/
private static String toString(WALRecord walRecord, ProcessSensitiveData sensitiveData) {
if (walRecord instanceof DataRecord) {
final DataRecord dataRecord = (DataRecord)walRecord;
int entryCnt = dataRecord.entryCount();
final List<DataEntry> entryWrappers = new ArrayList<>(entryCnt);
for (int i = 0; i < entryCnt; i++)
entryWrappers.add(new DataEntryWrapper(dataRecord.get(i), sensitiveData));
dataRecord.setWriteEntries(entryWrappers);
}
else if (walRecord instanceof MetastoreDataRecord)
walRecord = new MetastoreDataRecordWrapper((MetastoreDataRecord)walRecord, sensitiveData);
return walRecord.toString();
}
/**
* Getting WAL iterator.
*
* @param walIter WAL iterator.
* @param pageIds Pages for searching in format grpId:pageId.
* @return WAL iterator.
*/
private static WALIterator walIterator(
WALIterator walIter,
Collection<T2<Integer, Long>> pageIds
) throws IgniteCheckedException {
Predicate<IgniteBiTuple<WALPointer, WALRecord>> filter = null;
if (!pageIds.isEmpty()) {
Set<T2<Integer, Long>> grpAndPageIds0 = new HashSet<>(pageIds);
// Collect all (group, partition) partition pairs.
Set<T2<Integer, Integer>> grpAndParts = grpAndPageIds0.stream()
.map((tup) -> new T2<>(tup.get1(), PageIdUtils.partId(tup.get2())))
.collect(Collectors.toSet());
// Build WAL filter. (Checkoint, Page, Partition meta)
filter = checkpoint().or(pageOwner(grpAndPageIds0)).or(partitionMetaStateUpdate(grpAndParts));
}
return filter != null ? new FilteredWalIterator(walIter, filter) : walIter;
}
}
|
String res = null;
try {
WALIterator walIter = it instanceof FilteredWalIterator ? U.field(it, "delegateWalIter") : it;
Integer curIdx = U.field(walIter, "curIdx");
List<FileDescriptor> walFileDescriptors = U.field(walIter, "walFileDescriptors");
if (curIdx != null && walFileDescriptors != null && curIdx < walFileDescriptors.size())
res = walFileDescriptors.get(curIdx).getAbsolutePath();
}
catch (Exception e) {
e.printStackTrace();
}
return res;
| 1,762
| 178
| 1,940
|
<no_super_class>
|
apache_ignite
|
ignite/modules/direct-io/src/main/java/org/apache/ignite/internal/processors/cache/persistence/file/AlignedBuffersDirectFileIOFactory.java
|
AlignedBuffersDirectFileIOFactory
|
createManagedBuffer
|
class AlignedBuffersDirectFileIOFactory implements FileIOFactory {
/** Logger. */
private final IgniteLogger log;
/** Page size from durable memory. */
private final int pageSize;
/** Backup factory for files in case native is not available or not applicable. */
private final FileIOFactory backupFactory;
/** File system/os block size, negative value if library init was failed. */
private final int ioBlockSize;
/** Use backup factory, {@code true} if direct IO setup failed. */
private boolean useBackupFactory;
/** Thread local with buffers with capacity = one page {@code pageSize} and aligned using {@code fsBlockSize}. */
private ThreadLocal<ByteBuffer> tlbOnePageAligned;
/**
* Managed aligned buffers. This collection is used to free buffers, an for checking if buffer is known to be
* already aligned.
*/
private final ConcurrentHashMap<Long, Thread> managedAlignedBuffers = new ConcurrentHashMap<>();
/**
* Creates direct native IO factory.
*
* @param log Logger.
* @param storePath Storage path, used to check FS settings.
* @param pageSize durable memory page size.
* @param backupFactory fallback factory if init failed.
*/
public AlignedBuffersDirectFileIOFactory(
final IgniteLogger log,
final File storePath,
final int pageSize,
final FileIOFactory backupFactory) {
this.log = log;
this.pageSize = pageSize;
this.backupFactory = backupFactory;
useBackupFactory = true;
ioBlockSize = IgniteNativeIoLib.getDirectIOBlockSize(storePath.getAbsolutePath(), log);
if (!IgniteSystemProperties.getBoolean(IgniteSystemProperties.IGNITE_DIRECT_IO_ENABLED, true)) {
if (log.isInfoEnabled())
log.info("Direct IO is explicitly disabled by system property.");
return;
}
if (ioBlockSize > 0) {
int blkSize = ioBlockSize;
if (pageSize % blkSize != 0) {
U.warn(log, String.format("Unable to setup Direct IO for Ignite [pageSize=%d bytes;" +
" file system block size=%d]. For speeding up Ignite consider setting %s.setPageSize(%d)." +
" Direct IO is disabled.",
pageSize, blkSize, DataStorageConfiguration.class.getSimpleName(), blkSize));
}
else {
useBackupFactory = false;
tlbOnePageAligned = new ThreadLocal<ByteBuffer>() {
@Override protected ByteBuffer initialValue() {
return createManagedBuffer(pageSize);
}
};
if (log.isInfoEnabled()) {
log.info(String.format("Direct IO is enabled for block IO operations on aligned memory structures." +
" [block size = %d, durable memory page size = %d]", blkSize, pageSize));
}
}
}
else {
if (log.isInfoEnabled()) {
log.info(String.format("Direct IO library is not available on current operating system [%s]." +
" Direct IO is not enabled.", System.getProperty("os.version")));
}
}
}
/**
* <b>Note: </b> Use only if {@link #isDirectIoAvailable()}.
*
* @param size buffer size to allocate.
* @return new byte buffer.
*/
@NotNull ByteBuffer createManagedBuffer(int size) {<FILL_FUNCTION_BODY>}
/** {@inheritDoc} */
@Override public FileIO create(File file, OpenOption... modes) throws IOException {
if (useBackupFactory)
return backupFactory.create(file, modes);
return new AlignedBuffersDirectFileIO(ioBlockSize, pageSize, file, modes, tlbOnePageAligned, managedAlignedBuffers, log);
}
/**
* @return {@code true} if Direct IO can be used on current OS and file system settings
*/
boolean isDirectIoAvailable() {
return !useBackupFactory;
}
/**
* Managed aligned buffers and its associated threads. This collection is used to free buffers, an for checking if
* buffer is known to be already aligned.
*
* @return map address->thread.
*/
ConcurrentHashMap<Long, Thread> managedAlignedBuffers() {
return managedAlignedBuffers;
}
}
|
assert !useBackupFactory : "Direct IO is disabled, aligned managed buffer creation is disabled now";
assert managedAlignedBuffers != null : "Direct buffers not available";
ByteBuffer allocate = AlignedBuffers.allocate(ioBlockSize, size).order(ByteOrder.nativeOrder());
managedAlignedBuffers.put(GridUnsafe.bufferAddress(allocate), Thread.currentThread());
return allocate;
| 1,143
| 107
| 1,250
|
<no_super_class>
|
apache_ignite
|
ignite/modules/indexing/src/main/java/org/apache/ignite/internal/processors/query/h2/DmlStatementsProcessor.java
|
ModifyingEntryProcessor
|
getRemoveClosure
|
class ModifyingEntryProcessor implements EntryProcessor<Object, Object, Boolean> {
/** Value to expect. */
private final Object val;
/** Action to perform on entry. */
private final IgniteInClosure<MutableEntry<Object, Object>> entryModifier;
/** */
public ModifyingEntryProcessor(Object val, IgniteInClosure<MutableEntry<Object, Object>> entryModifier) {
assert val != null;
this.val = val;
this.entryModifier = entryModifier;
}
/** {@inheritDoc} */
@Override public Boolean process(MutableEntry<Object, Object> entry, Object... arguments)
throws EntryProcessorException {
if (!entry.exists())
return null; // Someone got ahead of us and removed this entry, let's skip it.
Object entryVal = entry.getValue();
if (entryVal == null)
return null;
// Something happened to the cache while we were performing map-reduce.
if (!F.eq(entryVal, val))
return false;
entryModifier.apply(entry);
return null; // To leave out only erroneous keys - nulls are skipped on results' processing.
}
}
/** Dummy anonymous class to advance RMV anonymous value to 5. */
private static final Runnable DUMMY_1 = new Runnable() {
@Override public void run() {
// No-op.
}
};
/** Dummy anonymous class to advance RMV anonymous value to 5. */
private static final Runnable DUMMY_2 = new Runnable() {
@Override public void run() {
// No-op.
}
};
/** Dummy anonymous class to advance RMV anonymous value to 5. */
private static final Runnable DUMMY_3 = new Runnable() {
@Override public void run() {
// No-op.
}
};
/** Remove updater for compatibility with < 2.7.0. Must not be moved around to keep at anonymous position 4. */
private static final IgniteInClosure<MutableEntry<Object, Object>> RMV_OLD =
new IgniteInClosure<MutableEntry<Object, Object>>() {
@Override public void apply(MutableEntry<Object, Object> e) {
e.remove();
}
};
/** Remove updater. Must not be moved around to keep at anonymous position 5. */
private static final IgniteInClosure<MutableEntry<Object, Object>> RMV =
new IgniteInClosure<MutableEntry<Object, Object>>() {
@Override public void apply(MutableEntry<Object, Object> e) {
e.remove();
}
};
/**
* Returns the remove closure based on the version of the primary node.
*
* @param node Primary node.
* @param key Key.
* @return Remove closure.
*/
public static IgniteInClosure<MutableEntry<Object, Object>> getRemoveClosure(ClusterNode node, Object key) {<FILL_FUNCTION_BODY>
|
assert node != null;
assert key != null;
IgniteInClosure<MutableEntry<Object, Object>> rmvC = RMV;
if (node.version().compareTo(RMV_ANON_CLS_POS_CHANGED_SINCE) < 0)
rmvC = RMV_OLD;
return rmvC;
| 794
| 100
| 894
|
<no_super_class>
|
apache_ignite
|
ignite/modules/indexing/src/main/java/org/apache/ignite/internal/processors/query/h2/H2StatementCache.java
|
H2StatementCache
|
queryFlags
|
class H2StatementCache {
/** Last usage. */
private volatile long lastUsage;
/** */
private final LinkedHashMap<H2CachedStatementKey, PreparedStatement> lruStmtCache;
/**
* @param size Maximum number of statements this cache can store.
*/
H2StatementCache(int size) {
lruStmtCache = new LinkedHashMap<H2CachedStatementKey, PreparedStatement>(size, .75f, true) {
@Override protected boolean removeEldestEntry(Map.Entry<H2CachedStatementKey, PreparedStatement> eldest) {
if (size() <= size)
return false;
U.closeQuiet(eldest.getValue());
return true;
}
};
}
/**
* Caches a statement.
*
* @param key Key associated with statement.
* @param stmt Statement which will be cached.
*/
void put(H2CachedStatementKey key, @NotNull PreparedStatement stmt) {
lastUsage = System.nanoTime();
lruStmtCache.put(key, stmt);
}
/**
* Retrieves cached statement.
*
* @param key Key for a statement.
* @return Statement associated with a key.
*/
@Nullable PreparedStatement get(H2CachedStatementKey key) {
lastUsage = System.nanoTime();
return lruStmtCache.get(key);
}
/**
* Checks if the current cache has not been used for at least {@code nanos} nanoseconds.
*
* @param nanos Interval in nanoseconds.
* @return {@code true} if the current cache has not been used for the specified period.
*/
boolean inactiveFor(long nanos) {
return System.nanoTime() - lastUsage >= nanos;
}
/**
* Remove statement for given schema and SQL.
*
* @param schemaName Schema name.
* @param sql SQL statement.
*/
void remove(String schemaName, String sql, byte qryFlags) {
lastUsage = System.nanoTime();
lruStmtCache.remove(new H2CachedStatementKey(schemaName, sql, qryFlags));
}
/**
* @return Cache size.
*/
int size() {
return lruStmtCache.size();
}
/** */
public static byte queryFlags(QueryDescriptor qryDesc) {
assert qryDesc != null;
return queryFlags(qryDesc.distributedJoins(), qryDesc.enforceJoinOrder());
}
/** */
public static byte queryFlags(boolean distributedJoins, boolean enforceJoinOrder) {<FILL_FUNCTION_BODY>}
}
|
return (byte)((distributedJoins ? 1 : 0) + (enforceJoinOrder ? 2 : 0));
| 714
| 34
| 748
|
<no_super_class>
|
apache_ignite
|
ignite/modules/indexing/src/main/java/org/apache/ignite/internal/processors/query/h2/H2TableEngine.java
|
H2TableEngine
|
createTable
|
class H2TableEngine implements TableEngine {
/** */
private static GridH2RowDescriptor rowDesc0;
/** */
private static H2TableDescriptor tblDesc0;
/** */
private static GridH2Table resTbl0;
/** */
private static IndexProcessor idxMgr0;
/**
* Creates table using given connection, DDL clause for given type descriptor and list of indexes.
*
* @param conn Connection.
* @param sql DDL clause.
* @param rowDesc Row descriptor.
* @param tblDesc Table descriptor.
* @throws SQLException If failed.
* @return Created table.
*/
public static synchronized GridH2Table createTable(
Connection conn,
String sql,
GridH2RowDescriptor rowDesc,
H2TableDescriptor tblDesc,
IndexProcessor idxMgr
)
throws SQLException {<FILL_FUNCTION_BODY>}
/** {@inheritDoc} */
@Override public TableBase createTable(CreateTableData createTblData) {
resTbl0 = new GridH2Table(createTblData, rowDesc0, tblDesc0, tblDesc0.cacheInfo());
return resTbl0;
}
}
|
rowDesc0 = rowDesc;
tblDesc0 = tblDesc;
try {
try (Statement s = conn.createStatement()) {
s.execute(sql + " engine \"" + H2TableEngine.class.getName() + "\"");
}
tblDesc.table(resTbl0);
return resTbl0;
}
finally {
resTbl0 = null;
tblDesc0 = null;
rowDesc0 = null;
}
| 317
| 129
| 446
|
<no_super_class>
|
apache_ignite
|
ignite/modules/indexing/src/main/java/org/apache/ignite/internal/processors/query/h2/QueryParameters.java
|
QueryParameters
|
toSingleBatchedArguments
|
class QueryParameters {
/** Arguments. */
private final Object[] args;
/** Partitions. */
private final int[] parts;
/** Timeout. */
private final int timeout;
/** Lazy flag. */
private final boolean lazy;
/** Page size. */
private final int pageSize;
/** Data page scan enabled flag. */
private final Boolean dataPageScanEnabled;
/** Nexted transactional mode. */
private final NestedTxMode nestedTxMode;
/** Auto-commit flag. */
private final boolean autoCommit;
/** Batched arguments. */
private final List<Object[]> batchedArgs;
/**
* Update internal batch size.
* Default is 1 to prevent deadlock on update where keys sequence are different in several concurrent updates.
*/
private final int updateBatchSize;
/**
* Constructor.
*
* @param args Arguments.
* @param parts Partitions.
* @param timeout Timeout.
* @param lazy Lazy flag.
* @param pageSize Page size.
* @param dataPageScanEnabled Data page scan enabled flag.
* @param nestedTxMode Nested TX mode.
* @param autoCommit Auto-commit flag.
* @param batchedArgs Batched arguments.
* @param updateBatchSize Update internal batch size.
*/
@SuppressWarnings("AssignmentOrReturnOfFieldWithMutableType")
QueryParameters(
Object[] args,
int[] parts,
int timeout,
boolean lazy,
int pageSize,
Boolean dataPageScanEnabled,
NestedTxMode nestedTxMode,
boolean autoCommit,
List<Object[]> batchedArgs,
int updateBatchSize
) {
this.args = args;
this.parts = parts;
this.timeout = timeout;
this.lazy = lazy;
this.pageSize = pageSize;
this.dataPageScanEnabled = dataPageScanEnabled;
this.nestedTxMode = nestedTxMode;
this.autoCommit = autoCommit;
this.batchedArgs = batchedArgs;
this.updateBatchSize = updateBatchSize;
}
/**
* @return Arguments.
*/
@SuppressWarnings("AssignmentOrReturnOfFieldWithMutableType")
public Object[] arguments() {
return args;
}
/**
* @return Partitions.
*/
@SuppressWarnings("AssignmentOrReturnOfFieldWithMutableType")
public int[] partitions() {
return parts;
}
/**
* @return Timeout.
*/
public int timeout() {
return timeout;
}
/**
* @return Lazy flag.
*/
public boolean lazy() {
return lazy;
}
/**
* @return Page size.
*/
public int pageSize() {
return pageSize;
}
/**
* @return Data page scan enabled flag.
*/
public Boolean dataPageScanEnabled() {
return dataPageScanEnabled;
}
/**
* @return Nested TX mode.
*/
public NestedTxMode nestedTxMode() {
return nestedTxMode;
}
/**
* @return Auto-commit flag.
*/
public boolean autoCommit() {
return autoCommit;
}
/**
* @return Batched arguments.
*/
@SuppressWarnings("AssignmentOrReturnOfFieldWithMutableType")
public List<Object[]> batchedArguments() {
return batchedArgs;
}
/**
* Gets update internal bach size.
* Default is 1 to prevent deadlock on update where keys sequance are different in several concurrent updates.
*
* @return Update internal batch size
*/
public int updateBatchSize() {
return updateBatchSize;
}
/**
* Convert current batched arguments to a form with single arguments.
*
* @param args Arguments.
* @return Result.
*/
public QueryParameters toSingleBatchedArguments(Object[] args) {<FILL_FUNCTION_BODY>}
}
|
return new QueryParameters(
args,
this.parts,
this.timeout,
this.lazy,
this.pageSize,
this.dataPageScanEnabled,
this.nestedTxMode,
this.autoCommit,
null,
this.updateBatchSize
);
| 1,066
| 80
| 1,146
|
<no_super_class>
|
apache_ignite
|
ignite/modules/indexing/src/main/java/org/apache/ignite/internal/processors/query/h2/opt/GridH2Cursor.java
|
GridH2Cursor
|
next
|
class GridH2Cursor implements Cursor {
/** */
public static final Cursor EMPTY = new Cursor() {
@Override public Row get() {
return null;
}
@Override public SearchRow getSearchRow() {
return null;
}
@Override public boolean next() {
return false;
}
@Override public boolean previous() {
return false;
}
};
/** */
protected Iterator<? extends Row> iter;
/** */
protected Row cur;
/**
* Constructor.
*
* @param iter Rows iterator.
*/
public GridH2Cursor(Iterator<? extends Row> iter) {
assert iter != null;
this.iter = iter;
}
/** {@inheritDoc} */
@Override public Row get() {
return cur;
}
/** {@inheritDoc} */
@Override public SearchRow getSearchRow() {
return get();
}
/** {@inheritDoc} */
@Override public boolean next() {<FILL_FUNCTION_BODY>}
/** {@inheritDoc} */
@Override public boolean previous() {
// Should never be called.
throw DbException.getUnsupportedException("previous");
}
}
|
cur = iter.hasNext() ? iter.next() : null;
return cur != null;
| 329
| 29
| 358
|
<no_super_class>
|
apache_ignite
|
ignite/modules/indexing/src/main/java/org/apache/ignite/internal/processors/query/h2/opt/GridH2ProxySpatialIndex.java
|
GridH2ProxySpatialIndex
|
findByGeometry
|
class GridH2ProxySpatialIndex extends GridH2ProxyIndex implements SpatialIndex {
/**
*
* @param tbl Table.
* @param name Name of the proxy index.
* @param colsList Column list for the proxy index.
* @param idx Target index.
*/
public GridH2ProxySpatialIndex(GridH2Table tbl,
String name,
List<IndexColumn> colsList,
Index idx) {
super(tbl, name, colsList, idx);
}
/** {@inheritDoc} */
@Override public double getCost(Session ses, int[] masks, TableFilter[] filters, int filter,
SortOrder sortOrder, HashSet<Column> cols) {
return SpatialTreeIndex.getCostRangeIndex(masks, columns) / 10;
}
/** {@inheritDoc} */
@Override public Cursor findByGeometry(TableFilter filter, SearchRow first, SearchRow last, SearchRow intersection) {<FILL_FUNCTION_BODY>}
}
|
GridQueryRowDescriptor desc = ((GridH2Table)idx.getTable()).rowDescriptor();
return ((SpatialIndex)idx).findByGeometry(filter,
prepareProxyIndexRow(desc, first),
prepareProxyIndexRow(desc, last),
prepareProxyIndexRow(desc, intersection));
| 260
| 76
| 336
|
<methods>public void <init>(org.apache.ignite.internal.processors.query.h2.opt.GridH2Table, java.lang.String, List<IndexColumn>, Index) ,public void add(Session, Row) ,public boolean canGetFirstOrLast() ,public void checkRename() ,public void close(Session) ,public IndexLookupBatch createLookupBatch(TableFilter[], int) ,public Cursor find(Session, SearchRow, SearchRow) ,public Cursor findFirstOrLast(Session, boolean) ,public double getCost(Session, int[], TableFilter[], int, SortOrder, HashSet<Column>) ,public long getDiskSpaceUsed() ,public long getRowCount(Session) ,public long getRowCountApproximation() ,public boolean needRebuild() ,public static SearchRow prepareProxyIndexRow(org.apache.ignite.internal.processors.query.GridQueryRowDescriptor, SearchRow) ,public void remove(Session, Row) ,public void remove(Session) ,public void truncate(Session) ,public Index underlyingIndex() <variables>protected Index idx
|
apache_ignite
|
ignite/modules/indexing/src/main/java/org/apache/ignite/internal/processors/query/h2/opt/H2PlainRowPair.java
|
H2PlainRowPair
|
setValue
|
class H2PlainRowPair extends H2Row {
/** */
private Value v1;
/** */
private Value v2;
/**
* @param v1 First value.
* @param v2 Second value.
*/
public H2PlainRowPair(Value v1, Value v2) {
this.v1 = v1;
this.v2 = v2;
}
/** {@inheritDoc} */
@Override public int getColumnCount() {
return 2;
}
/** {@inheritDoc} */
@Override public Value getValue(int idx) {
return idx == 0 ? v1 : v2;
}
/** {@inheritDoc} */
@Override public void setValue(int idx, Value v) {<FILL_FUNCTION_BODY>}
/** {@inheritDoc} */
@Override public boolean indexSearchRow() {
return true;
}
/** {@inheritDoc} */
@Override public String toString() {
return S.toString(H2PlainRowPair.class, this);
}
}
|
if (idx == 0)
v1 = v;
else {
assert idx == 1 : idx;
v2 = v;
}
| 279
| 42
| 321
|
<methods>public non-sealed void <init>() ,public void commit() ,public long expireTime() ,public int getByteCount(Data) ,public Row getCopy() ,public long getKey() ,public int getMemory() ,public int getSessionId() ,public Value[] getValueList() ,public int getVersion() ,public abstract boolean indexSearchRow() ,public boolean isDeleted() ,public boolean isEmpty() ,public void setDeleted(boolean) ,public void setKey(long) ,public void setKeyAndVersion(SearchRow) ,public void setSessionId(int) ,public void setVersion(int) <variables>
|
apache_ignite
|
ignite/modules/indexing/src/main/java/org/apache/ignite/internal/processors/query/h2/opt/H2PlainRowSingle.java
|
H2PlainRowSingle
|
setValue
|
class H2PlainRowSingle extends H2Row {
/** */
private Value v;
/**
* @param v Value.
*/
public H2PlainRowSingle(Value v) {
this.v = v;
}
/** {@inheritDoc} */
@Override public int getColumnCount() {
return 1;
}
/** {@inheritDoc} */
@Override public Value getValue(int idx) {
assert idx == 0 : idx;
return v;
}
/** {@inheritDoc} */
@Override public void setValue(int idx, Value v) {<FILL_FUNCTION_BODY>}
/** {@inheritDoc} */
@Override public boolean indexSearchRow() {
return true;
}
/** {@inheritDoc} */
@Override public String toString() {
return S.toString(H2PlainRowSingle.class, this);
}
}
|
assert idx == 0 : idx;
this.v = v;
| 239
| 21
| 260
|
<methods>public non-sealed void <init>() ,public void commit() ,public long expireTime() ,public int getByteCount(Data) ,public Row getCopy() ,public long getKey() ,public int getMemory() ,public int getSessionId() ,public Value[] getValueList() ,public int getVersion() ,public abstract boolean indexSearchRow() ,public boolean isDeleted() ,public boolean isEmpty() ,public void setDeleted(boolean) ,public void setKey(long) ,public void setKeyAndVersion(SearchRow) ,public void setSessionId(int) ,public void setVersion(int) <variables>
|
apache_ignite
|
ignite/modules/indexing/src/main/java/org/apache/ignite/internal/processors/query/h2/opt/QueryContextKey.java
|
QueryContextKey
|
hashCode
|
class QueryContextKey {
/** */
private final UUID nodeId;
/** */
private final long qryId;
/** */
private final int segmentId;
/**
* Constructor.
*
* @param nodeId The node who initiated the query.
* @param qryId The query ID.
* @param segmentId Index segment ID.
*/
public QueryContextKey(UUID nodeId, long qryId, int segmentId) {
assert nodeId != null;
this.nodeId = nodeId;
this.qryId = qryId;
this.segmentId = segmentId;
}
/**
* @return Node ID.
*/
public UUID nodeId() {
return nodeId;
}
/**
* @return Query ID.
*/
public long queryId() {
return qryId;
}
/**
* @return Segment ID.
*/
public int segmentId() {
return segmentId;
}
/** {@inheritDoc} */
@Override public boolean equals(Object o) {
if (this == o)
return true;
if (o == null || getClass() != o.getClass())
return false;
QueryContextKey other = (QueryContextKey)o;
return qryId == other.qryId && segmentId == other.segmentId && F.eq(nodeId, other.nodeId);
}
/** {@inheritDoc} */
@Override public int hashCode() {<FILL_FUNCTION_BODY>}
/** {@inheritDoc} */
@Override public String toString() {
return S.toString(QueryContextKey.class, this);
}
}
|
int res = nodeId.hashCode();
res = 31 * res + (int)(qryId ^ (qryId >>> 32));
res = 31 * res + segmentId;
return res;
| 445
| 59
| 504
|
<no_super_class>
|
apache_ignite
|
ignite/modules/indexing/src/main/java/org/apache/ignite/internal/processors/query/h2/opt/join/DistributedJoinContext.java
|
DistributedJoinContext
|
nodeForPartition
|
class DistributedJoinContext {
/** */
private final AffinityTopologyVersion topVer;
/** */
private final Map<UUID, int[]> partsMap;
/** */
private final UUID originNodeId;
/** */
private final long qryId;
/** */
private final int segment;
/** */
private final int pageSize;
/** Range streams for indexes. */
private Map<Integer, Object> streams;
/** Range sources for indexes. */
private Map<SourceKey, Object> sources;
/** */
private int batchLookupIdGen;
/** */
private UUID[] partsNodes;
/** */
private volatile boolean cancelled;
/**
* Constructor.
*
* @param topVer Topology version.
* @param partsMap Partitions map.
* @param originNodeId ID of the node started the query.
* @param qryId Query ID.
* @param segment Segment.
* @param pageSize Pahe size.
*/
@SuppressWarnings("AssignmentOrReturnOfFieldWithMutableType")
public DistributedJoinContext(
AffinityTopologyVersion topVer,
Map<UUID, int[]> partsMap,
UUID originNodeId,
long qryId,
int segment,
int pageSize
) {
this.topVer = topVer;
this.partsMap = partsMap;
this.originNodeId = originNodeId;
this.qryId = qryId;
this.segment = segment;
this.pageSize = pageSize;
}
/**
* @return Affinity topology version.
*/
public AffinityTopologyVersion topologyVersion() {
return topVer;
}
/**
* @return Partitions map.
*/
@SuppressWarnings("AssignmentOrReturnOfFieldWithMutableType")
public Map<UUID, int[]> partitionsMap() {
return partsMap;
}
/**
* @return Origin node ID.
*/
public UUID originNodeId() {
return originNodeId;
}
/**
* @return Query request ID.
*/
public long queryId() {
return qryId;
}
/**
* @return index segment ID.
*/
public int segment() {
return segment;
}
/**
* @return Page size.
*/
public int pageSize() {
return pageSize;
}
/**
* @param p Partition.
* @param cctx Cache context.
* @return Owning node ID.
*/
public UUID nodeForPartition(int p, GridCacheContext<?, ?> cctx) {<FILL_FUNCTION_BODY>}
/**
* @param batchLookupId Batch lookup ID.
* @param streams Range streams.
*/
public synchronized void putStreams(int batchLookupId, Object streams) {
if (this.streams == null) {
if (streams == null)
return;
this.streams = new HashMap<>();
}
if (streams == null)
this.streams.remove(batchLookupId);
else
this.streams.put(batchLookupId, streams);
}
/**
* @param batchLookupId Batch lookup ID.
* @return Range streams.
*/
@SuppressWarnings("unchecked")
public synchronized <T> T getStreams(int batchLookupId) {
if (streams == null)
return null;
return (T)streams.get(batchLookupId);
}
/**
* @param ownerId Owner node ID.
* @param segmentId Index segment ID.
* @param batchLookupId Batch lookup ID.
* @param src Range source.
*/
public synchronized void putSource(UUID ownerId, int segmentId, int batchLookupId, Object src) {
SourceKey srcKey = new SourceKey(ownerId, segmentId, batchLookupId);
if (src != null) {
if (sources == null)
sources = new HashMap<>();
sources.put(srcKey, src);
}
else if (sources != null)
sources.remove(srcKey);
}
/**
* @param ownerId Owner node ID.
* @param segmentId Index segment ID.
* @param batchLookupId Batch lookup ID.
* @return Range source.
*/
@SuppressWarnings("unchecked")
public synchronized <T> T getSource(UUID ownerId, int segmentId, int batchLookupId) {
if (sources == null)
return null;
return (T)sources.get(new SourceKey(ownerId, segmentId, batchLookupId));
}
/**
* @return Next batch ID.
*/
public int nextBatchLookupId() {
return ++batchLookupIdGen;
}
/**
* @return Cleared flag.
*/
public boolean isCancelled() {
return cancelled;
}
/**
* Mark as cleared.
*/
public void cancel() {
cancelled = true;
}
/** {@inheritDoc} */
@Override public String toString() {
return S.toString(DistributedJoinContext.class, this);
}
}
|
UUID[] nodeIds = partsNodes;
if (nodeIds == null) {
assert partsMap != null;
nodeIds = new UUID[cctx.affinity().partitions()];
for (Map.Entry<UUID, int[]> e : partsMap.entrySet()) {
UUID nodeId = e.getKey();
int[] nodeParts = e.getValue();
assert nodeId != null;
assert !F.isEmpty(nodeParts);
for (int part : nodeParts) {
assert nodeIds[part] == null;
nodeIds[part] = nodeId;
}
}
partsNodes = nodeIds;
}
return nodeIds[p];
| 1,387
| 183
| 1,570
|
<no_super_class>
|
apache_ignite
|
ignite/modules/indexing/src/main/java/org/apache/ignite/internal/processors/query/h2/opt/join/SegmentKey.java
|
SegmentKey
|
equals
|
class SegmentKey {
/** */
private final ClusterNode node;
/** */
private final int segmentId;
/**
* Constructor.
*
* @param node Node.
* @param segmentId Segment ID.
*/
public SegmentKey(ClusterNode node, int segmentId) {
assert node != null;
this.node = node;
this.segmentId = segmentId;
}
/**
* @return Node.
*/
public ClusterNode node() {
return node;
}
/**
* @return Segment ID.
*/
public int segmentId() {
return segmentId;
}
/** {@inheritDoc} */
@Override public boolean equals(Object o) {<FILL_FUNCTION_BODY>}
/** {@inheritDoc} */
@Override public int hashCode() {
int res = node.hashCode();
res = 31 * res + segmentId;
return res;
}
}
|
if (this == o)
return true;
if (o == null || getClass() != o.getClass())
return false;
SegmentKey key = (SegmentKey)o;
return segmentId == key.segmentId && node.id().equals(key.node.id());
| 264
| 80
| 344
|
<no_super_class>
|
apache_ignite
|
ignite/modules/indexing/src/main/java/org/apache/ignite/internal/processors/query/h2/opt/join/SourceKey.java
|
SourceKey
|
hashCode
|
class SourceKey {
/** */
private final UUID ownerId;
/** */
private final int segmentId;
/** */
private final int batchLookupId;
/**
* @param ownerId Owner node ID.
* @param segmentId Index segment ID.
* @param batchLookupId Batch lookup ID.
*/
public SourceKey(UUID ownerId, int segmentId, int batchLookupId) {
this.ownerId = ownerId;
this.segmentId = segmentId;
this.batchLookupId = batchLookupId;
}
/** {@inheritDoc} */
@Override public boolean equals(Object o) {
if (!(o instanceof SourceKey))
return false;
SourceKey srcKey = (SourceKey)o;
return batchLookupId == srcKey.batchLookupId && segmentId == srcKey.segmentId &&
ownerId.equals(srcKey.ownerId);
}
/** {@inheritDoc} */
@Override public int hashCode() {<FILL_FUNCTION_BODY>}
}
|
int hash = ownerId.hashCode();
hash = 31 * hash + segmentId;
hash = 31 * hash + batchLookupId;
return hash;
| 274
| 47
| 321
|
<no_super_class>
|
apache_ignite
|
ignite/modules/indexing/src/main/java/org/apache/ignite/internal/processors/query/h2/sql/GridSqlElement.java
|
GridSqlElement
|
child
|
class GridSqlElement implements GridSqlAst {
/** */
private final List<GridSqlAst> children;
/** */
private GridSqlType resultType;
/**
* @param children Initial child list.
*/
protected GridSqlElement(List<GridSqlAst> children) {
assert children != null;
this.children = children;
}
/** {@inheritDoc} */
@Override public GridSqlType resultType() {
return resultType;
}
/**
* @param type Optional expression result type (if this is an expression and result type is known).
* @return {@code this}.
*/
public GridSqlElement resultType(GridSqlType type) {
resultType = type;
return this;
}
/**
* @param expr Expr.
* @return {@code this}.
*/
public GridSqlElement addChild(GridSqlAst expr) {
if (expr == null)
throw new NullPointerException();
children.add(expr);
return this;
}
/** {@inheritDoc} */
@Override public <E extends GridSqlAst> E child() {
return child(0);
}
/** {@inheritDoc} */
@SuppressWarnings("unchecked")
@Override public <E extends GridSqlAst> E child(int idx) {
return (E)children.get(idx);
}
/** {@inheritDoc} */
@Override public <E extends GridSqlAst> void child(int idx, E child) {<FILL_FUNCTION_BODY>}
/** {@inheritDoc} */
@Override public int size() {
return children.size();
}
/** {@inheritDoc} */
@Override public String toString() {
return getSQL();
}
/** {@inheritDoc} */
@Override public int hashCode() {
throw new IllegalStateException();
}
/** {@inheritDoc} */
@Override public boolean equals(Object o) {
return this == o || (!(o == null || getClass() != o.getClass()) &&
children.equals(((GridSqlElement)o).children));
}
}
|
if (child == null)
throw new NullPointerException();
children.set(idx, child);
| 552
| 30
| 582
|
<no_super_class>
|
apache_ignite
|
ignite/modules/indexing/src/main/java/org/apache/ignite/internal/processors/query/h2/sql/GridSqlFunction.java
|
GridSqlFunction
|
getSQL
|
class GridSqlFunction extends GridSqlElement {
/** */
private static final Map<String, GridSqlFunctionType> TYPE_MAP = new HashMap<>();
/*
*
*/
static {
for (GridSqlFunctionType type : GridSqlFunctionType.values())
TYPE_MAP.put(type.name(), type);
}
/** */
private final String schema;
/** */
private final String name;
/** */
protected final GridSqlFunctionType type;
/**
* @param type Function type.
*/
public GridSqlFunction(GridSqlFunctionType type) {
this(null, type, type.functionName());
}
/**
* @param schema Schema.
* @param type Type.
* @param name Name.
*/
private GridSqlFunction(String schema, GridSqlFunctionType type, String name) {
super(new ArrayList<GridSqlAst>());
if (name == null)
throw new NullPointerException("name");
if (type == null)
type = UNKNOWN_FUNCTION;
this.schema = schema;
this.name = name;
this.type = type;
}
/**
* @param schema Schema.
* @param name Name.
*/
public GridSqlFunction(String schema, String name) {
this(schema, TYPE_MAP.get(name), name);
}
/** {@inheritDoc} */
@Override public String getSQL() {<FILL_FUNCTION_BODY>}
/**
* @return Name.
*/
public String name() {
return name;
}
/**
* @return Type.
*/
public GridSqlFunctionType type() {
return type;
}
}
|
StatementBuilder buff = new StatementBuilder();
if (schema != null)
buff.append(Parser.quoteIdentifier(schema)).append('.');
// We don't need to quote identifier as long as H2 never does so with function names when generating plan SQL.
// On the other hand, quoting identifiers that also serve as keywords (like CURRENT_DATE() and CURRENT_DATE)
// turns CURRENT_DATE() into "CURRENT_DATE"(), which is not good.
buff.append(name);
if (type == CASE) {
buff.append(' ').append(child().getSQL());
for (int i = 1, len = size() - 1; i < len; i += 2) {
buff.append(" WHEN ").append(child(i).getSQL());
buff.append(" THEN ").append(child(i + 1).getSQL());
}
if ((size() & 1) == 0)
buff.append(" ELSE ").append(child(size() - 1).getSQL());
return buff.append(" END").toString();
}
buff.append('(');
switch (type) {
case CAST:
case CONVERT:
assert size() == 1;
String castType = resultType().sql();
assert !F.isEmpty(castType) : castType;
buff.append(child().getSQL());
buff.append(type == CAST ? " AS " : ",");
buff.append(castType);
break;
case EXTRACT:
ValueString v = (ValueString)((GridSqlConst)child(0)).value();
buff.append(v.getString()).append(" FROM ").append(child(1).getSQL());
break;
case TABLE:
for (int i = 0; i < size(); i++) {
buff.appendExceptFirst(", ");
GridSqlElement e = child(i);
// id int = ?, name varchar = ('aaa', 'bbb')
buff.append(Parser.quoteIdentifier(((GridSqlAlias)e).alias()))
.append(' ')
.append(e.resultType().sql())
.append('=')
.append(e.child().getSQL());
}
break;
default:
for (int i = 0; i < size(); i++) {
buff.appendExceptFirst(", ");
buff.append(child(i).getSQL());
}
}
return buff.append(')').toString();
| 453
| 643
| 1,096
|
<methods>public org.apache.ignite.internal.processors.query.h2.sql.GridSqlElement addChild(org.apache.ignite.internal.processors.query.h2.sql.GridSqlAst) ,public E child() ,public E child(int) ,public void child(int, E) ,public boolean equals(java.lang.Object) ,public int hashCode() ,public org.apache.ignite.internal.processors.query.h2.sql.GridSqlType resultType() ,public org.apache.ignite.internal.processors.query.h2.sql.GridSqlElement resultType(org.apache.ignite.internal.processors.query.h2.sql.GridSqlType) ,public int size() ,public java.lang.String toString() <variables>private final non-sealed List<org.apache.ignite.internal.processors.query.h2.sql.GridSqlAst> children,private org.apache.ignite.internal.processors.query.h2.sql.GridSqlType resultType
|
apache_ignite
|
ignite/modules/indexing/src/main/java/org/apache/ignite/internal/processors/query/h2/sql/GridSqlQuery.java
|
GridSqlQuery
|
child
|
class GridSqlQuery extends GridSqlStatement implements GridSqlAst {
/** */
public static final int OFFSET_CHILD = 0;
/** */
public static final int LIMIT_CHILD = 1;
/** */
protected List<GridSqlSortColumn> sort = new ArrayList<>();
/** */
private GridSqlAst offset;
/**
* @return Offset.
*/
public GridSqlAst offset() {
return offset;
}
/**
* @param offset Offset.
*/
public void offset(GridSqlAst offset) {
this.offset = offset;
}
/**
* @return Sort.
*/
public List<GridSqlSortColumn> sort() {
return sort;
}
/**
*
*/
public void clearSort() {
sort = new ArrayList<>();
}
/**
* @param sortCol The sort column.
*/
public void addSort(GridSqlSortColumn sortCol) {
sort.add(sortCol);
}
/**
* @return Number of visible columns.
*/
protected abstract int visibleColumns();
/**
* @param col Column index.
* @return Expression for column index.
*/
protected abstract GridSqlAst column(int col);
/** {@inheritDoc} */
@Override public GridSqlType resultType() {
return GridSqlType.RESULT_SET;
}
/** {@inheritDoc} */
@Override public <E extends GridSqlAst> E child() {
return child(0);
}
/** {@inheritDoc} */
@Override public <E extends GridSqlAst> E child(int childIdx) {<FILL_FUNCTION_BODY>}
/**
* @param x Element.
* @return Empty placeholder if the element is {@code null}.
*/
@SuppressWarnings("unchecked")
protected static <E extends GridSqlAst> E maskNull(GridSqlAst x, GridSqlAst dflt) {
return (E)(x == null ? dflt : x);
}
/** {@inheritDoc} */
@Override public <E extends GridSqlAst> void child(int childIdx, E child) {
switch (childIdx) {
case OFFSET_CHILD:
offset = child;
break;
case LIMIT_CHILD:
limit = child;
break;
default:
throw new IllegalStateException("Child index: " + childIdx);
}
}
/**
* @return If this is a simple query with no conditions, expressions, sorting, etc...
*/
public abstract boolean skipMergeTable();
/**
* @param buff Statement builder.
*/
protected void getSortLimitSQL(StatementBuilder buff) {
if (!sort.isEmpty()) {
buff.append(delimeter()).append("ORDER BY ");
int visibleCols = visibleColumns();
buff.resetCount();
for (GridSqlSortColumn col : sort) {
buff.appendExceptFirst(", ");
int idx = col.column();
assert idx >= 0 : idx;
if (idx < visibleCols)
buff.append(idx + 1);
else {
GridSqlAst expr = column(idx);
if (expr == null) // For plain select should never be null, for union H2 itself can't parse query.
throw new IllegalStateException("Failed to build query: " + buff.toString());
if (expr instanceof GridSqlAlias)
expr = expr.child(0);
buff.append('=').append(StringUtils.unEnclose(expr.getSQL()));
}
if (!col.asc())
buff.append(" DESC");
if (col.nullsFirst())
buff.append(" NULLS FIRST");
else if (col.nullsLast())
buff.append(" NULLS LAST");
}
}
if (limit != null)
buff.append(" LIMIT ").append(StringUtils.unEnclose(limit.getSQL()));
if (offset != null)
buff.append(" OFFSET ").append(StringUtils.unEnclose(offset.getSQL()));
}
/**
* Whether offset or limit exists.
*
* @return {@code true} If we have OFFSET LIMIT.
*/
public boolean hasOffsetLimit() {
return limit() != null || offset() != null;
}
}
|
switch (childIdx) {
case OFFSET_CHILD:
return maskNull(offset, GridSqlPlaceholder.EMPTY);
case LIMIT_CHILD:
return maskNull(limit, GridSqlPlaceholder.EMPTY);
default:
throw new IllegalStateException("Child index: " + childIdx);
}
| 1,134
| 89
| 1,223
|
<methods>public non-sealed void <init>() ,public org.apache.ignite.internal.processors.query.h2.sql.GridSqlStatement explain(boolean) ,public boolean explain() ,public abstract java.lang.String getSQL() ,public void limit(org.apache.ignite.internal.processors.query.h2.sql.GridSqlAst) ,public org.apache.ignite.internal.processors.query.h2.sql.GridSqlAst limit() ,public java.lang.String toString() <variables>private boolean explain,protected org.apache.ignite.internal.processors.query.h2.sql.GridSqlAst limit
|
apache_ignite
|
ignite/modules/indexing/src/main/java/org/apache/ignite/internal/processors/query/h2/sql/GridSqlUnion.java
|
GridSqlUnion
|
size
|
class GridSqlUnion extends GridSqlQuery {
/** */
public static final int LEFT_CHILD = 2;
/** */
public static final int RIGHT_CHILD = 3;
/** */
private SelectUnion.UnionType unionType;
/** */
private GridSqlQuery right;
/** */
private GridSqlQuery left;
/** {@inheritDoc} */
@SuppressWarnings("unchecked")
@Override public <E extends GridSqlAst> E child(int childIdx) {
if (childIdx < LEFT_CHILD)
return super.child(childIdx);
switch (childIdx) {
case LEFT_CHILD:
assert left != null;
return (E)left;
case RIGHT_CHILD:
assert right != null;
return (E)right;
default:
throw new IllegalStateException("Child index: " + childIdx);
}
}
/** {@inheritDoc} */
@Override public <E extends GridSqlAst> void child(int childIdx, E child) {
if (childIdx < LEFT_CHILD) {
super.child(childIdx, child);
return;
}
switch (childIdx) {
case LEFT_CHILD:
left = (GridSqlQuery)child;
break;
case RIGHT_CHILD:
right = (GridSqlQuery)child;
break;
default:
throw new IllegalStateException("Child index: " + childIdx);
}
}
/** {@inheritDoc} */
@Override public int size() {<FILL_FUNCTION_BODY>}
/** {@inheritDoc} */
@Override protected int visibleColumns() {
return left.visibleColumns();
}
/** {@inheritDoc} */
@Override protected GridSqlElement column(int col) {
throw new IllegalStateException();
}
/** {@inheritDoc} */
@Override public String getSQL() {
char delim = delimeter();
StatementBuilder buff = new StatementBuilder(explain() ? "EXPLAIN " + delim : "");
buff.append('(').append(left.getSQL()).append(')');
switch (unionType()) {
case UNION_ALL:
buff.append(delim).append("UNION ALL").append(delim);
break;
case UNION:
buff.append(delim).append("UNION").append(delim);
break;
case INTERSECT:
buff.append(delim).append("INTERSECT").append(delim);
break;
case EXCEPT:
buff.append(delim).append("EXCEPT").append(delim);
break;
default:
throw new CacheException("type=" + unionType);
}
buff.append('(').append(right.getSQL()).append(')');
getSortLimitSQL(buff);
return buff.toString();
}
/** {@inheritDoc} */
@Override public boolean skipMergeTable() {
return unionType() == SelectUnion.UnionType.UNION_ALL && sort().isEmpty() &&
offset() == null && limit() == null &&
left().skipMergeTable() && right().skipMergeTable();
}
/**
* @return Union type.
*/
public SelectUnion.UnionType unionType() {
return unionType;
}
/**
* @param unionType New union type.
*/
public void unionType(SelectUnion.UnionType unionType) {
this.unionType = unionType;
}
/**
* @return Right.
*/
public GridSqlQuery right() {
return right;
}
/**
* @param right New right.
*/
public void right(GridSqlQuery right) {
this.right = right;
}
/**
* @return Left.
*/
public GridSqlQuery left() {
return left;
}
/**
* @param left New left.
*/
public void left(GridSqlQuery left) {
this.left = left;
}
}
|
return 4; // OFFSET + LIMIT + LEFT + RIGHT
| 1,082
| 20
| 1,102
|
<methods>public non-sealed void <init>() ,public void addSort(org.apache.ignite.internal.processors.query.h2.sql.GridSqlSortColumn) ,public E child() ,public E child(int) ,public void child(int, E) ,public void clearSort() ,public boolean hasOffsetLimit() ,public org.apache.ignite.internal.processors.query.h2.sql.GridSqlAst offset() ,public void offset(org.apache.ignite.internal.processors.query.h2.sql.GridSqlAst) ,public org.apache.ignite.internal.processors.query.h2.sql.GridSqlType resultType() ,public abstract boolean skipMergeTable() ,public List<org.apache.ignite.internal.processors.query.h2.sql.GridSqlSortColumn> sort() <variables>public static final int LIMIT_CHILD,public static final int OFFSET_CHILD,private org.apache.ignite.internal.processors.query.h2.sql.GridSqlAst offset,protected List<org.apache.ignite.internal.processors.query.h2.sql.GridSqlSortColumn> sort
|
apache_ignite
|
ignite/modules/indexing/src/main/java/org/apache/ignite/internal/processors/query/h2/sys/view/SqlAbstractLocalSystemView.java
|
SqlAbstractLocalSystemView
|
toStringSafe
|
class SqlAbstractLocalSystemView extends SqlAbstractSystemView {
/**
* @param tblName Table name.
* @param desc Description.
* @param ctx Context.
* @param indexes Indexes.
* @param cols Columns.
*/
protected SqlAbstractLocalSystemView(String tblName, String desc, GridKernalContext ctx, String[] indexes,
Column... cols) {
super(tblName, desc, ctx, cols, indexes);
assert tblName != null;
assert cols != null;
}
/**
* @param tblName Table name.
* @param desc Description.
* @param ctx Context.
* @param indexedCols Indexed columns.
* @param cols Columns.
*/
protected SqlAbstractLocalSystemView(String tblName, String desc, GridKernalContext ctx, String indexedCols,
Column... cols) {
this(tblName, desc, ctx, new String[] {indexedCols}, cols);
}
/**
* @param tblName Table name.
* @param desc Description.
* @param ctx Context.
* @param cols Columns.
*/
@SuppressWarnings("ZeroLengthArrayAllocation")
protected SqlAbstractLocalSystemView(String tblName, String desc, GridKernalContext ctx, Column... cols) {
this(tblName, desc, ctx, new String[] {}, cols);
}
/**
* @param ses Session.
* @param data Data for each column.
*/
protected Row createRow(Session ses, Object... data) {
Value[] values = new Value[data.length];
for (int i = 0; i < data.length; i++) {
Object o = data[i];
Value v = (o == null) ? ValueNull.INSTANCE :
(o instanceof Value) ? (Value)o : ValueString.get(o.toString());
values[i] = cols[i].convert(v);
}
return ses.getDatabase().createRow(values, 0);
}
/**
* Gets column index by name.
*
* @param colName Column name.
*/
protected int getColumnIndex(String colName) {
assert colName != null;
for (int i = 0; i < cols.length; i++)
if (colName.equalsIgnoreCase(cols[i].getName()))
return i;
return -1;
}
/** {@inheritDoc} */
@Override public boolean isDistributed() {
return false;
}
/**
* Parse condition for column.
*
* @param colName Column name.
* @param first First.
* @param last Last.
*/
protected SqlSystemViewColumnCondition conditionForColumn(String colName, SearchRow first, SearchRow last) {
return SqlSystemViewColumnCondition.forColumn(getColumnIndex(colName), first, last);
}
/**
* Converts value to UUID safe (suppressing exceptions).
*
* @param val UUID.
*/
protected static UUID uuidFromValue(Value val) {
try {
return UUID.fromString(val.getString());
}
catch (RuntimeException e) {
return null;
}
}
/**
* Converts millis to ValueTimestamp
*
* @param millis Millis.
*/
protected static Value valueTimestampFromMillis(long millis) {
if (millis <= 0L || millis == Long.MAX_VALUE)
return ValueNull.INSTANCE;
else
return ValueTimestamp.fromMillis(millis);
}
/**
* Get node's filter string representation.
*
* @param ccfg Cache configuration.
*
* @return String representation of node filter.
*/
@Nullable protected static String nodeFilter(CacheConfiguration<?, ?> ccfg) {
IgnitePredicate<ClusterNode> nodeFilter = ccfg.getNodeFilter();
if (nodeFilter instanceof CacheConfiguration.IgniteAllNodesPredicate)
nodeFilter = null;
return toStringSafe(nodeFilter);
}
/**
* Get string representation of an object properly catching all exceptions.
*
* @param obj Object.
* @return Result or {@code null}.
*/
@Nullable protected static String toStringSafe(@Nullable Object obj) {<FILL_FUNCTION_BODY>}
}
|
if (obj == null)
return null;
else {
try {
return obj.toString();
}
catch (Exception e) {
try {
return "Failed to convert object to string: " + e.getMessage();
}
catch (Exception e0) {
return "Failed to convert object to string (error message is not available)";
}
}
}
| 1,140
| 103
| 1,243
|
<methods>public void <init>(java.lang.String, java.lang.String, org.apache.ignite.internal.GridKernalContext, Column[], java.lang.String[]) ,public boolean canGetRowCount() ,public Column[] getColumns() ,public java.lang.String getCreateSQL() ,public java.lang.String getDescription() ,public java.lang.String[] getIndexes() ,public long getRowCount() ,public long getRowCountApproximation() ,public java.lang.String getTableName() <variables>protected static final long DEFAULT_ROW_COUNT_APPROXIMATION,protected final non-sealed Column[] cols,protected final non-sealed org.apache.ignite.internal.GridKernalContext ctx,protected final non-sealed java.lang.String desc,protected final non-sealed java.lang.String[] indexes,protected final non-sealed org.apache.ignite.IgniteLogger log,protected final non-sealed java.lang.String tblName
|
apache_ignite
|
ignite/modules/indexing/src/main/java/org/apache/ignite/internal/processors/query/h2/sys/view/SqlAbstractSystemView.java
|
SqlAbstractSystemView
|
getCreateSQL
|
class SqlAbstractSystemView implements SqlSystemView {
/** Default row count approximation. */
protected static final long DEFAULT_ROW_COUNT_APPROXIMATION = 100L;
/** Table name. */
protected final String tblName;
/** Description. */
protected final String desc;
/** Grid context. */
protected final GridKernalContext ctx;
/** Logger. */
protected final IgniteLogger log;
/** Columns. */
protected final Column[] cols;
/** Indexed column names. */
protected final String[] indexes;
/**
* @param tblName Table name.
* @param desc Descriptor.
* @param ctx Context.
* @param cols Columns.
* @param indexes Indexes.
*/
public SqlAbstractSystemView(String tblName, String desc, GridKernalContext ctx, Column[] cols,
String[] indexes) {
this.tblName = tblName;
this.desc = desc;
this.ctx = ctx;
this.cols = cols;
this.indexes = indexes;
this.log = ctx.log(this.getClass());
}
/**
* @param name Name.
*/
protected static Column newColumn(String name) {
return newColumn(name, Value.STRING);
}
/**
* @param name Name.
* @param type Type.
*/
protected static Column newColumn(String name, int type) {
return new Column(name, type);
}
/** {@inheritDoc} */
@Override public String getTableName() {
return tblName;
}
/** {@inheritDoc} */
@Override public String getDescription() {
return desc;
}
/** {@inheritDoc} */
@Override public Column[] getColumns() {
return cols;
}
/** {@inheritDoc} */
@Override public String[] getIndexes() {
return indexes;
}
/** {@inheritDoc} */
@Override public long getRowCount() {
return DEFAULT_ROW_COUNT_APPROXIMATION;
}
/** {@inheritDoc} */
@Override public long getRowCountApproximation() {
return getRowCount();
}
/** {@inheritDoc} */
@Override public boolean canGetRowCount() {
return false;
}
/** {@inheritDoc} */
@SuppressWarnings("StringConcatenationInsideStringBufferAppend")
@Override public String getCreateSQL() {<FILL_FUNCTION_BODY>}
}
|
StringBuilder sql = new StringBuilder();
sql.append("CREATE TABLE " + getTableName() + '(');
boolean isFirst = true;
for (Column col : getColumns()) {
if (isFirst)
isFirst = false;
else
sql.append(", ");
sql.append(col.getCreateSQL());
}
sql.append(')');
return sql.toString();
| 661
| 111
| 772
|
<no_super_class>
|
apache_ignite
|
ignite/modules/indexing/src/main/java/org/apache/ignite/internal/processors/query/h2/twostep/AbstractReduceIndexAdapter.java
|
AbstractReduceIndexAdapter
|
getRowCount
|
class AbstractReduceIndexAdapter extends BaseIndex {
/**
* @param ctx Context.
* @param tbl Table.
* @param name Index name.
* @param type Type.
* @param cols Columns.
*/
protected AbstractReduceIndexAdapter(GridKernalContext ctx,
Table tbl,
String name,
IndexType type,
IndexColumn[] cols
) {
initBaseIndex(tbl, 0, name, cols, type);
}
/**
* @return Index reducer.
*/
abstract AbstractReducer reducer();
/** {@inheritDoc} */
@Override public long getRowCount(Session ses) {<FILL_FUNCTION_BODY>}
/** {@inheritDoc} */
@Override public long getRowCountApproximation() {
return 10_000;
}
/** {@inheritDoc} */
@Override public final Cursor find(Session ses, SearchRow first, SearchRow last) {
return reducer().find(first, last);
}
/** {@inheritDoc} */
@Override public void checkRename() {
throw DbException.getUnsupportedException("rename");
}
/** {@inheritDoc} */
@Override public void close(Session ses) {
// No-op.
}
/** {@inheritDoc} */
@Override public void add(Session ses, Row row) {
throw DbException.getUnsupportedException("add");
}
/** {@inheritDoc} */
@Override public void remove(Session ses, Row row) {
throw DbException.getUnsupportedException("remove row");
}
/** {@inheritDoc} */
@Override public void remove(Session ses) {
throw DbException.getUnsupportedException("remove index");
}
/** {@inheritDoc} */
@Override public void truncate(Session ses) {
throw DbException.getUnsupportedException("truncate");
}
/** {@inheritDoc} */
@Override public boolean canGetFirstOrLast() {
return false;
}
/** {@inheritDoc} */
@Override public Cursor findFirstOrLast(Session ses, boolean first) {
throw DbException.getUnsupportedException("findFirstOrLast");
}
/** {@inheritDoc} */
@Override public boolean needRebuild() {
return false;
}
/** {@inheritDoc} */
@Override public long getDiskSpaceUsed() {
return 0;
}
}
|
Cursor c = find(ses, null, null);
long cnt = 0;
while (c.next())
cnt++;
return cnt;
| 643
| 48
| 691
|
<no_super_class>
|
apache_ignite
|
ignite/modules/indexing/src/main/java/org/apache/ignite/internal/processors/query/h2/twostep/ReduceIndexIterator.java
|
ReduceIndexIterator
|
close
|
class ReduceIndexIterator implements Iterator<List<?>>, AutoCloseable {
/** Reduce query executor. */
private final GridReduceQueryExecutor rdcExec;
/** Participating nodes. */
private final Collection<ClusterNode> nodes;
/** Query run. */
private final ReduceQueryRun run;
/** Query request ID. */
private final long qryReqId;
/** Distributed joins. */
private final boolean distributedJoins;
/** Iterator over indexes. */
private final Iterator<Reducer> rdcIter;
/** Current cursor. */
private Cursor cursor;
/** Next row to return. */
private List<Object> next;
/** Whether remote resources were released. */
private boolean released;
/** Tracing processor. */
private final Tracing tracing;
/**
* Constructor.
*
* @param rdcExec Reduce query executor.
* @param nodes Participating nodes.
* @param run Query run.
* @param qryReqId Query request ID.
* @param distributedJoins Distributed joins.
* @param tracing Tracing processor.
*/
public ReduceIndexIterator(GridReduceQueryExecutor rdcExec,
Collection<ClusterNode> nodes,
ReduceQueryRun run,
long qryReqId,
boolean distributedJoins,
Tracing tracing
) {
this.rdcExec = rdcExec;
this.nodes = nodes;
this.run = run;
this.qryReqId = qryReqId;
this.distributedJoins = distributedJoins;
this.tracing = tracing;
rdcIter = run.reducers().iterator();
advance();
}
/** {@inheritDoc} */
@Override public boolean hasNext() {
return next != null;
}
/** {@inheritDoc} */
@Override public List<?> next() {
List<Object> res = next;
if (res == null)
throw new NoSuchElementException();
advance();
return res;
}
/** {@inheritDoc} */
@Override public void remove() {
throw new UnsupportedOperationException("Remove is not supported");
}
/** {@inheritDoc} */
@Override public void close() throws Exception {<FILL_FUNCTION_BODY>}
/**
* Advance iterator.
*/
private void advance() {
next = null;
try {
boolean hasNext = false;
while (cursor == null || !(hasNext = cursor.next())) {
if (rdcIter.hasNext())
cursor = rdcIter.next().find(null, null);
else {
releaseIfNeeded();
break;
}
}
if (hasNext) {
Row row = cursor.get();
int cols = row.getColumnCount();
List<Object> res = new ArrayList<>(cols);
for (int c = 0; c < cols; c++)
res.add(row.getValue(c).getObject());
next = res;
}
}
catch (Exception e) {
releaseIfNeeded();
throw e;
}
}
/**
* Close routine.
*/
private void releaseIfNeeded() {
if (!released) {
try {
rdcExec.releaseRemoteResources(nodes, run, qryReqId, distributedJoins);
}
finally {
released = true;
}
}
}
}
|
try (TraceSurroundings ignored = MTC.support(tracing.create(SQL_ITER_CLOSE, MTC.span()))) {
releaseIfNeeded();
}
| 919
| 49
| 968
|
<no_super_class>
|
apache_ignite
|
ignite/modules/indexing/src/main/java/org/apache/ignite/internal/processors/query/h2/twostep/ReduceResultPage.java
|
ReduceResultPage
|
rows
|
class ReduceResultPage {
/** */
private final UUID src;
/** */
private final GridQueryNextPageResponse res;
/** */
private final int rowsInPage;
/** */
private Iterator<Value[]> rows;
/** */
private boolean last;
/**
* @param ctx Kernal context.
* @param src Source.
* @param res Response.
*/
@SuppressWarnings("unchecked")
public ReduceResultPage(final GridKernalContext ctx, UUID src, GridQueryNextPageResponse res) {
assert src != null;
this.src = src;
this.res = res;
// res == null means that it is a terminating dummy page for the given source node ID.
if (res != null) {
Collection<?> plainRows = res.plainRows();
if (plainRows != null) {
assert plainRows instanceof RandomAccess : "instance of " + plainRows.getClass();
rowsInPage = plainRows.size();
rows = (Iterator<Value[]>)plainRows.iterator();
}
else {
final int cols = res.columns();
rowsInPage = res.values().size() / cols;
final Iterator<Message> valsIter = res.values().iterator();
rows = new Iterator<Value[]>() {
/** */
int rowIdx;
@Override public boolean hasNext() {
return rowIdx < rowsInPage;
}
@Override public Value[] next() {
if (!hasNext())
throw new NoSuchElementException();
rowIdx++;
try {
return fillArray(valsIter, new Value[cols], ctx);
}
catch (IgniteCheckedException e) {
throw new CacheException(e);
}
}
@Override public void remove() {
throw new UnsupportedOperationException();
}
};
}
}
else {
rowsInPage = 0;
rows = Collections.emptyIterator();
}
}
/**
* @return {@code true} If this is a dummy fail page.
*/
public boolean isFail() {
return false;
}
/**
* @return {@code true} If this is either a real last page for a source or
* a dummy terminating page with no rows.
*/
public boolean isLast() {
return last;
}
/**
* @return {@code true} If it is a dummy last page.
*/
public boolean isDummyLast() {
return last && res == null;
}
/**
* @param last Last page for a source.
* @return {@code this}.
*/
public ReduceResultPage setLast(boolean last) {
this.last = last;
return this;
}
/**
* @return Number on rows in this page.
*/
public int rowsInPage() {
return rowsInPage;
}
/**
* @return Rows.
*/
public Iterator<Value[]> rows() {<FILL_FUNCTION_BODY>}
/**
* @return Result source node ID.
*/
public UUID source() {
return src;
}
/**
* @return Segment ID.
*/
public int segmentId() {
return res.segmentId();
}
/**
* @return Response.
*/
public GridQueryNextPageResponse response() {
return res;
}
/**
* Request next page.
*/
public void fetchNextPage() {
throw new CacheException("Failed to fetch data from node: " + src);
}
/** {@inheritDoc} */
@Override public String toString() {
return S.toString(ReduceResultPage.class, this);
}
}
|
Iterator<Value[]> r = rows;
assert r != null;
rows = null;
return r;
| 1,000
| 37
| 1,037
|
<no_super_class>
|
apache_ignite
|
ignite/modules/indexing/src/main/java/org/apache/ignite/internal/processors/query/h2/twostep/ReduceTableEngine.java
|
ReduceTableEngine
|
createTable
|
class ReduceTableEngine implements TableEngine {
/** */
private static final ThreadLocal<ReduceTableWrapper> CREATED_TBL = new ThreadLocal<>();
/**
* Create merge table over the given connection with provided index.
*
* @param conn Connection.
* @param idx Index.
* @return Created table.
*/
public static ReduceTableWrapper create(Connection conn, int idx) {
try (Statement stmt = conn.createStatement()) {
stmt.executeUpdate("CREATE TABLE " + mergeTableIdentifier(idx) +
"(fake BOOL) ENGINE \"" + ReduceTableEngine.class.getName() + '"');
}
catch (SQLException e) {
throw new IllegalStateException(e);
}
ReduceTableWrapper tbl = CREATED_TBL.get();
assert tbl != null;
CREATED_TBL.remove();
return tbl;
}
/** {@inheritDoc} */
@Override public Table createTable(CreateTableData d) {<FILL_FUNCTION_BODY>}
}
|
assert CREATED_TBL.get() == null;
ReduceTableWrapper tbl = new ReduceTableWrapper(
d.schema,
d.id,
d.tableName,
d.persistIndexes,
d.persistData
);
CREATED_TBL.set(tbl);
return tbl;
| 275
| 91
| 366
|
<no_super_class>
|
apache_ignite
|
ignite/modules/indexing/src/main/java/org/apache/ignite/internal/processors/query/h2/twostep/SortedReduceIndexAdapter.java
|
SortedReduceIndexAdapter
|
compareRows
|
class SortedReduceIndexAdapter extends AbstractReduceIndexAdapter {
/** */
private static final IndexType TYPE = IndexType.createNonUnique(false);
/** */
private final SortedReducer delegate;
/**
* @param ctx Kernal context.
* @param tbl Table.
* @param name Index name,
* @param cols Columns.
*/
public SortedReduceIndexAdapter(
GridKernalContext ctx,
ReduceTable tbl,
String name,
IndexColumn[] cols
) {
super(ctx, tbl, name, TYPE, cols);
delegate = new SortedReducer(ctx, this::compareRows);
}
/** {@inheritDoc} */
@Override protected SortedReducer reducer() {
return delegate;
}
/** {@inheritDoc} */
@Override public double getCost(Session ses, int[] masks, TableFilter[] filters, int filter, SortOrder sortOrder,
HashSet<Column> allColumnsSet) {
return getCostRangeIndex(masks, getRowCountApproximation(), filters, filter, sortOrder, false, allColumnsSet);
}
/** {@inheritDoc} */
@Override public int compareRows(SearchRow rowData, SearchRow compare) {<FILL_FUNCTION_BODY>}
}
|
if (rowData == compare)
return 0;
for (int i = 0, len = indexColumns.length; i < len; i++) {
int idx = columnIds[i];
int sortType = indexColumns[i].sortType;
Value v1 = rowData.getValue(idx);
Value v2 = compare.getValue(idx);
if (v1 == null || v2 == null)
return 0;
else if (v1 == v2) continue;
else if (v1 == ValueNull.INSTANCE || v2 == ValueNull.INSTANCE) {
if ((sortType & SortOrder.NULLS_FIRST) != 0)
return v1 == ValueNull.INSTANCE ? -1 : 1;
else if ((sortType & SortOrder.NULLS_LAST) != 0)
return v1 == ValueNull.INSTANCE ? 1 : -1;
}
int comp = table.compareTypeSafe(v1, v2);
if ((sortType & SortOrder.DESCENDING) != 0)
comp = -comp;
if (comp != 0)
return comp;
}
return 0;
| 340
| 300
| 640
|
<methods>public void add(Session, Row) ,public boolean canGetFirstOrLast() ,public void checkRename() ,public void close(Session) ,public final Cursor find(Session, SearchRow, SearchRow) ,public Cursor findFirstOrLast(Session, boolean) ,public long getDiskSpaceUsed() ,public long getRowCount(Session) ,public long getRowCountApproximation() ,public boolean needRebuild() ,public void remove(Session, Row) ,public void remove(Session) ,public void truncate(Session) <variables>
|
apache_ignite
|
ignite/modules/indexing/src/main/java/org/apache/ignite/internal/processors/query/h2/twostep/UnsortedReducer.java
|
FetchingCursor
|
fetchRows
|
class FetchingCursor implements Cursor {
/** */
private Iterator<Row> stream;
/** */
private List<Row> rows;
/** */
private int cur;
/**
* @param stream Stream of all the rows from remote nodes.
*/
FetchingCursor(Iterator<Row> stream) {
assert stream != null;
// Initially we will use all the fetched rows, after we will switch to the last block.
rows = fetched;
this.stream = stream;
cur--; // Set current position before the first row.
}
/**
* Fetch rows from the stream.
*/
private void fetchRows() {<FILL_FUNCTION_BODY>}
/** {@inheritDoc} */
@Override public boolean next() {
if (cur == Integer.MAX_VALUE)
return false;
if (++cur == rows.size())
fetchRows();
return cur < Integer.MAX_VALUE;
}
/** {@inheritDoc} */
@Override public Row get() {
return rows.get(cur);
}
/** {@inheritDoc} */
@Override public SearchRow getSearchRow() {
return get();
}
/** {@inheritDoc} */
@Override public boolean previous() {
// Should never be called.
throw DbException.getUnsupportedException("previous");
}
}
|
// Take the current last block and set the position after last.
rows = fetched.lastBlock();
cur = rows.size();
// Fetch stream.
if (stream.hasNext()) {
fetched.add(requireNonNull(stream.next()));
// Evict block if we've fetched too many rows.
if (fetched.size() == MAX_FETCH_SIZE) {
onBlockEvict(fetched.evictFirstBlock());
assert fetched.size() < MAX_FETCH_SIZE;
}
}
if (cur == rows.size())
cur = Integer.MAX_VALUE; // We were not able to fetch anything. Done.
| 360
| 176
| 536
|
<methods>public void <init>(org.apache.ignite.internal.GridKernalContext) ,public boolean fetchedAll() ,public void setSources(Map<org.apache.ignite.cluster.ClusterNode,java.util.BitSet>) <variables>protected final java.util.concurrent.atomic.AtomicInteger activeSourcesCnt,protected Iterator<Value[]> iter,protected final PollableQueue<org.apache.ignite.internal.processors.query.h2.twostep.ReduceResultPage> queue
|
apache_ignite
|
ignite/modules/indexing/src/main/java/org/apache/ignite/internal/processors/query/h2/twostep/msg/GridH2Byte.java
|
GridH2Byte
|
writeTo
|
class GridH2Byte extends GridH2ValueMessage {
/** */
private byte x;
/**
*
*/
public GridH2Byte() {
// No-op.
}
/**
* @param val Value.
*/
public GridH2Byte(Value val) {
assert val.getType() == Value.BYTE : val.getType();
x = val.getByte();
}
/** {@inheritDoc} */
@Override public Value value(GridKernalContext ctx) {
return ValueByte.get(x);
}
/** {@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;
if (!super.readFrom(buf, reader))
return false;
switch (reader.state()) {
case 0:
x = reader.readByte("x");
if (!reader.isLastRead())
return false;
reader.incrementState();
}
return reader.afterMessageRead(GridH2Byte.class);
}
/** {@inheritDoc} */
@Override public short directType() {
return -6;
}
/** {@inheritDoc} */
@Override public byte fieldsCount() {
return 1;
}
/** {@inheritDoc} */
@Override public String toString() {
return String.valueOf(x);
}
}
|
writer.setBuffer(buf);
if (!super.writeTo(buf, writer))
return false;
if (!writer.isHeaderWritten()) {
if (!writer.writeHeader(directType(), fieldsCount()))
return false;
writer.onHeaderWritten();
}
switch (writer.state()) {
case 0:
if (!writer.writeByte("x", x))
return false;
writer.incrementState();
}
return true;
| 425
| 130
| 555
|
<methods>public non-sealed void <init>() ,public void onAckReceived() ,public boolean readFrom(java.nio.ByteBuffer, org.apache.ignite.plugin.extensions.communication.MessageReader) ,public abstract Value value(org.apache.ignite.internal.GridKernalContext) throws org.apache.ignite.IgniteCheckedException,public boolean writeTo(java.nio.ByteBuffer, org.apache.ignite.plugin.extensions.communication.MessageWriter) <variables>
|
apache_ignite
|
ignite/modules/indexing/src/main/java/org/apache/ignite/internal/processors/query/h2/twostep/msg/GridH2CacheObject.java
|
GridH2CacheObject
|
value
|
class GridH2CacheObject extends GridH2ValueMessage {
/** */
private CacheObject obj;
/**
*
*/
public GridH2CacheObject() {
// No-op.
}
/**
* @param v Value.
* @throws IgniteCheckedException If failed.
*/
public GridH2CacheObject(GridH2ValueCacheObject v) throws IgniteCheckedException {
this.obj = v.getCacheObject();
obj.prepareMarshal(v.valueContext());
}
/** {@inheritDoc} */
@Override public Value value(GridKernalContext ctx) throws IgniteCheckedException {<FILL_FUNCTION_BODY>}
/** {@inheritDoc} */
@Override public boolean readFrom(ByteBuffer buf, MessageReader reader) {
reader.setBuffer(buf);
if (!reader.beforeMessageRead())
return false;
if (!super.readFrom(buf, reader))
return false;
switch (reader.state()) {
case 0:
obj = reader.readMessage("obj");
if (!reader.isLastRead())
return false;
reader.incrementState();
}
return reader.afterMessageRead(GridH2CacheObject.class);
}
/** {@inheritDoc} */
@Override public boolean writeTo(ByteBuffer buf, MessageWriter writer) {
writer.setBuffer(buf);
if (!super.writeTo(buf, writer))
return false;
if (!writer.isHeaderWritten()) {
if (!writer.writeHeader(directType(), fieldsCount()))
return false;
writer.onHeaderWritten();
}
switch (writer.state()) {
case 0:
if (!writer.writeMessage("obj", obj))
return false;
writer.incrementState();
}
return true;
}
/** {@inheritDoc} */
@Override public short directType() {
return -22;
}
/** {@inheritDoc} */
@Override public byte fieldsCount() {
return 1;
}
/** {@inheritDoc} */
@Override public String toString() {
return String.valueOf(obj);
}
}
|
CacheObjectValueContext valCtx = ctx.query().objectContext();
obj.finishUnmarshal(valCtx, ctx.cache().context().deploy().globalLoader());
return new GridH2ValueCacheObject(obj, valCtx);
| 575
| 65
| 640
|
<methods>public non-sealed void <init>() ,public void onAckReceived() ,public boolean readFrom(java.nio.ByteBuffer, org.apache.ignite.plugin.extensions.communication.MessageReader) ,public abstract Value value(org.apache.ignite.internal.GridKernalContext) throws org.apache.ignite.IgniteCheckedException,public boolean writeTo(java.nio.ByteBuffer, org.apache.ignite.plugin.extensions.communication.MessageWriter) <variables>
|
apache_ignite
|
ignite/modules/indexing/src/main/java/org/apache/ignite/internal/processors/query/h2/twostep/msg/GridH2DmlResponse.java
|
GridH2DmlResponse
|
unmarshall
|
class GridH2DmlResponse implements Message, GridCacheQueryMarshallable {
/** */
private static final long serialVersionUID = 0L;
/** Request id. */
@GridToStringInclude
private long reqId;
/** Number of updated rows. */
@GridToStringInclude
private long updCnt;
/** Error message. */
@GridToStringInclude
private String err;
/** Keys that failed. */
@GridToStringInclude
@GridDirectTransient
private Object[] errKeys;
/** Keys that failed (after marshalling). */
private byte[] errKeysBytes;
/**
* Default constructor.
*/
public GridH2DmlResponse() {
// No-op.
}
/**
* Constructor.
*
* @param reqId Request id.
* @param updCnt Updated row number.
* @param errKeys Erroneous keys.
* @param error Error message.
*/
public GridH2DmlResponse(long reqId, long updCnt, Object[] errKeys, String error) {
this.reqId = reqId;
this.updCnt = updCnt;
this.errKeys = errKeys;
this.err = error;
}
/**
* @return Request id.
*/
public long requestId() {
return reqId;
}
/**
* @return Update counter.
*/
public long updateCounter() {
return updCnt;
}
/**
* @return Error keys.
*/
public Object[] errorKeys() {
return errKeys;
}
/**
* @return Error message.
*/
public String error() {
return err;
}
/** {@inheritDoc} */
@Override public void marshall(Marshaller m) {
if (errKeysBytes != null || errKeys == null)
return;
try {
errKeysBytes = U.marshal(m, errKeys);
}
catch (IgniteCheckedException e) {
throw new IgniteException(e);
}
}
/** {@inheritDoc} */
@SuppressWarnings("IfMayBeConditional")
@Override public void unmarshall(Marshaller m, GridKernalContext ctx) {<FILL_FUNCTION_BODY>}
/** {@inheritDoc} */
@Override public String toString() {
return S.toString(GridH2DmlResponse.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.writeString("err", err))
return false;
writer.incrementState();
case 1:
if (!writer.writeByteArray("errKeysBytes", errKeysBytes))
return false;
writer.incrementState();
case 2:
if (!writer.writeLong("reqId", reqId))
return false;
writer.incrementState();
case 3:
if (!writer.writeLong("updCnt", updCnt))
return false;
writer.incrementState();
}
return true;
}
/** {@inheritDoc} */
@Override public boolean readFrom(ByteBuffer buf, MessageReader reader) {
reader.setBuffer(buf);
if (!reader.beforeMessageRead())
return false;
switch (reader.state()) {
case 0:
err = reader.readString("err");
if (!reader.isLastRead())
return false;
reader.incrementState();
case 1:
errKeysBytes = reader.readByteArray("errKeysBytes");
if (!reader.isLastRead())
return false;
reader.incrementState();
case 2:
reqId = reader.readLong("reqId");
if (!reader.isLastRead())
return false;
reader.incrementState();
case 3:
updCnt = reader.readLong("updCnt");
if (!reader.isLastRead())
return false;
reader.incrementState();
}
return reader.afterMessageRead(GridH2DmlResponse.class);
}
/** {@inheritDoc} */
@Override public short directType() {
return -56;
}
/** {@inheritDoc} */
@Override public byte fieldsCount() {
return 4;
}
/** {@inheritDoc} */
@Override public void onAckReceived() {
// No-op
}
}
|
if (errKeys != null || errKeysBytes == null)
return;
try {
final ClassLoader ldr = U.resolveClassLoader(ctx.config());
if (m instanceof BinaryMarshaller)
// To avoid deserializing of enum types.
errKeys = BinaryUtils.rawArrayFromBinary(((BinaryMarshaller)m).binaryMarshaller().unmarshal(errKeysBytes, ldr));
else
errKeys = U.unmarshal(m, errKeysBytes, ldr);
}
catch (IgniteCheckedException e) {
throw new IgniteException(e);
}
| 1,261
| 160
| 1,421
|
<no_super_class>
|
apache_ignite
|
ignite/modules/indexing/src/main/java/org/apache/ignite/internal/processors/query/h2/twostep/msg/GridH2Float.java
|
GridH2Float
|
writeTo
|
class GridH2Float extends GridH2ValueMessage {
/** */
private float x;
/**
*
*/
public GridH2Float() {
// No-op.
}
/**
* @param val Value.
*/
public GridH2Float(Value val) {
assert val.getType() == Value.FLOAT : val.getType();
x = val.getFloat();
}
/** {@inheritDoc} */
@Override public Value value(GridKernalContext ctx) {
return ValueFloat.get(x);
}
/** {@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;
if (!super.readFrom(buf, reader))
return false;
switch (reader.state()) {
case 0:
x = reader.readFloat("x");
if (!reader.isLastRead())
return false;
reader.incrementState();
}
return reader.afterMessageRead(GridH2Float.class);
}
/** {@inheritDoc} */
@Override public short directType() {
return -12;
}
/** {@inheritDoc} */
@Override public byte fieldsCount() {
return 1;
}
/** {@inheritDoc} */
@Override public String toString() {
return String.valueOf(x);
}
}
|
writer.setBuffer(buf);
if (!super.writeTo(buf, writer))
return false;
if (!writer.isHeaderWritten()) {
if (!writer.writeHeader(directType(), fieldsCount()))
return false;
writer.onHeaderWritten();
}
switch (writer.state()) {
case 0:
if (!writer.writeFloat("x", x))
return false;
writer.incrementState();
}
return true;
| 427
| 130
| 557
|
<methods>public non-sealed void <init>() ,public void onAckReceived() ,public boolean readFrom(java.nio.ByteBuffer, org.apache.ignite.plugin.extensions.communication.MessageReader) ,public abstract Value value(org.apache.ignite.internal.GridKernalContext) throws org.apache.ignite.IgniteCheckedException,public boolean writeTo(java.nio.ByteBuffer, org.apache.ignite.plugin.extensions.communication.MessageWriter) <variables>
|
apache_ignite
|
ignite/modules/indexing/src/main/java/org/apache/ignite/internal/processors/query/h2/twostep/msg/GridH2IndexRangeResponse.java
|
GridH2IndexRangeResponse
|
readFrom
|
class GridH2IndexRangeResponse implements Message {
/** */
public static final byte STATUS_OK = 0;
/** */
public static final byte STATUS_ERROR = 1;
/** */
public static final byte STATUS_NOT_FOUND = 2;
/** */
private UUID originNodeId;
/** */
private long qryId;
/** */
private int segmentId;
/** */
private int originSegmentId;
/** */
private int batchLookupId;
/** */
@GridDirectCollection(Message.class)
private List<GridH2RowRange> ranges;
/** */
private byte status;
/** */
private String err;
/**
* @param ranges Ranges.
*/
public void ranges(List<GridH2RowRange> ranges) {
this.ranges = ranges;
}
/**
* @return Ranges.
*/
public List<GridH2RowRange> ranges() {
return ranges;
}
/**
* @return Origin node ID.
*/
public UUID originNodeId() {
return originNodeId;
}
/**
* @param originNodeId Origin node ID.
*/
public void originNodeId(UUID originNodeId) {
this.originNodeId = originNodeId;
}
/**
* @return Query ID.
*/
public long queryId() {
return qryId;
}
/**
* @param qryId Query ID.
*/
public void queryId(long qryId) {
this.qryId = qryId;
}
/**
* @param err Error message.
*/
public void error(String err) {
this.err = err;
}
/**
* @return Error message or {@code null} if everything is ok.
*/
public String error() {
return err;
}
/**
* @param status Status.
*/
public void status(byte status) {
this.status = status;
}
/**
* @return Status.
*/
public byte status() {
return status;
}
/**
* @param segmentId Index segment ID.
*/
public void segment(int segmentId) {
this.segmentId = segmentId;
}
/**
* @return Index segment ID.
*/
public int segment() {
return segmentId;
}
/**
* @return Origin index segment ID.
*/
public int originSegmentId() {
return originSegmentId;
}
/**
* @param segmentId Origin index segment ID.
*/
public void originSegmentId(int segmentId) {
this.originSegmentId = segmentId;
}
/**
* @param batchLookupId Batch lookup ID.
*/
public void batchLookupId(int batchLookupId) {
this.batchLookupId = batchLookupId;
}
/**
* @return Batch lookup ID.
*/
public int batchLookupId() {
return batchLookupId;
}
/** {@inheritDoc} */
@Override public boolean writeTo(ByteBuffer buf, MessageWriter writer) {
writer.setBuffer(buf);
if (!writer.isHeaderWritten()) {
if (!writer.writeHeader(directType(), fieldsCount()))
return false;
writer.onHeaderWritten();
}
switch (writer.state()) {
case 0:
if (!writer.writeInt("batchLookupId", batchLookupId))
return false;
writer.incrementState();
case 1:
if (!writer.writeString("err", err))
return false;
writer.incrementState();
case 2:
if (!writer.writeUuid("originNodeId", originNodeId))
return false;
writer.incrementState();
case 3:
if (!writer.writeLong("qryId", qryId))
return false;
writer.incrementState();
case 4:
if (!writer.writeCollection("ranges", ranges, MessageCollectionItemType.MSG))
return false;
writer.incrementState();
case 5:
if (!writer.writeByte("status", status))
return false;
writer.incrementState();
case 6:
if (!writer.writeInt("originSegId", originSegmentId))
return false;
writer.incrementState();
case 7:
if (!writer.writeInt("segmentId", segmentId))
return false;
writer.incrementState();
}
return true;
}
/** {@inheritDoc} */
@Override public boolean readFrom(ByteBuffer buf, MessageReader reader) {<FILL_FUNCTION_BODY>}
/** {@inheritDoc} */
@Override public short directType() {
return -31;
}
/** {@inheritDoc} */
@Override public byte fieldsCount() {
return 8;
}
/** {@inheritDoc} */
@Override public void onAckReceived() {
// No-op.
}
/** {@inheritDoc} */
@Override public String toString() {
return S.toString(GridH2IndexRangeResponse.class, this, "rangesSize", ranges == null ? null : ranges.size());
}
}
|
reader.setBuffer(buf);
if (!reader.beforeMessageRead())
return false;
switch (reader.state()) {
case 0:
batchLookupId = reader.readInt("batchLookupId");
if (!reader.isLastRead())
return false;
reader.incrementState();
case 1:
err = reader.readString("err");
if (!reader.isLastRead())
return false;
reader.incrementState();
case 2:
originNodeId = reader.readUuid("originNodeId");
if (!reader.isLastRead())
return false;
reader.incrementState();
case 3:
qryId = reader.readLong("qryId");
if (!reader.isLastRead())
return false;
reader.incrementState();
case 4:
ranges = reader.readCollection("ranges", MessageCollectionItemType.MSG);
if (!reader.isLastRead())
return false;
reader.incrementState();
case 5:
status = reader.readByte("status");
if (!reader.isLastRead())
return false;
reader.incrementState();
case 6:
originSegmentId = reader.readInt("originSegId");
if (!reader.isLastRead())
return false;
reader.incrementState();
case 7:
segmentId = reader.readInt("segmentId");
if (!reader.isLastRead())
return false;
reader.incrementState();
}
return reader.afterMessageRead(GridH2IndexRangeResponse.class);
| 1,413
| 434
| 1,847
|
<no_super_class>
|
apache_ignite
|
ignite/modules/indexing/src/main/java/org/apache/ignite/internal/processors/query/h2/twostep/msg/GridH2Integer.java
|
GridH2Integer
|
equals
|
class GridH2Integer extends GridH2ValueMessage {
/** */
private int x;
/**
*
*/
public GridH2Integer() {
// No-op.
}
/**
* @param val Value.
*/
public GridH2Integer(Value val) {
assert val.getType() == Value.INT : val.getType();
x = val.getInt();
}
/** {@inheritDoc} */
@Override public Value value(GridKernalContext ctx) {
return ValueInt.get(x);
}
/** {@inheritDoc} */
@Override public boolean writeTo(ByteBuffer buf, MessageWriter writer) {
writer.setBuffer(buf);
if (!super.writeTo(buf, writer))
return false;
if (!writer.isHeaderWritten()) {
if (!writer.writeHeader(directType(), fieldsCount()))
return false;
writer.onHeaderWritten();
}
switch (writer.state()) {
case 0:
if (!writer.writeInt("x", x))
return false;
writer.incrementState();
}
return true;
}
/** {@inheritDoc} */
@Override public boolean readFrom(ByteBuffer buf, MessageReader reader) {
reader.setBuffer(buf);
if (!reader.beforeMessageRead())
return false;
if (!super.readFrom(buf, reader))
return false;
switch (reader.state()) {
case 0:
x = reader.readInt("x");
if (!reader.isLastRead())
return false;
reader.incrementState();
}
return reader.afterMessageRead(GridH2Integer.class);
}
/** {@inheritDoc} */
@Override public short directType() {
return -8;
}
/** {@inheritDoc} */
@Override public byte fieldsCount() {
return 1;
}
/** {@inheritDoc} */
@Override public boolean equals(Object obj) {<FILL_FUNCTION_BODY>}
/** {@inheritDoc} */
@Override public int hashCode() {
return x;
}
/** {@inheritDoc} */
@Override public String toString() {
return String.valueOf(x);
}
}
|
return obj == this || (obj != null && obj.getClass() == GridH2Integer.class && x == ((GridH2Integer)obj).x);
| 602
| 42
| 644
|
<methods>public non-sealed void <init>() ,public void onAckReceived() ,public boolean readFrom(java.nio.ByteBuffer, org.apache.ignite.plugin.extensions.communication.MessageReader) ,public abstract Value value(org.apache.ignite.internal.GridKernalContext) throws org.apache.ignite.IgniteCheckedException,public boolean writeTo(java.nio.ByteBuffer, org.apache.ignite.plugin.extensions.communication.MessageWriter) <variables>
|
apache_ignite
|
ignite/modules/indexing/src/main/java/org/apache/ignite/internal/processors/query/h2/twostep/msg/GridH2RowRange.java
|
GridH2RowRange
|
writeTo
|
class GridH2RowRange implements Message {
/** */
private static int FLAG_PARTIAL = 1;
/** */
private int rangeId;
/** */
@GridDirectCollection(Message.class)
@GridToStringInclude
private List<GridH2RowMessage> rows;
/** */
private byte flags;
/**
* @param rangeId Range ID.
*/
public void rangeId(int rangeId) {
this.rangeId = rangeId;
}
/**
* @return Range ID.
*/
public int rangeId() {
return rangeId;
}
/**
* @param rows Rows.
*/
public void rows(List<GridH2RowMessage> rows) {
this.rows = rows;
}
/**
* @return Rows.
*/
public List<GridH2RowMessage> rows() {
return rows;
}
/**
* Sets that this is a partial range.
*/
public void setPartial() {
flags |= FLAG_PARTIAL;
}
/**
* @return {@code true} If this is a partial range.
*/
public boolean isPartial() {
return (flags & FLAG_PARTIAL) == FLAG_PARTIAL;
}
/** {@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:
flags = reader.readByte("flags");
if (!reader.isLastRead())
return false;
reader.incrementState();
case 1:
rangeId = reader.readInt("rangeId");
if (!reader.isLastRead())
return false;
reader.incrementState();
case 2:
rows = reader.readCollection("rows", MessageCollectionItemType.MSG);
if (!reader.isLastRead())
return false;
reader.incrementState();
}
return reader.afterMessageRead(GridH2RowRange.class);
}
/** {@inheritDoc} */
@Override public short directType() {
return -34;
}
/** {@inheritDoc} */
@Override public byte fieldsCount() {
return 3;
}
/** {@inheritDoc} */
@Override public void onAckReceived() {
// No-op.
}
/**
* @return Number of rows.
*/
public int rowsSize() {
return rows == null ? 0 : rows.size();
}
/** {@inheritDoc} */
@Override public String toString() {
return S.toString(GridH2RowRange.class, this, "rowsSize", rowsSize());
}
}
|
writer.setBuffer(buf);
if (!writer.isHeaderWritten()) {
if (!writer.writeHeader(directType(), fieldsCount()))
return false;
writer.onHeaderWritten();
}
switch (writer.state()) {
case 0:
if (!writer.writeByte("flags", flags))
return false;
writer.incrementState();
case 1:
if (!writer.writeInt("rangeId", rangeId))
return false;
writer.incrementState();
case 2:
if (!writer.writeCollection("rows", rows, MessageCollectionItemType.MSG))
return false;
writer.incrementState();
}
return true;
| 781
| 189
| 970
|
<no_super_class>
|
apache_ignite
|
ignite/modules/indexing/src/main/java/org/apache/ignite/internal/processors/query/h2/twostep/msg/GridH2ValueMessageFactory.java
|
GridH2ValueMessageFactory
|
registerAll
|
class GridH2ValueMessageFactory implements MessageFactoryProvider {
/** {@inheritDoc} */
@Override public void registerAll(IgniteMessageFactory factory) {<FILL_FUNCTION_BODY>}
/** {@inheritDoc} */
@Override @Nullable public Message create(short type) {
throw new UnsupportedOperationException();
}
/**
* @param src Source values.
* @param dst Destination collection.
* @param cnt Number of columns to actually send.
* @return Destination collection.
* @throws IgniteCheckedException If failed.
*/
public static Collection<Message> toMessages(Collection<Value[]> src, Collection<Message> dst, int cnt)
throws IgniteCheckedException {
for (Value[] row : src) {
assert row.length >= cnt;
for (int i = 0; i < cnt; i++)
dst.add(toMessage(row[i]));
}
return dst;
}
/**
* @param src Source iterator.
* @param dst Array to fill with values.
* @param ctx Kernal context.
* @return Filled array.
* @throws IgniteCheckedException If failed.
*/
public static Value[] fillArray(Iterator<? extends Message> src, Value[] dst, GridKernalContext ctx)
throws IgniteCheckedException {
for (int i = 0; i < dst.length; i++) {
Message msg = src.next();
dst[i] = ((GridH2ValueMessage)msg).value(ctx);
}
return dst;
}
/**
* @param v Value.
* @return Message.
* @throws IgniteCheckedException If failed.
*/
public static GridH2ValueMessage toMessage(Value v) throws IgniteCheckedException {
switch (v.getType()) {
case Value.NULL:
return GridH2Null.INSTANCE;
case Value.BOOLEAN:
return new GridH2Boolean(v);
case Value.BYTE:
return new GridH2Byte(v);
case Value.SHORT:
return new GridH2Short(v);
case Value.INT:
return new GridH2Integer(v);
case Value.LONG:
return new GridH2Long(v);
case Value.DECIMAL:
return new GridH2Decimal(v);
case Value.DOUBLE:
return new GridH2Double(v);
case Value.FLOAT:
return new GridH2Float(v);
case Value.DATE:
return new GridH2Date(v);
case Value.TIME:
return new GridH2Time(v);
case Value.TIMESTAMP:
return new GridH2Timestamp(v);
case Value.BYTES:
return new GridH2Bytes(v);
case Value.STRING:
case Value.STRING_FIXED:
case Value.STRING_IGNORECASE:
return new GridH2String(v);
case Value.ARRAY:
return new GridH2Array(v);
case Value.JAVA_OBJECT:
if (v instanceof GridH2ValueCacheObject)
return new GridH2CacheObject((GridH2ValueCacheObject)v);
return new GridH2JavaObject(v);
case Value.UUID:
return new GridH2Uuid(v);
case Value.GEOMETRY:
return new GridH2Geometry(v);
default:
throw new IllegalStateException("Unsupported H2 type: " + v.getType());
}
}
}
|
factory.register((short)-4, () -> GridH2Null.INSTANCE);
factory.register((short)-5, GridH2Boolean::new);
factory.register((short)-6, GridH2Byte::new);
factory.register((short)-7, GridH2Short::new);
factory.register((short)-8, GridH2Integer::new);
factory.register((short)-9, GridH2Long::new);
factory.register((short)-10, GridH2Decimal::new);
factory.register((short)-11, GridH2Double::new);
factory.register((short)-12, GridH2Float::new);
factory.register((short)-13, GridH2Time::new);
factory.register((short)-14, GridH2Date::new);
factory.register((short)-15, GridH2Timestamp::new);
factory.register((short)-16, GridH2Bytes::new);
factory.register((short)-17, GridH2String::new);
factory.register((short)-18, GridH2Array::new);
factory.register((short)-19, GridH2JavaObject::new);
factory.register((short)-20, GridH2Uuid::new);
factory.register((short)-21, GridH2Geometry::new);
factory.register((short)-22, GridH2CacheObject::new);
factory.register((short)-30, GridH2IndexRangeRequest::new);
factory.register((short)-31, GridH2IndexRangeResponse::new);
factory.register((short)-32, GridH2RowMessage::new);
factory.register((short)-33, GridH2QueryRequest::new);
factory.register((short)-34, GridH2RowRange::new);
factory.register((short)-35, GridH2RowRangeBounds::new);
factory.register((short)-54, QueryTable::new);
factory.register((short)-55, GridH2DmlRequest::new);
factory.register((short)-56, GridH2DmlResponse::new);
| 945
| 520
| 1,465
|
<no_super_class>
|
apache_ignite
|
ignite/modules/jta/src/main/java/org/apache/ignite/cache/jta/jndi/CacheJndiTmLookup.java
|
CacheJndiTmLookup
|
getTm
|
class CacheJndiTmLookup implements CacheTmLookup {
/** */
private List<String> jndiNames;
/**
* Gets a list of JNDI names.
*
* @return List of JNDI names that is used to find TM.
*/
public List<String> getJndiNames() {
return jndiNames;
}
/**
* Sets a list of JNDI names used by this TM.
*
* @param jndiNames List of JNDI names that is used to find TM.
*/
public void setJndiNames(List<String> jndiNames) {
this.jndiNames = jndiNames;
}
/** {@inheritDoc} */
@Nullable @Override public TransactionManager getTm() throws IgniteException {<FILL_FUNCTION_BODY>}
}
|
assert jndiNames != null;
assert !jndiNames.isEmpty();
try {
InitialContext ctx = new InitialContext();
for (String s : jndiNames) {
Object obj = ctx.lookup(s);
if (obj != null && obj instanceof TransactionManager)
return (TransactionManager)obj;
}
}
catch (NamingException e) {
throw new IgniteException("Unable to lookup TM by: " + jndiNames, e);
}
return null;
| 228
| 141
| 369
|
<no_super_class>
|
apache_ignite
|
ignite/modules/jta/src/main/java/org/apache/ignite/cache/jta/reflect/CacheReflectionTmLookup.java
|
CacheReflectionTmLookup
|
getTm
|
class CacheReflectionTmLookup implements CacheTmLookup {
/** */
private String cls;
/** */
private String mtd;
/**
* Creates uninitialized reflection TM lookup.
*/
public CacheReflectionTmLookup() { /* No-op. */ }
/**
* Creates generic TM lookup with given class and method name.
*
* @param cls Class name.
* @param mtd Method name on that the class.
*/
public CacheReflectionTmLookup(String cls, String mtd) {
A.notNull(cls, "cls");
A.notNull(mtd, "mtd");
this.cls = cls;
this.mtd = mtd;
}
/**
* Gets class name to use.
*
* @return Class name to use.
*/
public String getClassName() {
return cls;
}
/**
* Sets class name to use.
*
* @param cls Class name to use.
*/
public void setClassName(String cls) {
A.notNull(cls, "cls");
this.cls = cls;
}
/**
* Gets method name.
*
* @return Method name to use.
*/
public String getMethodName() {
return mtd;
}
/**
* Sets method name.
*
* @param mtd Method name to use.
*/
public void setMethodName(String mtd) {
A.notNull(mtd, "mtd");
this.mtd = mtd;
}
/** {@inheritDoc} */
@Override public TransactionManager getTm() throws IgniteException {<FILL_FUNCTION_BODY>}
}
|
assert cls != null;
assert mtd != null;
try {
return (TransactionManager)Class.forName(cls).getMethod(mtd).invoke(null);
}
catch (ClassNotFoundException e) {
throw new IgniteException("Failed to find class: " + cls, e);
}
catch (NoSuchMethodException e) {
throw new IgniteException("Failed to find method: " + mtd, e);
}
catch (InvocationTargetException | IllegalAccessException e) {
throw new IgniteException("Failed to invoke method: " + mtd, e);
}
| 468
| 158
| 626
|
<no_super_class>
|
apache_ignite
|
ignite/modules/kubernetes/src/main/java/org/apache/ignite/spi/discovery/tcp/ipfinder/kubernetes/TcpDiscoveryKubernetesIpFinder.java
|
TcpDiscoveryKubernetesIpFinder
|
getRegisteredAddresses
|
class TcpDiscoveryKubernetesIpFinder extends TcpDiscoveryIpFinderAdapter {
/** Kubernetes connection configuration */
private final KubernetesConnectionConfiguration cfg;
/**
* Creates an instance of Kubernetes IP finder.
*/
public TcpDiscoveryKubernetesIpFinder() {
this(new KubernetesConnectionConfiguration());
}
/**
* Creates an instance of Kubernetes IP finder.
*
* @param cfg Kubernetes IP finder configuration.
*/
public TcpDiscoveryKubernetesIpFinder(KubernetesConnectionConfiguration cfg) {
setShared(true);
this.cfg = cfg;
}
/** {@inheritDoc} */
@Override public Collection<InetSocketAddress> getRegisteredAddresses() throws IgniteSpiException {<FILL_FUNCTION_BODY>}
/** {@inheritDoc} */
@Override public void registerAddresses(Collection<InetSocketAddress> addrs) throws IgniteSpiException {
// No-op
}
/** {@inheritDoc} */
@Override public void unregisterAddresses(Collection<InetSocketAddress> addrs) throws IgniteSpiException {
// No-op
}
/**
* @param service Kubernetes service name.
* @deprecated set parameters with {@code KubernetesConnectionConfiguration} instead.
*/
@Deprecated
public void setServiceName(String service) {
cfg.setServiceName(service);
}
/**
* @param namespace Namespace of the Kubernetes service.
* @deprecated set parameters with {@code KubernetesConnectionConfiguration} instead.
*/
@Deprecated
public void setNamespace(String namespace) {
cfg.setNamespace(namespace);
}
/**
* @param master Host name of the Kubernetes API server.
* @deprecated set parameters with {@code KubernetesConnectionConfiguration} instead.
*/
@Deprecated
public void setMasterUrl(String master) {
cfg.setMasterUrl(master);
}
/**
* @param accountToken Path to the service token file.
* @deprecated set parameters with {@code KubernetesConnectionConfiguration} instead.
*/
@Deprecated
public void setAccountToken(String accountToken) {
cfg.setAccountToken(accountToken);
}
/**
* @param includeNotReadyAddresses Whether addresses of not-ready pods should be included.
* @deprecated set parameters with {@code KubernetesConnectionConfiguration} instead.
*/
@Deprecated
public void includeNotReadyAddresses(boolean includeNotReadyAddresses) {
cfg.setIncludeNotReadyAddresses(includeNotReadyAddresses);
}
}
|
try {
return new KubernetesServiceAddressResolver(cfg)
.getServiceAddresses()
.stream().map(addr -> new InetSocketAddress(addr, cfg.getDiscoveryPort()))
.collect(Collectors.toCollection(ArrayList::new));
}
catch (Exception e) {
throw new IgniteSpiException(e);
}
| 692
| 95
| 787
|
<methods>public non-sealed void <init>() ,public void close() ,public void initializeLocalAddresses(Collection<InetSocketAddress>) throws org.apache.ignite.spi.IgniteSpiException,public boolean isShared() ,public void onSpiContextDestroyed() ,public void onSpiContextInitialized(org.apache.ignite.spi.IgniteSpiContext) throws org.apache.ignite.spi.IgniteSpiException,public org.apache.ignite.spi.discovery.tcp.ipfinder.TcpDiscoveryIpFinderAdapter setShared(boolean) ,public java.lang.String toString() <variables>protected org.apache.ignite.Ignite ignite,private boolean shared,private volatile org.apache.ignite.spi.IgniteSpiContext spiCtx
|
apache_ignite
|
ignite/modules/spring/src/main/java/org/apache/ignite/IgniteClientSpringBean.java
|
IgniteClientSpringBean
|
start
|
class IgniteClientSpringBean implements IgniteClient, SmartLifecycle {
/** Default Ignite client {@link SmartLifecycle} phase. */
public static final int DFLT_IGNITE_CLI_LIFECYCLE_PHASE = 0;
/** Whether this component is initialized and running. */
private volatile boolean isRunning;
/** Ignite client instance to which operations are delegated. */
private IgniteClient cli;
/** Ignite client configuration. */
private ClientConfiguration cfg;
/** Ignite client {@link SmartLifecycle} phase. */
private int phase = DFLT_IGNITE_CLI_LIFECYCLE_PHASE;
/** {@inheritDoc} */
@Override public boolean isAutoStartup() {
return true;
}
/** {@inheritDoc} */
@Override public void stop(Runnable callback) {
stop();
callback.run();
}
/** {@inheritDoc} */
@Override public void stop() {
isRunning = false;
}
/** {@inheritDoc} */
@Override public boolean isRunning() {
return isRunning;
}
/** {@inheritDoc} */
@Override public void start() {<FILL_FUNCTION_BODY>}
/** {@inheritDoc} */
@Override public int getPhase() {
return phase;
}
/** {@inheritDoc} */
@Override public <K, V> ClientCache<K, V> getOrCreateCache(String name) throws ClientException {
return cli.getOrCreateCache(name);
}
/** {@inheritDoc} */
@Override public <K, V> IgniteClientFuture<ClientCache<K, V>> getOrCreateCacheAsync(
String name
) throws ClientException {
return cli.getOrCreateCacheAsync(name);
}
/** {@inheritDoc} */
@Override public <K, V> ClientCache<K, V> getOrCreateCache(ClientCacheConfiguration cfg) throws ClientException {
return cli.getOrCreateCache(cfg);
}
/** {@inheritDoc} */
@Override public <K, V> IgniteClientFuture<ClientCache<K, V>> getOrCreateCacheAsync(
ClientCacheConfiguration cfg
) throws ClientException {
return cli.getOrCreateCacheAsync(cfg);
}
/** {@inheritDoc} */
@Override public <K, V> ClientCache<K, V> cache(String name) {
return cli.cache(name);
}
/** {@inheritDoc} */
@Override public Collection<String> cacheNames() throws ClientException {
return cli.cacheNames();
}
/** {@inheritDoc} */
@Override public IgniteClientFuture<Collection<String>> cacheNamesAsync() throws ClientException {
return cli.cacheNamesAsync();
}
/** {@inheritDoc} */
@Override public void destroyCache(String name) throws ClientException {
cli.destroyCache(name);
}
/** {@inheritDoc} */
@Override public IgniteClientFuture<Void> destroyCacheAsync(String name) throws ClientException {
return cli.destroyCacheAsync(name);
}
/** {@inheritDoc} */
@Override public <K, V> ClientCache<K, V> createCache(String name) throws ClientException {
return cli.createCache(name);
}
/** {@inheritDoc} */
@Override public <K, V> IgniteClientFuture<ClientCache<K, V>> createCacheAsync(String name) throws ClientException {
return cli.createCacheAsync(name);
}
/** {@inheritDoc} */
@Override public <K, V> ClientCache<K, V> createCache(ClientCacheConfiguration cfg) throws ClientException {
return cli.createCache(cfg);
}
/** {@inheritDoc} */
@Override public <K, V> IgniteClientFuture<ClientCache<K, V>> createCacheAsync(
ClientCacheConfiguration cfg
) throws ClientException {
return cli.createCacheAsync(cfg);
}
/** {@inheritDoc} */
@Override public IgniteBinary binary() {
return cli.binary();
}
/** {@inheritDoc} */
@Override public FieldsQueryCursor<List<?>> query(SqlFieldsQuery qry) {
return cli.query(qry);
}
/** {@inheritDoc} */
@Override public ClientTransactions transactions() {
return cli.transactions();
}
/** {@inheritDoc} */
@Override public ClientCompute compute() {
return cli.compute();
}
/** {@inheritDoc} */
@Override public ClientCompute compute(ClientClusterGroup grp) {
return cli.compute(grp);
}
/** {@inheritDoc} */
@Override public ClientCluster cluster() {
return cli.cluster();
}
/** {@inheritDoc} */
@Override public ClientServices services() {
return cli.services();
}
/** {@inheritDoc} */
@Override public ClientServices services(ClientClusterGroup grp) {
return cli.services(grp);
}
/** {@inheritDoc} */
@Override public ClientAtomicLong atomicLong(String name, long initVal, boolean create) {
return cli.atomicLong(name, initVal, create);
}
/** {@inheritDoc} */
@Override public ClientAtomicLong atomicLong(String name, ClientAtomicConfiguration cfg, long initVal, boolean create) {
return cli.atomicLong(name, cfg, initVal, create);
}
/** {@inheritDoc} */
@Override public <T> ClientIgniteSet<T> set(String name, @Nullable ClientCollectionConfiguration cfg) {
return cli.set(name, cfg);
}
/** {@inheritDoc} */
@Override public void close() {
cli.close();
}
/**
* Sets Ignite client configuration.
*
* @param cfg Ignite thin client configuration.
* @return {@code this} for chaining.
*/
public IgniteClientSpringBean setClientConfiguration(ClientConfiguration cfg) {
this.cfg = cfg;
return this;
}
/** @return Ignite client configuration. */
public ClientConfiguration getClientConfiguration() {
return cfg;
}
/**
* Sets {@link SmartLifecycle} phase during which the current bean will be initialized. Note, underlying Ignite
* client will be closed during handling of {@link DisposableBean} since {@link IgniteClient}
* implements {@link AutoCloseable} interface.
*
* @param phase {@link SmartLifecycle} phase.
* @return {@code this} for chaining.
*/
public IgniteClientSpringBean setPhase(int phase) {
this.phase = phase;
return this;
}
}
|
if (cfg == null)
throw new IllegalArgumentException("Ignite client configuration must be set.");
cli = Ignition.startClient(cfg);
isRunning = true;
| 1,757
| 48
| 1,805
|
<no_super_class>
|
apache_ignite
|
ignite/modules/spring/src/main/java/org/apache/ignite/internal/processors/resource/GridSpringResourceContextImpl.java
|
GridSpringResourceContextImpl
|
unwrapTarget
|
class GridSpringResourceContextImpl implements GridSpringResourceContext {
/** Spring application context injector. */
private GridResourceInjector springCtxInjector;
/** Spring bean resources injector. */
private GridResourceInjector springBeanInjector;
/**
* @param springCtx Spring application context.
*/
public GridSpringResourceContextImpl(@Nullable ApplicationContext springCtx) {
springCtxInjector = new GridResourceBasicInjector<>(springCtx);
springBeanInjector = new GridResourceSpringBeanInjector(springCtx);
}
/** {@inheritDoc} */
@Override public GridResourceInjector springBeanInjector() {
return springBeanInjector;
}
/** {@inheritDoc} */
@Override public GridResourceInjector springContextInjector() {
return springCtxInjector;
}
/** {@inheritDoc} */
@Override public Object unwrapTarget(Object target) throws IgniteCheckedException {<FILL_FUNCTION_BODY>}
}
|
if (target instanceof Advised) {
try {
return ((Advised)target).getTargetSource().getTarget();
}
catch (Exception e) {
throw new IgniteCheckedException("Failed to unwrap Spring proxy target [cls=" + target.getClass().getName() +
", target=" + target + ']', e);
}
}
return target;
| 269
| 100
| 369
|
<no_super_class>
|
apache_ignite
|
ignite/modules/urideploy/src/main/java/org/apache/ignite/spi/deployment/uri/GridUriDeploymentClassLoader.java
|
GridUriDeploymentClassLoader
|
loadClassIsolated
|
class GridUriDeploymentClassLoader extends URLClassLoader {
/**
* Creates new instance of class loader.
*
* @param urls The URLs from which to load classes and resources.
* @param parent The parent class loader for delegation.
*/
GridUriDeploymentClassLoader(URL[] urls, ClassLoader parent) {
super(urls, parent);
}
/** {@inheritDoc} */
@Override protected synchronized Class<?> loadClass(String name, boolean resolve) throws ClassNotFoundException {
// First, check if the class has already been loaded.
Class cls = findLoadedClass(name);
if (cls == null) {
try {
try {
// Search classes in a deployment unit.
// NOTE: findClass(String) is not overridden since it is always called after
// findLoadedClass(String) in exclusive synchronization block.
cls = findClass(name);
}
catch (ClassNotFoundException ignored) {
// If still not found, then invoke parent class loader in order
// to find the class.
cls = super.loadClass(name, resolve);
}
}
catch (ClassNotFoundException e) {
throw e;
}
// Catch Throwable to secure against any errors resulted from
// corrupted class definitions or other user errors.
catch (Exception e) {
throw new ClassNotFoundException("Failed to load class due to unexpected error: " + name, e);
}
}
return cls;
}
/**
* Load class from a deployment unit.
*
* @param name Class name.
* @return Loaded class.
* @throws ClassNotFoundException If no class found.
*/
public synchronized Class<?> loadClassIsolated(String name) throws ClassNotFoundException {<FILL_FUNCTION_BODY>}
/**
* Load class from GAR file.
*
* @param name Class name.
* @return Loaded class.
* @throws ClassNotFoundException If no class found.
* @deprecated Use {@link GridUriDeploymentClassLoader#loadClassIsolated(String)} instead.
*/
@Deprecated
public synchronized Class<?> loadClassGarOnly(String name) throws ClassNotFoundException {
return loadClassIsolated(name);
}
/** {@inheritDoc} */
@Override public URL getResource(String name) {
URL url = findResource(name);
if (url == null)
url = ClassLoader.getSystemResource(name);
if (url == null)
url = super.getResource(name);
return url;
}
/** {@inheritDoc} */
@Override public InputStream getResourceAsStream(String name) {
// Find resource in a deployment unit first.
InputStream in = getResourceAsStreamIsolated(name);
// Find resource in parent class loader.
if (in == null)
in = ClassLoader.getSystemResourceAsStream(name);
if (in == null)
in = super.getResourceAsStream(name);
return in;
}
/**
* Returns an input stream for reading the specified resource from a deployment unit only.
*
* @param name Resource name.
* @return An input stream for reading the resource, or {@code null}
* if the resource could not be found.
*/
@Nullable public InputStream getResourceAsStreamIsolated(String name) {
URL url = findResource(name);
try {
return url != null ? url.openStream() : null;
}
catch (IOException ignored) {
return null;
}
}
/**
* Returns an input stream for reading the specified resource from GAR file only.
*
* @param name Resource name.
* @return An input stream for reading the resource, or {@code null}
* if the resource could not be found.
*
* @deprecated Use {@link GridUriDeploymentClassLoader#getResourceAsStreamIsolated(String)} instead.
*/
@Deprecated
@Nullable public InputStream getResourceAsStreamGarOnly(String name) {
return getResourceAsStreamIsolated(name);
}
/** {@inheritDoc} */
@Override public String toString() {
return S.toString(GridUriDeploymentClassLoader.class, this, "urls", Arrays.toString(getURLs()));
}
}
|
// First, check if the class has already been loaded.
Class<?> cls = findLoadedClass(name);
if (cls == null) {
try {
// Search classes in deployment unit.
// NOTE: findClass(String) is not overridden since it is always called after
// findLoadedClass(String) in exclusive synchronization block.
cls = findClass(name);
}
catch (ClassNotFoundException e) {
throw e;
}
// Catch Throwable to secure against any errors resulted from
// corrupted class definitions or other user errors.
catch (Exception e) {
throw new ClassNotFoundException("Failed to load class due to unexpected error: " + name, e);
}
}
return cls;
| 1,116
| 196
| 1,312
|
<no_super_class>
|
apache_ignite
|
ignite/modules/urideploy/src/main/java/org/apache/ignite/spi/deployment/uri/GridUriDeploymentDiscovery.java
|
GridUriDeploymentDiscovery
|
findResourcesInDirectory
|
class GridUriDeploymentDiscovery {
/**
* Enforces singleton.
*/
private GridUriDeploymentDiscovery() {
// No-op.
}
/**
* Load classes from given file. File could be either directory or JAR file.
*
* @param clsLdr Class loader to load files.
* @param file Either directory or JAR file which contains classes or
* references to them.
* @return Set of found and loaded classes or empty set if file does not
* exist.
* @throws org.apache.ignite.spi.IgniteSpiException Thrown if given JAR file references to none
* existed class or IOException occurred during processing.
*/
static Set<Class<? extends ComputeTask<?, ?>>> getClasses(ClassLoader clsLdr, File file)
throws IgniteSpiException {
Set<Class<? extends ComputeTask<?, ?>>> rsrcs = new HashSet<>();
if (!file.exists())
return rsrcs;
GridUriDeploymentFileResourceLoader fileRsrcLdr = new GridUriDeploymentFileResourceLoader(clsLdr, file);
if (file.isDirectory())
findResourcesInDirectory(fileRsrcLdr, file, rsrcs);
else {
try {
for (JarEntry entry : U.asIterable(new JarFile(file.getAbsolutePath()).entries())) {
Class<? extends ComputeTask<?, ?>> rsrc = fileRsrcLdr.createResource(entry.getName(), false);
if (rsrc != null)
rsrcs.add(rsrc);
}
}
catch (IOException e) {
throw new IgniteSpiException("Failed to discover classes in file: " + file.getAbsolutePath(), e);
}
}
return rsrcs;
}
/**
* Recursively scans given directory and load all found files by loader.
*
* @param clsLdr Loader that could load class from given file.
* @param dir Directory which should be scanned.
* @param rsrcs Set which will be filled in.
*/
private static void findResourcesInDirectory(GridUriDeploymentFileResourceLoader clsLdr, File dir,
Set<Class<? extends ComputeTask<?, ?>>> rsrcs) {<FILL_FUNCTION_BODY>}
}
|
assert dir.isDirectory();
for (File file : dir.listFiles()) {
if (file.isDirectory()) {
// Recurse down into directories.
findResourcesInDirectory(clsLdr, file, rsrcs);
}
else {
Class<? extends ComputeTask<?, ?>> rsrc = null;
try {
rsrc = clsLdr.createResource(file.getAbsolutePath(), true);
}
catch (IgniteSpiException e) {
// Must never happen because we use 'ignoreUnknownRsrc=true'.
assert false;
}
if (rsrc != null)
rsrcs.add(rsrc);
}
}
| 601
| 181
| 782
|
<no_super_class>
|
apache_ignite
|
ignite/modules/urideploy/src/main/java/org/apache/ignite/spi/deployment/uri/GridUriDeploymentSpringDocument.java
|
GridUriDeploymentSpringDocument
|
getTasks
|
class GridUriDeploymentSpringDocument {
/** Initialized springs beans factory. */
private final XmlBeanFactory factory;
/** List of tasks from package description. */
private List<Class<? extends ComputeTask<?, ?>>> tasks;
/**
* Creates new instance of configuration helper with given configuration.
*
* @param factory Configuration factory.
*/
GridUriDeploymentSpringDocument(XmlBeanFactory factory) {
assert factory != null;
this.factory = factory;
}
/**
* Loads tasks declared in configuration by given class loader.
*
* @param clsLdr Class loader.
* @return Declared tasks.
* @throws org.apache.ignite.spi.IgniteSpiException Thrown if there are no tasks in
* configuration or configuration could not be read.
*/
@SuppressWarnings({"unchecked"})
List<Class<? extends ComputeTask<?, ?>>> getTasks(ClassLoader clsLdr) throws IgniteSpiException {<FILL_FUNCTION_BODY>}
/** {@inheritDoc} */
@Override public String toString() {
return S.toString(GridUriDeploymentSpringDocument.class, this);
}
}
|
assert clsLdr != null;
try {
if (tasks == null) {
tasks = new ArrayList<>();
Map<String, List> beans = factory.getBeansOfType(List.class);
if (!beans.isEmpty()) {
for (List<String> list : beans.values()) {
for (String clsName : list) {
Class taskCls;
try {
taskCls = clsLdr.loadClass(clsName);
}
catch (ClassNotFoundException e) {
throw new IgniteSpiException("Failed to load task class [className=" + clsName + ']', e);
}
assert taskCls != null;
tasks.add(taskCls);
}
}
}
}
}
catch (BeansException e) {
throw new IgniteSpiException("Failed to get tasks declared in XML file.", e);
}
return tasks;
| 315
| 248
| 563
|
<no_super_class>
|
apache_ignite
|
ignite/modules/urideploy/src/main/java/org/apache/ignite/spi/deployment/uri/scanners/UriDeploymentScannerManager.java
|
UriDeploymentScannerManager
|
start
|
class UriDeploymentScannerManager implements UriDeploymentScannerContext {
/** Ignite instance name. */
private final String igniteInstanceName;
/** URI that scanner should looks after. */
@GridToStringExclude
private final URI uri;
/** Temporary deployment directory. */
private final File deployDir;
/** Scan frequency. */
private final long freq;
/** Found files filter. */
private final FilenameFilter filter;
/** Scanner listener which should be notified about changes. */
private final GridUriDeploymentScannerListener lsnr;
/** Logger. */
private final IgniteLogger log;
/** Underlying scanner. */
private final UriDeploymentScanner scanner;
/** Scanner implementation. */
private IgniteSpiThread scannerThread;
/** Whether first scan completed or not. */
private boolean firstScan = true;
/**
* Creates new scanner.
*
* @param igniteInstanceName Ignite instance name.
* @param uri URI which scanner should looks after.
* @param deployDir Temporary deployment directory.
* @param freq Scan frequency.
* @param filter Found files filter.
* @param lsnr Scanner listener which should be notifier about changes.
* @param log Logger.
* @param scanner Scanner.
*/
public UriDeploymentScannerManager(
String igniteInstanceName,
URI uri,
File deployDir,
long freq,
FilenameFilter filter,
GridUriDeploymentScannerListener lsnr,
IgniteLogger log,
UriDeploymentScanner scanner) {
assert uri != null;
assert freq > 0;
assert deployDir != null;
assert filter != null;
assert log != null;
assert lsnr != null;
assert scanner != null;
this.igniteInstanceName = igniteInstanceName;
this.uri = uri;
this.deployDir = deployDir;
this.freq = freq;
this.filter = filter;
this.log = log.getLogger(getClass());
this.lsnr = lsnr;
this.scanner = scanner;
}
/**
* Starts scanner.
*/
public void start() {<FILL_FUNCTION_BODY>}
/**
* Cancels scanner execution.
*/
public void cancel() {
U.interrupt(scannerThread);
}
/**
* Joins scanner thread.
*/
public void join() {
U.join(scannerThread, log);
if (log.isDebugEnabled())
log.debug("Grid URI deployment scanner stopped: " + this);
}
/** {@inheritDoc} */
@Override public boolean isCancelled() {
assert scannerThread != null;
return scannerThread.isInterrupted();
}
/** {@inheritDoc} */
@Override public File createTempFile(String fileName, File tmpDir) throws IOException {
assert fileName != null;
int idx = fileName.lastIndexOf('.');
if (idx == -1)
idx = fileName.length();
String prefix = fileName.substring(0, idx);
if (idx < 3) { // Prefix must be at least 3 characters long. See File.createTempFile(...).
prefix += "___";
}
String suffix = fileName.substring(idx);
return File.createTempFile(prefix, suffix, tmpDir);
}
/** {@inheritDoc} */
@Override public boolean isFirstScan() {
return firstScan;
}
/** {@inheritDoc} */
@Override public URI getUri() {
return uri;
}
/** {@inheritDoc} */
@Override public File getDeployDirectory() {
return deployDir;
}
/** {@inheritDoc} */
@Override public FilenameFilter getFilter() {
return filter;
}
/** {@inheritDoc} */
@Override public GridUriDeploymentScannerListener getListener() {
return lsnr;
}
/** {@inheritDoc} */
@Override public IgniteLogger getLogger() {
return log;
}
/** {@inheritDoc} */
@Override public String toString() {
return S.toString(UriDeploymentScannerManager.class, this, "uri", U.hidePassword(uri.toString()));
}
}
|
scannerThread = new IgniteSpiThread(igniteInstanceName, "grid-uri-scanner", log) {
/** {@inheritDoc} */
@SuppressWarnings({"BusyWait"})
@Override protected void body() throws InterruptedException {
try {
while (!isInterrupted()) {
try {
scanner.scan(UriDeploymentScannerManager.this);
}
catch (Exception e) {
log.error("Uncaught error in URI deployment scanner", e);
}
finally {
// Do it in finally to avoid any hanging.
if (firstScan) {
firstScan = false;
lsnr.onFirstScanFinished();
}
}
Thread.sleep(freq);
}
}
finally {
// Double check. If we were cancelled before anything has been scanned.
if (firstScan) {
firstScan = false;
lsnr.onFirstScanFinished();
}
}
}
};
scannerThread.start();
if (log.isDebugEnabled())
log.debug("Grid URI deployment scanner started: " + this);
| 1,151
| 298
| 1,449
|
<no_super_class>
|
apache_ignite
|
ignite/modules/web/src/main/java/org/apache/ignite/cache/websession/WebSessionListener.java
|
AttributesProcessor
|
process
|
class AttributesProcessor implements EntryProcessor<String, WebSession, Void>, Externalizable {
/** */
private static final long serialVersionUID = 0L;
/** Updates list. */
private Collection<T2<String, Object>> updates;
/**
* Required by {@link Externalizable}.
*/
public AttributesProcessor() {
// No-op.
}
/**
* @param updates Updates list.
*/
AttributesProcessor(Collection<T2<String, Object>> updates) {
assert updates != null;
this.updates = updates;
}
/** {@inheritDoc} */
@Override public Void process(MutableEntry<String, WebSession> entry, Object... args) {<FILL_FUNCTION_BODY>}
/** {@inheritDoc} */
@Override public void writeExternal(ObjectOutput out) throws IOException {
U.writeCollection(out, updates);
}
/** {@inheritDoc} */
@Override public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException {
updates = U.readCollection(in);
}
}
|
if (!entry.exists())
return null;
WebSession ses0 = entry.getValue();
WebSession ses = new WebSession(ses0.getId(), ses0);
for (T2<String, Object> update : updates) {
String name = update.get1();
assert name != null;
Object val = update.get2();
if (val != null)
ses.setAttribute(name, val);
else
ses.removeAttribute(name);
}
entry.setValue(ses);
return null;
| 285
| 146
| 431
|
<no_super_class>
|
apache_ignite
|
ignite/modules/zookeeper/src/main/java/org/apache/ignite/spi/discovery/zk/internal/ZkBulkJoinContext.java
|
ZkBulkJoinContext
|
addJoinedNode
|
class ZkBulkJoinContext {
/** */
List<T2<ZkJoinedNodeEvtData, Map<Integer, Serializable>>> nodes;
/**
* @param nodeEvtData Node event data.
* @param discoData Discovery data for node.
*/
void addJoinedNode(ZkJoinedNodeEvtData nodeEvtData, Map<Integer, Serializable> discoData) {<FILL_FUNCTION_BODY>}
/**
* @return Number of joined nodes.
*/
int nodes() {
return nodes != null ? nodes.size() : 0;
}
}
|
if (nodes == null)
nodes = new ArrayList<>();
nodes.add(new T2<>(nodeEvtData, discoData));
| 161
| 40
| 201
|
<no_super_class>
|
apache_ignite
|
ignite/modules/zookeeper/src/main/java/org/apache/ignite/spi/discovery/zk/internal/ZkDistributedCollectDataFuture.java
|
ZkDistributedCollectDataFuture
|
onTopologyChange
|
class ZkDistributedCollectDataFuture extends GridFutureAdapter<Void> {
/** */
private final IgniteLogger log;
/** */
private final String futPath;
/** */
private final Set<Long> remainingNodes;
/** */
private final Callable<Void> lsnr;
/**
* @param impl Disovery impl
* @param rtState Runtime state.
* @param futPath Future path.
* @param lsnr Future listener.
* @throws Exception If listener call failed.
*/
ZkDistributedCollectDataFuture(
ZookeeperDiscoveryImpl impl,
ZkRuntimeState rtState,
String futPath,
Callable<Void> lsnr
) throws Exception {
this.log = impl.log();
this.futPath = futPath;
this.lsnr = lsnr;
ZkClusterNodes top = rtState.top;
// Assume new nodes can not join while future is in progress.
remainingNodes = U.newHashSet(top.nodesByOrder.size());
for (ZookeeperClusterNode node : top.nodesByInternalId.values())
remainingNodes.add(node.order());
NodeResultsWatcher watcher = new NodeResultsWatcher(rtState, impl);
if (remainingNodes.isEmpty())
completeAndNotifyListener();
else {
if (log.isInfoEnabled()) {
log.info("Initialize data collect future [futPath=" + futPath + ", " +
"remainingNodes=" + remainingNodes.size() + ']');
}
rtState.zkClient.getChildrenAsync(futPath, watcher, watcher);
}
}
/**
* @throws Exception If listener call failed.
*/
private void completeAndNotifyListener() throws Exception {
if (super.onDone())
lsnr.call();
}
/**
* @param futPath
* @param client
* @param nodeOrder
* @param data
* @throws Exception If failed.
*/
static void saveNodeResult(String futPath, ZookeeperClient client, long nodeOrder, byte[] data) throws Exception {
client.createIfNeeded(futPath + "/" + nodeOrder, data, CreateMode.PERSISTENT);
}
/**
* @param futPath
* @param client
* @param nodeOrder
* @return Node result data.
* @throws Exception If fai.ed
*/
static byte[] readNodeResult(String futPath, ZookeeperClient client, long nodeOrder) throws Exception {
return client.getData(futPath + "/" + nodeOrder);
}
/**
* @param futResPath Result path.
* @param client Client.
* @param data Result data.
* @throws Exception If failed.
*/
static void saveResult(String futResPath, ZookeeperClient client, byte[] data) throws Exception {
client.createIfNeeded(futResPath, data, CreateMode.PERSISTENT);
}
/** */
static byte[] readResult(ZookeeperClient client, ZkIgnitePaths paths, UUID futId) throws Exception {
return client.getData(paths.distributedFutureResultPath(futId));
}
/**
* @param client Client.
* @param paths Paths utils.
* @param futId Future ID.
* @param log Ignite Logger.
* @throws Exception If failed.
*/
static void deleteFutureData(ZookeeperClient client,
ZkIgnitePaths paths,
UUID futId,
IgniteLogger log
) throws Exception {
List<String> batch = new LinkedList<>();
String evtDir = paths.distributedFutureBasePath(futId);
if (client.exists(evtDir)) {
batch.addAll(client.getChildrenPaths(evtDir));
batch.add(evtDir);
}
batch.add(paths.distributedFutureResultPath(futId));
client.deleteAll(batch, -1);
}
/**
* @param top Current topology.
* @throws Exception If listener call failed.
*/
void onTopologyChange(ZkClusterNodes top) throws Exception {<FILL_FUNCTION_BODY>}
/**
*
*/
class NodeResultsWatcher extends ZkAbstractWatcher implements AsyncCallback.Children2Callback {
/**
* @param rtState Runtime state.
* @param impl Discovery impl.
*/
NodeResultsWatcher(ZkRuntimeState rtState, ZookeeperDiscoveryImpl impl) {
super(rtState, impl);
}
/** {@inheritDoc} */
@Override protected void process0(WatchedEvent evt) {
if (evt.getType() == Watcher.Event.EventType.NodeChildrenChanged)
rtState.zkClient.getChildrenAsync(evt.getPath(), this, this);
}
/** {@inheritDoc} */
@Override public void processResult(int rc, String path, Object ctx, List<String> children, Stat stat) {
if (!onProcessStart())
return;
try {
if (!isDone()) {
assert rc == 0 : KeeperException.Code.get(rc);
for (int i = 0; i < children.size(); i++) {
Long nodeOrder = Long.parseLong(children.get(i));
if (remainingNodes.remove(nodeOrder)) {
int remaining = remainingNodes.size();
if (log.isInfoEnabled()) {
log.info("ZkDistributedCollectDataFuture added new result [node=" + nodeOrder +
", remaining=" + remaining +
", futPath=" + path + ']');
}
if (remaining == 0)
completeAndNotifyListener();
}
}
}
onProcessEnd();
}
catch (Throwable e) {
onProcessError(e);
}
}
}
}
|
if (remainingNodes.isEmpty())
return;
for (Iterator<Long> it = remainingNodes.iterator(); it.hasNext();) {
Long nodeOrder = it.next();
if (!top.nodesByOrder.containsKey(nodeOrder)) {
it.remove();
int remaining = remainingNodes.size();
if (log.isInfoEnabled()) {
log.info("ZkDistributedCollectDataFuture removed remaining failed node [node=" + nodeOrder +
", remaining=" + remaining +
", futPath=" + futPath + ']');
}
if (remaining == 0) {
completeAndNotifyListener();
break;
}
}
}
| 1,561
| 181
| 1,742
|
<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/zookeeper/src/main/java/org/apache/ignite/spi/discovery/zk/internal/ZkRuntimeState.java
|
ZkRuntimeState
|
onCloseStart
|
class ZkRuntimeState {
/** */
ZkWatcher watcher;
/** */
ZkAliveNodeDataWatcher aliveNodeDataWatcher;
/** */
volatile Exception errForClose;
/** */
final boolean reconnect;
/** */
volatile ZookeeperClient zkClient;
/** */
long internalOrder;
/** */
int joinDataPartCnt;
/** */
long gridStartTime;
/** */
volatile boolean joined;
/** */
ZkDiscoveryEventsData evtsData;
/** */
boolean crd;
/** */
String locNodeZkPath;
/** */
final ZkAliveNodeData locNodeInfo = new ZkAliveNodeData();
/** */
int procEvtCnt;
/** */
final ZkClusterNodes top = new ZkClusterNodes();
/** */
List<ClusterNode> commErrProcNodes;
/** Timeout callback registering watcher for join error
* (set this watcher after timeout as a minor optimization).
*/
ZkTimeoutObject joinErrTo;
/** Timeout callback set to wait for join timeout. */
ZkTimeoutObject joinTo;
/** Timeout callback to update processed events counter. */
ZkTimeoutObject procEvtsUpdateTo;
/** */
boolean updateAlives;
/**
* @param reconnect {@code True} if joined topology before reconnect attempt.
*/
ZkRuntimeState(boolean reconnect) {
this.reconnect = reconnect;
}
/**
* @param watcher Watcher.
* @param aliveNodeDataWatcher Alive nodes data watcher.
*/
void init(ZkWatcher watcher, ZkAliveNodeDataWatcher aliveNodeDataWatcher) {
this.watcher = watcher;
this.aliveNodeDataWatcher = aliveNodeDataWatcher;
}
/**
* @param err Error.
*/
void onCloseStart(Exception err) {<FILL_FUNCTION_BODY>}
/**
*
*/
interface ZkWatcher extends Watcher, AsyncCallback.Children2Callback, AsyncCallback.DataCallback {
// No-op.
}
/**
*
*/
interface ZkAliveNodeDataWatcher extends Watcher, AsyncCallback.DataCallback {
// No-op.
}
}
|
assert err != null;
errForClose = err;
ZookeeperClient zkClient = this.zkClient;
if (zkClient != null)
zkClient.onCloseStart();
| 636
| 60
| 696
|
<no_super_class>
|
wildfirechat_im-server
|
im-server/broker/src/main/java/cn/wildfirechat/push/PushServer.java
|
PushServer
|
pushMessageInternel
|
class PushServer {
private static final Logger LOG = LoggerFactory.getLogger(PushServer.class);
protected static final Gson gson = new GsonBuilder().disableHtmlEscaping().create();
public interface PushMessageType {
int PUSH_MESSAGE_TYPE_NORMAL = 0;
int PUSH_MESSAGE_TYPE_VOIP_INVITE = 1;
int PUSH_MESSAGE_TYPE_VOIP_BYE = 2;
int PUSH_MESSAGE_TYPE_FRIEND_REQUEST = 3;
int PUSH_MESSAGE_TYPE_VOIP_ANSWER = 4;
int PUSH_MESSAGE_TYPE_RECALLED = 5;
int PUSH_MESSAGE_TYPE_DELETED = 6;
}
private static PushServer INSTANCE = new PushServer();
private ISessionsStore sessionsStore;
private static ExecutorService executorService = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors()*5);
private String androidPushServerUrl;
private String iOSPushServerUrl;
private PushServer() {
}
public static PushServer getServer() {
return INSTANCE;
}
public void init(IConfig config, ISessionsStore sessionsStore) {
this.sessionsStore = sessionsStore;
this.androidPushServerUrl = config.getProperty(PUSH_ANDROID_SERVER_ADDRESS);
this.iOSPushServerUrl = config.getProperty(PUSH_IOS_SERVER_ADDRESS);
}
public void pushMessage(PushMessage pushMessage, String deviceId, String pushContent) {
LOG.info("try to delivery push diviceId = {}, conversationType = {}, pushContent = {}", deviceId, pushMessage.convType, pushContent);
executorService.execute(() ->{
try {
pushMessageInternel(pushMessage, deviceId, pushContent);
} catch (Exception e) {
e.printStackTrace();
Utility.printExecption(LOG, e, IMExceptionEvent.EventType.PUSH_SERVER_Exception);
}
});
}
private void pushMessageInternel(PushMessage pushMessage, String deviceId, String pushContent) {<FILL_FUNCTION_BODY>}
}
|
if (pushMessage.pushMessageType == PushMessageType.PUSH_MESSAGE_TYPE_NORMAL && StringUtil.isNullOrEmpty(pushContent)) {
LOG.info("push content empty, deviceId {}", deviceId);
return;
}
MemorySessionStore.Session session = sessionsStore.getSession(deviceId);
int badge = session.getUnReceivedMsgs();
if (badge <= 0) {
badge = 1;
}
if (StringUtil.isNullOrEmpty(session.getDeviceToken())) {
LOG.warn("Device token is empty for device {}", deviceId);
return;
}
pushMessage.packageName = session.getAppName();
pushMessage.pushType = session.getPushType();
pushMessage.pushContent = pushContent;
pushMessage.deviceToken = session.getDeviceToken();
pushMessage.unReceivedMsg = badge;
pushMessage.userId = session.getUsername();
if (session.getPlatform() == ProtoConstants.Platform.Platform_iOS ||
session.getPlatform() == ProtoConstants.Platform.Platform_iPad ||
session.getPlatform() == ProtoConstants.Platform.Platform_Android ||
session.getPlatform() == ProtoConstants.Platform.Platform_APad ||
session.getPlatform() == ProtoConstants.Platform.Platform_Harmony ||
session.getPlatform() == ProtoConstants.Platform.Platform_HarmonyPad
) {
String url = androidPushServerUrl;
if (session.getPlatform() == ProtoConstants.Platform.Platform_iOS || session.getPlatform() == ProtoConstants.Platform.Platform_iPad) {
url = iOSPushServerUrl;
pushMessage.voipDeviceToken = session.getVoipDeviceToken();
}
HttpUtils.httpJsonPost(url, gson.toJson(pushMessage, pushMessage.getClass()), POST_TYPE_Push);
} else {
LOG.info("Not mobile platform {}", session.getPlatform());
}
| 586
| 508
| 1,094
|
<no_super_class>
|
wildfirechat_im-server
|
im-server/broker/src/main/java/cn/wildfirechat/server/ThreadPoolExecutorWrapper.java
|
ThreadPoolExecutorWrapper
|
execute
|
class ThreadPoolExecutorWrapper {
private static final Logger LOG = LoggerFactory.getLogger(ThreadPoolExecutorWrapper.class);
private final ScheduledExecutorService executor;
private final int count;
private final AtomicInteger runCounter;
private final String name;
public ThreadPoolExecutorWrapper(ScheduledExecutorService executor, int count, String name) {
this.executor = executor;
this.count = count;
this.runCounter = new AtomicInteger();
this.name = name;
}
public void execute(Runnable task) {<FILL_FUNCTION_BODY>}
public void shutdown() {
executor.shutdown();
}
}
|
int startCount = runCounter.incrementAndGet();
LOG.debug("Submit task and current task count {}", startCount);
final long startTime = System.currentTimeMillis();
executor.execute(() -> {
try {
task.run();
} finally {
int endCount = runCounter.decrementAndGet();
LOG.debug("Finish task and current task count {} use time {}", endCount, System.currentTimeMillis()-startTime);
}
});
| 176
| 126
| 302
|
<no_super_class>
|
wildfirechat_im-server
|
im-server/broker/src/main/java/com/xiaoleilu/loServer/LoFileServer.java
|
LoFileServer
|
start
|
class LoFileServer {
private static final org.slf4j.Logger Logger = LoggerFactory.getLogger(LoFileServer.class);
private int port;
private IMessagesStore messagesStore;
private Channel channel;
public LoFileServer(int port, IMessagesStore messagesStore) {
this.port = port;
this.messagesStore = messagesStore;
}
/**
* 启动服务
* @throws InterruptedException
*/
public void start() throws InterruptedException {<FILL_FUNCTION_BODY>}
public void shutdown() {
if (this.channel != null) {
this.channel.close();
try {
this.channel.closeFuture().sync();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
|
long start = System.currentTimeMillis();
// Configure the server.
final EventLoopGroup bossGroup = new NioEventLoopGroup(1);
final EventLoopGroup workerGroup = new NioEventLoopGroup();
try {
final ServerBootstrap b = new ServerBootstrap();
b.group(bossGroup, workerGroup)
.channel(NioServerSocketChannel.class)
.option(ChannelOption.SO_BACKLOG, 1024) // 服务端可连接队列大小
.option(ChannelOption.SO_KEEPALIVE, true)
.option(ChannelOption.SO_REUSEADDR, true)
.option(ChannelOption.TCP_NODELAY, true)
.option(ChannelOption.SO_SNDBUF, 1024*1024*10)
.option(ChannelOption.SO_RCVBUF, 1024*1024*10)
.childHandler(new ChannelInitializer<SocketChannel>() {
@Override
protected void initChannel(SocketChannel socketChannel) throws Exception {
socketChannel.pipeline().addLast(new HttpRequestDecoder());
socketChannel.pipeline().addLast(new HttpResponseEncoder());
socketChannel.pipeline().addLast(new ChunkedWriteHandler());
socketChannel.pipeline().addLast(new HttpObjectAggregator(100 * 1024 * 1024));
socketChannel.pipeline().addLast(new HttpFileServerHandler());
}
});
channel = b.bind(port).sync().channel();
Logger.info("***** Welcome To LoServer on port [{}], startting spend {}ms *****", port, DateUtil.spendMs(start));
} catch (Exception e) {
e.printStackTrace();
Logger.error("端口 {} 已经被占用。请检查该端口被那个程序占用,找到程序停掉。\n查找端口被那个程序占用的命令是: netstat -tunlp | grep {}", port, port);
System.out.println("端口 " + port + " 已经被占用。请检查该端口被那个程序占用,找到程序停掉。\n查找端口被那个程序占用的命令是: netstat -tunlp | grep " + port);
System.exit(-1);
}
| 210
| 595
| 805
|
<no_super_class>
|
wildfirechat_im-server
|
im-server/broker/src/main/java/com/xiaoleilu/loServer/LoServer.java
|
LoServer
|
start
|
class LoServer {
private static final org.slf4j.Logger Logger = LoggerFactory.getLogger(LoServer.class);
private int port;
private int adminPort;
private IMessagesStore messagesStore;
private ISessionsStore sessionsStore;
private Channel channel;
private Channel adminChannel;
public LoServer(int port, int adminPort, IMessagesStore messagesStore, ISessionsStore sessionsStore) {
this.port = port;
this.adminPort = adminPort;
this.messagesStore = messagesStore;
this.sessionsStore = sessionsStore;
}
/**
* 启动服务
* @throws InterruptedException
*/
public void start() throws InterruptedException {<FILL_FUNCTION_BODY>}
public void shutdown() {
if (this.channel!= null) {
this.channel.close();
try {
this.channel.closeFuture().sync();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
if (this.adminChannel != null) {
this.adminChannel.close();
try {
this.adminChannel.closeFuture().sync();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
private void registerAllAction() {
try {
for (Class cls:ClassUtil.getAllAssignedClass(Action.class)
) {
if(cls.getAnnotation(Route.class) != null) {
ServerSetting.setAction((Class<? extends Action>)cls);
}
}
} catch (IOException e) {
e.printStackTrace();
Utility.printExecption(Logger, e);
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
}
|
long start = System.currentTimeMillis();
// Configure the server.
final EventLoopGroup bossGroup = new NioEventLoopGroup(2);
final EventLoopGroup workerGroup = new NioEventLoopGroup();
registerAllAction();
int bindingPort = port;
try {
final ServerBootstrap b = new ServerBootstrap();
final ServerBootstrap adminB = new ServerBootstrap();
b.group(bossGroup, workerGroup)
.channel(NioServerSocketChannel.class)
.option(ChannelOption.SO_BACKLOG, 10240) // 服务端可连接队列大小
.childOption(ChannelOption.SO_KEEPALIVE, true)
.option(ChannelOption.SO_REUSEADDR, true)
.childOption(ChannelOption.TCP_NODELAY, true)
.childOption(ChannelOption.SO_SNDBUF, 1024*64)
.childOption(ChannelOption.SO_RCVBUF, 1024*64)
.childHandler(new ChannelInitializer<SocketChannel>() {
@Override
protected void initChannel(SocketChannel socketChannel) throws Exception {
socketChannel.pipeline().addLast(new HttpRequestDecoder());
socketChannel.pipeline().addLast(new HttpResponseEncoder());
socketChannel.pipeline().addLast(new ChunkedWriteHandler());
socketChannel.pipeline().addLast(new HttpObjectAggregator(100 * 1024 * 1024));
socketChannel.pipeline().addLast(new IMActionHandler(messagesStore, sessionsStore));
}
});
channel = b.bind(port).sync().channel();
bindingPort = adminPort;
adminB.group(bossGroup, workerGroup)
.channel(NioServerSocketChannel.class)
.option(ChannelOption.SO_BACKLOG, 10240) // 服务端可连接队列大小
.childOption(ChannelOption.SO_KEEPALIVE, true)
.option(ChannelOption.SO_REUSEADDR, true)
.childOption(ChannelOption.TCP_NODELAY, true)
.childOption(ChannelOption.SO_SNDBUF, 1024*64)
.childOption(ChannelOption.SO_RCVBUF, 1024*64)
.childHandler(new ChannelInitializer<SocketChannel>() {
@Override
protected void initChannel(SocketChannel socketChannel) throws Exception {
socketChannel.pipeline().addLast(new HttpRequestDecoder());
socketChannel.pipeline().addLast(new HttpResponseEncoder());
socketChannel.pipeline().addLast(new ChunkedWriteHandler());
socketChannel.pipeline().addLast(new HttpObjectAggregator(100 * 1024 * 1024));
socketChannel.pipeline().addLast(new AdminActionHandler(messagesStore, sessionsStore));
}
});
adminChannel = adminB.bind(adminPort).sync().channel();
Logger.info("***** Welcome To LoServer on port [{},{}], startting spend {}ms *****", port, adminPort, DateUtil.spendMs(start));
} catch (Exception e) {
e.printStackTrace();
Logger.error("端口 {} 已经被占用。请检查该端口被那个程序占用,找到程序停掉。\n查找端口被那个程序占用的命令是: netstat -tunlp | grep {}", bindingPort, bindingPort);
System.out.println("端口 " + bindingPort + " 已经被占用。请检查该端口被那个程序占用,找到程序停掉。\n查找端口被那个程序占用的命令是: netstat -tunlp | grep " + bindingPort);
System.exit(-1);
}
| 460
| 969
| 1,429
|
<no_super_class>
|
wildfirechat_im-server
|
im-server/broker/src/main/java/com/xiaoleilu/loServer/RestResult.java
|
RestResult
|
resultOf
|
class RestResult {
int code;
String msg;
Object result;
public static RestResult ok(Object object) {
return resultOf(ErrorCode.ERROR_CODE_SUCCESS, ErrorCode.ERROR_CODE_SUCCESS.getMsg(), object);
}
public static RestResult ok() {
return resultOf(ErrorCode.ERROR_CODE_SUCCESS, ErrorCode.ERROR_CODE_SUCCESS.getMsg(), null);
}
public static RestResult resultOf(ErrorCode errorCode) {
return resultOf(errorCode, errorCode.msg, null);
}
public static RestResult resultOf(ErrorCode errorCode, String msg) {
return resultOf(errorCode, msg, null);
}
public static RestResult resultOf(ErrorCode errorCode, String msg, Object object) {<FILL_FUNCTION_BODY>}
public void setErrorCode(ErrorCode errorCode) {
setCode(errorCode.code);
}
public int getCode() {
return code;
}
public void setCode(int code) {
this.code = code;
}
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
public Object getResult() {
return result;
}
public void setResult(Object result) {
this.result = result;
}
}
|
RestResult result = new RestResult();
result.code = errorCode.code;
result.msg = msg;
result.result = object;
return result;
| 370
| 45
| 415
|
<no_super_class>
|
wildfirechat_im-server
|
im-server/broker/src/main/java/com/xiaoleilu/loServer/action/Action.java
|
Result
|
doAction
|
class Result {
Object data;
ErrorCode errorCode;
public Result(ErrorCode errorCode) {
this.errorCode = errorCode;
}
public Result(ErrorCode errorCode, Object data) {
this.data = data;
this.errorCode = errorCode;
}
public Object getData() {
return data;
}
public ErrorCode getErrorCode() {
return errorCode;
}
}
protected interface ApiCallback {
Result onResult(byte[] response);
}
public ErrorCode preAction(Request request, Response response) {
if (getClass().getAnnotation(RequireAuthentication.class) != null) {
//do authentication
}
return ERROR_CODE_SUCCESS;
}
public boolean doAction(Request request, Response response) {<FILL_FUNCTION_BODY>
|
ErrorCode errorCode = preAction(request, response);
boolean isSync = true;
if (errorCode == ErrorCode.ERROR_CODE_SUCCESS) {
//事务逻辑有缺陷,先注释掉
// if (isTransactionAction() && !(this instanceof IMAction)) {
// DBUtil.beginTransaction();
// try {
// action(request, response);
// DBUtil.commit();
// } catch (Exception e) {
// e.printStackTrace();
// DBUtil.roolback();
// throw e;
// }
// } else {
isSync = action(request, response);
// }
} else {
response.setStatus(HttpResponseStatus.OK);
if (errorCode == null) {
errorCode = ErrorCode.ERROR_CODE_SUCCESS;
}
RestResult result = RestResult.resultOf(errorCode, errorCode.getMsg(), RestResult.resultOf(errorCode));
response.setContent(gson.toJson(result));
response.send();
}
return isSync;
| 222
| 277
| 499
|
<no_super_class>
|
wildfirechat_im-server
|
im-server/broker/src/main/java/com/xiaoleilu/loServer/action/CheckTokenAction.java
|
CheckTokenAction
|
action
|
class CheckTokenAction extends Action {
private final RateLimiter mLimitCounter = new RateLimiter(10, 1);
@Override
public boolean action(Request request, Response response) {<FILL_FUNCTION_BODY>}
}
|
if (request.getNettyRequest() instanceof FullHttpRequest) {
if(closeApiVersion) {
response.sendError(HttpResponseStatus.NOT_FOUND, "404 Not found!");
return true;
}
response.setStatus(HttpResponseStatus.OK);
String userId = request.getParam("userId");
String clientId = request.getParam("clientId");
String token = request.getParam("token");
String result = "这是个检查token有效性的接口,如果客户端无法连接成功,可以使用这个接口检查token是否正确。\n";
result += "使用方法是在浏览器中输入http://imserverip/api/verify_token?userId=${userId}&clientId=${clientId}&token=${token}。\n";
result += "例如:http://localhost/api/verify_token?userId=123&clientId=456&token=789。\n";
result += "特别注意的是:必须使用正确的clientId,clientId必须是在测试手机上调用im接口获取。不用手机上获取到的clientId也都是不同的,一定不能用错!!!\n\n\n";
if (StringUtil.isNullOrEmpty(userId)) {
result += "错误,userId为空";
} else if (StringUtil.isNullOrEmpty(clientId)) {
result += "错误,clientId为空";
} else if (StringUtil.isNullOrEmpty(token)) {
result += "错误,token为空";
} else if(!mLimitCounter.isGranted("verify_token")) {
result += "接口请求超频!接口限制每10秒只能验证一次!";
} else {
MemorySessionStore.Session session = sessionsStore.getSession(clientId);
if (session == null) {
result += "错误,session不存在。请确认token是从本服务通过getToken接口获取的,另外请确认clientId是否正确";
} else if (session.getDeleted() == 1) {
result += "错误,session已经被清除,请确认当前客户没有多端登录或者主动退出";
} else if(!session.getUsername().equals(userId)) {
result += "错误,当前客户端的登录用户不是" + userId + "。这一般发生在当前clientId又为其它用户获取过token";
} else {
String id = Tokenor.getUserId(token.getBytes());
if (id == null) {
result += "错误,无效的token";
} else if(!id.equals(userId)) {
result += "错误,改token是用户" + id + "的";
} else {
result += "恭喜,您的信息是正确的";
}
}
}
response.setContent(result);
}
return true;
| 63
| 714
| 777
|
<methods>public non-sealed void <init>() ,public abstract boolean action(com.xiaoleilu.loServer.handler.Request, com.xiaoleilu.loServer.handler.Response) ,public boolean doAction(com.xiaoleilu.loServer.handler.Request, com.xiaoleilu.loServer.handler.Response) ,public static void init(io.moquette.server.config.IConfig) ,public boolean isTransactionAction() ,public cn.wildfirechat.common.ErrorCode preAction(com.xiaoleilu.loServer.handler.Request, com.xiaoleilu.loServer.handler.Response) <variables>protected static win.liyufan.im.RateLimiter adminLimiter,protected static win.liyufan.im.RateLimiter channelLimiter,protected static boolean closeApiVersion,public ChannelHandlerContext ctx,protected static final com.google.gson.Gson gson,public static io.moquette.spi.IMessagesStore messagesStore,protected static win.liyufan.im.RateLimiter robotLimiter,public static io.moquette.spi.ISessionsStore sessionsStore
|
wildfirechat_im-server
|
im-server/broker/src/main/java/com/xiaoleilu/loServer/action/FileAction.java
|
FileAction
|
action
|
class FileAction extends Action {
private static final org.slf4j.Logger Logger = LoggerFactory.getLogger(FileAction.class);
@Override
public boolean action(Request request, Response response) {<FILL_FUNCTION_BODY>}
private static final Pattern INSECURE_URI = Pattern.compile(".*[<>&\"].*");
private static final SimpleDateFormat HTTP_DATE_FORMATER = new SimpleDateFormat(HTTP_DATETIME_PATTERN, Locale.US);
/**
* 通过URL中的path获得文件的绝对路径
*
* @param httpPath Http请求的Path
* @return 文件绝对路径
*/
public static File getFileByPath(String httpPath) {
// Decode the path.
try {
httpPath = URLDecoder.decode(httpPath, "UTF-8");
} catch (UnsupportedEncodingException e) {
throw new Error(e);
}
if (httpPath.isEmpty() || httpPath.charAt(0) != '/') {
return null;
}
// 路径安全检查
String path = httpPath.substring(0, httpPath.lastIndexOf("/"));
if (path.contains("/.") || path.contains("./") || ReUtil.isMatch(INSECURE_URI, path)) {
return null;
}
// 转换为绝对路径
return FileUtil.file(ServerSetting.getRoot(), httpPath);
}
}
|
response.setHeader("Access-Control-Allow-Origin", "*");
if (false == Request.METHOD_GET.equalsIgnoreCase(request.getMethod())) {
response.sendError(HttpResponseStatus.METHOD_NOT_ALLOWED, "Please use GET method to request file!");
return true;
}
if(ServerSetting.isRootAvailable() == false){
response.sendError(HttpResponseStatus.NOT_FOUND, "404 Root dir not avaliable!");
return true;
}
File file = null;
try {
file = getFileByPath(request.getPath());
} catch (Exception e) {
response.sendError(HttpResponseStatus.NOT_FOUND, "404 File not found!");
return true;
}
// 隐藏文件或不存在,跳过
if (file == null || file.isHidden() || !file.exists()) {
response.sendError(HttpResponseStatus.NOT_FOUND, "404 File not found!");
return true;
}
// 非文件,跳过
if (!file.isFile()) {
response.sendError(HttpResponseStatus.FORBIDDEN, "403 Forbidden!");
return true;
}
Logger.debug("Client [{}] get file [{}]", request.getIp(), file.getPath());
// Cache Validation
String ifModifiedSince = request.getHeader(HttpHeaderNames.IF_MODIFIED_SINCE.toString());
if (StrUtil.isNotBlank(ifModifiedSince)) {
Date ifModifiedSinceDate = null;
try {
ifModifiedSinceDate = DateUtil.parse(ifModifiedSince, HTTP_DATE_FORMATER);
} catch (Exception e) {
Logger.warn("If-Modified-Since header parse error: {}", e.getMessage());
}
if(ifModifiedSinceDate != null) {
// 只对比到秒一级别
long ifModifiedSinceDateSeconds = ifModifiedSinceDate.getTime() / 1000;
long fileLastModifiedSeconds = file.lastModified() / 1000;
if (ifModifiedSinceDateSeconds == fileLastModifiedSeconds) {
Logger.debug("File {} not modified.", file.getPath());
response.sendNotModified();
return true;
}
}
}
response.setContent(file);
response.setHeader("Content-Disposition", "attachment; filename=\"" + file.getName() + "\"");
return true;
| 380
| 659
| 1,039
|
<methods>public non-sealed void <init>() ,public abstract boolean action(com.xiaoleilu.loServer.handler.Request, com.xiaoleilu.loServer.handler.Response) ,public boolean doAction(com.xiaoleilu.loServer.handler.Request, com.xiaoleilu.loServer.handler.Response) ,public static void init(io.moquette.server.config.IConfig) ,public boolean isTransactionAction() ,public cn.wildfirechat.common.ErrorCode preAction(com.xiaoleilu.loServer.handler.Request, com.xiaoleilu.loServer.handler.Response) <variables>protected static win.liyufan.im.RateLimiter adminLimiter,protected static win.liyufan.im.RateLimiter channelLimiter,protected static boolean closeApiVersion,public ChannelHandlerContext ctx,protected static final com.google.gson.Gson gson,public static io.moquette.spi.IMessagesStore messagesStore,protected static win.liyufan.im.RateLimiter robotLimiter,public static io.moquette.spi.ISessionsStore sessionsStore
|
wildfirechat_im-server
|
im-server/broker/src/main/java/com/xiaoleilu/loServer/action/IMAction.java
|
IMAction
|
action
|
class IMAction extends Action {
@Override
public boolean action(Request request, Response response) {<FILL_FUNCTION_BODY>}
private void sendResponse(Response response, ErrorCode errorCode, byte[] contents) {
response.setStatus(HttpResponseStatus.OK);
if(contents == null) {
ByteBuf ackPayload = Unpooled.buffer();
ackPayload.ensureWritable(1).writeByte(errorCode.getCode());
response.setContent(ackPayload);
} else {
response.setContent(contents);
}
response.send();
}
}
|
if (request.getNettyRequest() instanceof FullHttpRequest) {
FullHttpRequest fullHttpRequest = (FullHttpRequest)request.getNettyRequest();
byte[] bytes = Utils.readBytesAndRewind(fullHttpRequest.content());
String str = new String(bytes);
try {
bytes = Base64.getDecoder().decode(str);
} catch (IllegalArgumentException e) {
sendResponse(response, ErrorCode.ERROR_CODE_SECRECT_KEY_MISMATCH, null);
return true;
}
String cid = fullHttpRequest.headers().get("cid");
byte[] cbytes = Base64.getDecoder().decode(cid);
cbytes = AES.AESDecrypt(cbytes, "", true);
if (cbytes == null) {
sendResponse(response, ErrorCode.ERROR_CODE_SECRECT_KEY_MISMATCH, null);
return true;
}
cid = new String(cbytes);
MemorySessionStore.Session session = sessionsStore.getSession(cid);
if (session != null) {
bytes = AES.AESDecrypt(bytes, session.getSecret(), true);
} else {
sendResponse(response, ErrorCode.ERROR_CODE_SECRECT_KEY_MISMATCH, null);
return true;
}
if (bytes == null) {
sendResponse(response, ErrorCode.ERROR_CODE_SECRECT_KEY_MISMATCH, null);
return true;
}
try {
WFCMessage.IMHttpWrapper wrapper = WFCMessage.IMHttpWrapper.parseFrom(bytes);
String token = wrapper.getToken();
String userId = Tokenor.getUserId(token.getBytes());
if (userId == null) {
sendResponse(response, ErrorCode.ERROR_CODE_TOKEN_ERROR, null);
} else {
if(messagesStore.getUserStatus(userId) == ProtoConstants.UserStatus.Forbidden) {
sendResponse(response, ErrorCode.ERROR_CODE_USER_BLOCKED, null);
return true;
}
ServerAPIHelper.sendRequest(userId, wrapper.getClientId(), wrapper.getRequest(), wrapper.getData().toByteArray(), new ServerAPIHelper.Callback() {
@Override
public void onSuccess(byte[] result) {
sendResponse(response, null, result);
}
@Override
public void onError(ErrorCode errorCode) {
sendResponse(response, errorCode, null);
}
@Override
public void onTimeout() {
sendResponse(response, ErrorCode.ERROR_CODE_TIMEOUT, null);
}
@Override
public Executor getResponseExecutor() {
return command -> {
ctx.executor().execute(command);
};
}
}, ProtoConstants.RequestSourceType.Request_From_User);
return false;
}
} catch (InvalidProtocolBufferException e) {
sendResponse(response, ErrorCode.ERROR_CODE_INVALID_DATA, null);
}
}
return true;
| 158
| 787
| 945
|
<methods>public non-sealed void <init>() ,public abstract boolean action(com.xiaoleilu.loServer.handler.Request, com.xiaoleilu.loServer.handler.Response) ,public boolean doAction(com.xiaoleilu.loServer.handler.Request, com.xiaoleilu.loServer.handler.Response) ,public static void init(io.moquette.server.config.IConfig) ,public boolean isTransactionAction() ,public cn.wildfirechat.common.ErrorCode preAction(com.xiaoleilu.loServer.handler.Request, com.xiaoleilu.loServer.handler.Response) <variables>protected static win.liyufan.im.RateLimiter adminLimiter,protected static win.liyufan.im.RateLimiter channelLimiter,protected static boolean closeApiVersion,public ChannelHandlerContext ctx,protected static final com.google.gson.Gson gson,public static io.moquette.spi.IMessagesStore messagesStore,protected static win.liyufan.im.RateLimiter robotLimiter,public static io.moquette.spi.ISessionsStore sessionsStore
|
wildfirechat_im-server
|
im-server/broker/src/main/java/com/xiaoleilu/loServer/action/RouteAction.java
|
RouteAction
|
action
|
class RouteAction extends Action {
private static final Logger LOG = LoggerFactory.getLogger(RouteAction.class);
@Override
public boolean action(Request request, Response response) {<FILL_FUNCTION_BODY>}
private void sendResponse(Response response, ErrorCode errorCode, byte[] contents) {
response.setStatus(HttpResponseStatus.OK);
if (contents == null) {
ByteBuf ackPayload = Unpooled.buffer();
ackPayload.ensureWritable(1).writeByte(errorCode.getCode());
contents = ackPayload.array();
}
response.setContent(contents);
response.send();
}
}
|
if (request.getNettyRequest() instanceof FullHttpRequest) {
response.setContentType("application/octet-stream");
response.setHeader("Access-Control-Allow-Origin", "*");
FullHttpRequest fullHttpRequest = (FullHttpRequest) request.getNettyRequest();
byte[] bytes = Utils.readBytesAndRewind(fullHttpRequest.content());
String str = new String(bytes);
try {
bytes = Base64.getDecoder().decode(str);
} catch (IllegalArgumentException e) {
sendResponse(response, ErrorCode.ERROR_CODE_INVALID_DATA, null);
return true;
}
String cid = fullHttpRequest.headers().get("cid");
byte[] cbytes = Base64.getDecoder().decode(cid);
boolean[] invalidTime = new boolean[1];
cbytes = AES.AESDecrypt(cbytes, "", true, invalidTime);
if (cbytes == null) {
if(invalidTime[0]) {
sendResponse(response, ErrorCode.ERROR_CODE_TIME_INCONSISTENT, null);
} else {
sendResponse(response, ErrorCode.ERROR_CODE_INVALID_DATA, null);
}
return true;
}
cid = new String(cbytes);
String uid = fullHttpRequest.headers().get("uid");
byte[] ubytes = Base64.getDecoder().decode(uid);
ubytes = AES.AESDecrypt(ubytes, "", true);
if (ubytes == null) {
sendResponse(response, ErrorCode.ERROR_CODE_INVALID_DATA, null);
return true;
}
uid = new String(ubytes);
MemorySessionStore.Session session = sessionsStore.sessionForClientAndUser(uid, cid);
if (session == null) {
ErrorCode errorCode = sessionsStore.loadActiveSession(uid, cid);
if (errorCode != ErrorCode.ERROR_CODE_SUCCESS) {
sendResponse(response, errorCode, null);
return true;
}
session = sessionsStore.sessionForClientAndUser(uid, cid);
}
if (session != null) {
bytes = AES.AESDecrypt(bytes, session.getSecret(), true);
} else {
sendResponse(response, ErrorCode.ERROR_CODE_SECRECT_KEY_MISMATCH, null);
return true;
}
if (bytes == null) {
sendResponse(response, ErrorCode.ERROR_CODE_SECRECT_KEY_MISMATCH, null);
return true;
}
if(messagesStore.getUserStatus(uid) == ProtoConstants.UserStatus.Forbidden) {
sendResponse(response, ErrorCode.ERROR_CODE_USER_BLOCKED, null);
return true;
}
try {
WFCMessage.IMHttpWrapper wrapper = WFCMessage.IMHttpWrapper.parseFrom(bytes);
String token = wrapper.getToken();
String userId = Tokenor.getUserId(token.getBytes());
LOG.info("RouteAction token={}, userId={}", token, userId);
if (userId == null) {
sendResponse(response, ErrorCode.ERROR_CODE_TOKEN_ERROR, null);
} else {
ServerAPIHelper.sendRequest(userId, wrapper.getClientId(), wrapper.getRequest(), wrapper.getData().toByteArray(), new ServerAPIHelper.Callback() {
@Override
public void onSuccess(byte[] result) {
sendResponse(response, null, result);
}
@Override
public void onError(ErrorCode errorCode) {
sendResponse(response, errorCode, null);
}
@Override
public void onTimeout() {
sendResponse(response, ErrorCode.ERROR_CODE_TIMEOUT, null);
}
@Override
public Executor getResponseExecutor() {
return command -> {
ctx.executor().execute(command);
};
}
}, ProtoConstants.RequestSourceType.Request_From_User);
return false;
}
} catch (InvalidProtocolBufferException e) {
sendResponse(response, ErrorCode.ERROR_CODE_INVALID_DATA, null);
}
}
return true;
| 174
| 1,094
| 1,268
|
<methods>public non-sealed void <init>() ,public abstract boolean action(com.xiaoleilu.loServer.handler.Request, com.xiaoleilu.loServer.handler.Response) ,public boolean doAction(com.xiaoleilu.loServer.handler.Request, com.xiaoleilu.loServer.handler.Response) ,public static void init(io.moquette.server.config.IConfig) ,public boolean isTransactionAction() ,public cn.wildfirechat.common.ErrorCode preAction(com.xiaoleilu.loServer.handler.Request, com.xiaoleilu.loServer.handler.Response) <variables>protected static win.liyufan.im.RateLimiter adminLimiter,protected static win.liyufan.im.RateLimiter channelLimiter,protected static boolean closeApiVersion,public ChannelHandlerContext ctx,protected static final com.google.gson.Gson gson,public static io.moquette.spi.IMessagesStore messagesStore,protected static win.liyufan.im.RateLimiter robotLimiter,public static io.moquette.spi.ISessionsStore sessionsStore
|
wildfirechat_im-server
|
im-server/broker/src/main/java/com/xiaoleilu/loServer/action/VersionAction.java
|
VersionAction
|
action
|
class VersionAction extends Action {
@Override
public boolean action(Request request, Response response) {<FILL_FUNCTION_BODY>}
}
|
if (request.getNettyRequest() instanceof FullHttpRequest) {
if(closeApiVersion) {
response.sendError(HttpResponseStatus.NOT_FOUND, "404 Not found!");
return true;
}
response.setStatus(HttpResponseStatus.OK);
try {
response.setContent(Utility.formatJson(gson.toJson(GitRepositoryState.getGitRepositoryState())));
} catch (IOException e) {
e.printStackTrace();
response.setContent("{\"version\":\"unknown\"}");
}
}
return true;
| 40
| 157
| 197
|
<methods>public non-sealed void <init>() ,public abstract boolean action(com.xiaoleilu.loServer.handler.Request, com.xiaoleilu.loServer.handler.Response) ,public boolean doAction(com.xiaoleilu.loServer.handler.Request, com.xiaoleilu.loServer.handler.Response) ,public static void init(io.moquette.server.config.IConfig) ,public boolean isTransactionAction() ,public cn.wildfirechat.common.ErrorCode preAction(com.xiaoleilu.loServer.handler.Request, com.xiaoleilu.loServer.handler.Response) <variables>protected static win.liyufan.im.RateLimiter adminLimiter,protected static win.liyufan.im.RateLimiter channelLimiter,protected static boolean closeApiVersion,public ChannelHandlerContext ctx,protected static final com.google.gson.Gson gson,public static io.moquette.spi.IMessagesStore messagesStore,protected static win.liyufan.im.RateLimiter robotLimiter,public static io.moquette.spi.ISessionsStore sessionsStore
|
wildfirechat_im-server
|
im-server/broker/src/main/java/com/xiaoleilu/loServer/action/admin/AddFriendRequestAction.java
|
AddFriendRequestAction
|
action
|
class AddFriendRequestAction extends AdminAction {
@Override
public boolean isTransactionAction() {
return true;
}
@Override
public boolean action(Request request, Response response) {<FILL_FUNCTION_BODY>}
}
|
if (request.getNettyRequest() instanceof FullHttpRequest) {
InputAddFriendRequest input = getRequestBody(request.getNettyRequest(), InputAddFriendRequest.class);
if (StringUtil.isNullOrEmpty(input.getUserId()) || StringUtil.isNullOrEmpty(input.getFriendUid())) {
sendResponse(response, ErrorCode.INVALID_PARAMETER, null);
return true;
}
WFCMessage.AddFriendRequest addFriendRequest = WFCMessage.AddFriendRequest.newBuilder().setReason(input.getReason()).setTargetUid(input.getFriendUid()).build();
sendApiMessage(response, input.getUserId(), IMTopic.AddFriendRequestTopic, addFriendRequest.toByteArray(), result -> {
ByteBuf byteBuf = Unpooled.buffer();
byteBuf.writeBytes(result);
ErrorCode errorCode = ErrorCode.fromCode(byteBuf.readByte());
return new Result(errorCode);
}, !input.isForce());
return false;
}
return true;
| 65
| 265
| 330
|
<methods>public non-sealed void <init>() ,public static java.lang.String getSecretKey() ,public cn.wildfirechat.common.ErrorCode preAction(com.xiaoleilu.loServer.handler.Request, com.xiaoleilu.loServer.handler.Response) ,public static void setNoCheckTime(java.lang.String) ,public static void setSecretKey(java.lang.String) <variables>private static final org.slf4j.Logger LOG,private static boolean NO_CHECK_TIME,private static java.lang.String SECRET_KEY
|
wildfirechat_im-server
|
im-server/broker/src/main/java/com/xiaoleilu/loServer/action/admin/AddGroupMemberAction.java
|
AddGroupMemberAction
|
action
|
class AddGroupMemberAction extends AdminAction {
@Override
public boolean isTransactionAction() {
return true;
}
@Override
public boolean action(Request request, Response response) {<FILL_FUNCTION_BODY>}
}
|
if (request.getNettyRequest() instanceof FullHttpRequest) {
InputAddGroupMember inputAddGroupMember = getRequestBody(request.getNettyRequest(), InputAddGroupMember.class);
if (inputAddGroupMember.isValide()) {
sendApiMessage(response, inputAddGroupMember.getOperator(), IMTopic.AddGroupMemberTopic, inputAddGroupMember.toProtoGroupRequest().toByteArray(), result -> {
ByteBuf byteBuf = Unpooled.buffer();
byteBuf.writeBytes(result);
ErrorCode errorCode = ErrorCode.fromCode(byteBuf.readByte());
return new Result(errorCode);
});
return false;
} else {
setResponseContent(RestResult.resultOf(ErrorCode.INVALID_PARAMETER), response);
}
}
return true;
| 65
| 206
| 271
|
<methods>public non-sealed void <init>() ,public static java.lang.String getSecretKey() ,public cn.wildfirechat.common.ErrorCode preAction(com.xiaoleilu.loServer.handler.Request, com.xiaoleilu.loServer.handler.Response) ,public static void setNoCheckTime(java.lang.String) ,public static void setSecretKey(java.lang.String) <variables>private static final org.slf4j.Logger LOG,private static boolean NO_CHECK_TIME,private static java.lang.String SECRET_KEY
|
wildfirechat_im-server
|
im-server/broker/src/main/java/com/xiaoleilu/loServer/action/admin/AdminAction.java
|
AdminAction
|
preAction
|
class AdminAction extends Action {
private static final org.slf4j.Logger LOG = LoggerFactory.getLogger(AdminAction.class);
private static String SECRET_KEY = "123456";
private static boolean NO_CHECK_TIME = false;
public static void setSecretKey(String secretKey) {
SECRET_KEY = secretKey;
}
public static String getSecretKey() {
return SECRET_KEY;
}
public static void setNoCheckTime(String noCheckTime) {
try {
NO_CHECK_TIME = Boolean.parseBoolean(noCheckTime);
} catch (Exception e) {
}
}
@Override
public ErrorCode preAction(Request request, Response response) {<FILL_FUNCTION_BODY>}
protected void sendResponse(Response response, ErrorCode errorCode, Object data) {
if(response != null) {
response.setStatus(HttpResponseStatus.OK);
if (errorCode == null) {
errorCode = ErrorCode.ERROR_CODE_SUCCESS;
}
RestResult result = RestResult.resultOf(errorCode, errorCode.getMsg(), data);
response.setContent(gson.toJson(result));
response.send();
}
}
protected void sendApiMessage(Response response, String fromUser, String topic, byte[] message, ApiCallback callback) {
sendApiMessage(response, fromUser, null, topic, message, callback, false);
}
protected void sendApiMessage(Response response, String fromUser, String topic, byte[] message, ApiCallback callback, boolean noAdmin) {
sendApiMessage(response, fromUser, null, topic, message, callback, noAdmin);
}
protected void sendApiMessage(Response response, String fromUser, String clientId, String topic, byte[] message, ApiCallback callback, boolean noAdmin) {
ServerAPIHelper.sendRequest(fromUser, clientId, topic, message, callback == null ? null : new ServerAPIHelper.Callback() {
@Override
public void onSuccess(byte[] result) {
if(callback != null) {
Result r = callback.onResult(result);
sendResponse(response, r.getErrorCode(), r.getData());
}
}
@Override
public void onError(ErrorCode errorCode) {
sendResponse(response, errorCode, null);
}
@Override
public void onTimeout() {
sendResponse(response, ErrorCode.ERROR_CODE_TIMEOUT, null);
}
@Override
public Executor getResponseExecutor() {
return command -> {
ctx.executor().execute(command);
};
}
}, noAdmin ? ProtoConstants.RequestSourceType.Request_From_User : ProtoConstants.RequestSourceType.Request_From_Admin);
}
}
|
if (!adminLimiter.isGranted("admin")) {
return ErrorCode.ERROR_CODE_OVER_FREQUENCY;
}
if(APIPath.Health.equals(request.getUri())) {
return ErrorCode.ERROR_CODE_SUCCESS;
}
String nonce = request.getHeader("nonce");
if (StringUtil.isNullOrEmpty(nonce)) {
nonce = request.getHeader("Nonce");
}
String timestamp = request.getHeader("timestamp");
if (StringUtil.isNullOrEmpty(timestamp)) {
timestamp = request.getHeader("Timestamp");
}
String sign = request.getHeader("sign");
if (StringUtil.isNullOrEmpty(sign)) {
sign = request.getHeader("Sign");
}
if (StringUtil.isNullOrEmpty(nonce) || StringUtil.isNullOrEmpty(timestamp) || StringUtil.isNullOrEmpty(sign)) {
return ErrorCode.ERROR_CODE_API_NOT_SIGNED;
}
Long ts;
try {
ts = Long.parseLong(timestamp);
} catch (Exception e) {
e.printStackTrace();
Utility.printExecption(LOG, e);
return ErrorCode.ERROR_CODE_API_NOT_SIGNED;
}
if (!NO_CHECK_TIME && System.currentTimeMillis() - ts > 2 * 60 * 60 * 1000) {
return ErrorCode.ERROR_CODE_SIGN_EXPIRED;
}
String str = nonce + "|" + SECRET_KEY + "|" + timestamp;
String localSign = DigestUtils.sha1Hex(str);
return localSign.equals(sign) ? ErrorCode.ERROR_CODE_SUCCESS : ErrorCode.ERROR_CODE_AUTH_FAILURE;
| 715
| 474
| 1,189
|
<methods>public non-sealed void <init>() ,public abstract boolean action(com.xiaoleilu.loServer.handler.Request, com.xiaoleilu.loServer.handler.Response) ,public boolean doAction(com.xiaoleilu.loServer.handler.Request, com.xiaoleilu.loServer.handler.Response) ,public static void init(io.moquette.server.config.IConfig) ,public boolean isTransactionAction() ,public cn.wildfirechat.common.ErrorCode preAction(com.xiaoleilu.loServer.handler.Request, com.xiaoleilu.loServer.handler.Response) <variables>protected static win.liyufan.im.RateLimiter adminLimiter,protected static win.liyufan.im.RateLimiter channelLimiter,protected static boolean closeApiVersion,public ChannelHandlerContext ctx,protected static final com.google.gson.Gson gson,public static io.moquette.spi.IMessagesStore messagesStore,protected static win.liyufan.im.RateLimiter robotLimiter,public static io.moquette.spi.ISessionsStore sessionsStore
|
wildfirechat_im-server
|
im-server/broker/src/main/java/com/xiaoleilu/loServer/action/admin/AliasGetAction.java
|
AliasGetAction
|
action
|
class AliasGetAction extends AdminAction {
@Override
public boolean isTransactionAction() {
return true;
}
@Override
public boolean action(Request request, Response response) {<FILL_FUNCTION_BODY>}
}
|
if (request.getNettyRequest() instanceof FullHttpRequest) {
InputGetAlias input = getRequestBody(request.getNettyRequest(), InputGetAlias.class);
List<FriendData> dataList = messagesStore.getFriendList(input.getOperator(), null, 0);
List<String> list = new ArrayList<>();
OutputGetAlias out = new OutputGetAlias(input.getOperator(), input.getTargetId());
for (FriendData data : dataList) {
if (data.getFriendUid().equals(input.getTargetId())) {
out.setAlias(data.getAlias());
break;
}
}
setResponseContent(RestResult.ok(out), response);
}
return true;
| 65
| 191
| 256
|
<methods>public non-sealed void <init>() ,public static java.lang.String getSecretKey() ,public cn.wildfirechat.common.ErrorCode preAction(com.xiaoleilu.loServer.handler.Request, com.xiaoleilu.loServer.handler.Response) ,public static void setNoCheckTime(java.lang.String) ,public static void setSecretKey(java.lang.String) <variables>private static final org.slf4j.Logger LOG,private static boolean NO_CHECK_TIME,private static java.lang.String SECRET_KEY
|
wildfirechat_im-server
|
im-server/broker/src/main/java/com/xiaoleilu/loServer/action/admin/AliasPutAction.java
|
AliasPutAction
|
action
|
class AliasPutAction extends AdminAction {
@Override
public boolean isTransactionAction() {
return true;
}
@Override
public boolean action(Request request, Response response) {<FILL_FUNCTION_BODY>}
}
|
if (request.getNettyRequest() instanceof FullHttpRequest) {
InputUpdateAlias input = getRequestBody(request.getNettyRequest(), InputUpdateAlias.class);
if(!StringUtil.isNullOrEmpty(input.getOperator()) && !StringUtil.isNullOrEmpty(input.getTargetId())) {
WFCMessage.AddFriendRequest addFriendRequest = WFCMessage.AddFriendRequest.newBuilder().setTargetUid(input.getTargetId()).setReason(input.getAlias()==null?"":input.getAlias()).build();
sendApiMessage(response, input.getOperator(), IMTopic.SetFriendAliasTopic, addFriendRequest.toByteArray(), result -> {
ByteBuf byteBuf = Unpooled.buffer();
byteBuf.writeBytes(result);
ErrorCode errorCode = ErrorCode.fromCode(byteBuf.readByte());
if (errorCode == ErrorCode.ERROR_CODE_SUCCESS) {
byte[] data = new byte[byteBuf.readableBytes()];
byteBuf.readBytes(data);
String channelId = new String(data);
return new Result(ErrorCode.ERROR_CODE_SUCCESS, new OutputCreateChannel(channelId));
} else {
return new Result(errorCode);
}
});
return false;
} else {
ErrorCode errorCode = messagesStore.setFriendAliasRequest(input.getOperator(), input.getTargetId(), input.getAlias(), new long[1]);
setResponseContent(RestResult.resultOf(errorCode), response);
}
}
return true;
| 65
| 392
| 457
|
<methods>public non-sealed void <init>() ,public static java.lang.String getSecretKey() ,public cn.wildfirechat.common.ErrorCode preAction(com.xiaoleilu.loServer.handler.Request, com.xiaoleilu.loServer.handler.Response) ,public static void setNoCheckTime(java.lang.String) ,public static void setSecretKey(java.lang.String) <variables>private static final org.slf4j.Logger LOG,private static boolean NO_CHECK_TIME,private static java.lang.String SECRET_KEY
|
wildfirechat_im-server
|
im-server/broker/src/main/java/com/xiaoleilu/loServer/action/admin/ApplicationGetUserInfoAction.java
|
ApplicationGetUserInfoAction
|
action
|
class ApplicationGetUserInfoAction extends AdminAction {
@Override
public boolean isTransactionAction() {
return true;
}
@Override
public boolean action(Request request, Response response) {<FILL_FUNCTION_BODY>}
}
|
if (request.getNettyRequest() instanceof FullHttpRequest) {
InputApplicationGetUserInfo inputUserToken = getRequestBody(request.getNettyRequest(), InputApplicationGetUserInfo.class);
RestResult result;
if (inputUserToken == null || StringUtil.isNullOrEmpty(inputUserToken.getAuthCode())) {
result = RestResult.resultOf(ErrorCode.INVALID_PARAMETER);
} else {
String userId = messagesStore.verifyApplicationAuthCode(inputUserToken.getAuthCode(), "admin", ProtoConstants.ApplicationType.ApplicationType_Admin);
if(userId != null) {
OutputApplicationUserInfo outputVerifyApplicationUser = new OutputApplicationUserInfo();
outputVerifyApplicationUser.setUserId(userId);
WFCMessage.User user = messagesStore.getUserInfo(userId);
if(user != null) {
outputVerifyApplicationUser.setDisplayName(user.getDisplayName());
outputVerifyApplicationUser.setPortraitUrl(user.getPortrait());
}
result = RestResult.ok(outputVerifyApplicationUser);
} else {
result = RestResult.resultOf(ErrorCode.ERROR_CODE_TOKEN_ERROR);
}
}
response.setStatus(HttpResponseStatus.OK);
response.setContent(gson.toJson(result));
}
return true;
| 66
| 341
| 407
|
<methods>public non-sealed void <init>() ,public static java.lang.String getSecretKey() ,public cn.wildfirechat.common.ErrorCode preAction(com.xiaoleilu.loServer.handler.Request, com.xiaoleilu.loServer.handler.Response) ,public static void setNoCheckTime(java.lang.String) ,public static void setSecretKey(java.lang.String) <variables>private static final org.slf4j.Logger LOG,private static boolean NO_CHECK_TIME,private static java.lang.String SECRET_KEY
|
wildfirechat_im-server
|
im-server/broker/src/main/java/com/xiaoleilu/loServer/action/admin/BlacklistAction.java
|
BlacklistAction
|
action
|
class BlacklistAction extends AdminAction {
@Override
public boolean isTransactionAction() {
return true;
}
@Override
public boolean action(Request request, Response response) {<FILL_FUNCTION_BODY>}
}
|
if (request.getNettyRequest() instanceof FullHttpRequest) {
InputBlacklistRequest inputData = getRequestBody(request.getNettyRequest(), InputBlacklistRequest.class);
if (inputData != null
&& !StringUtil.isNullOrEmpty(inputData.getUserId())
&& !StringUtil.isNullOrEmpty(inputData.getTargetUid())
) {
WFCMessage.BlackUserRequest friendRequest = WFCMessage.BlackUserRequest.newBuilder().setUid(inputData.getTargetUid()).setStatus(inputData.getStatus()).build();
sendApiMessage(response, inputData.getUserId(), IMTopic.BlackListUserTopic, friendRequest.toByteArray(), result -> {
ByteBuf byteBuf = Unpooled.buffer();
byteBuf.writeBytes(result);
ErrorCode errorCode = ErrorCode.fromCode(byteBuf.readByte());
return new Result(errorCode);
});
return false;
} else {
setResponseContent(RestResult.resultOf(ErrorCode.INVALID_PARAMETER), response);
}
}
return true;
| 64
| 281
| 345
|
<methods>public non-sealed void <init>() ,public static java.lang.String getSecretKey() ,public cn.wildfirechat.common.ErrorCode preAction(com.xiaoleilu.loServer.handler.Request, com.xiaoleilu.loServer.handler.Response) ,public static void setNoCheckTime(java.lang.String) ,public static void setSecretKey(java.lang.String) <variables>private static final org.slf4j.Logger LOG,private static boolean NO_CHECK_TIME,private static java.lang.String SECRET_KEY
|
wildfirechat_im-server
|
im-server/broker/src/main/java/com/xiaoleilu/loServer/action/admin/BlacklistGetAction.java
|
BlacklistGetAction
|
action
|
class BlacklistGetAction extends AdminAction {
@Override
public boolean isTransactionAction() {
return true;
}
@Override
public boolean action(Request request, Response response) {<FILL_FUNCTION_BODY>}
}
|
if (request.getNettyRequest() instanceof FullHttpRequest) {
InputUserId inputGetFriendList = getRequestBody(request.getNettyRequest(), InputUserId.class);
List<FriendData> dataList = messagesStore.getFriendList(inputGetFriendList.getUserId(), null, 0);
List<String> list = new ArrayList<>();
for (FriendData data : dataList) {
if (data.getBlacked() > 0) {
list.add(data.getFriendUid());
}
}
setResponseContent(RestResult.ok(new OutputStringList(list)), response);
}
return true;
| 65
| 163
| 228
|
<methods>public non-sealed void <init>() ,public static java.lang.String getSecretKey() ,public cn.wildfirechat.common.ErrorCode preAction(com.xiaoleilu.loServer.handler.Request, com.xiaoleilu.loServer.handler.Response) ,public static void setNoCheckTime(java.lang.String) ,public static void setSecretKey(java.lang.String) <variables>private static final org.slf4j.Logger LOG,private static boolean NO_CHECK_TIME,private static java.lang.String SECRET_KEY
|
wildfirechat_im-server
|
im-server/broker/src/main/java/com/xiaoleilu/loServer/action/admin/BlockUserAction.java
|
BlockUserAction
|
action
|
class BlockUserAction extends AdminAction {
@Override
public boolean isTransactionAction() {
return true;
}
@Override
public boolean action(Request request, Response response) {<FILL_FUNCTION_BODY>}
}
|
if (request.getNettyRequest() instanceof FullHttpRequest) {
InputOutputUserBlockStatus inputUserBlock = getRequestBody(request.getNettyRequest(), InputOutputUserBlockStatus.class);
if (inputUserBlock != null
&& !StringUtil.isNullOrEmpty(inputUserBlock.getUserId())) {
ErrorCode errorCode = messagesStore.modifyUserStatus(inputUserBlock.getUserId(), inputUserBlock.getStatus());
response.setStatus(HttpResponseStatus.OK);
RestResult result;
result = RestResult.resultOf(errorCode);
response.setContent(gson.toJson(result));
if (inputUserBlock.getStatus() == 2) {
sendApiMessage(null, null, ServerAPIHelper.KICKOFF_USER_REQUEST, inputUserBlock.getUserId().getBytes(), null);
}
sendResponse(response, ErrorCode.ERROR_CODE_SUCCESS, null);
} else {
setResponseContent(RestResult.resultOf(ErrorCode.INVALID_PARAMETER), response);
}
}
return true;
| 64
| 275
| 339
|
<methods>public non-sealed void <init>() ,public static java.lang.String getSecretKey() ,public cn.wildfirechat.common.ErrorCode preAction(com.xiaoleilu.loServer.handler.Request, com.xiaoleilu.loServer.handler.Response) ,public static void setNoCheckTime(java.lang.String) ,public static void setSecretKey(java.lang.String) <variables>private static final org.slf4j.Logger LOG,private static boolean NO_CHECK_TIME,private static java.lang.String SECRET_KEY
|
wildfirechat_im-server
|
im-server/broker/src/main/java/com/xiaoleilu/loServer/action/admin/BroadcastMessageAction.java
|
BroadcastMessageAction
|
action
|
class BroadcastMessageAction extends AdminAction {
@Override
public boolean isTransactionAction() {
return true;
}
@Override
public boolean action(Request request, Response response) {<FILL_FUNCTION_BODY>}
}
|
if (request.getNettyRequest() instanceof FullHttpRequest) {
BroadMessageData sendMessageData = getRequestBody(request.getNettyRequest(), BroadMessageData.class);
if (BroadMessageData.isValide(sendMessageData) && !StringUtil.isNullOrEmpty(sendMessageData.getSender())) {
sendApiMessage(response, sendMessageData.getSender(), IMTopic.BroadcastMessageTopic, sendMessageData.toProtoMessage().toByteArray(), result -> {
ByteBuf byteBuf = Unpooled.buffer();
byteBuf.writeBytes(result);
ErrorCode errorCode = ErrorCode.fromCode(byteBuf.readByte());
if (errorCode == ErrorCode.ERROR_CODE_SUCCESS) {
long messageId = byteBuf.readLong();
long count = byteBuf.readLong();
return new Result(errorCode, new BroadMessageResult(messageId, count));
} else {
return new Result(errorCode);
}
});
return false;
} else {
setResponseContent(RestResult.resultOf(ErrorCode.INVALID_PARAMETER), response);
}
}
return true;
| 65
| 293
| 358
|
<methods>public non-sealed void <init>() ,public static java.lang.String getSecretKey() ,public cn.wildfirechat.common.ErrorCode preAction(com.xiaoleilu.loServer.handler.Request, com.xiaoleilu.loServer.handler.Response) ,public static void setNoCheckTime(java.lang.String) ,public static void setSecretKey(java.lang.String) <variables>private static final org.slf4j.Logger LOG,private static boolean NO_CHECK_TIME,private static java.lang.String SECRET_KEY
|
wildfirechat_im-server
|
im-server/broker/src/main/java/com/xiaoleilu/loServer/action/admin/ChannelSubscriberAction.java
|
ChannelSubscriberAction
|
action
|
class ChannelSubscriberAction extends AdminAction {
@Override
public boolean action(Request request, Response response) {<FILL_FUNCTION_BODY>}
}
|
if (request.getNettyRequest() instanceof FullHttpRequest) {
InputSubscribeChannel inputSubscribeChannel = getRequestBody(request.getNettyRequest(), InputSubscribeChannel.class);
if (inputSubscribeChannel != null
&& !io.netty.util.internal.StringUtil.isNullOrEmpty(inputSubscribeChannel.getChannelId())
&& !io.netty.util.internal.StringUtil.isNullOrEmpty(inputSubscribeChannel.getUserId())) {
WFCMessage.ListenChannel.Builder builder = WFCMessage.ListenChannel.newBuilder().setChannelId(inputSubscribeChannel.getChannelId()).setListen(inputSubscribeChannel.getSubscribe());
sendApiMessage(response, inputSubscribeChannel.getUserId(), IMTopic.ChannelListenTopic, builder.build().toByteArray(), result -> {
ErrorCode errorCode = ErrorCode.fromCode(result[0]);
if (errorCode == ErrorCode.ERROR_CODE_SUCCESS) {
return new Result(ErrorCode.ERROR_CODE_SUCCESS);
} else {
return new Result(errorCode);
}
});
return false;
} else {
setResponseContent(RestResult.resultOf(ErrorCode.INVALID_PARAMETER), response);
}
}
return true;
| 44
| 326
| 370
|
<methods>public non-sealed void <init>() ,public static java.lang.String getSecretKey() ,public cn.wildfirechat.common.ErrorCode preAction(com.xiaoleilu.loServer.handler.Request, com.xiaoleilu.loServer.handler.Response) ,public static void setNoCheckTime(java.lang.String) ,public static void setSecretKey(java.lang.String) <variables>private static final org.slf4j.Logger LOG,private static boolean NO_CHECK_TIME,private static java.lang.String SECRET_KEY
|
wildfirechat_im-server
|
im-server/broker/src/main/java/com/xiaoleilu/loServer/action/admin/CheckUserOnlineAction.java
|
CheckUserOnlineAction
|
action
|
class CheckUserOnlineAction extends AdminAction {
@Override
public boolean isTransactionAction() {
return false;
}
@Override
public boolean action(Request request, Response response) {<FILL_FUNCTION_BODY>}
}
|
if (request.getNettyRequest() instanceof FullHttpRequest) {
InputGetUserInfo inputUserId = getRequestBody(request.getNettyRequest(), InputGetUserInfo.class);
if (inputUserId == null || !StringUtil.isNullOrEmpty(inputUserId.getUserId())) {
sendApiMessage(response, inputUserId.getUserId(), ServerAPIHelper.CHECK_USER_ONLINE_REQUEST, inputUserId.getUserId().getBytes(), res -> {
OutputCheckUserOnline out = gson.fromJson(new String(res), OutputCheckUserOnline.class);
return new Result(ErrorCode.ERROR_CODE_SUCCESS, out);
});
return false;
} else {
sendResponse(response, ErrorCode.INVALID_PARAMETER, null);
}
}
return true;
| 65
| 208
| 273
|
<methods>public non-sealed void <init>() ,public static java.lang.String getSecretKey() ,public cn.wildfirechat.common.ErrorCode preAction(com.xiaoleilu.loServer.handler.Request, com.xiaoleilu.loServer.handler.Response) ,public static void setNoCheckTime(java.lang.String) ,public static void setSecretKey(java.lang.String) <variables>private static final org.slf4j.Logger LOG,private static boolean NO_CHECK_TIME,private static java.lang.String SECRET_KEY
|
wildfirechat_im-server
|
im-server/broker/src/main/java/com/xiaoleilu/loServer/action/admin/CheckUserSubscribeChannelAction.java
|
CheckUserSubscribeChannelAction
|
action
|
class CheckUserSubscribeChannelAction extends AdminAction {
@Override
public boolean isTransactionAction() {
return true;
}
@Override
public boolean action(Request request, Response response) {<FILL_FUNCTION_BODY>}
}
|
if (request.getNettyRequest() instanceof FullHttpRequest) {
InputSubscribeChannel inputSubscribeChannel = getRequestBody(request.getNettyRequest(), InputSubscribeChannel.class);
if (inputSubscribeChannel != null
&& !StringUtil.isNullOrEmpty(inputSubscribeChannel.getChannelId())
&& !StringUtil.isNullOrEmpty(inputSubscribeChannel.getUserId())) {
boolean isInChannel = messagesStore.checkUserInChannel(inputSubscribeChannel.getUserId(), inputSubscribeChannel.getChannelId());
OutputBooleanValue outputBooleanValue = new OutputBooleanValue();
outputBooleanValue.value = isInChannel;
setResponseContent(RestResult.ok(outputBooleanValue), response);
} else {
setResponseContent(RestResult.resultOf(ErrorCode.INVALID_PARAMETER), response);
}
}
return true;
| 67
| 219
| 286
|
<methods>public non-sealed void <init>() ,public static java.lang.String getSecretKey() ,public cn.wildfirechat.common.ErrorCode preAction(com.xiaoleilu.loServer.handler.Request, com.xiaoleilu.loServer.handler.Response) ,public static void setNoCheckTime(java.lang.String) ,public static void setSecretKey(java.lang.String) <variables>private static final org.slf4j.Logger LOG,private static boolean NO_CHECK_TIME,private static java.lang.String SECRET_KEY
|
wildfirechat_im-server
|
im-server/broker/src/main/java/com/xiaoleilu/loServer/action/admin/CreateChannelAction.java
|
CreateChannelAction
|
action
|
class CreateChannelAction extends AdminAction {
@Override
public boolean isTransactionAction() {
return true;
}
@Override
public boolean action(Request request, Response response) {<FILL_FUNCTION_BODY>}
}
|
if (request.getNettyRequest() instanceof FullHttpRequest) {
InputCreateChannel inputCreateChannel = getRequestBody(request.getNettyRequest(), InputCreateChannel.class);
if (inputCreateChannel != null
&& !StringUtil.isNullOrEmpty(inputCreateChannel.getName())
&& !StringUtil.isNullOrEmpty(inputCreateChannel.getOwner())) {
if(StringUtil.isNullOrEmpty(inputCreateChannel.getTargetId())) {
inputCreateChannel.setTargetId(messagesStore.getShortUUID());
}
sendApiMessage(response, inputCreateChannel.getOwner(), IMTopic.CreateChannelTopic, inputCreateChannel.toProtoChannelInfo().toByteArray(), result -> {
ByteBuf byteBuf = Unpooled.buffer();
byteBuf.writeBytes(result);
ErrorCode errorCode = ErrorCode.fromCode(byteBuf.readByte());
if (errorCode == ErrorCode.ERROR_CODE_SUCCESS) {
byte[] data = new byte[byteBuf.readableBytes()];
byteBuf.readBytes(data);
String channelId = new String(data);
return new Result(ErrorCode.ERROR_CODE_SUCCESS, new OutputCreateChannel(channelId));
} else {
return new Result(errorCode);
}
});
return false;
} else {
setResponseContent(RestResult.resultOf(ErrorCode.INVALID_PARAMETER), response);
}
}
return true;
| 64
| 369
| 433
|
<methods>public non-sealed void <init>() ,public static java.lang.String getSecretKey() ,public cn.wildfirechat.common.ErrorCode preAction(com.xiaoleilu.loServer.handler.Request, com.xiaoleilu.loServer.handler.Response) ,public static void setNoCheckTime(java.lang.String) ,public static void setSecretKey(java.lang.String) <variables>private static final org.slf4j.Logger LOG,private static boolean NO_CHECK_TIME,private static java.lang.String SECRET_KEY
|
wildfirechat_im-server
|
im-server/broker/src/main/java/com/xiaoleilu/loServer/action/admin/CreateChatroomAction.java
|
CreateChatroomAction
|
action
|
class CreateChatroomAction extends AdminAction {
@Override
public boolean isTransactionAction() {
return true;
}
@Override
public boolean action(Request request, Response response) {<FILL_FUNCTION_BODY>}
}
|
if (request.getNettyRequest() instanceof FullHttpRequest) {
FullHttpRequest fullHttpRequest = (FullHttpRequest)request.getNettyRequest();
byte[] bytes = Utils.readBytesAndRewind(fullHttpRequest.content());
String content = new String(bytes);
InputCreateChatroom inputCreateChatroom = gson.fromJson(content, InputCreateChatroom.class);
if (inputCreateChatroom != null
&& !StringUtil.isNullOrEmpty(inputCreateChatroom.getTitle())) {
if (StringUtil.isNullOrEmpty(inputCreateChatroom.getChatroomId())) {
inputCreateChatroom.setChatroomId(messagesStore.getShortUUID());
}
WFCMessage.ChatroomInfo info = inputCreateChatroom.toChatroomInfo();
messagesStore.createChatroom(inputCreateChatroom.getChatroomId(), info);
setResponseContent(RestResult.ok(new OutputCreateChatroom(inputCreateChatroom.getChatroomId())), response);
} else {
setResponseContent(RestResult.resultOf(ErrorCode.INVALID_PARAMETER), response);
}
}
return true;
| 65
| 293
| 358
|
<methods>public non-sealed void <init>() ,public static java.lang.String getSecretKey() ,public cn.wildfirechat.common.ErrorCode preAction(com.xiaoleilu.loServer.handler.Request, com.xiaoleilu.loServer.handler.Response) ,public static void setNoCheckTime(java.lang.String) ,public static void setSecretKey(java.lang.String) <variables>private static final org.slf4j.Logger LOG,private static boolean NO_CHECK_TIME,private static java.lang.String SECRET_KEY
|
wildfirechat_im-server
|
im-server/broker/src/main/java/com/xiaoleilu/loServer/action/admin/CreateGroupAction.java
|
CreateGroupAction
|
action
|
class CreateGroupAction extends AdminAction {
@Override
public boolean isTransactionAction() {
return true;
}
@Override
public boolean action(Request request, Response response) {<FILL_FUNCTION_BODY>}
}
|
if (request.getNettyRequest() instanceof FullHttpRequest) {
InputCreateGroup inputCreateGroup = getRequestBody(request.getNettyRequest(), InputCreateGroup.class);
if (inputCreateGroup.isValide()) {
sendApiMessage(response, inputCreateGroup.getOperator(), IMTopic.CreateGroupTopic, inputCreateGroup.toProtoGroupRequest().toByteArray(), result -> {
ByteBuf byteBuf = Unpooled.buffer();
byteBuf.writeBytes(result);
ErrorCode errorCode = ErrorCode.fromCode(byteBuf.readByte());
if (errorCode == ErrorCode.ERROR_CODE_SUCCESS) {
byte[] data = new byte[byteBuf.readableBytes()];
byteBuf.readBytes(data);
String groupId = new String(data);
return new Result(ErrorCode.ERROR_CODE_SUCCESS, new OutputCreateGroupResult(groupId));
} else {
return new Result(errorCode);
}
});
return false;
} else {
setResponseContent(RestResult.resultOf(ErrorCode.INVALID_PARAMETER), response);
}
}
return true;
| 64
| 289
| 353
|
<methods>public non-sealed void <init>() ,public static java.lang.String getSecretKey() ,public cn.wildfirechat.common.ErrorCode preAction(com.xiaoleilu.loServer.handler.Request, com.xiaoleilu.loServer.handler.Response) ,public static void setNoCheckTime(java.lang.String) ,public static void setSecretKey(java.lang.String) <variables>private static final org.slf4j.Logger LOG,private static boolean NO_CHECK_TIME,private static java.lang.String SECRET_KEY
|
wildfirechat_im-server
|
im-server/broker/src/main/java/com/xiaoleilu/loServer/action/admin/CreateRobotAction.java
|
CreateRobotAction
|
action
|
class CreateRobotAction extends AdminAction {
private static final Logger LOG = LoggerFactory.getLogger(CreateRobotAction.class);
@Override
public boolean isTransactionAction() {
return true;
}
@Override
public boolean action(Request request, Response response) {<FILL_FUNCTION_BODY>}
}
|
if (request.getNettyRequest() instanceof FullHttpRequest) {
InputCreateRobot inputCreateRobot = getRequestBody(request.getNettyRequest(), InputCreateRobot.class);
if (inputCreateRobot != null
&& !StringUtil.isNullOrEmpty(inputCreateRobot.getName())) {
if(StringUtil.isNullOrEmpty(inputCreateRobot.getUserId())) {
inputCreateRobot.setUserId(messagesStore.getShortUUID());
}
WFCMessage.User newUser = inputCreateRobot.toUser();
try {
messagesStore.addUserInfo(newUser);
} catch (Exception e) {
e.printStackTrace();
Utility.printExecption(LOG, e, IMExceptionEvent.EventType.ADMIN_API_Exception);
response.setStatus(HttpResponseStatus.OK);
RestResult result = RestResult.resultOf(ErrorCode.ERROR_CODE_SERVER_ERROR, e.getMessage());
response.setContent(gson.toJson(result));
return true;
}
if (StringUtil.isNullOrEmpty(inputCreateRobot.getOwner())) {
inputCreateRobot.setOwner(inputCreateRobot.getUserId());
}
if (StringUtil.isNullOrEmpty(inputCreateRobot.getSecret())) {
inputCreateRobot.setSecret(UUIDGenerator.getUUID());
}
messagesStore.addRobot(inputCreateRobot.toRobot());
setResponseContent(RestResult.ok(new OutputCreateRobot(inputCreateRobot.getUserId(), inputCreateRobot.getSecret())), response);
} else {
setResponseContent(RestResult.resultOf(ErrorCode.INVALID_PARAMETER), response);
}
}
return true;
| 88
| 446
| 534
|
<methods>public non-sealed void <init>() ,public static java.lang.String getSecretKey() ,public cn.wildfirechat.common.ErrorCode preAction(com.xiaoleilu.loServer.handler.Request, com.xiaoleilu.loServer.handler.Response) ,public static void setNoCheckTime(java.lang.String) ,public static void setSecretKey(java.lang.String) <variables>private static final org.slf4j.Logger LOG,private static boolean NO_CHECK_TIME,private static java.lang.String SECRET_KEY
|
wildfirechat_im-server
|
im-server/broker/src/main/java/com/xiaoleilu/loServer/action/admin/CreateUserAction.java
|
CreateUserAction
|
action
|
class CreateUserAction extends AdminAction {
private static final Logger LOG = LoggerFactory.getLogger(CreateUserAction.class);
@Override
public boolean isTransactionAction() {
return true;
}
@Override
public boolean action(Request request, Response response) {<FILL_FUNCTION_BODY>}
}
|
if (request.getNettyRequest() instanceof FullHttpRequest) {
InputOutputUserInfo inputCreateUser = getRequestBody(request.getNettyRequest(), InputOutputUserInfo.class);
if (inputCreateUser != null
&& !StringUtil.isNullOrEmpty(inputCreateUser.getName())
&& (inputCreateUser.getType() == ProtoConstants.UserType.UserType_Normal || inputCreateUser.getType() == ProtoConstants.UserType.UserType_Admin || inputCreateUser.getType() == ProtoConstants.UserType.UserType_Super_Admin)) {
if(StringUtil.isNullOrEmpty(inputCreateUser.getUserId())) {
inputCreateUser.setUserId(messagesStore.getShortUUID());
}
WFCMessage.User.Builder newUserBuilder = WFCMessage.User.newBuilder()
.setUid(StringUtil.isNullOrEmpty(inputCreateUser.getUserId()) ? "" : inputCreateUser.getUserId());
if (inputCreateUser.getName() != null)
newUserBuilder.setName(inputCreateUser.getName());
if (inputCreateUser.getDisplayName() != null)
newUserBuilder.setDisplayName(StringUtil.isNullOrEmpty(inputCreateUser.getDisplayName()) ? inputCreateUser.getName() : inputCreateUser.getDisplayName());
if (inputCreateUser.getPortrait() != null)
newUserBuilder.setPortrait(inputCreateUser.getPortrait());
if (inputCreateUser.getEmail() != null)
newUserBuilder.setEmail(inputCreateUser.getEmail());
if (inputCreateUser.getAddress() != null)
newUserBuilder.setAddress(inputCreateUser.getAddress());
if (inputCreateUser.getCompany() != null)
newUserBuilder.setCompany(inputCreateUser.getCompany());
if (inputCreateUser.getSocial() != null)
newUserBuilder.setSocial(inputCreateUser.getSocial());
if (inputCreateUser.getMobile() != null)
newUserBuilder.setMobile(inputCreateUser.getMobile());
newUserBuilder.setGender(inputCreateUser.getGender());
if (inputCreateUser.getExtra() != null)
newUserBuilder.setExtra(inputCreateUser.getExtra());
newUserBuilder.setType(inputCreateUser.getType());
newUserBuilder.setUpdateDt(System.currentTimeMillis());
try {
messagesStore.addUserInfo(newUserBuilder.build());
} catch (Exception e) {
e.printStackTrace();
Utility.printExecption(LOG, e, IMExceptionEvent.EventType.ADMIN_API_Exception);
setResponseContent(RestResult.resultOf(ErrorCode.ERROR_CODE_SERVER_ERROR, e.getMessage()), response);
return true;
}
setResponseContent(RestResult.ok(new OutputCreateUser(inputCreateUser.getUserId(), inputCreateUser.getName())), response);
} else {
setResponseContent(RestResult.resultOf(ErrorCode.INVALID_PARAMETER), response);
}
}
return true;
| 86
| 781
| 867
|
<methods>public non-sealed void <init>() ,public static java.lang.String getSecretKey() ,public cn.wildfirechat.common.ErrorCode preAction(com.xiaoleilu.loServer.handler.Request, com.xiaoleilu.loServer.handler.Response) ,public static void setNoCheckTime(java.lang.String) ,public static void setSecretKey(java.lang.String) <variables>private static final org.slf4j.Logger LOG,private static boolean NO_CHECK_TIME,private static java.lang.String SECRET_KEY
|
wildfirechat_im-server
|
im-server/broker/src/main/java/com/xiaoleilu/loServer/action/admin/DestoryChatroomAction.java
|
DestoryChatroomAction
|
action
|
class DestoryChatroomAction extends AdminAction {
@Override
public boolean isTransactionAction() {
return true;
}
@Override
public boolean action(Request request, Response response) {<FILL_FUNCTION_BODY>}
}
|
if (request.getNettyRequest() instanceof FullHttpRequest) {
FullHttpRequest fullHttpRequest = (FullHttpRequest)request.getNettyRequest();
byte[] bytes = Utils.readBytesAndRewind(fullHttpRequest.content());
String content = new String(bytes);
InputDestoryChatroom inputDestoryChatroom = gson.fromJson(content, InputDestoryChatroom.class);
if (inputDestoryChatroom != null
&& !StringUtil.isNullOrEmpty(inputDestoryChatroom.getChatroomId())) {
messagesStore.destoryChatroom(inputDestoryChatroom.getChatroomId());
setResponseContent(RestResult.ok(), response);
} else {
setResponseContent(RestResult.resultOf(ErrorCode.INVALID_PARAMETER), response);
}
}
return true;
| 66
| 215
| 281
|
<methods>public non-sealed void <init>() ,public static java.lang.String getSecretKey() ,public cn.wildfirechat.common.ErrorCode preAction(com.xiaoleilu.loServer.handler.Request, com.xiaoleilu.loServer.handler.Response) ,public static void setNoCheckTime(java.lang.String) ,public static void setSecretKey(java.lang.String) <variables>private static final org.slf4j.Logger LOG,private static boolean NO_CHECK_TIME,private static java.lang.String SECRET_KEY
|
wildfirechat_im-server
|
im-server/broker/src/main/java/com/xiaoleilu/loServer/action/admin/DestroyChannelAction.java
|
DestroyChannelAction
|
action
|
class DestroyChannelAction extends AdminAction {
@Override
public boolean isTransactionAction() {
return true;
}
@Override
public boolean action(Request request, Response response) {<FILL_FUNCTION_BODY>}
}
|
if (request.getNettyRequest() instanceof FullHttpRequest) {
InputChannelId inputCreateChannel = getRequestBody(request.getNettyRequest(), InputChannelId.class);
if (inputCreateChannel != null
&& !StringUtil.isNullOrEmpty(inputCreateChannel.channelId)) {
WFCMessage.ChannelInfo channelInfo = messagesStore.getChannelInfo(inputCreateChannel.channelId);
if(channelInfo == null) {
setResponseContent(RestResult.resultOf(ErrorCode.ERROR_CODE_NOT_EXIST), response);
return true;
}
WFCMessage.IDBuf.Builder builder = WFCMessage.IDBuf.newBuilder().setId(inputCreateChannel.channelId);
sendApiMessage(response, channelInfo.getOwner(), IMTopic.DestroyChannelInfoTopic, builder.build().toByteArray(), result -> {
ByteBuf byteBuf = Unpooled.buffer();
byteBuf.writeBytes(result);
ErrorCode errorCode = ErrorCode.fromCode(byteBuf.readByte());
return new Result(errorCode);
});
return false;
} else {
setResponseContent(RestResult.resultOf(ErrorCode.INVALID_PARAMETER), response);
}
}
return true;
| 65
| 314
| 379
|
<methods>public non-sealed void <init>() ,public static java.lang.String getSecretKey() ,public cn.wildfirechat.common.ErrorCode preAction(com.xiaoleilu.loServer.handler.Request, com.xiaoleilu.loServer.handler.Response) ,public static void setNoCheckTime(java.lang.String) ,public static void setSecretKey(java.lang.String) <variables>private static final org.slf4j.Logger LOG,private static boolean NO_CHECK_TIME,private static java.lang.String SECRET_KEY
|
wildfirechat_im-server
|
im-server/broker/src/main/java/com/xiaoleilu/loServer/action/admin/DestroyUserAction.java
|
DestroyUserAction
|
action
|
class DestroyUserAction extends AdminAction {
@Override
public boolean isTransactionAction() {
return true;
}
@Override
public boolean action(Request request, Response response) {<FILL_FUNCTION_BODY>}
}
|
if (request.getNettyRequest() instanceof FullHttpRequest) {
InputDestroyUser inputDestroyUser = getRequestBody(request.getNettyRequest(), InputDestroyUser.class);
if (inputDestroyUser != null
&& !StringUtil.isNullOrEmpty(inputDestroyUser.getUserId())) {
WFCMessage.IDBuf idBuf = WFCMessage.IDBuf.newBuilder().setId(inputDestroyUser.getUserId()).build();
sendApiMessage(response, inputDestroyUser.getUserId(), IMTopic.DestroyUserTopic, idBuf.toByteArray(), result -> {
ErrorCode errorCode1 = ErrorCode.fromCode(result[0]);
return new Result(errorCode1);
});
return false;
} else {
setResponseContent(RestResult.resultOf(ErrorCode.INVALID_PARAMETER), response);
}
}
return true;
| 65
| 233
| 298
|
<methods>public non-sealed void <init>() ,public static java.lang.String getSecretKey() ,public cn.wildfirechat.common.ErrorCode preAction(com.xiaoleilu.loServer.handler.Request, com.xiaoleilu.loServer.handler.Response) ,public static void setNoCheckTime(java.lang.String) ,public static void setSecretKey(java.lang.String) <variables>private static final org.slf4j.Logger LOG,private static boolean NO_CHECK_TIME,private static java.lang.String SECRET_KEY
|
wildfirechat_im-server
|
im-server/broker/src/main/java/com/xiaoleilu/loServer/action/admin/DismissGroupAction.java
|
DismissGroupAction
|
action
|
class DismissGroupAction extends AdminAction {
@Override
public boolean isTransactionAction() {
return true;
}
@Override
public boolean action(Request request, Response response) {<FILL_FUNCTION_BODY>}
}
|
if (request.getNettyRequest() instanceof FullHttpRequest) {
InputDismissGroup inputDismissGroup = getRequestBody(request.getNettyRequest(), InputDismissGroup.class);
if (inputDismissGroup.isValide()) {
sendApiMessage(response, inputDismissGroup.getOperator(), IMTopic.DismissGroupTopic, inputDismissGroup.toProtoGroupRequest().toByteArray(), result -> {
ByteBuf byteBuf = Unpooled.buffer();
byteBuf.writeBytes(result);
ErrorCode errorCode = ErrorCode.fromCode(byteBuf.readByte());
return new Result(errorCode);
});
return false;
} else {
setResponseContent(RestResult.resultOf(ErrorCode.INVALID_PARAMETER), response);
}
}
return true;
| 66
| 213
| 279
|
<methods>public non-sealed void <init>() ,public static java.lang.String getSecretKey() ,public cn.wildfirechat.common.ErrorCode preAction(com.xiaoleilu.loServer.handler.Request, com.xiaoleilu.loServer.handler.Response) ,public static void setNoCheckTime(java.lang.String) ,public static void setSecretKey(java.lang.String) <variables>private static final org.slf4j.Logger LOG,private static boolean NO_CHECK_TIME,private static java.lang.String SECRET_KEY
|
wildfirechat_im-server
|
im-server/broker/src/main/java/com/xiaoleilu/loServer/action/admin/FriendExtraPutAction.java
|
FriendExtraPutAction
|
action
|
class FriendExtraPutAction extends AdminAction {
@Override
public boolean isTransactionAction() {
return true;
}
@Override
public boolean action(Request request, Response response) {<FILL_FUNCTION_BODY>}
}
|
if (request.getNettyRequest() instanceof FullHttpRequest) {
InputUpdateFriendExtra input = getRequestBody(request.getNettyRequest(), InputUpdateFriendExtra.class);
ErrorCode errorCode = messagesStore.setFriendExtraRequest(input.getOperator(), input.getTargetId(), input.getExtra(), new long[1]);
setResponseContent(RestResult.resultOf(errorCode), response);
}
return true;
| 65
| 107
| 172
|
<methods>public non-sealed void <init>() ,public static java.lang.String getSecretKey() ,public cn.wildfirechat.common.ErrorCode preAction(com.xiaoleilu.loServer.handler.Request, com.xiaoleilu.loServer.handler.Response) ,public static void setNoCheckTime(java.lang.String) ,public static void setSecretKey(java.lang.String) <variables>private static final org.slf4j.Logger LOG,private static boolean NO_CHECK_TIME,private static java.lang.String SECRET_KEY
|
wildfirechat_im-server
|
im-server/broker/src/main/java/com/xiaoleilu/loServer/action/admin/FriendRelationAction.java
|
FriendRelationAction
|
action
|
class FriendRelationAction extends AdminAction {
@Override
public boolean isTransactionAction() {
return true;
}
@Override
public boolean action(Request request, Response response) {<FILL_FUNCTION_BODY>}
}
|
if (request.getNettyRequest() instanceof FullHttpRequest) {
InputUpdateFriendStatusRequest friendAdd = getRequestBody(request.getNettyRequest(), InputUpdateFriendStatusRequest.class);
if (friendAdd != null
&& !StringUtil.isNullOrEmpty(friendAdd.getUserId())
&& !StringUtil.isNullOrEmpty(friendAdd.getFriendUid())
) {
WFCMessage.HandleFriendRequest.Builder friendRequestBuilder = WFCMessage.HandleFriendRequest.newBuilder().setTargetUid(friendAdd.getFriendUid()).setStatus(friendAdd.getStatus());
if (!StringUtil.isNullOrEmpty(friendAdd.getExtra())) {
friendRequestBuilder = friendRequestBuilder.setExtra(friendAdd.getExtra());
}
sendApiMessage(response, friendAdd.getUserId(), IMTopic.HandleFriendRequestTopic, friendRequestBuilder.build().toByteArray(), result -> {
ByteBuf byteBuf = Unpooled.buffer();
byteBuf.writeBytes(result);
ErrorCode errorCode = ErrorCode.fromCode(byteBuf.readByte());
return new Result(errorCode);
});
return false;
} else {
setResponseContent(RestResult.resultOf(ErrorCode.INVALID_PARAMETER), response);
}
}
return true;
| 65
| 329
| 394
|
<methods>public non-sealed void <init>() ,public static java.lang.String getSecretKey() ,public cn.wildfirechat.common.ErrorCode preAction(com.xiaoleilu.loServer.handler.Request, com.xiaoleilu.loServer.handler.Response) ,public static void setNoCheckTime(java.lang.String) ,public static void setSecretKey(java.lang.String) <variables>private static final org.slf4j.Logger LOG,private static boolean NO_CHECK_TIME,private static java.lang.String SECRET_KEY
|
wildfirechat_im-server
|
im-server/broker/src/main/java/com/xiaoleilu/loServer/action/admin/FriendRelationGetAction.java
|
FriendRelationGetAction
|
action
|
class FriendRelationGetAction extends AdminAction {
@Override
public boolean isTransactionAction() {
return true;
}
@Override
public boolean action(Request request, Response response) {<FILL_FUNCTION_BODY>}
}
|
if (request.getNettyRequest() instanceof FullHttpRequest) {
InputUserId inputGetFriendList = getRequestBody(request.getNettyRequest(), InputUserId.class);
List<FriendData> dataList = messagesStore.getFriendList(inputGetFriendList.getUserId(), null, 0);
List<String> list = new ArrayList<>();
dataList.sort(Comparator.comparingLong(FriendData::getTimestamp));
for (FriendData data : dataList) {
if (data.getState() == 0) {
list.add(data.getFriendUid());
}
}
setResponseContent(RestResult.ok(new OutputStringList(list)), response);
}
return true;
| 66
| 183
| 249
|
<methods>public non-sealed void <init>() ,public static java.lang.String getSecretKey() ,public cn.wildfirechat.common.ErrorCode preAction(com.xiaoleilu.loServer.handler.Request, com.xiaoleilu.loServer.handler.Response) ,public static void setNoCheckTime(java.lang.String) ,public static void setSecretKey(java.lang.String) <variables>private static final org.slf4j.Logger LOG,private static boolean NO_CHECK_TIME,private static java.lang.String SECRET_KEY
|
wildfirechat_im-server
|
im-server/broker/src/main/java/com/xiaoleilu/loServer/action/admin/GetAllUserAction.java
|
GetAllUserAction
|
action
|
class GetAllUserAction extends AdminAction {
@Override
public boolean isTransactionAction() {
return true;
}
@Override
public boolean action(Request request, Response response) {<FILL_FUNCTION_BODY>}
}
|
if (request.getNettyRequest() instanceof FullHttpRequest) {
InputGetUserList input = getRequestBody(request.getNettyRequest(), InputGetUserList.class);
if (input != null && input.count > 0 && input.offset >= 0) {
List<WFCMessage.User> users = messagesStore.getUserInfoList(input.count, input.offset);
OutputGetUserList outputGetUserList = new OutputGetUserList();
outputGetUserList.userInfoList = new ArrayList<>();
for (WFCMessage.User user : users) {
outputGetUserList.userInfoList.add(InputOutputUserInfo.fromPbUser(user));
}
RestResult result = RestResult.ok(outputGetUserList);
setResponseContent(result, response);
} else {
setResponseContent(RestResult.resultOf(ErrorCode.INVALID_PARAMETER), response);
}
}
return true;
| 65
| 238
| 303
|
<methods>public non-sealed void <init>() ,public static java.lang.String getSecretKey() ,public cn.wildfirechat.common.ErrorCode preAction(com.xiaoleilu.loServer.handler.Request, com.xiaoleilu.loServer.handler.Response) ,public static void setNoCheckTime(java.lang.String) ,public static void setSecretKey(java.lang.String) <variables>private static final org.slf4j.Logger LOG,private static boolean NO_CHECK_TIME,private static java.lang.String SECRET_KEY
|
wildfirechat_im-server
|
im-server/broker/src/main/java/com/xiaoleilu/loServer/action/admin/GetChannelAction.java
|
GetChannelAction
|
action
|
class GetChannelAction extends AdminAction {
@Override
public boolean isTransactionAction() {
return true;
}
@Override
public boolean action(Request request, Response response) {<FILL_FUNCTION_BODY>}
}
|
if (request.getNettyRequest() instanceof FullHttpRequest) {
InputChannelId inputCreateChannel = getRequestBody(request.getNettyRequest(), InputChannelId.class);
if (inputCreateChannel != null
&& !StringUtil.isNullOrEmpty(inputCreateChannel.channelId)) {
WFCMessage.ChannelInfo channelInfo = messagesStore.getChannelInfo(inputCreateChannel.channelId);
if (channelInfo == null) {
setResponseContent(RestResult.resultOf(ErrorCode.ERROR_CODE_NOT_EXIST), response);
} else {
setResponseContent(RestResult.ok(OutputGetChannelInfo.fromPbInfo(channelInfo)), response);
}
} else {
setResponseContent(RestResult.resultOf(ErrorCode.INVALID_PARAMETER), response);
}
}
return true;
| 64
| 211
| 275
|
<methods>public non-sealed void <init>() ,public static java.lang.String getSecretKey() ,public cn.wildfirechat.common.ErrorCode preAction(com.xiaoleilu.loServer.handler.Request, com.xiaoleilu.loServer.handler.Response) ,public static void setNoCheckTime(java.lang.String) ,public static void setSecretKey(java.lang.String) <variables>private static final org.slf4j.Logger LOG,private static boolean NO_CHECK_TIME,private static java.lang.String SECRET_KEY
|
wildfirechat_im-server
|
im-server/broker/src/main/java/com/xiaoleilu/loServer/action/admin/GetChatroomInfoAction.java
|
GetChatroomInfoAction
|
action
|
class GetChatroomInfoAction extends AdminAction {
@Override
public boolean isTransactionAction() {
return true;
}
@Override
public boolean action(Request request, Response response) {<FILL_FUNCTION_BODY>}
}
|
if (request.getNettyRequest() instanceof FullHttpRequest) {
InputGetChatroomInfo getChatroomInfo = getRequestBody(request.getNettyRequest(), InputGetChatroomInfo.class);
String chatroomid = getChatroomInfo.getChatroomId();
if (!StringUtil.isNullOrEmpty(chatroomid)) {
WFCMessage.ChatroomInfo info = messagesStore.getChatroomInfo(chatroomid);
RestResult result;
if (info != null) {
result = RestResult.ok(new OutputGetChatroomInfo(chatroomid, messagesStore.getChatroomMemberCount(chatroomid), info));
} else {
result = RestResult.resultOf(ErrorCode.ERROR_CODE_NOT_EXIST);
}
setResponseContent(result, response);
} else {
setResponseContent(RestResult.resultOf(ErrorCode.INVALID_PARAMETER), response);
}
}
return true;
| 66
| 242
| 308
|
<methods>public non-sealed void <init>() ,public static java.lang.String getSecretKey() ,public cn.wildfirechat.common.ErrorCode preAction(com.xiaoleilu.loServer.handler.Request, com.xiaoleilu.loServer.handler.Response) ,public static void setNoCheckTime(java.lang.String) ,public static void setSecretKey(java.lang.String) <variables>private static final org.slf4j.Logger LOG,private static boolean NO_CHECK_TIME,private static java.lang.String SECRET_KEY
|
wildfirechat_im-server
|
im-server/broker/src/main/java/com/xiaoleilu/loServer/action/admin/GetChatroomMembersAction.java
|
GetChatroomMembersAction
|
action
|
class GetChatroomMembersAction extends AdminAction {
@Override
public boolean isTransactionAction() {
return true;
}
@Override
public boolean action(Request request, Response response) {<FILL_FUNCTION_BODY>}
}
|
if (request.getNettyRequest() instanceof FullHttpRequest) {
InputGetChatroomInfo getChatroomInfo = getRequestBody(request.getNettyRequest(), InputGetChatroomInfo.class);
String chatroomid = getChatroomInfo.getChatroomId();
if (!StringUtil.isNullOrEmpty(chatroomid)) {
Collection<UserClientEntry> members = messagesStore.getChatroomMembers(chatroomid);
List<String> list = new ArrayList<>();
for (UserClientEntry entry : members) {
list.add(entry.userId);
}
RestResult result;
if (!list.isEmpty()) {
result = RestResult.ok(new OutputStringList(list));
} else {
result = RestResult.resultOf(ErrorCode.ERROR_CODE_NOT_EXIST);
}
setResponseContent(result, response);
} else {
setResponseContent(RestResult.resultOf(ErrorCode.INVALID_PARAMETER), response);
}
}
return true;
| 66
| 260
| 326
|
<methods>public non-sealed void <init>() ,public static java.lang.String getSecretKey() ,public cn.wildfirechat.common.ErrorCode preAction(com.xiaoleilu.loServer.handler.Request, com.xiaoleilu.loServer.handler.Response) ,public static void setNoCheckTime(java.lang.String) ,public static void setSecretKey(java.lang.String) <variables>private static final org.slf4j.Logger LOG,private static boolean NO_CHECK_TIME,private static java.lang.String SECRET_KEY
|
wildfirechat_im-server
|
im-server/broker/src/main/java/com/xiaoleilu/loServer/action/admin/GetCommonGroupsAction.java
|
GetCommonGroupsAction
|
action
|
class GetCommonGroupsAction extends AdminAction {
@Override
public boolean isTransactionAction() {
return true;
}
@Override
public boolean action(Request request, Response response) {<FILL_FUNCTION_BODY>}
}
|
if (request.getNettyRequest() instanceof FullHttpRequest) {
StringPairPojo input = getRequestBody(request.getNettyRequest(), StringPairPojo.class);
if (input != null
&& (!StringUtil.isNullOrEmpty(input.getFirst())) && (!StringUtil.isNullOrEmpty(input.getSecond()))) {
Set<String> groupIds = messagesStore.getCommonGroupIds(input.getFirst(), input.getSecond());
OutputGroupIds outputGroupIds = new OutputGroupIds();
outputGroupIds.setGroupIds(new ArrayList<>(groupIds));
RestResult result = RestResult.ok(outputGroupIds);
setResponseContent(result, response);
} else {
setResponseContent(RestResult.resultOf(ErrorCode.INVALID_PARAMETER), response);
}
}
return true;
| 65
| 213
| 278
|
<methods>public non-sealed void <init>() ,public static java.lang.String getSecretKey() ,public cn.wildfirechat.common.ErrorCode preAction(com.xiaoleilu.loServer.handler.Request, com.xiaoleilu.loServer.handler.Response) ,public static void setNoCheckTime(java.lang.String) ,public static void setSecretKey(java.lang.String) <variables>private static final org.slf4j.Logger LOG,private static boolean NO_CHECK_TIME,private static java.lang.String SECRET_KEY
|
wildfirechat_im-server
|
im-server/broker/src/main/java/com/xiaoleilu/loServer/action/admin/GetGroupInfoAction.java
|
GetGroupInfoAction
|
action
|
class GetGroupInfoAction extends AdminAction {
@Override
public boolean isTransactionAction() {
return true;
}
@Override
public boolean action(Request request, Response response) {<FILL_FUNCTION_BODY>}
}
|
if (request.getNettyRequest() instanceof FullHttpRequest) {
InputGetGroup inputGetGroup = getRequestBody(request.getNettyRequest(), InputGetGroup.class);
if (inputGetGroup != null
&& (!StringUtil.isNullOrEmpty(inputGetGroup.getGroupId()))) {
WFCMessage.GroupInfo groupInfo = messagesStore.getGroupInfo(inputGetGroup.getGroupId());
RestResult result;
if (groupInfo == null) {
result = RestResult.resultOf(ErrorCode.ERROR_CODE_NOT_EXIST);
} else {
PojoGroupInfo pojoGroupInfo = new PojoGroupInfo();
pojoGroupInfo.setExtra(groupInfo.getExtra());
pojoGroupInfo.setName(groupInfo.getName());
pojoGroupInfo.setOwner(groupInfo.getOwner());
pojoGroupInfo.setPortrait(groupInfo.getPortrait());
pojoGroupInfo.setTarget_id(groupInfo.getTargetId());
pojoGroupInfo.setType(groupInfo.getType());
pojoGroupInfo.setMute(groupInfo.getMute());
pojoGroupInfo.setJoin_type(groupInfo.getJoinType());
pojoGroupInfo.setPrivate_chat(groupInfo.getPrivateChat());
pojoGroupInfo.setSearchable(groupInfo.getSearchable());
pojoGroupInfo.setMax_member_count(groupInfo.getMemberCount());
pojoGroupInfo.setHistory_message(groupInfo.getHistoryMessage());
pojoGroupInfo.setSuper_group(groupInfo.getSuperGroup()>0);
pojoGroupInfo.setDeleted(groupInfo.getDeleted()>0);
result = RestResult.ok(pojoGroupInfo);
}
setResponseContent(result, response);
} else {
setResponseContent(RestResult.resultOf(ErrorCode.INVALID_PARAMETER), response);
}
}
return true;
| 65
| 490
| 555
|
<methods>public non-sealed void <init>() ,public static java.lang.String getSecretKey() ,public cn.wildfirechat.common.ErrorCode preAction(com.xiaoleilu.loServer.handler.Request, com.xiaoleilu.loServer.handler.Response) ,public static void setNoCheckTime(java.lang.String) ,public static void setSecretKey(java.lang.String) <variables>private static final org.slf4j.Logger LOG,private static boolean NO_CHECK_TIME,private static java.lang.String SECRET_KEY
|
wildfirechat_im-server
|
im-server/broker/src/main/java/com/xiaoleilu/loServer/action/admin/GetGroupMemberAction.java
|
GetGroupMemberAction
|
action
|
class GetGroupMemberAction extends AdminAction {
@Override
public boolean isTransactionAction() {
return true;
}
@Override
public boolean action(Request request, Response response) {<FILL_FUNCTION_BODY>}
}
|
if (request.getNettyRequest() instanceof FullHttpRequest) {
InputGetGroupMember input = getRequestBody(request.getNettyRequest(), InputGetGroupMember.class);
if (input != null
&& (!StringUtil.isNullOrEmpty(input.getGroupId()))
&& (!StringUtil.isNullOrEmpty(input.getMemberId()))) {
WFCMessage.GroupMember groupMember = messagesStore.getGroupMember(input.getGroupId(), input.getMemberId());
RestResult result;
if (groupMember == null || StringUtil.isNullOrEmpty(groupMember.getMemberId()) || groupMember.getType() == ProtoConstants.GroupMemberType.GroupMemberType_Removed) {
result = RestResult.resultOf(ErrorCode.ERROR_CODE_NOT_EXIST);
} else {
PojoGroupMember pm = new PojoGroupMember();
pm.setMember_id(groupMember.getMemberId());
pm.setAlias(groupMember.getAlias());
pm.setType(groupMember.getType());
pm.setExtra(groupMember.getExtra());
pm.setCreateDt(groupMember.getCreateDt());
result = RestResult.ok(pm);
}
setResponseContent(result, response);
} else {
setResponseContent(RestResult.resultOf(ErrorCode.INVALID_PARAMETER), response);
}
}
return true;
| 65
| 358
| 423
|
<methods>public non-sealed void <init>() ,public static java.lang.String getSecretKey() ,public cn.wildfirechat.common.ErrorCode preAction(com.xiaoleilu.loServer.handler.Request, com.xiaoleilu.loServer.handler.Response) ,public static void setNoCheckTime(java.lang.String) ,public static void setSecretKey(java.lang.String) <variables>private static final org.slf4j.Logger LOG,private static boolean NO_CHECK_TIME,private static java.lang.String SECRET_KEY
|
wildfirechat_im-server
|
im-server/broker/src/main/java/com/xiaoleilu/loServer/action/admin/GetGroupMembersAction.java
|
GetGroupMembersAction
|
action
|
class GetGroupMembersAction extends AdminAction {
@Override
public boolean isTransactionAction() {
return true;
}
@Override
public boolean action(Request request, Response response) {<FILL_FUNCTION_BODY>}
}
|
if (request.getNettyRequest() instanceof FullHttpRequest) {
InputGetGroup inputGetGroup = getRequestBody(request.getNettyRequest(), InputGetGroup.class);
if (inputGetGroup != null
&& (!StringUtil.isNullOrEmpty(inputGetGroup.getGroupId()))) {
List<WFCMessage.GroupMember> members = new ArrayList<>();
ErrorCode errorCode = messagesStore.getGroupMembers(null, inputGetGroup.getGroupId(), 0, members);
RestResult result;
if (errorCode != ErrorCode.ERROR_CODE_SUCCESS) {
result = RestResult.resultOf(errorCode);
} else {
OutputGroupMemberList out = new OutputGroupMemberList();
out.setMembers(new ArrayList<>());
for (WFCMessage.GroupMember member : members) {
if (member.getType() == ProtoConstants.GroupMemberType.GroupMemberType_Removed) {
continue;
}
PojoGroupMember pm = new PojoGroupMember();
pm.setMember_id(member.getMemberId());
pm.setAlias(member.getAlias());
pm.setType(member.getType());
pm.setExtra(member.getExtra());
pm.setCreateDt(member.getCreateDt());
out.getMembers().add(pm);
}
result = RestResult.ok(out);
}
setResponseContent(result, response);
} else {
setResponseContent(RestResult.resultOf(ErrorCode.INVALID_PARAMETER), response);
}
}
return true;
| 65
| 406
| 471
|
<methods>public non-sealed void <init>() ,public static java.lang.String getSecretKey() ,public cn.wildfirechat.common.ErrorCode preAction(com.xiaoleilu.loServer.handler.Request, com.xiaoleilu.loServer.handler.Response) ,public static void setNoCheckTime(java.lang.String) ,public static void setSecretKey(java.lang.String) <variables>private static final org.slf4j.Logger LOG,private static boolean NO_CHECK_TIME,private static java.lang.String SECRET_KEY
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.