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
|
|---|---|---|---|---|---|---|---|---|---|
hs-web_hsweb-framework
|
hsweb-framework/hsweb-starter/src/main/java/org/hswebframework/web/starter/jackson/CustomTypeFactory.java
|
CustomTypeFactory
|
withModifier
|
class CustomTypeFactory extends TypeFactory {
private EntityFactory entityFactory;
public CustomTypeFactory(EntityFactory factory) {
super(new LRUMap<>(64, 1024));
this.entityFactory = factory;
}
protected CustomTypeFactory(LookupCache<Object, JavaType> typeCache, TypeParser p,
TypeModifier[] mods, ClassLoader classLoader) {
super(typeCache, p, mods, classLoader);
}
@Override
public TypeFactory withCache(LRUMap<Object, JavaType> cache) {
return new CustomTypeFactory(cache, _parser, _modifiers, _classLoader);
}
@Override
public TypeFactory withClassLoader(ClassLoader classLoader) {
return new CustomTypeFactory(_typeCache, _parser, _modifiers, _classLoader);
}
@Override
public TypeFactory withModifier(TypeModifier mod) {<FILL_FUNCTION_BODY>}
@Override
protected JavaType _fromWellKnownInterface(ClassStack context, Class<?> rawType, TypeBindings bindings, JavaType superClass, JavaType[] superInterfaces) {
JavaType javaType = super._fromWellKnownInterface(context, rawType, bindings, superClass, superInterfaces);
if (javaType == null) {
rawType = entityFactory.getInstanceType(rawType, false);
if (rawType != null) {
javaType = SimpleType.constructUnsafe(rawType);
}
}
return javaType;
}
@Override
protected JavaType _fromWellKnownClass(ClassStack context, Class<?> rawType, TypeBindings bindings, JavaType superClass, JavaType[] superInterfaces) {
JavaType javaType = super._fromWellKnownClass(context, rawType, bindings, superClass, superInterfaces);
if (javaType == null) {
rawType = entityFactory.getInstanceType(rawType, false);
if (rawType != null) {
javaType = SimpleType.constructUnsafe(rawType);
}
}
return javaType;
}
}
|
LookupCache<Object, JavaType> typeCache = _typeCache;
TypeModifier[] mods;
if (mod == null) { // mostly for unit tests
mods = null;
// 30-Jun-2016, tatu: for some reason expected semantics are to clear cache
// in this case; can't recall why, but keeping the same
typeCache = null;
} else if (_modifiers == null) {
mods = new TypeModifier[]{mod};
// 29-Jul-2019, tatu: Actually I think we better clear cache in this case
// as well to ensure no leakage occurs (see [databind#2395])
typeCache = null;
} else {
// but may keep existing cache otherwise
mods = ArrayBuilders.insertInListNoDup(_modifiers, mod);
}
return new CustomTypeFactory(typeCache, _parser, mods, _classLoader);
| 542
| 244
| 786
|
<no_super_class>
|
hs-web_hsweb-framework
|
hsweb-framework/hsweb-starter/src/main/java/org/hswebframework/web/starter/jackson/Jackson2Tokenizer.java
|
Jackson2Tokenizer
|
tokenize
|
class Jackson2Tokenizer {
private final JsonParser parser;
private final DeserializationContext deserializationContext;
private final boolean tokenizeArrayElements;
private TokenBuffer tokenBuffer;
private int objectDepth;
private int arrayDepth;
// TODO: change to ByteBufferFeeder when supported by Jackson
// See https://github.com/FasterXML/jackson-core/issues/478
private final ByteArrayFeeder inputFeeder;
private Jackson2Tokenizer(
JsonParser parser, DeserializationContext deserializationContext, boolean tokenizeArrayElements) {
this.parser = parser;
this.deserializationContext = deserializationContext;
this.tokenizeArrayElements = tokenizeArrayElements;
this.tokenBuffer = new TokenBuffer(parser, deserializationContext);
this.inputFeeder = (ByteArrayFeeder) this.parser.getNonBlockingInputFeeder();
}
private List<TokenBuffer> tokenize(DataBuffer dataBuffer) {
byte[] bytes = new byte[dataBuffer.readableByteCount()];
dataBuffer.read(bytes);
DataBufferUtils.release(dataBuffer);
try {
this.inputFeeder.feedInput(bytes, 0, bytes.length);
return parseTokenBufferFlux();
}
catch (JsonProcessingException ex) {
throw new DecodingException("JSON decoding error: " + ex.getOriginalMessage(), ex);
}
catch (IOException ex) {
throw Exceptions.propagate(ex);
}
}
private Flux<TokenBuffer> endOfInput() {
return Flux.defer(() -> {
this.inputFeeder.endOfInput();
try {
return Flux.fromIterable(parseTokenBufferFlux());
}
catch (JsonProcessingException ex) {
throw new DecodingException("JSON decoding error: " + ex.getOriginalMessage(), ex);
}
catch (IOException ex) {
throw Exceptions.propagate(ex);
}
});
}
private List<TokenBuffer> parseTokenBufferFlux() throws IOException {
List<TokenBuffer> result = new ArrayList<>();
while (true) {
JsonToken token = this.parser.nextToken();
// SPR-16151: Smile data format uses null to separate documents
if (token == JsonToken.NOT_AVAILABLE ||
(token == null && (token = this.parser.nextToken()) == null)) {
break;
}
updateDepth(token);
if (!this.tokenizeArrayElements) {
processTokenNormal(token, result);
}
else {
processTokenArray(token, result);
}
}
return result;
}
private void updateDepth(JsonToken token) {
switch (token) {
case START_OBJECT:
this.objectDepth++;
break;
case END_OBJECT:
this.objectDepth--;
break;
case START_ARRAY:
this.arrayDepth++;
break;
case END_ARRAY:
this.arrayDepth--;
break;
}
}
private void processTokenNormal(JsonToken token, List<TokenBuffer> result) throws IOException {
this.tokenBuffer.copyCurrentEvent(this.parser);
if ((token.isStructEnd() || token.isScalarValue()) && this.objectDepth == 0 && this.arrayDepth == 0) {
result.add(this.tokenBuffer);
this.tokenBuffer = new TokenBuffer(this.parser, this.deserializationContext);
}
}
private void processTokenArray(JsonToken token, List<TokenBuffer> result) throws IOException {
if (!isTopLevelArrayToken(token)) {
this.tokenBuffer.copyCurrentEvent(this.parser);
}
if (this.objectDepth == 0 && (this.arrayDepth == 0 || this.arrayDepth == 1) &&
(token == JsonToken.END_OBJECT || token.isScalarValue())) {
result.add(this.tokenBuffer);
this.tokenBuffer = new TokenBuffer(this.parser, this.deserializationContext);
}
}
private boolean isTopLevelArrayToken(JsonToken token) {
return this.objectDepth == 0 && ((token == JsonToken.START_ARRAY && this.arrayDepth == 1) ||
(token == JsonToken.END_ARRAY && this.arrayDepth == 0));
}
/**
* Tokenize the given {@code Flux<DataBuffer>} into {@code Flux<TokenBuffer>}.
* @param dataBuffers the source data buffers
* @param jsonFactory the factory to use
* @param objectMapper the current mapper instance
* @param tokenizeArrayElements if {@code true} and the "top level" JSON object is
* an array, each element is returned individually immediately after it is received
* @return the resulting token buffers
*/
public static Flux<TokenBuffer> tokenize(Flux<DataBuffer> dataBuffers, JsonFactory jsonFactory,
ObjectMapper objectMapper, boolean tokenizeArrayElements) {<FILL_FUNCTION_BODY>}
}
|
try {
JsonParser parser = jsonFactory.createNonBlockingByteArrayParser();
DeserializationContext context = objectMapper.getDeserializationContext();
if (context instanceof DefaultDeserializationContext) {
context = ((DefaultDeserializationContext) context).createInstance(
objectMapper.getDeserializationConfig(), parser, objectMapper.getInjectableValues());
}
Jackson2Tokenizer tokenizer = new Jackson2Tokenizer(parser, context, tokenizeArrayElements);
return dataBuffers.concatMapIterable(tokenizer::tokenize).concatWith(tokenizer.endOfInput());
}
catch (IOException ex) {
return Flux.error(ex);
}
| 1,303
| 180
| 1,483
|
<no_super_class>
|
hs-web_hsweb-framework
|
hsweb-framework/hsweb-system/hsweb-system-authorization/hsweb-system-authorization-api/src/main/java/org/hswebframework/web/system/authorization/api/entity/AuthorizationSettingEntity.java
|
AuthorizationSettingEntity
|
copy
|
class AuthorizationSettingEntity implements Entity {
@Id
@Column(length = 32)
@GeneratedValue(generator = "md5")
@Schema(description = "ID")
private String id;
@Column(length = 32, nullable = false, updatable = false)
@Comment("权限ID")
@NotBlank(message = "权限ID不能为空",groups = CreateGroup.class)
@Schema(description = "权限ID")
private String permission;
@Column(name = "dimension_type",length = 32, nullable = false,updatable = false)
@Comment("维度类型")//如:user,role
@NotBlank(message = "维度不能为空",groups = CreateGroup.class)
@Schema(description = "维度类型,如: user,role")
private String dimensionType;
@Column(name = "dimension_type_name", length = 64)
@Comment("维度类型名称")//如:用户,角色
@Schema(description = "维度类型名称,如: 用户,角色")
private String dimensionTypeName;
@Column(name = "dimension_target", length = 32, updatable = false)
@Comment("维度目标")//具体的某个维度实例ID
@NotBlank(message = "维度目标不能为空",groups = CreateGroup.class)
@Schema(description = "维度目标,如: 用户的ID,角色的ID")
private String dimensionTarget;
@Column(name = "dimension_target_name", length = 64)
@Comment("维度目标名称")//维度实例名称.如: 用户名. 角色名
@Schema(description = "维度类型,如: 用户名,角色名")
private String dimensionTargetName;
@Column(name = "state", nullable = false)
@Comment("状态")
@NotNull(message = "状态不能为空",groups = CreateGroup.class)
@Schema(description = "状态,0禁用,1启用")
@DefaultValue("1")
private Byte state;
@Column
@ColumnType(jdbcType = JDBCType.CLOB)
@JsonCodec
@Comment("可操作权限")
@Schema(description = "授权可对此权限进行的操作")
private Set<String> actions;
@Column(name = "data_accesses")
@ColumnType(jdbcType = JDBCType.CLOB)
@JsonCodec
@Comment("数据权限")
@Schema(description = "数据权限配置")
private List<DataAccessEntity> dataAccesses;
@Column
@Comment("优先级")
@Schema(description = "冲突时,合并优先级")
private Integer priority;
@Column
@Comment("是否合并")
@Schema(description = "冲突时,是否合并")
private Boolean merge;
public AuthorizationSettingEntity copy(Predicate<String> actionFilter,
Predicate<DataAccessEntity> dataAccessFilter){<FILL_FUNCTION_BODY>}
}
|
AuthorizationSettingEntity newSetting= FastBeanCopier.copy(this,new AuthorizationSettingEntity());
if(!CollectionUtils.isEmpty(newSetting.getActions())){
newSetting.setActions(newSetting.getActions().stream().filter(actionFilter).collect(Collectors.toSet()));
}
if(!CollectionUtils.isEmpty(newSetting.getDataAccesses())){
newSetting.setDataAccesses(newSetting.getDataAccesses().stream().filter(dataAccessFilter).collect(Collectors.toList()));
}
return newSetting;
| 791
| 137
| 928
|
<no_super_class>
|
hs-web_hsweb-framework
|
hsweb-framework/hsweb-system/hsweb-system-authorization/hsweb-system-authorization-api/src/main/java/org/hswebframework/web/system/authorization/api/entity/DataAccessEntity.java
|
DataAccessEntity
|
toMap
|
class DataAccessEntity {
@Schema(description = "操作标识")
private String action;
@Schema(description = "数据权限类型")
private String type;
@Schema(description = "说明")
private String describe;
@Schema(description = "配置")
private Map<String,Object> config;
public Map<String,Object> toMap(){<FILL_FUNCTION_BODY>}
}
|
Map<String,Object> map = new HashMap<>();
map.put("type",type);
map.put("action",action);
map.put("describe",describe);
if(config!=null){
map.putAll(config);
}
return map;
| 111
| 78
| 189
|
<no_super_class>
|
hs-web_hsweb-framework
|
hsweb-framework/hsweb-system/hsweb-system-authorization/hsweb-system-authorization-api/src/main/java/org/hswebframework/web/system/authorization/api/entity/DimensionUserEntity.java
|
DimensionUserEntity
|
generateId
|
class DimensionUserEntity extends GenericEntity<String> {
@Comment("维度类型ID")
@Column(name = "dimension_type_id", nullable = false, length = 32)
@Schema(description = "维度类型ID,如: org,tenant")
private String dimensionTypeId;
@Comment("维度ID")
@Column(name = "dimension_id", nullable = false, length = 64)
@Schema(description = "维度ID")
private String dimensionId;
@Comment("维度名称")
@Column(name = "dimension_name", nullable = false)
@NotBlank
@Schema(description = "维度名称")
private String dimensionName;
@Comment("用户ID")
@Column(name = "user_id", nullable = false, length = 64)
@Schema(description = "用户ID")
@NotBlank
private String userId;
@Comment("用户名")
@Column(name = "user_name", nullable = false)
@Schema(description = "用户名")
private String userName;
@Comment("关系")
@Column(length = 32)
@Schema(description = "维度关系")
private String relation;
@Column(name = "relation_name")
@Comment("关系名称")
@Schema(description = "维度关系名称")
private String relationName;
@Column(name = "features")
@ColumnType(jdbcType = JDBCType.NUMERIC, javaType = Long.class)
@EnumCodec(toMask = true)
@Schema(description = "其他功能")
private DimensionUserFeature[] features;
public void generateId() {<FILL_FUNCTION_BODY>}
public boolean hasFeature(DimensionUserFeature feature) {
return features != null && EnumDict.in(feature, features);
}
}
|
if (StringUtils.isEmpty(getId())) {
String id = DigestUtils
.md5DigestAsHex(String.format("%s-%s-%s",
dimensionTypeId,
dimensionId, userId).getBytes());
setId(id);
}
| 493
| 75
| 568
|
<methods>public non-sealed void <init>() ,public transient java.lang.String toString(java.lang.String[]) ,public java.lang.String toString() <variables>private java.lang.String id
|
hs-web_hsweb-framework
|
hsweb-framework/hsweb-system/hsweb-system-authorization/hsweb-system-authorization-api/src/main/java/org/hswebframework/web/system/authorization/api/entity/PermissionEntity.java
|
PermissionEntity
|
copy
|
class PermissionEntity extends GenericEntity<String> implements RecordCreationEntity, RecordModifierEntity {
@Override
@Pattern(regexp = "^[0-9a-zA-Z_\\-]+$", message = "ID只能由数字,字母,下划线和中划线组成", groups = CreateGroup.class)
public String getId() {
return super.getId();
}
@Column
@Comment("权限名称")
@Schema(description = "权限名称")
@NotBlank(message = "权限名称不能为空", groups = CreateGroup.class)
private String name;
@Column
@Comment("说明")
@Schema(description = "说明")
private String describe;
@Column(nullable = false)
@Comment("状态")
@Schema(description = "状态")
@DefaultValue("1")
private Byte status;
@Column
@ColumnType(jdbcType = JDBCType.LONGVARCHAR)
@JsonCodec
@Comment("可选操作")
@Schema(description = "可选操作")
private List<ActionEntity> actions;
@Column(name = "optional_fields")
@ColumnType(jdbcType = JDBCType.LONGVARCHAR)
@JsonCodec
@Comment("可操作的字段")
@Schema(description = "可操作字段")
private List<OptionalField> optionalFields;
@Column
@ColumnType(jdbcType = JDBCType.LONGVARCHAR)
@JsonCodec
@Comment("关联权限")
@Schema(description = "关联权限")
private List<ParentPermission> parents;
@Column
@ColumnType(jdbcType = JDBCType.LONGVARCHAR)
@JsonCodec
@Comment("其他配置")
@Schema(description = "其他配置")
private Map<String, Object> properties;
@Schema(description = "创建时间")
@Column(updatable = false)
@DefaultValue(generator = Generators.CURRENT_TIME)
private Long createTime;
@Schema(description = "创建人ID")
@Column(length = 64, updatable = false)
private String creatorId;
@Schema(description = "修改时间")
@Column
@DefaultValue(generator = Generators.CURRENT_TIME)
private Long modifyTime;
@Schema(description = "修改人ID")
@Column(length = 64, updatable = false)
private String modifierId;
public PermissionEntity copy(Predicate<ActionEntity> actionFilter,
Predicate<OptionalField> fieldFilter) {<FILL_FUNCTION_BODY>}
}
|
PermissionEntity entity = FastBeanCopier.copy(this, new PermissionEntity());
if (!CollectionUtils.isEmpty(entity.getActions())) {
entity.setActions(entity.getActions().stream().filter(actionFilter).collect(Collectors.toList()));
}
if (!CollectionUtils.isEmpty(entity.getOptionalFields())) {
entity.setOptionalFields(entity
.getOptionalFields()
.stream()
.filter(fieldFilter)
.collect(Collectors.toList()));
}
return entity;
| 691
| 135
| 826
|
<methods>public non-sealed void <init>() ,public transient java.lang.String toString(java.lang.String[]) ,public java.lang.String toString() <variables>private java.lang.String id
|
hs-web_hsweb-framework
|
hsweb-framework/hsweb-system/hsweb-system-authorization/hsweb-system-authorization-api/src/main/java/org/hswebframework/web/system/authorization/api/event/ClearUserAuthorizationCacheEvent.java
|
ClearUserAuthorizationCacheEvent
|
of
|
class ClearUserAuthorizationCacheEvent extends DefaultAsyncEvent {
private Set<String> userId;
private boolean all;
private boolean async;
private static final String DISABLE_KEY = ClearUserAuthorizationCacheEvent.class + "_Disabled";
public static <T> Flux<T> disable(Flux<T> task) {
return task.contextWrite(Context.of(DISABLE_KEY, true));
}
public static <T> Mono<T> disable(Mono<T> task) {
return task.contextWrite(Context.of(DISABLE_KEY, true));
}
public static Mono<Void> doOnEnabled(Mono<Void> task) {
return Mono.deferContextual(ctx -> {
if (ctx.hasKey(DISABLE_KEY)) {
return Mono.empty();
}
return task;
});
}
@Override
public synchronized void async(Publisher<?> publisher) {
super.async(doOnEnabled(Mono.fromDirect(publisher).then()));
}
public static ClearUserAuthorizationCacheEvent of(Collection<String> collection) {<FILL_FUNCTION_BODY>}
public static ClearUserAuthorizationCacheEvent all() {
return ClearUserAuthorizationCacheEvent.of((String[]) null);
}
//兼容async
public ClearUserAuthorizationCacheEvent useAsync() {
this.async = true;
return this;
}
@Override
public Mono<Void> publish(ApplicationEventPublisher eventPublisher) {
this.async = true;
return super.publish(eventPublisher);
}
public static ClearUserAuthorizationCacheEvent of(String... userId) {
return of(userId == null ? null : Arrays.asList(userId));
}
}
|
ClearUserAuthorizationCacheEvent event = new ClearUserAuthorizationCacheEvent();
if (collection == null || collection.isEmpty()) {
event.all = true;
} else {
event.userId = new HashSet<>(collection);
}
return event;
| 469
| 69
| 538
|
<methods>public non-sealed void <init>() ,public synchronized void async(Publisher<?>) ,public synchronized void first(Publisher<?>) ,public Mono<java.lang.Void> getAsync() ,public boolean hasListener() ,public Mono<java.lang.Void> publish(ApplicationEventPublisher) ,public void transform(Function<Mono<?>,Publisher<?>>) ,public void transformFirst(Function<Mono<?>,Publisher<?>>) <variables>private transient Mono<?> async,private transient Mono<?> first,private transient boolean hasListener
|
hs-web_hsweb-framework
|
hsweb-framework/hsweb-system/hsweb-system-authorization/hsweb-system-authorization-default/src/main/java/org/hswebframework/web/system/authorization/defaults/configuration/PermissionProperties.java
|
PermissionFilter
|
doFilter
|
class PermissionFilter {
//开启权限过滤
private boolean enabled = false;
//越权赋权时处理逻辑
private UnAuthStrategy unAuthStrategy = UnAuthStrategy.error;
private Set<String> excludeUsername = new HashSet<>();
public AuthorizationSettingEntity handleSetting(Authentication authentication,
AuthorizationSettingEntity setting) {
if (!enabled || excludeUsername.contains(authentication.getUser().getUsername())) {
return setting;
}
//有全部权限
if (authentication.hasPermission(setting.getPermission(), setting.getActions())) {
return setting;
}
//交给具体的策略处理
return unAuthStrategy.handle(authentication, setting);
}
public Flux<PermissionEntity> doFilter(Flux<PermissionEntity> flux, Authentication authentication) {<FILL_FUNCTION_BODY>}
public enum UnAuthStrategy {
//忽略赋权
ignore {
@Override
public AuthorizationSettingEntity handle(Authentication authentication, AuthorizationSettingEntity setting) {
return setting.copy(action -> authentication.hasPermission(setting.getPermission(), action), access -> true);
}
},
//抛出错误
error {
@Override
public AuthorizationSettingEntity handle(Authentication authentication, AuthorizationSettingEntity setting) {
Set<String> actions = new HashSet<>(setting.getActions());
actions.removeAll(authentication
.getPermission(setting.getPermission())
.map(Permission::getActions)
.orElseGet(Collections::emptySet));
throw new AccessDenyException(setting.getPermission(), actions);
}
};
public abstract AuthorizationSettingEntity handle(Authentication authentication,
AuthorizationSettingEntity setting);
}
}
|
if (!enabled || excludeUsername.contains(authentication.getUser().getUsername())) {
return flux;
}
return flux
.map(entity -> entity
.copy(action -> authentication.hasPermission(entity.getId(), action.getAction()),
optionalField -> true))
.filter(entity -> !CollectionUtils.isEmpty(entity.getActions()));
| 446
| 96
| 542
|
<no_super_class>
|
hs-web_hsweb-framework
|
hsweb-framework/hsweb-system/hsweb-system-authorization/hsweb-system-authorization-default/src/main/java/org/hswebframework/web/system/authorization/defaults/service/DefaultAuthorizationSettingService.java
|
DefaultAuthorizationSettingService
|
clearUserAuthCache
|
class DefaultAuthorizationSettingService extends GenericReactiveCrudService<AuthorizationSettingEntity, String> {
@Autowired
private ApplicationEventPublisher eventPublisher;
@Autowired
private List<DimensionProvider> providers;
protected AuthorizationSettingEntity generateId(AuthorizationSettingEntity entity) {
if (StringUtils.isEmpty(entity.getId())) {
entity.setId(DigestUtils.md5Hex(entity.getPermission() + entity.getDimensionType() + entity.getDimensionTarget()));
}
return entity;
}
@Override
public Mono<SaveResult> save(AuthorizationSettingEntity data) {
generateId(data);
return super.save(data);
}
@Override
public Mono<SaveResult> save(Collection<AuthorizationSettingEntity> collection) {
collection.forEach(this::generateId);
return super.save(collection);
}
@Override
public Mono<SaveResult> save(Publisher<AuthorizationSettingEntity> entityPublisher) {
return Flux.from(entityPublisher)
.map(this::generateId)
.as(super::save);
}
@Override
public Mono<Integer> insert(Publisher<AuthorizationSettingEntity> entityPublisher) {
return Flux.from(entityPublisher)
.map(this::generateId)
.as(super::insert);
}
@Override
public Mono<Integer> insertBatch(Publisher<? extends Collection<AuthorizationSettingEntity>> entityPublisher) {
return Flux
.from(entityPublisher)
.doOnNext(list -> list.forEach(this::generateId))
.as(super::insertBatch);
}
protected Mono<Void> clearUserAuthCache(List<AuthorizationSettingEntity> settings) {<FILL_FUNCTION_BODY>}
@EventListener
public void handleAuthSettingDeleted(EntityDeletedEvent<AuthorizationSettingEntity> event) {
event.async(
clearUserAuthCache(event.getEntity())
);
}
@EventListener
public void handleAuthSettingChanged(EntityModifyEvent<AuthorizationSettingEntity> event) {
event.async(
clearUserAuthCache(event.getAfter())
);
}
@EventListener
public void handleAuthSettingSaved(EntitySavedEvent<AuthorizationSettingEntity> event) {
event.async(
clearUserAuthCache(event.getEntity())
);
}
@EventListener
public void handleAuthSettingAdded(EntityCreatedEvent<AuthorizationSettingEntity> event) {
event.async(
clearUserAuthCache(event.getEntity())
);
}
@EventListener
public void handleDimensionAdd(DimensionDeletedEvent event) {
event.async(
createDelete()
.where(AuthorizationSettingEntity::getDimensionType, event.getDimensionType())
.and(AuthorizationSettingEntity::getDimensionTarget, event.getDimensionId())
.execute()
);
}
@EventListener
public void handleDimensionDeletedEvent(DimensionDeletedEvent event) {
event.async(
createDelete()
.where(AuthorizationSettingEntity::getDimensionType, event.getDimensionType())
.and(AuthorizationSettingEntity::getDimensionTarget, event.getDimensionId())
.execute()
);
}
}
|
return Flux
.fromIterable(providers)
.flatMap(provider ->
//按维度类型进行映射
provider.getAllType()
.map(DimensionType::getId)
.map(t -> Tuples.of(t, provider)))
.collectMap(Tuple2::getT1, Tuple2::getT2)
.flatMapMany(typeProviderMapping -> Flux
.fromIterable(settings)//根据维度获取所有userId
.flatMap(setting -> Mono
.justOrEmpty(typeProviderMapping.get(setting.getDimensionType()))
.flatMapMany(provider -> provider.getUserIdByDimensionId(setting.getDimensionTarget()))))
.collectList()
.flatMap(lst-> ClearUserAuthorizationCacheEvent.of(lst).publish(eventPublisher))
.then();
| 858
| 226
| 1,084
|
<methods>public non-sealed void <init>() ,public ReactiveRepository<org.hswebframework.web.system.authorization.api.entity.AuthorizationSettingEntity,java.lang.String> getRepository() <variables>private ReactiveRepository<org.hswebframework.web.system.authorization.api.entity.AuthorizationSettingEntity,java.lang.String> repository
|
hs-web_hsweb-framework
|
hsweb-framework/hsweb-system/hsweb-system-authorization/hsweb-system-authorization-default/src/main/java/org/hswebframework/web/system/authorization/defaults/service/DefaultDimensionService.java
|
DefaultDimensionService
|
getDimensionsById
|
class DefaultDimensionService
extends GenericReactiveTreeSupportCrudService<DimensionEntity, String>
implements
DimensionProvider, DimensionUserBindProvider {
@Autowired
private ReactiveRepository<DimensionUserEntity, String> dimensionUserRepository;
@Autowired
private ReactiveRepository<DimensionTypeEntity, String> dimensionTypeRepository;
@Autowired
private ApplicationEventPublisher eventPublisher;
@Override
public IDGenerator<String> getIDGenerator() {
return IDGenerator.MD5;
}
@Override
public void setChildren(DimensionEntity entity, List<DimensionEntity> children) {
entity.setChildren(children);
}
@Override
public Flux<DimensionTypeEntity> getAllType() {
return dimensionTypeRepository
.createQuery()
.fetch();
}
@Override
public Mono<DynamicDimension> getDimensionById(DimensionType type, String id) {
return createQuery()
.where(DimensionEntity::getId, id)
.fetch()
.singleOrEmpty()
.map(entity -> DynamicDimension.of(entity, type));
}
@Override
public Flux<? extends Dimension> getDimensionsById(DimensionType type, Collection<String> idList) {<FILL_FUNCTION_BODY>}
@Override
public Flux<DynamicDimension> getDimensionByUserId(String userId) {
return getAllType()
.collect(Collectors.toMap(DimensionType::getId, Function.identity()))
.flatMapMany(typeGrouping -> dimensionUserRepository
.createQuery()
.where(DimensionUserEntity::getUserId, userId)
.fetch()
.collectList()
.filter(CollectionUtils::isNotEmpty)
.flatMapMany(list -> {
//查询所有的维度
return this
.queryIncludeChildren(list.stream()
.map(DimensionUserEntity::getDimensionId)
.collect(Collectors.toSet()))
.filter(dimension -> typeGrouping.containsKey(dimension.getTypeId()))
.map(dimension ->
DynamicDimension.of(dimension, typeGrouping.get(dimension.getTypeId()))
);
})
);
}
@Override
public Flux<DimensionUserBind> getDimensionBindInfo(Collection<String> userIdList) {
return dimensionUserRepository
.createQuery()
.in(DimensionUserEntity::getUserId, userIdList)
.fetch()
.map(entity -> DimensionUserBind.of(entity.getUserId(), entity.getDimensionTypeId(), entity.getDimensionId()));
}
@Override
@SuppressWarnings("all")
public Flux<String> getUserIdByDimensionId(String dimensionId) {
return dimensionUserRepository
.createQuery()
.select(DimensionUserEntity::getUserId)
.where(DimensionUserEntity::getDimensionId, dimensionId)
.fetch()
.map(DimensionUserEntity::getUserId);
}
@EventListener
public void handleDimensionChanged(EntitySavedEvent<DimensionEntity> event) {
event.async(
ClearUserAuthorizationCacheEvent.all().publish(eventPublisher)
);
}
@EventListener
public void handleDimensionChanged(EntityModifyEvent<DimensionEntity> event) {
event.async(
ClearUserAuthorizationCacheEvent.all().publish(eventPublisher)
);
}
@EventListener
public void dispatchDimensionDeleteEvent(EntityDeletedEvent<DimensionEntity> event) {
event.async(
Flux.fromIterable(event.getEntity())
.flatMap(e -> new DimensionDeletedEvent(e.getTypeId(), e.getId()).publish(eventPublisher))
);
}
}
|
return this.createQuery()
.where(DimensionEntity::getTypeId, type.getId())
.in(DimensionEntity::getId, idList)
.fetch()
.map(entity -> DynamicDimension.of(entity, type));
| 1,005
| 66
| 1,071
|
<methods>public non-sealed void <init>() ,public ReactiveRepository<org.hswebframework.web.system.authorization.api.entity.DimensionEntity,java.lang.String> getRepository() <variables>private ReactiveRepository<org.hswebframework.web.system.authorization.api.entity.DimensionEntity,java.lang.String> repository
|
hs-web_hsweb-framework
|
hsweb-framework/hsweb-system/hsweb-system-authorization/hsweb-system-authorization-default/src/main/java/org/hswebframework/web/system/authorization/defaults/service/DefaultDimensionUserService.java
|
DefaultDimensionUserService
|
publishEvent
|
class DefaultDimensionUserService extends GenericReactiveCrudService<DimensionUserEntity, String> {
@Autowired
private ApplicationEventPublisher eventPublisher;
//处理用户被删除时,同步删除维度绑定信息
@EventListener
public void handleUserDeleteEntity(UserDeletedEvent event) {
event.async(this.createDelete()
.where(DimensionUserEntity::getUserId, event.getUser().getId())
.execute()
.doOnSuccess(i -> log.debug("user deleted,clear user dimension!"))
);
}
//转发保存维度信息到DimensionBindEvent事件,并清空权限缓存
@EventListener
public void dispatchDimensionBind(EntitySavedEvent<DimensionUserEntity> event) {
event.async(
this.publishEvent(Flux.fromIterable(event.getEntity()), DimensionBindEvent::new)
);
}
//新增绑定时转发DimensionBindEvent并清空用户权限信息
@EventListener
public void dispatchDimensionBind(EntityCreatedEvent<DimensionUserEntity> event) {
event.async(
this.publishEvent(Flux.fromIterable(event.getEntity()), DimensionBindEvent::new)
);
}
//删除绑定时转发DimensionUnbindEvent并清空用户权限信息
@EventListener
public void dispatchDimensionUnbind(EntityDeletedEvent<DimensionUserEntity> event) {
event.async(
this.publishEvent(Flux.fromIterable(event.getEntity()), DimensionUnbindEvent::new)
);
}
//修改绑定信息时清空权限
@EventListener
public void handleModifyEvent(EntityModifyEvent<DimensionUserEntity> event) {
event.async(
this.clearUserCache(event.getAfter())
);
}
//维度被删除时同时删除绑定信息
@EventListener
public void handleDimensionDeletedEntity(EntityDeletedEvent<DimensionEntity> event) {
event.async(
Flux.fromIterable(event.getEntity())
.collect(groupingBy(DimensionEntity::getTypeId,
mapping(DimensionEntity::getId, toSet())))
.flatMapIterable(Map::entrySet)
.flatMap(entry -> this
.createDelete()
.where(DimensionUserEntity::getDimensionTypeId, entry.getKey())
.in(DimensionUserEntity::getDimensionId, entry.getValue())
.execute())
);
}
private Flux<DimensionUserEntity> publishEvent(Publisher<DimensionUserEntity> stream,
Function3<String, String, List<String>, AsyncEvent> event) {<FILL_FUNCTION_BODY>}
private Mono<Void> clearUserCache(List<DimensionUserEntity> entities) {
return Flux.fromIterable(entities)
.map(DimensionUserEntity::getUserId)
.distinct()
.collectList()
.flatMap(list -> ClearUserAuthorizationCacheEvent.of(list).publish(eventPublisher));
}
}
|
Flux<DimensionUserEntity> cache = Flux.from(stream).doOnNext(DimensionUserEntity::generateId).cache();
Set<Mono<Void>> jobs = ConcurrentHashMap.newKeySet();
return cache
.groupBy(DimensionUserEntity::getDimensionTypeId)
.flatMap(typeGroup -> {
String type = typeGroup.key();
return typeGroup
.groupBy(DimensionUserEntity::getDimensionId)
.flatMap(dimensionIdGroup -> {
String dimensionId = dimensionIdGroup.key();
return dimensionIdGroup
.map(DimensionUserEntity::getUserId)
.collectList()
.doOnNext(userIdList -> jobs.add(event.apply(type, dimensionId, userIdList).publish(eventPublisher)))
.flatMapIterable(Function.identity());
});
})
.<Collection<String>>collect(HashSet::new, Collection::add)
.flatMap(userList -> ClearUserAuthorizationCacheEvent.of(userList).publish(eventPublisher))
.then(Mono.defer(() -> Flux.concat(jobs).then()))
.thenMany(cache);
| 812
| 306
| 1,118
|
<methods>public non-sealed void <init>() ,public ReactiveRepository<org.hswebframework.web.system.authorization.api.entity.DimensionUserEntity,java.lang.String> getRepository() <variables>private ReactiveRepository<org.hswebframework.web.system.authorization.api.entity.DimensionUserEntity,java.lang.String> repository
|
hs-web_hsweb-framework
|
hsweb-framework/hsweb-system/hsweb-system-authorization/hsweb-system-authorization-default/src/main/java/org/hswebframework/web/system/authorization/defaults/service/DefaultPermissionService.java
|
DefaultPermissionService
|
createDelete
|
class DefaultPermissionService extends GenericReactiveCrudService<PermissionEntity, String> {
@Autowired
private ApplicationEventPublisher eventPublisher;
@Override
public Mono<SaveResult> save(Publisher<PermissionEntity> entityPublisher) {
return super.save(entityPublisher)
.flatMap(e -> ClearUserAuthorizationCacheEvent.all().publish(eventPublisher).thenReturn(e));
}
@Override
public Mono<Integer> updateById(String id, Mono<PermissionEntity> entityPublisher) {
return super.updateById(id, entityPublisher)
.flatMap(e -> ClearUserAuthorizationCacheEvent.all().publish(eventPublisher).thenReturn(e));
}
@Override
public Mono<Integer> deleteById(Publisher<String> idPublisher) {
return super.deleteById(idPublisher)
.flatMap(e -> ClearUserAuthorizationCacheEvent.all().publish(eventPublisher).thenReturn(e));
}
@Override
public ReactiveDelete createDelete() {<FILL_FUNCTION_BODY>}
@Override
public ReactiveUpdate<PermissionEntity> createUpdate() {
return super.createUpdate()
.onExecute((ignore, i) -> i
.flatMap(e -> ClearUserAuthorizationCacheEvent
.all()
.publish(eventPublisher)
.thenReturn(e)));
}
}
|
return super.createDelete()
.onExecute((ignore, i) -> i
.flatMap(e -> ClearUserAuthorizationCacheEvent
.all()
.publish(eventPublisher)
.thenReturn(e)));
| 369
| 62
| 431
|
<methods>public non-sealed void <init>() ,public ReactiveRepository<org.hswebframework.web.system.authorization.api.entity.PermissionEntity,java.lang.String> getRepository() <variables>private ReactiveRepository<org.hswebframework.web.system.authorization.api.entity.PermissionEntity,java.lang.String> repository
|
hs-web_hsweb-framework
|
hsweb-framework/hsweb-system/hsweb-system-authorization/hsweb-system-authorization-default/src/main/java/org/hswebframework/web/system/authorization/defaults/service/DefaultReactiveAuthenticationInitializeService.java
|
DefaultReactiveAuthenticationInitializeService
|
handlePermission
|
class DefaultReactiveAuthenticationInitializeService
implements ReactiveAuthenticationInitializeService {
@Autowired
private ReactiveUserService userService;
@Autowired
private ReactiveRepository<AuthorizationSettingEntity, String> settingRepository;
@Autowired
private ReactiveRepository<PermissionEntity, String> permissionRepository;
@Autowired(required = false)
private DataAccessConfigBuilderFactory builderFactory = new SimpleDataAccessConfigBuilderFactory();
@Autowired(required = false)
private List<DimensionProvider> dimensionProviders = new ArrayList<>();
@Autowired
private ApplicationEventPublisher eventPublisher;
@Override
public Mono<Authentication> initUserAuthorization(String userId) {
return doInit(userService.findById(userId));
}
public Mono<Authentication> doInit(Mono<UserEntity> userEntityMono) {
return userEntityMono.flatMap(user -> {
SimpleAuthentication authentication = new SimpleAuthentication();
authentication.setUser(SimpleUser
.builder()
.id(user.getId())
.name(user.getName())
.username(user.getUsername())
.userType(user.getType())
.build());
return initPermission(authentication)
.defaultIfEmpty(authentication)
.onErrorResume(err -> {
log.warn(err.getMessage(), err);
return Mono.just(authentication);
})
.flatMap(auth -> {
AuthorizationInitializeEvent event = new AuthorizationInitializeEvent(auth);
return event
.publish(eventPublisher)
.then(Mono.fromSupplier(event::getAuthentication));
});
});
}
protected Flux<AuthorizationSettingEntity> getSettings(List<Dimension> dimensions) {
return Flux.fromIterable(dimensions)
.filter(dimension -> dimension.getType() != null)
.groupBy(d -> d.getType().getId(), (Function<Dimension, Object>) Dimension::getId)
.flatMap(group ->
group.collectList()
.flatMapMany(list -> settingRepository
.createQuery()
.where(AuthorizationSettingEntity::getState, 1)
.and(AuthorizationSettingEntity::getDimensionType, group.key())
.in(AuthorizationSettingEntity::getDimensionTarget, list)
.fetch()));
}
protected Mono<Authentication> initPermission(SimpleAuthentication authentication) {
return Flux.fromIterable(dimensionProviders)
.flatMap(provider -> provider.getDimensionByUserId(authentication.getUser().getId()))
.cast(Dimension.class)
.doOnNext(authentication::addDimension)
.collectList()
.then(Mono.defer(() -> Mono
.zip(getAllPermission(),
getSettings(authentication.getDimensions()).collect(Collectors.groupingBy(AuthorizationSettingEntity::getPermission)),
(_p, _s) -> handlePermission(authentication, _p, _s)
)));
}
protected SimpleAuthentication handlePermission(SimpleAuthentication authentication,
Map<String, PermissionEntity> permissions,
Map<String, List<AuthorizationSettingEntity>> settings) {<FILL_FUNCTION_BODY>}
protected Mono<Map<String, PermissionEntity>> getAllPermission() {
return permissionRepository
.createQuery()
.where(PermissionEntity::getStatus, 1)
.fetch()
.collect(Collectors.toMap(PermissionEntity::getId, Function.identity()))
.switchIfEmpty(Mono.just(Collections.emptyMap()));
}
}
|
Map<String, PermissionEntity> permissionMap = new HashMap<>();
Map<String, SimplePermission> allowed = new HashMap<>();
try {
for (PermissionEntity permissionEntity : permissions.values()) {
permissionMap.put(permissionEntity.getId(), permissionEntity);
List<AuthorizationSettingEntity> permissionSettings = settings.get(permissionEntity.getId());
if (CollectionUtils.isEmpty(permissionSettings)) {
continue;
}
permissionSettings.sort(Comparator.comparingInt(e -> e.getPriority() == null ? 0 : e.getPriority()));
SimplePermission permission = new SimplePermission();
permission.setId(permissionEntity.getId());
permission.setName(permissionEntity.getName());
permission.setOptions(permissionEntity.getProperties());
Set<DataAccessConfig> configs = new HashSet<>();
for (AuthorizationSettingEntity permissionSetting : permissionSettings) {
boolean merge = Boolean.TRUE.equals(permissionSetting.getMerge());
if (!merge) {
permission.getActions().clear();
}
if (permissionSetting.getDataAccesses() != null) {
permissionSetting.getDataAccesses()
.stream()
.map(conf -> {
DataAccessConfig config = builderFactory
.create()
.fromMap(conf.toMap())
.build();
if (config == null) {
log.warn("unsupported data access:{}", conf.toMap());
}
return config;
})
.filter(Objects::nonNull)
.forEach(configs::add);
}
if (CollectionUtils.isNotEmpty(permissionSetting.getActions())) {
permission.getActions().addAll(permissionSetting.getActions());
}
}
allowed.put(permissionEntity.getId(), permission);
permission.setDataAccesses(configs);
}
//处理关联权限
for (PermissionEntity permissionEntity : permissions.values()) {
SimplePermission allow = allowed.get(permissionEntity.getId());
if (allow == null || CollectionUtils.isEmpty(permissionEntity.getParents())) {
continue;
}
for (ParentPermission parent : permissionEntity.getParents()) {
if (StringUtils.isEmpty(parent.getPermission())) {
continue;
}
Set<String> pre = parent.getPreActions();
//满足前置条件
if (CollectionUtils.isEmpty(pre) || allow.getActions().containsAll(pre)) {
PermissionEntity mergePermission = permissionMap.get(parent.getPermission());
if (mergePermission == null) {
continue;
}
SimplePermission merge = allowed.get(parent.getPermission());
if (merge == null) {
merge = new SimplePermission();
merge.setName(mergePermission.getName());
merge.setId(mergePermission.getId());
allowed.put(merge.getId(), merge);
}
if (CollectionUtils.isNotEmpty(parent.getActions())) {
merge.getActions().addAll(parent.getActions());
}
}
}
}
authentication.setPermissions(new ArrayList<>(allowed.values()));
} catch (Exception e) {
log.error(e.getLocalizedMessage(), e);
}
return authentication;
| 945
| 815
| 1,760
|
<no_super_class>
|
hs-web_hsweb-framework
|
hsweb-framework/hsweb-system/hsweb-system-authorization/hsweb-system-authorization-default/src/main/java/org/hswebframework/web/system/authorization/defaults/service/DefaultReactiveAuthenticationManager.java
|
DefaultReactiveAuthenticationManager
|
authenticate
|
class DefaultReactiveAuthenticationManager implements ReactiveAuthenticationManagerProvider {
@Autowired
private ReactiveUserService reactiveUserService;
@Autowired
private ReactiveAuthenticationInitializeService initializeService;
@Autowired(required = false)
private ReactiveCacheManager cacheManager;
@EventListener
public void handleClearAuthCache(ClearUserAuthorizationCacheEvent event) {
if (cacheManager != null) {
Mono<Void> operator;
if (event.isAll()) {
operator = cacheManager
.getCache("user-auth")
.clear()
.doOnSuccess(nil -> log.info("clear all user authentication cache success"))
.doOnError(err -> log.error(err.getMessage(), err));
} else {
operator = cacheManager
.getCache("user-auth")
.evictAll(event.getUserId())
.doOnError(err -> log.error(err.getMessage(), err))
.doOnSuccess(__ -> log.info("clear user {} authentication cache success", event.getUserId()));
}
if (event.isAsync()) {
event.first(operator);
} else {
log.warn("please use async for ClearUserAuthorizationCacheEvent");
operator.subscribe();
}
}
}
@Override
public Mono<Authentication> authenticate(Mono<AuthenticationRequest> request) {<FILL_FUNCTION_BODY>}
@Override
public Mono<Authentication> getByUserId(String userId) {
if (userId == null) {
return Mono.empty();
}
if (cacheManager == null) {
return initializeService.initUserAuthorization(userId);
}
return cacheManager
.<Authentication>getCache("user-auth")
.getMono(userId, () -> initializeService.initUserAuthorization(userId));
}
}
|
return request
.filter(PlainTextUsernamePasswordAuthenticationRequest.class::isInstance)
.switchIfEmpty(Mono.error(() -> new UnsupportedOperationException("不支持的请求类型")))
.map(PlainTextUsernamePasswordAuthenticationRequest.class::cast)
.flatMap(pwdRequest -> reactiveUserService.findByUsernameAndPassword(pwdRequest.getUsername(), pwdRequest.getPassword()))
.filter(user -> Byte.valueOf((byte) 1).equals(user.getStatus()))
.map(UserEntity::getId)
.flatMap(this::getByUserId);
| 484
| 157
| 641
|
<no_super_class>
|
hs-web_hsweb-framework
|
hsweb-framework/hsweb-system/hsweb-system-authorization/hsweb-system-authorization-default/src/main/java/org/hswebframework/web/system/authorization/defaults/service/DynamicDimension.java
|
DynamicDimension
|
of
|
class DynamicDimension implements Dimension {
private String id;
private String name;
private DimensionType type;
private Map<String, Object> options;
public static DynamicDimension of(DimensionEntity entity,
DimensionType type) {<FILL_FUNCTION_BODY>}
}
|
DynamicDimension dynamicDimension = new DynamicDimension();
dynamicDimension.setId(entity.getId());
dynamicDimension.setName(entity.getName());
dynamicDimension.setType(type);
Map<String, Object> options = new HashMap<>();
options.put("parentId", entity.getParentId());
options.put("path", entity.getPath());
dynamicDimension.setOptions(options);
return dynamicDimension;
| 81
| 118
| 199
|
<no_super_class>
|
hs-web_hsweb-framework
|
hsweb-framework/hsweb-system/hsweb-system-authorization/hsweb-system-authorization-default/src/main/java/org/hswebframework/web/system/authorization/defaults/service/PermissionSynchronization.java
|
PermissionSynchronization
|
convert
|
class PermissionSynchronization implements CommandLineRunner {
private final ReactiveRepository<PermissionEntity, String> permissionRepository;
private final AuthorizeDefinitionCustomizer customizer;
private final MergedAuthorizeDefinition definition = new MergedAuthorizeDefinition();
private final Map<String, List<OptionalField>> entityFieldsMapping = new HashMap<>();
public PermissionSynchronization(ReactiveRepository<PermissionEntity, String> permissionRepository,
AuthorizeDefinitionCustomizer customizer) {
this.permissionRepository = permissionRepository;
this.customizer = customizer;
}
@EventListener
public void handleResourceParseEvent(AuthorizeDefinitionInitializedEvent event) {
definition.merge(event.getAllDefinition());
for (AuthorizeDefinition authorizeDefinition : event.getAllDefinition()) {
if (authorizeDefinition.getResources().getResources().isEmpty()) {
continue;
}
String id = authorizeDefinition.getResources().getResources().iterator().next().getId();
if (entityFieldsMapping.containsKey(id)) {
return;
}
if (authorizeDefinition instanceof AopAuthorizeDefinition) {
Class<?> target = ((AopAuthorizeDefinition) authorizeDefinition).getTargetClass();
if (ReactiveQueryController.class.isAssignableFrom(target)
|| ReactiveServiceQueryController.class.isAssignableFrom(target)) {
Class<?> entity = ClassUtils.getGenericType(target);
if (Entity.class.isAssignableFrom(entity)) {
Set<OptionalField> fields = new HashSet<>();
ReflectionUtils.doWithFields(entity, field -> {
if (null != field.getAnnotation(Column.class) && !"id".equals(field.getName())) {
OptionalField optionalField = new OptionalField();
optionalField.setName(field.getName());
Optional.ofNullable(field.getAnnotation(Schema.class))
.map(Schema::description)
.ifPresent(optionalField::setDescribe);
fields.add(optionalField);
}
});
entityFieldsMapping.put(id, new ArrayList<>(fields));
}
}
}
}
}
public static PermissionEntity convert(Map<String, PermissionEntity> old, ResourceDefinition definition,Map<String, List<OptionalField>> entityFieldsMapping) {<FILL_FUNCTION_BODY>}
@Override
public void run(String... args) throws Exception {
if (definition.getResources().isEmpty()) {
return;
}
customizer.custom(definition);
permissionRepository
.createQuery()
.fetch()
.collect(Collectors.toMap(PermissionEntity::getId, Function.identity()))
.flatMap(group -> Flux.fromIterable(definition.getResources())
.map(d -> PermissionSynchronization.convert(group, d,entityFieldsMapping))
.as(permissionRepository::save))
.doOnError(err -> log.warn("sync permission error", err))
.subscribe(l -> {
log.info("sync permission success:{}", l);
});
}
}
|
PermissionEntity entity = old.getOrDefault(definition.getId(), PermissionEntity.builder()
.name(definition.getName())
.describe(definition.getDescription())
.status((byte) 1)
.build());
entity.setId(definition.getId());
if (CollectionUtils.isEmpty(entity.getOptionalFields())) {
entity.setOptionalFields(entityFieldsMapping.get(entity.getId()));
}
Map<String, ActionEntity> oldAction = new HashMap<>();
if (entity.getActions() != null) {
entity.getActions().forEach(a -> oldAction.put(a.getAction(), a));
}
for (ResourceActionDefinition definitionAction : definition.getActions()) {
ActionEntity action = oldAction.getOrDefault(definitionAction.getId(), ActionEntity
.builder()
.action(definitionAction.getId())
.name(definitionAction.getName())
.describe(definitionAction.getName())
.build());
Map<String, Object> properties = Optional.ofNullable(action.getProperties()).orElse(new HashMap<>());
@SuppressWarnings("all")
Set<Object> types = (Set)Optional.of(properties.computeIfAbsent("supportDataAccessTypes", t -> new HashSet<>()))
.filter(Collection.class::isInstance)
.map(Collection.class::cast)
.map(HashSet::new)
.orElseGet(HashSet::new);
types.addAll(definitionAction.getDataAccess().getDataAccessTypes().stream().map(DataAccessTypeDefinition::getId).collect(Collectors.toSet()));
action.setProperties(properties);
oldAction.put(action.getAction(), action);
}
entity.setActions(new ArrayList<>(oldAction.values()));
return entity;
| 777
| 457
| 1,234
|
<no_super_class>
|
hs-web_hsweb-framework
|
hsweb-framework/hsweb-system/hsweb-system-authorization/hsweb-system-authorization-default/src/main/java/org/hswebframework/web/system/authorization/defaults/service/RemoveUserTokenWhenUserDisabled.java
|
RemoveUserTokenWhenUserDisabled
|
handleStateChangeEvent
|
class RemoveUserTokenWhenUserDisabled {
private final UserTokenManager userTokenManager;
@EventListener
public void handleStateChangeEvent(UserModifiedEvent event) {<FILL_FUNCTION_BODY>}
@EventListener
public void handleStateChangeEvent(UserStateChangedEvent event) {
if (event.getState() != 1) {
event.async(
Flux.fromIterable(event.getUserIdList())
.flatMap(userTokenManager::signOutByUserId)
);
}
}
}
|
if (event.getUserEntity().getStatus() != null && event.getUserEntity().getStatus() != 1) {
event.async(
Mono.just(event.getUserEntity().getId())
.flatMap(userTokenManager::signOutByUserId)
);
}
| 140
| 77
| 217
|
<no_super_class>
|
hs-web_hsweb-framework
|
hsweb-framework/hsweb-system/hsweb-system-authorization/hsweb-system-authorization-default/src/main/java/org/hswebframework/web/system/authorization/defaults/service/terms/DimensionTerm.java
|
DimensionTerm
|
createFragments
|
class DimensionTerm extends AbstractTermFragmentBuilder {
public DimensionTerm() {
super("dimension", "和维度关联的数据");
}
public static <T extends Conditional<?>> T inject(T query,
String column,
String dimensionType,
List<String> userId) {
return inject(query, column, dimensionType, false, false, userId);
}
public static <T extends Conditional<?>> T inject(T query,
String column,
String dimensionType,
boolean not,
boolean any,
List<String> userId) {
return (T) query.accept(column, createTermType(dimensionType, not, any), userId);
}
public static String createTermType(String dimensionType, boolean not, boolean any) {
StringJoiner joiner = new StringJoiner("$");
joiner.add("dimension");
joiner.add(dimensionType);
if (not) {
joiner.add("not");
}
if (any) {
joiner.add("any");
}
return joiner.toString();
}
@Override
public SqlFragments createFragments(String columnFullName, RDBColumnMetadata column, Term term) {<FILL_FUNCTION_BODY>}
}
|
List<Object> values = convertList(column, term);
if (values.isEmpty()) {
return EmptySqlFragments.INSTANCE;
}
List<String> options = term.getOptions();
if (CollectionUtils.isEmpty(options)) {
throw new IllegalArgumentException("查询条件错误,正确格式:" + column.getAlias() + "$dimension${type}$[not]");
}
PrepareSqlFragments fragments = PrepareSqlFragments.of();
if (options.contains("not")) {
fragments.addSql("not ");
}
fragments
.addSql("exists(select 1 from", getTableName("s_dimension_user", column), "d where d.dimension_type_id = ? and d.dimension_id =", columnFullName)
.addParameter(options.get(0));
if (!options.contains("any")) {
fragments.addSql("and d.user_id in(", values.stream().map(r -> "?").collect(Collectors.joining(",")), ")")
.addParameter(values);
}
fragments.addSql(")");
return fragments;
| 340
| 298
| 638
|
<no_super_class>
|
hs-web_hsweb-framework
|
hsweb-framework/hsweb-system/hsweb-system-authorization/hsweb-system-authorization-default/src/main/java/org/hswebframework/web/system/authorization/defaults/service/terms/UserDimensionTerm.java
|
UserDimensionTerm
|
createFragments
|
class UserDimensionTerm extends AbstractTermFragmentBuilder {
public UserDimensionTerm() {
super("in-dimension", "在维度中的用户数据");
}
@Override
public SqlFragments createFragments(String columnFullName, RDBColumnMetadata column, Term term) {<FILL_FUNCTION_BODY>}
}
|
List<Object> values = convertList(column, term);
if (values.isEmpty()) {
return EmptySqlFragments.INSTANCE;
}
PrepareSqlFragments fragments = PrepareSqlFragments.of();
List<String> options = term.getOptions();
if (options.contains("not")) {
fragments.addSql("not");
}
fragments.addSql("exists(select 1 from ",getTableName("s_dimension_user",column)," d where d.user_id =", columnFullName);
if (!options.isEmpty()) {
String typeId = options.get(0);
if (!"not".equals(typeId) && !"any".equals(typeId)) {
fragments.addSql("and d.dimension_type_id = ?").addParameter(typeId);
}
}
if (!options.contains("any")) {
fragments.addSql("and d.dimension_id in(",
values.stream().map(r -> "?").collect(Collectors.joining(",")), ")")
.addParameter(values);
}
fragments.addSql(")");
return fragments;
| 87
| 302
| 389
|
<no_super_class>
|
hs-web_hsweb-framework
|
hsweb-framework/hsweb-system/hsweb-system-authorization/hsweb-system-authorization-default/src/main/java/org/hswebframework/web/system/authorization/defaults/webflux/WebFluxAuthorizationSettingController.java
|
WebFluxAuthorizationSettingController
|
applyAuthentication
|
class WebFluxAuthorizationSettingController implements ReactiveServiceCrudController<AuthorizationSettingEntity, String> {
@Autowired
private DefaultAuthorizationSettingService settingService;
@Autowired
private PermissionProperties permissionProperties;
@Override
public ReactiveCrudService<AuthorizationSettingEntity, String> getService() {
return settingService;
}
@Override
public AuthorizationSettingEntity applyAuthentication(AuthorizationSettingEntity entity,
Authentication authentication) {<FILL_FUNCTION_BODY>}
}
|
AuthorizationSettingEntity setting = ReactiveServiceCrudController.super.applyAuthentication(entity, authentication);
return permissionProperties
.getFilter()
.handleSetting(authentication, setting);
| 136
| 50
| 186
|
<no_super_class>
|
hs-web_hsweb-framework
|
hsweb-framework/hsweb-system/hsweb-system-authorization/hsweb-system-authorization-default/src/main/java/org/hswebframework/web/system/authorization/defaults/webflux/WebFluxDimensionUserController.java
|
WebFluxDimensionUserController
|
deleteUserDimension
|
class WebFluxDimensionUserController implements ReactiveServiceCrudController<DimensionUserEntity, String> {
@Autowired
private DefaultDimensionUserService dimensionUserService;
@Override
public ReactiveCrudService<DimensionUserEntity, String> getService() {
return dimensionUserService;
}
@DeleteAction
@DeleteMapping("/user/{userId}/dimension/{dimensionId}")
@Operation(summary = "解除用户关联的指定维度")
public Mono<Integer> deleteByUserAndDimensionId(@PathVariable
@Parameter(description = "用户ID") String userId,
@PathVariable
@Parameter(description = "维度ID") String dimensionId) {
return dimensionUserService
.createDelete()
.where(DimensionUserEntity::getUserId, userId)
.and(DimensionUserEntity::getDimensionId, dimensionId)
.execute();
}
@DeleteAction
@DeleteMapping("/user/{userId}")
@Operation(summary = "解除用户关联的全部维度")
public Mono<Integer> deleteByUserId(@PathVariable
@Parameter(description = "用户ID") String userId) {
return dimensionUserService
.createDelete()
.where(DimensionUserEntity::getUserId, userId)
.execute();
}
@DeleteAction
@DeleteMapping("/dimension/{dimensionId}")
@Operation(summary = "解除全部用户关联的指定维度")
public Mono<Integer> deleteByDimension(@PathVariable
@Parameter(description = "维度ID") String dimensionId) {
return dimensionUserService
.createDelete()
.where(DimensionUserEntity::getDimensionId, dimensionId)
.execute();
}
@DeleteAction
@PostMapping("/user/{dimensionType}/{dimensionId}/_unbind")
@Operation(summary = "解除用户关联的指定维度")
public Mono<Integer> deleteUserDimension(@PathVariable
@Parameter(description = "维度类型,比如: role") String dimensionType,
@PathVariable
@Parameter(description = "维度ID,比如: 角色ID") String dimensionId,
@Parameter(description = "用户ID") @RequestBody Mono<List<String>> userId) {<FILL_FUNCTION_BODY>}
}
|
return userId
.flatMap(userIdList -> dimensionUserService
.createDelete()
.where(DimensionUserEntity::getDimensionId, dimensionId)
.and(DimensionUserEntity::getDimensionTypeId, dimensionType)
.in(DimensionUserEntity::getUserId, userIdList)
.execute());
| 595
| 88
| 683
|
<no_super_class>
|
hs-web_hsweb-framework
|
hsweb-framework/hsweb-system/hsweb-system-authorization/hsweb-system-authorization-default/src/main/java/org/hswebframework/web/system/authorization/defaults/webflux/WebFluxPermissionController.java
|
WebFluxPermissionController
|
queryForGrant
|
class WebFluxPermissionController implements ReactiveServiceCrudController<PermissionEntity, String> {
@Autowired
private DefaultPermissionService permissionService;
@Autowired
private PermissionProperties permissionProperties;
@Override
public ReactiveCrudService<PermissionEntity, String> getService() {
return permissionService;
}
@PutMapping("/status/{status}")
@SaveAction
@Operation(summary = "批量修改权限状态")
public Mono<Integer> changePermissionState(@PathVariable @Parameter(description = "状态值:0禁用,1启用.") Byte status,
@RequestBody List<String> idList) {
return Mono.just(idList)
.filter(CollectionUtils::isNotEmpty)
.flatMap(list -> permissionService
.createUpdate()
.set(PermissionEntity::getStatus, status)
.where()
.in(PermissionEntity::getId, list)
.execute())
.defaultIfEmpty(0);
}
@GetMapping("/_query/for-grant")
@ResourceAction(id = "grant", name = "赋权")
@QueryNoPagingOperation(summary = "获取用于赋权的权限列表")
public Flux<PermissionEntity> queryForGrant(QueryParamEntity query) {<FILL_FUNCTION_BODY>}
}
|
return Authentication
.currentReactive()
.flatMapMany(auth -> permissionProperties
.getFilter()
.doFilter(permissionService.query(query.noPaging()), auth));
| 344
| 52
| 396
|
<no_super_class>
|
hs-web_hsweb-framework
|
hsweb-framework/hsweb-system/hsweb-system-authorization/hsweb-system-authorization-default/src/main/java/org/hswebframework/web/system/authorization/defaults/webflux/WebFluxUserController.java
|
WebFluxUserController
|
updateLoginUserInfo
|
class WebFluxUserController implements ReactiveServiceQueryController<UserEntity, String> {
@Autowired
private DefaultReactiveUserService reactiveUserService;
@PatchMapping
@SaveAction
@Operation(summary = "保存用户信息")
public Mono<Boolean> saveUser(@RequestBody Mono<UserEntity> user) {
return Authentication
.currentReactive()
.zipWith(user, ((u, e) -> {
e.setCreateTimeNow();
e.setCreatorId(u.getUser().getId());
return e;
}))
.switchIfEmpty(user)
.as(reactiveUserService::saveUser);
}
@PutMapping("/me")
@Operation(summary = "修改当前用户信息")
@ResourceAction(id = "update-self-info",name = "修改当前用户信息")
public Mono<Boolean> updateLoginUserInfo(@RequestBody UserEntity request) {<FILL_FUNCTION_BODY>}
@PutMapping("/{id:.+}/{state}")
@SaveAction
@Operation(summary = "修改用户状态")
public Mono<Integer> changeState(@PathVariable @Parameter(description = "用户ID") String id,
@PathVariable @Parameter(description = "状态,0禁用,1启用") Byte state) {
return reactiveUserService.changeState(Mono.just(id), state);
}
@DeleteMapping("/{id:.+}")
@DeleteAction
@Operation(summary = "删除用户")
public Mono<Boolean> deleteUser(@PathVariable String id) {
return reactiveUserService.deleteUser(id);
}
@PutMapping("/passwd")
@ResourceAction(id = "update-self-pwd",name = "修改当前用户密码")
@Operation(summary = "修改当前用户密码")
public Mono<Boolean> changePassword(@RequestBody ChangePasswordRequest request) {
return Authentication
.currentReactive()
.switchIfEmpty(Mono.error(UnAuthorizedException::new))
.map(Authentication::getUser)
.map(User::getId)
.flatMap(userId -> reactiveUserService.changePassword(userId, request.getOldPassword(), request.getNewPassword()));
}
@Override
public DefaultReactiveUserService getService() {
return reactiveUserService;
}
@Getter
@Setter
public static class ChangePasswordRequest {
private String oldPassword;
private String newPassword;
}
}
|
return Authentication
.currentReactive()
.switchIfEmpty(Mono.error(UnAuthorizedException::new))
.map(Authentication::getUser)
.map(User::getId)
.flatMap(userId -> reactiveUserService.updateById(userId, Mono.just(request)).map(integer -> integer > 0));
| 649
| 90
| 739
|
<no_super_class>
|
hs-web_hsweb-framework
|
hsweb-framework/hsweb-system/hsweb-system-authorization/hsweb-system-authorization-oauth2/src/main/java/org/hswebframework/web/oauth2/entity/OAuth2ClientEntity.java
|
OAuth2ClientEntity
|
toOAuth2Client
|
class OAuth2ClientEntity extends GenericEntity<String> {
@Column(length = 1024)
@Schema(description = "Logo地址")
private String logoUrl;
@Column(length = 64, nullable = false)
@Schema(description = "客户端名称")
@NotBlank
private String name;
@Column(length = 128, nullable = false)
@Schema(description = "密钥")
@NotBlank
@ToString.Ignore
private String secret;
@Column(length = 64, nullable = false)
@Schema(description = "绑定用户ID")
@NotBlank
private String userId;
@Column(length = 1024, nullable = false)
@Schema(description = "回调地址")
@NotBlank
private String callbackUri;
@Column(length = 1024, nullable = false)
@Schema(description = "首页地址")
@NotBlank
private String homeUri;
@Column
@Schema(description = "说明")
private String description;
@Column(length = 32)
@EnumCodec
@ColumnType(javaType = String.class)
@DefaultValue("enabled")
@Schema(description = "状态")
private OAuth2ClientState state;
@Column(nullable = false)
@Schema(description = "创建时间")
@DefaultValue(generator = Generators.CURRENT_TIME)
private Long createTime;
public boolean enabled() {
return state == OAuth2ClientState.enabled;
}
public OAuth2Client toOAuth2Client() {<FILL_FUNCTION_BODY>}
}
|
OAuth2Client client = new OAuth2Client();
client.setClientSecret(secret);
client.setClientId(getId());
client.setName(getName());
client.setRedirectUrl(callbackUri);
client.setDescription(description);
client.setUserId(userId);
return client;
| 441
| 83
| 524
|
<methods>public non-sealed void <init>() ,public transient java.lang.String toString(java.lang.String[]) ,public java.lang.String toString() <variables>private java.lang.String id
|
hs-web_hsweb-framework
|
hsweb-framework/hsweb-system/hsweb-system-dictionary/src/main/java/org/hswebframework/web/dictionary/configuration/DictionaryAutoConfiguration.java
|
DictionaryServiceConfiguration
|
compositeDictDefineRepository
|
class DictionaryServiceConfiguration {
@Bean
public DefaultDictionaryItemService defaultDictionaryItemService() {
return new DefaultDictionaryItemService();
}
@Bean
public DefaultDictionaryService defaultDictionaryService() {
return new DefaultDictionaryService();
}
@Bean
public CompositeDictDefineRepository compositeDictDefineRepository(DictionaryProperties properties) {<FILL_FUNCTION_BODY>}
}
|
CompositeDictDefineRepository repository = new CompositeDictDefineRepository();
properties.doScanEnum()
.stream()
.map(CompositeDictDefineRepository::parseEnumDict)
.forEach(repository::addDefine);
return repository;
| 105
| 70
| 175
|
<no_super_class>
|
hs-web_hsweb-framework
|
hsweb-framework/hsweb-system/hsweb-system-dictionary/src/main/java/org/hswebframework/web/dictionary/configuration/DictionaryProperties.java
|
DictionaryProperties
|
doScanEnum
|
class DictionaryProperties {
private Set<String> enumPackages = new HashSet<>();
@SneakyThrows
public List<Class> doScanEnum() {<FILL_FUNCTION_BODY>}
}
|
Set<String> packages = new HashSet<>(enumPackages);
packages.add("org.hswebframework.web");
CachingMetadataReaderFactory metadataReaderFactory = new CachingMetadataReaderFactory();
ResourcePatternResolver resourcePatternResolver = new PathMatchingResourcePatternResolver();
List<Class> classes = new ArrayList<>();
for (String enumPackage : packages) {
String path = "classpath*:" + ClassUtils.convertClassNameToResourcePath(enumPackage) + "/**/*.class";
Resource[] resources = resourcePatternResolver.getResources(path);
for (Resource resource : resources) {
try {
MetadataReader reader = metadataReaderFactory.getMetadataReader(resource);
String name = reader.getClassMetadata().getClassName();
Class<?> clazz = ClassUtils.forName(name,null);
if (clazz.isEnum() && EnumDict.class.isAssignableFrom(clazz)) {
classes.add(clazz);
}
} catch (Throwable e) {
}
}
}
metadataReaderFactory.clearCache();
return classes;
| 57
| 277
| 334
|
<no_super_class>
|
hs-web_hsweb-framework
|
hsweb-framework/hsweb-system/hsweb-system-dictionary/src/main/java/org/hswebframework/web/dictionary/entity/DictionaryItemEntity.java
|
DictionaryItemEntity
|
getWriteJSONObject
|
class DictionaryItemEntity extends GenericTreeSortSupportEntity<String> implements EnumDict<String> {
//字典id
@Column(name = "dict_id", length = 64, updatable = false, nullable = false)
@Schema(description = "数据字典ID")
private String dictId;
//名称
@Column
@Schema(description = "选项名称")
private String name;
//字典值
@Column
@Schema(description = "值")
private String value;
//字典文本
@Column
@Schema(description = "文本内容")
private String text;
//字典值类型
@Column(name = "value_type")
@Schema(description = "值类型")
private String valueType;
//是否启用
@Column
@Schema(description = "状态,0禁用,1启用")
@DefaultValue("1")
private Byte status;
//说明
@Column
@Schema(description = "说明")
private String describe;
//快速搜索码
@Column(name = "search_code")
@Schema(description = "检索码")
private String searchCode;
@Column(name = "ordinal", nullable = false, updatable = false)
@Schema(description = "序列号,同一个字典中的选项不能重复,且不能修改.")
private Integer ordinal;
@Override
public int ordinal() {
return ordinal == null ? 0 : ordinal;
}
@Schema(description = "子节点")
private List<DictionaryItemEntity> children;
public void generateId() {
if (StringUtils.hasText(this.getId())) {
return;
}
this.setId(generateId(this.getDictId(), this.getOrdinal()));
}
public static String generateId(String dictId, Integer ordinal) {
return DigestUtils.md5Hex(String.join("|", dictId, ordinal.toString()));
}
@Override
public Object getWriteJSONObject() {<FILL_FUNCTION_BODY>}
}
|
JSONObject jsonObject = new JSONObject();
jsonObject.put("id", getId());
jsonObject.put("name", getName());
jsonObject.put("dictId", getDictId());
jsonObject.put("value", getValue());
jsonObject.put("text", getText());
jsonObject.put("ordinal", getOrdinal());
jsonObject.put("sortIndex", getSortIndex());
jsonObject.put("parentId", getParentId());
jsonObject.put("path", getPath());
jsonObject.put("mask", getMask());
jsonObject.put("searchCode", getSearchCode());
jsonObject.put("status", getStatus());
jsonObject.put("describe", getDescribe());
return jsonObject;
| 546
| 190
| 736
|
<methods>public non-sealed void <init>() <variables>private java.lang.Integer level,private java.lang.String parentId,private java.lang.String path,private java.lang.Long sortIndex
|
hs-web_hsweb-framework
|
hsweb-framework/hsweb-system/hsweb-system-dictionary/src/main/java/org/hswebframework/web/dictionary/service/CompositeDictDefineRepository.java
|
CompositeDictDefineRepository
|
handleClearCacheEvent
|
class CompositeDictDefineRepository extends DefaultDictDefineRepository {
@Autowired
private DefaultDictionaryService dictionaryService;
@Autowired
private ReactiveCacheManager cacheManager;
@EventListener
public void handleClearCacheEvent(ClearDictionaryCacheEvent event) {<FILL_FUNCTION_BODY>}
@Override
public Mono<DictDefine> getDefine(String id) {
return super.getDefine(id)
.switchIfEmpty(Mono.defer(() -> cacheManager
.<DictDefine>getCache("dic-define")
.getMono(id, () -> getFromDb(id))));
}
@Override
public Flux<DictDefine> getAllDefine() {
return Flux.concat(super.getAllDefine(), QueryParamEntity
.newQuery()
.noPaging()
.execute(paramEntity -> dictionaryService.findAllDetail(paramEntity,false))
.map(DictionaryEntity::toDictDefine));
}
private Mono<DictDefine> getFromDb(String id) {
return dictionaryService
.findDetailById(id)
.filter(e -> Byte.valueOf((byte) 1).equals(e.getStatus()))
.map(DictionaryEntity::toDictDefine);
}
}
|
if (StringUtils.isEmpty(event.getDictionaryId())) {
cacheManager.<DictDefine>getCache("dic-define")
.clear()
.doOnSuccess(r -> log.info("clear all dic cache success"))
.subscribe();
} else {
cacheManager.<DictDefine>getCache("dic-define")
.evict(event.getDictionaryId())
.doOnSuccess(r -> log.info("clear dict [{}] cache success", event.getDictionaryId()))
.subscribe();
}
| 344
| 139
| 483
|
<methods>public non-sealed void <init>() ,public void addDefine(org.hswebframework.web.dict.DictDefine) ,public Flux<org.hswebframework.web.dict.DictDefine> getAllDefine() ,public Mono<org.hswebframework.web.dict.DictDefine> getDefine(java.lang.String) ,public static org.hswebframework.web.dict.DictDefine parseEnumDict(Class<?>) ,public static void registerDefine(org.hswebframework.web.dict.DictDefine) <variables>protected static final Map<java.lang.String,org.hswebframework.web.dict.DictDefine> parsedDict
|
hs-web_hsweb-framework
|
hsweb-framework/hsweb-system/hsweb-system-dictionary/src/main/java/org/hswebframework/web/dictionary/service/DefaultDictionaryItemService.java
|
DefaultDictionaryItemService
|
fillOrdinal
|
class DefaultDictionaryItemService extends GenericReactiveCrudService<DictionaryItemEntity, String>
implements ReactiveTreeSortEntityService<DictionaryItemEntity, String> {
@Autowired
public ApplicationEventPublisher eventPublisher;
@Override
public IDGenerator<String> getIDGenerator() {
return IDGenerator.SNOW_FLAKE_STRING;
}
@Override
public void setChildren(DictionaryItemEntity entity, List<DictionaryItemEntity> children) {
entity.setChildren(children);
}
@Override
public Mono<Integer> insert(Publisher<DictionaryItemEntity> entityPublisher) {
return super.insert(this.fillOrdinal(entityPublisher))
.doOnSuccess(r -> eventPublisher.publishEvent(ClearDictionaryCacheEvent.of()));
}
@Override
public Mono<Integer> insertBatch(Publisher<? extends Collection<DictionaryItemEntity>> entityPublisher) {
return super.insertBatch(this.fillCollectionOrdinal(entityPublisher))
.doOnSuccess(r -> eventPublisher.publishEvent(ClearDictionaryCacheEvent.of()));
}
@Override
public Mono<Integer> updateById(String id, Mono<DictionaryItemEntity> entityPublisher) {
return super.updateById(id, entityPublisher)
.doOnSuccess(r -> eventPublisher.publishEvent(ClearDictionaryCacheEvent.of()));
}
@Override
public Mono<Integer> deleteById(Publisher<String> idPublisher) {
return super.deleteById(idPublisher)
.doOnSuccess(r -> eventPublisher.publishEvent(ClearDictionaryCacheEvent.of()));
}
@Override
public Mono<SaveResult> save(Publisher<DictionaryItemEntity> entityPublisher) {
return super.save(this.fillOrdinal(entityPublisher))
.doOnSuccess(r -> eventPublisher.publishEvent(ClearDictionaryCacheEvent.of()));
}
@Override
public ReactiveUpdate<DictionaryItemEntity> createUpdate() {
return super.createUpdate()
.onExecute((ignore, r) -> r.doOnSuccess(l -> eventPublisher.publishEvent(ClearDictionaryCacheEvent.of())));
}
@Override
public ReactiveDelete createDelete() {
return super.createDelete()
.onExecute((ignore, r) -> r.doOnSuccess(l -> eventPublisher.publishEvent(ClearDictionaryCacheEvent.of())));
}
public Publisher<? extends Collection<DictionaryItemEntity>> fillCollectionOrdinal(Publisher<? extends Collection<DictionaryItemEntity>> entityPublisher) {
return Flux
.from(entityPublisher)
.flatMap(collection -> fillOrdinal(Flux.fromIterable(collection)).collectList());
}
public Flux<DictionaryItemEntity> fillOrdinal(Publisher<DictionaryItemEntity> publisher) {<FILL_FUNCTION_BODY>}
private Flux<DictionaryItemEntity> fillOrdinal(String dictId, List<DictionaryItemEntity> list) {
return this
.createQuery()
.select(DictionaryItemEntity::getOrdinal)
.where(DictionaryItemEntity::getDictId, dictId)
.orderBy(SortOrder.desc(DictionaryItemEntity::getOrdinal))
.fetchOne()
.map(DictionaryItemEntity::getOrdinal)
.defaultIfEmpty(-1)
.flatMapMany(maxOrdinal -> Flux
.fromIterable(list)
.index()
.map(tp2 -> {
DictionaryItemEntity item = tp2.getT2();
int ordinal = tp2.getT1().intValue() + maxOrdinal + 1;
item.setOrdinal(ordinal);
item.generateId();
return item;
}));
}
}
|
return Flux
.from(publisher)
.groupBy(DictionaryItemEntity::getDictId)
.flatMap(group -> group
.collectList()
.flatMapMany(list -> {
boolean isAllNull = list.stream().allMatch(item -> item.getOrdinal() == null);
boolean notNull = list.stream().allMatch(item -> item.getOrdinal() != null);
if (notNull) {
return Flux
.fromIterable(list)
.doOnNext(DictionaryItemEntity::generateId);
}
if (isAllNull) {
return fillOrdinal(group.key(), list);
}
return Mono.error(() -> new BusinessException("error.ordinal_can_not_null"));
}));
| 979
| 207
| 1,186
|
<methods>public non-sealed void <init>() ,public ReactiveRepository<org.hswebframework.web.dictionary.entity.DictionaryItemEntity,java.lang.String> getRepository() <variables>private ReactiveRepository<org.hswebframework.web.dictionary.entity.DictionaryItemEntity,java.lang.String> repository
|
hs-web_hsweb-framework
|
hsweb-framework/hsweb-system/hsweb-system-dictionary/src/main/java/org/hswebframework/web/dictionary/service/DefaultDictionaryService.java
|
DefaultDictionaryService
|
fillDetail
|
class DefaultDictionaryService extends GenericReactiveCrudService<DictionaryEntity, String> {
@Autowired
private DefaultDictionaryItemService itemService;
@Autowired
private ApplicationEventPublisher eventPublisher;
@Override
public Mono<Integer> insert(Publisher<DictionaryEntity> entityPublisher) {
return super.insert(entityPublisher)
.doOnSuccess(r->eventPublisher.publishEvent(ClearDictionaryCacheEvent.of()));
}
@Override
public Mono<Integer> insertBatch(Publisher<? extends Collection<DictionaryEntity>> entityPublisher) {
return super.insertBatch(entityPublisher)
.doOnSuccess(r->eventPublisher.publishEvent(ClearDictionaryCacheEvent.of()));
}
@Override
public Mono<Integer> updateById(String id, Mono<DictionaryEntity> entityPublisher) {
return super.updateById(id,entityPublisher)
.doOnSuccess(r->eventPublisher.publishEvent(ClearDictionaryCacheEvent.of()));
}
@Override
public Mono<Integer> deleteById(Publisher<String> idPublisher) {
return super.deleteById(idPublisher)
.doOnSuccess(r->eventPublisher.publishEvent(ClearDictionaryCacheEvent.of()));
}
@Override
public Mono<SaveResult> save(Publisher<DictionaryEntity> entityPublisher) {
return super.save(entityPublisher)
.doOnSuccess(r->eventPublisher.publishEvent(ClearDictionaryCacheEvent.of()));
}
@Override
public ReactiveUpdate<DictionaryEntity> createUpdate() {
return super.createUpdate()
.onExecute((ignore,r)->r.doOnSuccess(l->eventPublisher.publishEvent(ClearDictionaryCacheEvent.of())));
}
@Override
public ReactiveDelete createDelete() {
return super.createDelete()
.onExecute((ignore,r)->r.doOnSuccess(l->eventPublisher.publishEvent(ClearDictionaryCacheEvent.of())));
}
public Mono<DictionaryEntity> findDetailById(String id) {
return findById(Mono.just(id))
.zipWith(itemService
.createQuery()
.where(DictionaryItemEntity::getDictId, id)
.orderBy(SortOrder.asc(DictionaryItemEntity::getOrdinal))
.fetch()
.collectList(),
(dic, items) -> {
dic.setItems(items);
return dic;
});
}
public Flux<DictionaryEntity> findAllDetail(QueryParamEntity paramEntity, boolean allowEmptyItem) {
return createQuery()
.setParam(paramEntity)
.fetch()
.as(flux -> fillDetail(flux, allowEmptyItem));
}
/**
* 查询字典详情
*
* @param dictionary 源数据
* @param allowEmptyItem 是否允许item为空
*/
public Flux<DictionaryEntity> fillDetail(Flux<DictionaryEntity> dictionary, boolean allowEmptyItem) {<FILL_FUNCTION_BODY>}
}
|
return QueryHelper
.combineOneToMany(
dictionary,
DictionaryEntity::getId,
itemService.createQuery(),
DictionaryItemEntity::getDictId,
DictionaryEntity::setItems
)
//根据条件过滤是否允许返回item为空的
.filter(dict -> allowEmptyItem || CollectionUtils.isNotEmpty(dict.getItems()));
| 800
| 96
| 896
|
<methods>public non-sealed void <init>() ,public ReactiveRepository<org.hswebframework.web.dictionary.entity.DictionaryEntity,java.lang.String> getRepository() <variables>private ReactiveRepository<org.hswebframework.web.dictionary.entity.DictionaryEntity,java.lang.String> repository
|
hs-web_hsweb-framework
|
hsweb-framework/hsweb-system/hsweb-system-file/src/main/java/org/hswebframework/web/file/FileUploadProperties.java
|
FileUploadProperties
|
denied
|
class FileUploadProperties {
private String staticFilePath = "./static";
private String staticLocation = "/static";
//是否使用原始文件名进行存储
private boolean useOriginalFileName = false;
private Set<String> allowFiles;
private Set<String> denyFiles;
private Set<String> allowMediaType;
private Set<String> denyMediaType;
private Set<PosixFilePermission> permissions;
public void applyFilePermission(File file) {
if (CollectionUtils.isEmpty(permissions)) {
return;
}
try {
Path path = Paths.get(file.toURI());
PosixFileAttributeView view = Files.getFileAttributeView(path, PosixFileAttributeView.class);
view.setPermissions(permissions);
} catch (Throwable ignore) {
}
}
public boolean denied(String name, MediaType mediaType) {<FILL_FUNCTION_BODY>}
public StaticFileInfo createStaticSavePath(String name) {
String fileName = IDGenerator.SNOW_FLAKE_STRING.generate();
String filePath = DateFormatter.toString(new Date(), "yyyyMMdd");
//文件后缀
String suffix = name.contains(".") ?
name.substring(name.lastIndexOf(".")) : "";
StaticFileInfo info = new StaticFileInfo();
if (useOriginalFileName) {
filePath = filePath + "/" + fileName;
fileName = name;
} else {
fileName = fileName + suffix;
}
String absPath = staticFilePath.concat("/").concat(filePath);
new File(absPath).mkdirs();
info.location = staticLocation + "/" + filePath + "/" + fileName;
info.savePath = absPath + "/" + fileName;
info.relativeLocation = filePath + "/" + fileName;
return info;
}
@Getter
@Setter
public static class StaticFileInfo {
private String savePath;
private String relativeLocation;
private String location;
}
}
|
String suffix = (name.contains(".") ? name.substring(name.lastIndexOf(".") + 1) : "").toLowerCase(Locale.ROOT);
boolean defaultDeny = false;
if (CollectionUtils.isNotEmpty(denyFiles)) {
if (denyFiles.contains(suffix)) {
return true;
}
defaultDeny = false;
}
if (CollectionUtils.isNotEmpty(allowFiles)) {
if (allowFiles.contains(suffix)) {
return false;
}
defaultDeny = true;
}
if (CollectionUtils.isNotEmpty(denyMediaType)) {
if (denyMediaType.contains(mediaType.toString())) {
return true;
}
defaultDeny = false;
}
if (CollectionUtils.isNotEmpty(allowMediaType)) {
if (allowMediaType.contains(mediaType.toString())) {
return false;
}
defaultDeny = true;
}
return defaultDeny;
| 546
| 263
| 809
|
<no_super_class>
|
hs-web_hsweb-framework
|
hsweb-framework/hsweb-system/hsweb-system-file/src/main/java/org/hswebframework/web/file/service/LocalFileStorageService.java
|
LocalFileStorageService
|
saveFile
|
class LocalFileStorageService implements FileStorageService {
private final FileUploadProperties properties;
@Override
public Mono<String> saveFile(FilePart filePart) {
FileUploadProperties.StaticFileInfo info = properties.createStaticSavePath(filePart.filename());
return createStaticFileInfo(filePart.filename())
.flatMap(into -> {
File file = new File(info.getSavePath());
return (filePart)
.transferTo(file)
.then(Mono.fromRunnable(() -> properties.applyFilePermission(file)))
.thenReturn(info.getLocation());
});
}
private static final OpenOption[] FILE_CHANNEL_OPTIONS = {
StandardOpenOption.CREATE,
StandardOpenOption.TRUNCATE_EXISTING,
StandardOpenOption.WRITE};
protected Mono<FileUploadProperties.StaticFileInfo> createStaticFileInfo(String fileName) {
return Mono.just(properties.createStaticSavePath(fileName));
}
@Override
@SneakyThrows
public Mono<String> saveFile(InputStream inputStream, String fileType) {<FILL_FUNCTION_BODY>}
}
|
String fileName = "_temp" + (fileType.startsWith(".") ? fileType : "." + fileType);
return createStaticFileInfo(fileName)
.flatMap(info -> Mono
.fromCallable(() -> {
try (ReadableByteChannel input = Channels.newChannel(inputStream);
FileChannel output = FileChannel.open(Paths.get(info.getSavePath()), FILE_CHANNEL_OPTIONS)) {
long size = (input instanceof FileChannel ? ((FileChannel) input).size() : Long.MAX_VALUE);
long totalWritten = 0;
while (totalWritten < size) {
long written = output.transferFrom(input, totalWritten, size - totalWritten);
if (written <= 0) {
break;
}
totalWritten += written;
}
return info.getLocation();
}
})
.doOnSuccess((ignore) -> properties.applyFilePermission(new File(info.getSavePath())))
.subscribeOn(Schedulers.boundedElastic()));
| 304
| 268
| 572
|
<no_super_class>
|
hs-web_hsweb-framework
|
hsweb-framework/hsweb-system/hsweb-system-file/src/main/java/org/hswebframework/web/file/web/ReactiveFileController.java
|
ReactiveFileController
|
uploadStatic
|
class ReactiveFileController {
private final FileUploadProperties properties;
private final FileStorageService fileStorageService;
public ReactiveFileController(FileUploadProperties properties, FileStorageService fileStorageService) {
this.properties = properties;
this.fileStorageService = fileStorageService;
}
@PostMapping("/static")
@SneakyThrows
@ResourceAction(id = "upload-static", name = "静态文件")
@Operation(summary = "上传静态文件")
public Mono<String> uploadStatic(@RequestPart("file")
@Parameter(name = "file", description = "文件", style = ParameterStyle.FORM) Mono<Part> partMono) {<FILL_FUNCTION_BODY>}
}
|
return partMono
.flatMap(part -> {
if (part instanceof FilePart) {
FilePart filePart = ((FilePart) part);
if (properties.denied(filePart.filename(), filePart.headers().getContentType())) {
return Mono.error( new AccessDenyException());
}
return fileStorageService.saveFile(filePart);
} else {
return Mono.error(() -> new IllegalArgumentException("[file] part is not a file"));
}
});
| 189
| 131
| 320
|
<no_super_class>
|
apache_ignite
|
ignite/modules/calcite/src/main/java/org/apache/ignite/internal/processors/query/calcite/Query.java
|
Query
|
onOutboundExchangeFinished
|
class Query<RowT> {
/** */
private final UUID initNodeId;
/** */
private final UUID id;
/** */
protected final Object mux = new Object();
/** */
protected final Set<RunningFragment<RowT>> fragments;
/** */
protected final GridQueryCancel cancel;
/** */
protected final BiConsumer<Query<RowT>, Throwable> unregister;
/** */
protected volatile QueryState state = QueryState.INITED;
/** */
protected final ExchangeService exch;
/** */
protected final int totalFragmentsCnt;
/** */
protected final AtomicInteger finishedFragmentsCnt = new AtomicInteger();
/** */
protected final Set<Long> initNodeStartedExchanges = new HashSet<>();
/** Logger. */
protected final IgniteLogger log;
/** */
private MemoryTracker memoryTracker;
/** */
public Query(
UUID id,
UUID initNodeId,
GridQueryCancel cancel,
ExchangeService exch,
BiConsumer<Query<RowT>, Throwable> unregister,
IgniteLogger log,
int totalFragmentsCnt
) {
this.id = id;
this.unregister = unregister;
this.initNodeId = initNodeId;
this.exch = exch;
this.log = log;
this.cancel = cancel != null ? cancel : new GridQueryCancel();
fragments = Collections.newSetFromMap(new ConcurrentHashMap<>());
this.totalFragmentsCnt = totalFragmentsCnt;
}
/** Query ID. */
public UUID id() {
return id;
}
/** Query state. */
public QueryState state() {
return state;
}
/** */
public UUID initiatorNodeId() {
return initNodeId;
}
/** */
public void onError(Throwable failure) {
tryClose(failure);
}
/** */
protected void tryClose(@Nullable Throwable failure) {
List<RunningFragment<RowT>> fragments = new ArrayList<>(this.fragments);
AtomicInteger cntDown = new AtomicInteger(fragments.size());
if (cntDown.get() == 0)
unregister.accept(this, failure);
for (RunningFragment<RowT> frag : fragments) {
frag.context().execute(() -> {
frag.root().close();
frag.context().cancel();
if (cntDown.decrementAndGet() == 0)
unregister.accept(this, failure);
}, frag.root()::onError);
}
synchronized (mux) {
if (memoryTracker != null)
memoryTracker.reset();
}
}
/** Cancel query. */
public void cancel() {
synchronized (mux) {
if (state == QueryState.CLOSED)
return;
if (state == QueryState.INITED) {
state = QueryState.CLOSING;
try {
exch.closeQuery(initNodeId, id);
return;
}
catch (IgniteCheckedException e) {
log.warning("Cannot send cancel request to query initiator", e);
}
}
if (state == QueryState.EXECUTING || state == QueryState.CLOSING)
state = QueryState.CLOSED;
}
for (RunningFragment<RowT> frag : fragments)
frag.context().execute(() -> frag.root().onError(new QueryCancelledException()), frag.root()::onError);
tryClose(queryCanceledException());
}
/** */
public void addFragment(RunningFragment<RowT> f) {
synchronized (mux) {
if (state == QueryState.INITED)
state = QueryState.EXECUTING;
if (state == QueryState.CLOSING || state == QueryState.CLOSED)
throw queryCanceledException();
fragments.add(f);
}
}
/** */
public boolean isCancelled() {
return cancel.isCanceled();
}
/** */
protected IgniteSQLException queryCanceledException() {
return new IgniteSQLException(
"The query was cancelled",
IgniteQueryErrorCode.QUERY_CANCELED,
new QueryCancelledException()
);
}
/** */
public void onNodeLeft(UUID nodeId) {
if (initNodeId.equals(nodeId))
cancel();
}
/**
* Callback after the first batch of the query fragment from the node is received.
*/
public void onInboundExchangeStarted(UUID nodeId, long exchangeId) {
// No-op.
}
/**
* Callback after the last batch of the query fragment from the node is processed.
*/
public void onInboundExchangeFinished(UUID nodeId, long exchangeId) {
// No-op.
}
/**
* Callback after the first batch of the query fragment from the node is sent.
*/
public void onOutboundExchangeStarted(UUID nodeId, long exchangeId) {
if (initNodeId.equals(nodeId))
initNodeStartedExchanges.add(exchangeId);
}
/**
* Callback after the last batch of the query fragment is sent to all nodes.
*/
public void onOutboundExchangeFinished(long exchangeId) {<FILL_FUNCTION_BODY>}
/** */
public boolean isExchangeWithInitNodeStarted(long fragmentId) {
// On remote node exchange ID is the same as fragment ID.
return initNodeStartedExchanges.contains(fragmentId);
}
/** */
public MemoryTracker createMemoryTracker(MemoryTracker globalMemoryTracker, long quota) {
synchronized (mux) {
// Query can have multiple fragments, each fragment requests memory tracker, but there should be only
// one memory tracker per query on each node, store it inside Query instance.
if (memoryTracker == null) {
memoryTracker = quota > 0 || globalMemoryTracker != NoOpMemoryTracker.INSTANCE ?
new QueryMemoryTracker(globalMemoryTracker, quota) : NoOpMemoryTracker.INSTANCE;
}
return memoryTracker;
}
}
/** {@inheritDoc} */
@Override public String toString() {
return S.toString(Query.class, this, "state", state, "fragments", fragments);
}
}
|
if (finishedFragmentsCnt.incrementAndGet() == totalFragmentsCnt) {
QueryState state0;
synchronized (mux) {
state0 = state;
if (state0 == QueryState.EXECUTING)
state = QueryState.CLOSED;
}
if (state0 == QueryState.EXECUTING)
tryClose(null);
}
| 1,697
| 108
| 1,805
|
<no_super_class>
|
apache_ignite
|
ignite/modules/calcite/src/main/java/org/apache/ignite/internal/processors/query/calcite/exec/ArrayRowHandler.java
|
ArrayRowHandler
|
factory
|
class ArrayRowHandler implements RowHandler<Object[]> {
/** */
public static final RowHandler<Object[]> INSTANCE = new ArrayRowHandler();
/** */
private ArrayRowHandler() {}
/** {@inheritDoc} */
@Override public Object get(int field, Object[] row) {
return row[field];
}
/** {@inheritDoc} */
@Override public void set(int field, Object[] row, Object val) {
row[field] = val;
}
/** {@inheritDoc} */
@Override public Object[] concat(Object[] left, Object[] right) {
return F.concat(left, right);
}
/** {@inheritDoc} */
@Override public int columnCount(Object[] row) {
return row.length;
}
/** {@inheritDoc} */
@Override public RowFactory<Object[]> factory(Type... types) {<FILL_FUNCTION_BODY>}
}
|
int rowLen = types.length;
return new RowFactory<Object[]>() {
/** {@inheritDoc} */
@Override public RowHandler<Object[]> handler() {
return ArrayRowHandler.this;
}
/** {@inheritDoc} */
@Override public Object[] create() {
return new Object[rowLen];
}
/** {@inheritDoc} */
@Override public Object[] create(Object... fields) {
assert fields.length == rowLen;
return fields;
}
};
| 241
| 136
| 377
|
<no_super_class>
|
apache_ignite
|
ignite/modules/calcite/src/main/java/org/apache/ignite/internal/processors/query/calcite/exec/RuntimeSortedIndex.java
|
Cursor
|
lowerBound
|
class Cursor implements GridCursor<Row> {
/** List of rows. */
private final List<Row> rows;
/** Upper bound. */
private final Row upper;
/** Include upper bound. */
private final boolean includeUpper;
/** Current row. */
private Row row;
/** Current index of list element. */
private int idx;
/**
* @param rows List of rows.
* @param lower Lower bound.
* @param upper Upper bound.
* @param lowerInclude {@code True} for inclusive lower bound.
* @param upperInclude {@code True} for inclusive upper bound.
*/
Cursor(List<Row> rows, @Nullable Row lower, @Nullable Row upper, boolean lowerInclude, boolean upperInclude) {
this.rows = rows;
this.upper = upper;
this.includeUpper = upperInclude;
idx = lower == null ? 0 : lowerBound(rows, lower, lowerInclude);
}
/**
* Searches the lower bound (skipping duplicates) using a binary search.
*
* @param rows List of rows.
* @param bound Lower bound.
* @return Lower bound position in the list.
*/
private int lowerBound(List<Row> rows, Row bound, boolean includeBound) {<FILL_FUNCTION_BODY>}
/** {@inheritDoc} */
@Override public boolean next() {
if (idx == rows.size() || (upper != null && comp.compare(upper, rows.get(idx)) < (includeUpper ? 0 : 1)))
return false;
row = rows.get(idx++);
return true;
}
/** {@inheritDoc} */
@Override public Row get() {
return row;
}
}
|
int low = 0, high = rows.size() - 1, idx = -1;
while (low <= high) {
int mid = (high - low) / 2 + low;
int compRes = comp.compare(rows.get(mid), bound);
if (compRes > 0)
high = mid - 1;
else if (compRes == 0 && includeBound) {
idx = mid;
high = mid - 1;
}
else
low = mid + 1;
}
return idx == -1 ? low : idx;
| 457
| 147
| 604
|
<no_super_class>
|
apache_ignite
|
ignite/modules/calcite/src/main/java/org/apache/ignite/internal/processors/query/calcite/exec/SystemViewScan.java
|
SystemViewScan
|
iterator
|
class SystemViewScan<Row, ViewRow> implements Iterable<Row> {
/** */
private final ExecutionContext<Row> ectx;
/** */
private final SystemViewTableDescriptorImpl<ViewRow> desc;
/** */
private final RowFactory<Row> factory;
/** */
private final RangeIterable<Row> ranges;
/** Participating colunms. */
private final ImmutableBitSet requiredColumns;
/** System view field names (for filtering). */
private final String[] filterableFieldNames;
/** System view field types (for filtering). */
private final Class<?>[] filterableFieldTypes;
/** */
public SystemViewScan(
ExecutionContext<Row> ectx,
SystemViewTableDescriptorImpl<ViewRow> desc,
@Nullable RangeIterable<Row> ranges,
@Nullable ImmutableBitSet requiredColumns
) {
this.ectx = ectx;
this.desc = desc;
this.ranges = ranges;
this.requiredColumns = requiredColumns;
RelDataType rowType = desc.rowType(ectx.getTypeFactory(), requiredColumns);
factory = ectx.rowHandler().factory(ectx.getTypeFactory(), rowType);
filterableFieldNames = new String[desc.columnDescriptors().size()];
filterableFieldTypes = new Class<?>[desc.columnDescriptors().size()];
if (desc.isFiltrable()) {
for (SystemViewColumnDescriptor col : desc.columnDescriptors()) {
if (col.isFiltrable()) {
filterableFieldNames[col.fieldIndex()] = col.originalName();
filterableFieldTypes[col.fieldIndex()] = col.storageType();
}
}
}
}
/** {@inheritDoc} */
@Override public Iterator<Row> iterator() {<FILL_FUNCTION_BODY>}
}
|
SystemView<ViewRow> view = desc.systemView();
Iterator<ViewRow> viewIter;
if (ranges != null) {
assert view instanceof FiltrableSystemView : view;
Iterator<RangeCondition<Row>> rangesIter = ranges.iterator();
RangeCondition<Row> range = rangesIter.next();
assert !rangesIter.hasNext();
Row searchValues = range.lower(); // Lower bound for the hash index should be the same as upper bound.
RowHandler<Row> rowHnd = ectx.rowHandler();
Map<String, Object> filterMap = null;
for (int i = 0; i < filterableFieldNames.length; i++) {
if (filterableFieldNames[i] == null)
continue;
Object val = rowHnd.get(i, searchValues);
if (val != ectx.unspecifiedValue()) {
if (filterMap == null)
filterMap = new HashMap<>();
filterMap.put(filterableFieldNames[i], TypeUtils.fromInternal(ectx, val, filterableFieldTypes[i]));
}
}
viewIter = F.isEmpty(filterMap) ? view.iterator() : ((FiltrableSystemView<ViewRow>)view).iterator(filterMap);
}
else
viewIter = view.iterator();
return F.iterator(viewIter, row -> desc.toRow(ectx, row, factory, requiredColumns), true);
| 481
| 373
| 854
|
<no_super_class>
|
apache_ignite
|
ignite/modules/calcite/src/main/java/org/apache/ignite/internal/processors/query/calcite/exec/TableScan.java
|
TableScan
|
reserve
|
class TableScan<Row> implements Iterable<Row>, AutoCloseable {
/** */
private final GridCacheContext<?, ?> cctx;
/** */
private final ExecutionContext<Row> ectx;
/** */
private final CacheTableDescriptor desc;
/** */
private final RowFactory<Row> factory;
/** */
private final AffinityTopologyVersion topVer;
/** */
private final int[] parts;
/** */
private final MvccSnapshot mvccSnapshot;
/** */
private volatile List<GridDhtLocalPartition> reserved;
/** Participating colunms. */
private final ImmutableBitSet requiredColunms;
/** */
public TableScan(
ExecutionContext<Row> ectx,
CacheTableDescriptor desc,
int[] parts,
@Nullable ImmutableBitSet requiredColunms
) {
this.ectx = ectx;
cctx = desc.cacheContext();
this.desc = desc;
this.parts = parts;
this.requiredColunms = requiredColunms;
RelDataType rowType = desc.rowType(this.ectx.getTypeFactory(), requiredColunms);
factory = this.ectx.rowHandler().factory(this.ectx.getTypeFactory(), rowType);
topVer = ectx.topologyVersion();
mvccSnapshot = ectx.mvccSnapshot();
}
/** {@inheritDoc} */
@Override public Iterator<Row> iterator() {
reserve();
try {
return new IteratorImpl();
}
catch (Exception e) {
release();
throw e;
}
}
/** */
@Override public void close() {
release();
}
/** */
private synchronized void reserve() {<FILL_FUNCTION_BODY>}
/** */
private synchronized void release() {
if (F.isEmpty(reserved))
return;
reserved.forEach(GridDhtLocalPartition::release);
reserved = null;
}
/**
* Table scan iterator.
*/
private class IteratorImpl extends GridIteratorAdapter<Row> {
/** */
private final Queue<GridDhtLocalPartition> parts;
/** */
private GridCursor<? extends CacheDataRow> cur;
/** */
private Row next;
/** */
private IteratorImpl() {
assert reserved != null;
parts = new ArrayDeque<>(reserved);
}
/** {@inheritDoc} */
@Override public boolean hasNextX() throws IgniteCheckedException {
advance();
return next != null;
}
/** {@inheritDoc} */
@Override public Row nextX() throws IgniteCheckedException {
advance();
if (next == null)
throw new NoSuchElementException();
Row next = this.next;
this.next = null;
return next;
}
/** {@inheritDoc} */
@Override public void removeX() {
throw new UnsupportedOperationException("Remove is not supported.");
}
/** */
private void advance() throws IgniteCheckedException {
assert parts != null;
if (next != null)
return;
while (true) {
if (cur == null) {
GridDhtLocalPartition part = parts.poll();
if (part == null)
break;
cur = part.dataStore().cursor(cctx.cacheId(), mvccSnapshot);
}
if (cur.next()) {
CacheDataRow row = cur.get();
if (row.expireTime() > 0 && row.expireTime() <= U.currentTimeMillis())
continue;
if (!desc.match(row))
continue;
next = desc.toRow(ectx, row, factory, requiredColunms);
break;
}
else
cur = null;
}
}
}
}
|
if (reserved != null)
return;
GridDhtPartitionTopology top = cctx.topology();
top.readLock();
GridDhtTopologyFuture topFut = top.topologyVersionFuture();
boolean done = topFut.isDone();
if (!done || !(topFut.topologyVersion().compareTo(topVer) >= 0
&& cctx.shared().exchange().lastAffinityChangedTopologyVersion(topFut.initialVersion()).compareTo(topVer) <= 0)) {
top.readUnlock();
throw new ClusterTopologyException("Topology was changed. Please retry on stable topology.");
}
List<GridDhtLocalPartition> toReserve;
if (cctx.isReplicated()) {
int partsCnt = cctx.affinity().partitions();
toReserve = new ArrayList<>(partsCnt);
for (int i = 0; i < partsCnt; i++)
toReserve.add(top.localPartition(i));
}
else if (cctx.isPartitioned()) {
assert parts != null;
toReserve = new ArrayList<>(parts.length);
for (int i = 0; i < parts.length; i++)
toReserve.add(top.localPartition(parts[i]));
}
else
toReserve = Collections.emptyList();
reserved = new ArrayList<>(toReserve.size());
try {
for (GridDhtLocalPartition part : toReserve) {
if (part == null || !part.reserve())
throw new ClusterTopologyException("Failed to reserve partition for query execution. Retry on stable topology.");
else if (part.state() != GridDhtPartitionState.OWNING) {
part.release();
throw new ClusterTopologyException("Failed to reserve partition for query execution. Retry on stable topology.");
}
reserved.add(part);
}
}
catch (Exception e) {
release();
throw e;
}
finally {
top.readUnlock();
}
| 1,025
| 530
| 1,555
|
<no_super_class>
|
apache_ignite
|
ignite/modules/calcite/src/main/java/org/apache/ignite/internal/processors/query/calcite/exec/exp/IgniteRexBuilder.java
|
IgniteRexBuilder
|
makeLiteral
|
class IgniteRexBuilder extends RexBuilder {
/** */
public IgniteRexBuilder(RelDataTypeFactory typeFactory) {
super(typeFactory);
}
/** {@inheritDoc} */
@Override protected RexLiteral makeLiteral(@Nullable Comparable o, RelDataType type, SqlTypeName typeName) {<FILL_FUNCTION_BODY>}
}
|
if (o != null && typeName == SqlTypeName.DECIMAL && TypeUtils.hasScale(type))
return super.makeLiteral(((BigDecimal)o).setScale(type.getScale(), RoundingMode.HALF_UP), type, typeName);
return super.makeLiteral(o, type, typeName);
| 95
| 86
| 181
|
<no_super_class>
|
apache_ignite
|
ignite/modules/calcite/src/main/java/org/apache/ignite/internal/processors/query/calcite/exec/exp/IgniteScalarFunction.java
|
IgniteScalarFunction
|
create
|
class IgniteScalarFunction extends ReflectiveFunctionBase implements ScalarFunction, ImplementableFunction {
/** Implementor. */
private final CallImplementor implementor;
/**
* Private constructor.
*/
private IgniteScalarFunction(Method method, CallImplementor implementor) {
super(method);
this.implementor = implementor;
}
/**
* Creates {@link ScalarFunction} from given method.
*
* @param method Method that is used to implement the function.
* @return Created {@link ScalarFunction}.
*/
public static ScalarFunction create(Method method) {<FILL_FUNCTION_BODY>}
/** {@inheritDoc} */
@Override public RelDataType getReturnType(RelDataTypeFactory typeFactory) {
return typeFactory.createJavaType(method.getReturnType());
}
/** {@inheritDoc} */
@Override public CallImplementor getImplementor() {
return implementor;
}
}
|
assert Modifier.isStatic(method.getModifiers());
CallImplementor implementor = RexImpTable.createImplementor(
new ReflectiveCallNotNullImplementor(method), NullPolicy.NONE, false);
return new IgniteScalarFunction(method, implementor);
| 257
| 77
| 334
|
<no_super_class>
|
apache_ignite
|
ignite/modules/calcite/src/main/java/org/apache/ignite/internal/processors/query/calcite/exec/partition/PartitionParameterNode.java
|
PartitionParameterNode
|
applySingle
|
class PartitionParameterNode extends PartitionSingleNode {
/** */
private final Class<?> colType;
/** */
private final RexDynamicParam param;
/** */
public PartitionParameterNode(int cacheId, RexDynamicParam param, Class<?> colType) {
super(cacheId);
this.param = param;
this.colType = colType;
}
/** {@inheritDoc} */
@Override Integer applySingle(PartitionPruningContext ctx) {<FILL_FUNCTION_BODY>}
}
|
int idx = param.getIndex();
Object val = TypeUtils.toInternal(ctx.dataContext(), ctx.resolveParameter(idx), colType);
if (val == null)
return null;
AffinityService affSvc = ctx.affinityService();
return affSvc.affinity(cacheId()).applyAsInt(val);
| 140
| 90
| 230
|
<methods>public Collection<java.lang.Integer> apply(org.apache.ignite.internal.processors.query.calcite.exec.partition.PartitionPruningContext) ,public int cacheId() <variables>private final non-sealed int cacheId
|
apache_ignite
|
ignite/modules/calcite/src/main/java/org/apache/ignite/internal/processors/query/calcite/exec/partition/PartitionSingleNode.java
|
PartitionSingleNode
|
apply
|
class PartitionSingleNode implements PartitionNode {
/** */
private final int cacheId;
/** */
protected PartitionSingleNode(int cacheId) {
this.cacheId = cacheId;
}
/** {@inheritDoc} */
@Override public Collection<Integer> apply(PartitionPruningContext ctx) {<FILL_FUNCTION_BODY>}
/** */
abstract Integer applySingle(PartitionPruningContext ctx);
/** {@inheritDoc} */
@Override public int cacheId() {
return cacheId;
}
}
|
Integer part = applySingle(ctx);
return part == null ? ImmutableList.of() : ImmutableList.of(part);
| 143
| 36
| 179
|
<no_super_class>
|
apache_ignite
|
ignite/modules/calcite/src/main/java/org/apache/ignite/internal/processors/query/calcite/exec/rel/MergeJoinNode.java
|
RightJoin
|
join
|
class RightJoin<Row> extends MergeJoinNode<Row> {
/** Right row factory. */
private final RowHandler.RowFactory<Row> leftRowFactory;
/** */
private Row left;
/** */
private Row right;
/** Used to store similar rows of rights stream in many-to-many join mode. */
private List<Row> rightMaterialization;
/** */
private int rightIdx;
/** */
private boolean drainMaterialization;
/** Whether current right row was matched (hence pushed to downstream) or not. */
private boolean matched;
/**
* @param ctx Execution context.
* @param rowType Row type.
* @param comp Join expression comparator.
* @param distributed If one of the inputs has exchange underneath.
* @param leftRowFactory Left row factory.
*/
public RightJoin(
ExecutionContext<Row> ctx,
RelDataType rowType,
Comparator<Row> comp,
boolean distributed,
RowHandler.RowFactory<Row> leftRowFactory
) {
super(ctx, rowType, comp, distributed);
this.leftRowFactory = leftRowFactory;
}
/** {@inheritDoc} */
@Override protected void rewindInternal() {
left = null;
right = null;
rightIdx = 0;
rightMaterialization = null;
drainMaterialization = false;
super.rewindInternal();
}
/** {@inheritDoc} */
@Override protected void join() throws Exception {<FILL_FUNCTION_BODY>}
}
|
inLoop = true;
try {
while (requested > 0 && !(left == null && leftInBuf.isEmpty() && waitingLeft != NOT_WAITING)
&& (right != null || !rightInBuf.isEmpty() || rightMaterialization != null)) {
checkState();
if (left == null && !leftInBuf.isEmpty())
left = leftInBuf.remove();
if (right == null) {
if (rightInBuf.isEmpty() && waitingRight != NOT_WAITING)
break;
if (!rightInBuf.isEmpty()) {
right = rightInBuf.remove();
matched = false;
}
}
if (right == null && rightMaterialization != null && !drainMaterialization) {
drainMaterialization = true;
left = null;
continue;
}
Row row;
if (!drainMaterialization) {
if (left == null) {
if (!matched) {
row = handler.concat(leftRowFactory.create(), right);
requested--;
downstream().push(row);
}
right = null;
continue;
}
int cmp = comp.compare(left, right);
if (cmp < 0) {
left = null;
rightIdx = 0;
if (rightMaterialization != null)
drainMaterialization = true;
continue;
}
else if (cmp > 0) {
if (!matched) {
row = handler.concat(leftRowFactory.create(), right);
requested--;
downstream().push(row);
}
right = null;
rightIdx = 0;
rightMaterialization = null;
continue;
}
if (rightMaterialization == null && (!rightInBuf.isEmpty() || waitingRight != NOT_WAITING)) {
if (rightInBuf.isEmpty())
break;
if (comp.compare(left, rightInBuf.peek()) == 0)
rightMaterialization = new ArrayList<>();
}
matched = true;
row = handler.concat(left, right);
if (rightMaterialization != null) {
rightMaterialization.add(right);
right = null;
}
else
left = null;
}
else {
if (left == null) {
if (waitingLeft == NOT_WAITING)
rightMaterialization = null;
break;
}
if (rightIdx >= rightMaterialization.size()) {
rightIdx = 0;
left = null;
continue;
}
Row right = rightMaterialization.get(rightIdx++);
int cmp = comp.compare(left, right);
if (cmp > 0) {
rightIdx = 0;
rightMaterialization = null;
drainMaterialization = false;
continue;
}
row = handler.concat(left, right);
}
requested--;
downstream().push(row);
}
}
finally {
inLoop = false;
}
if (waitingRight == 0)
rightSource().request(waitingRight = IN_BUFFER_SIZE);
if (waitingLeft == 0)
leftSource().request(waitingLeft = IN_BUFFER_SIZE);
if (requested > 0 && waitingRight == NOT_WAITING && right == null && rightInBuf.isEmpty() && rightMaterialization == null)
checkJoinFinished();
| 402
| 902
| 1,304
|
<methods>public void close() ,public ExecutionContext<Row> context() ,public Downstream<Row> downstream() ,public void onError(java.lang.Throwable) ,public void onRegister(Downstream<Row>) ,public void register(List<Node<Row>>) ,public void rewind() ,public RelDataType rowType() ,public List<Node<Row>> sources() <variables>protected static final int IN_BUFFER_SIZE,protected static final int IO_BATCH_CNT,protected static final int IO_BATCH_SIZE,protected static final int MODIFY_BATCH_SIZE,private boolean closed,private ExecutionContext<Row> ctx,private Downstream<Row> downstream,private RelDataType rowType,private List<Node<Row>> sources,private volatile java.lang.Thread thread
|
apache_ignite
|
ignite/modules/calcite/src/main/java/org/apache/ignite/internal/processors/query/calcite/exec/rel/MinusNode.java
|
MinusGrouping
|
addOnSingle
|
class MinusGrouping<Row> extends Grouping<Row> {
/** */
private MinusGrouping(ExecutionContext<Row> ctx, RowFactory<Row> rowFactory, AggregateType type, boolean all) {
super(ctx, rowFactory, type, all);
}
/** {@inheritDoc} */
@Override protected void addOnSingle(Row row, int setIdx) {<FILL_FUNCTION_BODY>}
/** {@inheritDoc} */
@Override protected void addOnMapper(Row row, int setIdx) {
// Value in the map will always have 2 elements, first - count of keys in the first set,
// second - count of keys in all sets except first.
int[] cntrs = groups.computeIfAbsent(key(row), k -> new int[2]);
cntrs[setIdx == 0 ? 0 : 1]++;
}
/** {@inheritDoc} */
@Override protected boolean affectResult(int[] cntrs) {
return cntrs[0] != cntrs[1];
}
/** {@inheritDoc} */
@Override protected int availableRows(int[] cntrs) {
assert cntrs.length == 2;
if (all)
return Math.max(cntrs[0] - cntrs[1], 0);
else
return cntrs[1] == 0 ? 1 : 0;
}
/** {@inheritDoc} */
@Override protected void decrementAvailableRows(int[] cntrs, int amount) {
assert amount > 0;
assert all;
cntrs[0] -= amount;
}
/** {@inheritDoc} */
@Override protected int countersSize() {
return 2;
}
}
|
int[] cntrs;
GroupKey key = key(row);
if (setIdx == 0) {
// Value in the map will always have 2 elements, first - count of keys in the first set,
// second - count of keys in all sets except first.
cntrs = groups.computeIfAbsent(key, k -> new int[2]);
cntrs[0]++;
}
else if (all) {
cntrs = groups.get(key);
if (cntrs != null) {
cntrs[1]++;
if (cntrs[1] >= cntrs[0])
groups.remove(key);
}
}
else
groups.remove(key);
| 451
| 195
| 646
|
<methods>public void end(int) throws java.lang.Exception,public void push(Row, int) throws java.lang.Exception,public void request(int) throws java.lang.Exception<variables>private int curSrcIdx,private final non-sealed Grouping<Row> grouping,private boolean inLoop,private int requested,private final non-sealed org.apache.ignite.internal.processors.query.calcite.exec.exp.agg.AggregateType type,private int waiting
|
apache_ignite
|
ignite/modules/calcite/src/main/java/org/apache/ignite/internal/processors/query/calcite/exec/rel/ScanNode.java
|
ScanNode
|
processNextBatch
|
class ScanNode<Row> extends AbstractNode<Row> implements SingleNode<Row> {
/** */
private final Iterable<Row> src;
/** */
@Nullable private final Predicate<Row> filter;
/** */
@Nullable private final Function<Row, Row> rowTransformer;
/** */
private Iterator<Row> it;
/** */
private int requested;
/** */
private boolean inLoop;
/** */
private boolean firstReq = true;
/**
* @param ctx Execution context.
* @param rowType Row type.
* @param src Source.
*/
public ScanNode(ExecutionContext<Row> ctx, RelDataType rowType, Iterable<Row> src) {
this(ctx, rowType, src, null, null);
}
/**
* @param ctx Execution context.
* @param rowType Row type.
* @param src Source.
* @param filter Row filter.
* @param rowTransformer Row transformer (projection).
*/
public ScanNode(
ExecutionContext<Row> ctx,
RelDataType rowType,
Iterable<Row> src,
@Nullable Predicate<Row> filter,
@Nullable Function<Row, Row> rowTransformer
) {
super(ctx, rowType);
this.src = src;
this.filter = filter;
this.rowTransformer = rowTransformer;
}
/** {@inheritDoc} */
@Override public void request(int rowsCnt) throws Exception {
assert rowsCnt > 0 && requested == 0 : "rowsCnt=" + rowsCnt + ", requested=" + requested;
checkState();
requested = rowsCnt;
if (!inLoop) {
if (firstReq) {
try {
push(); // Make first request sync to reduce latency in simple cases.
}
catch (Throwable e) {
onError(e);
}
firstReq = false;
}
else
context().execute(this::push, this::onError);
}
}
/** {@inheritDoc} */
@Override public void closeInternal() {
super.closeInternal();
Commons.closeQuiet(it);
it = null;
Commons.closeQuiet(src);
}
/** {@inheritDoc} */
@Override protected void rewindInternal() {
Commons.closeQuiet(it);
it = null;
}
/** {@inheritDoc} */
@Override public void register(List<Node<Row>> sources) {
throw new UnsupportedOperationException();
}
/** {@inheritDoc} */
@Override protected Downstream<Row> requestDownstream(int idx) {
throw new UnsupportedOperationException();
}
/** */
private void push() throws Exception {
if (isClosed())
return;
checkState();
inLoop = true;
try {
if (it == null)
it = src.iterator();
processNextBatch();
}
finally {
inLoop = false;
}
}
/**
* @return Count of processed rows.
*/
protected int processNextBatch() throws Exception {<FILL_FUNCTION_BODY>}
/** */
@Nullable public Predicate<Row> filter() {
return filter;
}
/** */
@Nullable public Function<Row, Row> rowTransformer() {
return rowTransformer;
}
}
|
int processed = 0;
while (requested > 0 && it.hasNext()) {
checkState();
Row r = it.next();
if (filter == null || filter.test(r)) {
requested--;
if (rowTransformer != null)
r = rowTransformer.apply(r);
downstream().push(r);
}
if (++processed == IN_BUFFER_SIZE && requested > 0) {
// Allow others to do their job.
context().execute(this::push, this::onError);
return processed;
}
}
if (requested > 0 && !it.hasNext()) {
Commons.closeQuiet(it);
it = null;
requested = 0;
downstream().end();
}
return processed;
| 892
| 213
| 1,105
|
<methods>public void close() ,public ExecutionContext<Row> context() ,public Downstream<Row> downstream() ,public void onError(java.lang.Throwable) ,public void onRegister(Downstream<Row>) ,public void register(List<Node<Row>>) ,public void rewind() ,public RelDataType rowType() ,public List<Node<Row>> sources() <variables>protected static final int IN_BUFFER_SIZE,protected static final int IO_BATCH_CNT,protected static final int IO_BATCH_SIZE,protected static final int MODIFY_BATCH_SIZE,private boolean closed,private ExecutionContext<Row> ctx,private Downstream<Row> downstream,private RelDataType rowType,private List<Node<Row>> sources,private volatile java.lang.Thread thread
|
apache_ignite
|
ignite/modules/calcite/src/main/java/org/apache/ignite/internal/processors/query/calcite/exec/rel/SortAggregateNode.java
|
Group
|
rowOnReducer
|
class Group {
/** */
private final List<AccumulatorWrapper<Row>> accumWrps;
/** */
private final Object[] grpKeys;
/** */
private Group(Object[] grpKeys) {
this.grpKeys = grpKeys;
accumWrps = hasAccumulators() ? accFactory.get() : Collections.emptyList();
}
/** */
private void add(Row row) {
if (type == REDUCE)
addOnReducer(row);
else
addOnMapper(row);
}
/** */
private Row row() {
if (type == AggregateType.MAP)
return rowOnMapper();
else
return rowOnReducer();
}
/** */
private void addOnMapper(Row row) {
for (AccumulatorWrapper<Row> wrapper : accumWrps)
wrapper.add(row);
}
/** */
private void addOnReducer(Row row) {
RowHandler<Row> hnd = context().rowHandler();
List<Accumulator> accums = hasAccumulators() ?
(List<Accumulator>)hnd.get(hnd.columnCount(row) - 1, row)
: Collections.emptyList();
for (int i = 0; i < accums.size(); i++) {
AccumulatorWrapper<Row> wrapper = accumWrps.get(i);
Accumulator accum = accums.get(i);
wrapper.apply(accum);
}
}
/** */
private Row rowOnMapper() {
Object[] fields = new Object[grpSet.cardinality() + (accFactory != null ? 1 : 0)];
int i = 0;
for (Object grpKey : grpKeys)
fields[i++] = grpKey;
// Last column is the accumulators collection.
if (hasAccumulators())
fields[i] = Commons.transform(accumWrps, AccumulatorWrapper::accumulator);
return rowFactory.create(fields);
}
/** */
private Row rowOnReducer() {<FILL_FUNCTION_BODY>}
}
|
Object[] fields = new Object[grpSet.cardinality() + accumWrps.size()];
int i = 0;
for (Object grpKey : grpKeys)
fields[i++] = grpKey;
for (AccumulatorWrapper<Row> accWrp : accumWrps)
fields[i++] = accWrp.end();
return rowFactory.create(fields);
| 575
| 107
| 682
|
<methods><variables>protected final non-sealed Supplier<List<AccumulatorWrapper<Row>>> accFactory,protected final non-sealed boolean hasAggAccum,protected final non-sealed RowFactory<Row> rowFactory,protected final non-sealed org.apache.ignite.internal.processors.query.calcite.exec.exp.agg.AggregateType type
|
apache_ignite
|
ignite/modules/calcite/src/main/java/org/apache/ignite/internal/processors/query/calcite/message/CalciteMessageFactory.java
|
CalciteMessageFactory
|
asMessage
|
class CalciteMessageFactory implements MessageFactoryProvider {
/** {@inheritDoc} */
@SuppressWarnings({"unchecked", "rawtypes"})
@Override public void registerAll(IgniteMessageFactory factory) {
for (MessageType type : MessageType.values())
factory.register(type.directType(), (Supplier)type.factory());
}
/**
* Produces a value message.
*/
public static ValueMessage asMessage(Object val) {<FILL_FUNCTION_BODY>}
}
|
if (val == null)
return null;
return new GenericValueMessage(val);
| 131
| 28
| 159
|
<no_super_class>
|
apache_ignite
|
ignite/modules/calcite/src/main/java/org/apache/ignite/internal/processors/query/calcite/message/GenericValueMessage.java
|
GenericValueMessage
|
writeTo
|
class GenericValueMessage implements ValueMessage {
/** */
@GridDirectTransient
private Object val;
/** */
private byte[] serialized;
/** */
public GenericValueMessage() {
}
/** */
public GenericValueMessage(Object val) {
this.val = val;
}
/** {@inheritDoc} */
@Override public Object value() {
return val;
}
/** {@inheritDoc} */
@Override public void prepareMarshal(MarshallingContext ctx) throws IgniteCheckedException {
if (val != null && serialized == null)
serialized = ctx.marshal(val);
}
/** {@inheritDoc} */
@Override public void prepareUnmarshal(MarshallingContext ctx) throws IgniteCheckedException {
if (serialized != null && val == null)
val = ctx.unmarshal(serialized);
}
/** {@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:
serialized = reader.readByteArray("serialized");
if (!reader.isLastRead())
return false;
reader.incrementState();
}
return reader.afterMessageRead(GenericValueMessage.class);
}
/** {@inheritDoc} */
@Override public MessageType type() {
return MessageType.GENERIC_VALUE_MESSAGE;
}
/** {@inheritDoc} */
@Override public byte fieldsCount() {
return 1;
}
}
|
writer.setBuffer(buf);
if (!writer.isHeaderWritten()) {
if (!writer.writeHeader(directType(), fieldsCount()))
return false;
writer.onHeaderWritten();
}
switch (writer.state()) {
case 0:
if (!writer.writeByteArray("serialized", serialized))
return false;
writer.incrementState();
}
return true;
| 473
| 114
| 587
|
<no_super_class>
|
apache_ignite
|
ignite/modules/calcite/src/main/java/org/apache/ignite/internal/processors/query/calcite/message/QueryBatchMessage.java
|
QueryBatchMessage
|
prepareMarshal
|
class QueryBatchMessage implements MarshalableMessage, ExecutionContextAware {
/** */
private UUID qryId;
/** */
private long fragmentId;
/** */
private long exchangeId;
/** */
private int batchId;
/** */
private boolean last;
/** */
@GridDirectTransient
private List<Object> rows;
/** */
@GridDirectCollection(ValueMessage.class)
private List<ValueMessage> mRows;
/** */
public QueryBatchMessage() {
}
/** */
public QueryBatchMessage(UUID qryId, long fragmentId, long exchangeId, int batchId, boolean last, List<Object> rows) {
this.qryId = qryId;
this.fragmentId = fragmentId;
this.exchangeId = exchangeId;
this.batchId = batchId;
this.last = last;
this.rows = rows;
}
/** {@inheritDoc} */
@Override public UUID queryId() {
return qryId;
}
/** {@inheritDoc} */
@Override public long fragmentId() {
return fragmentId;
}
/**
* @return Exchange ID.
*/
public long exchangeId() {
return exchangeId;
}
/**
* @return Batch ID.
*/
public int batchId() {
return batchId;
}
/**
* @return Last batch flag.
*/
public boolean last() {
return last;
}
/**
* @return Rows.
*/
public List<Object> rows() {
return rows;
}
/** {@inheritDoc} */
@Override public void prepareMarshal(MarshallingContext ctx) throws IgniteCheckedException {<FILL_FUNCTION_BODY>}
/** {@inheritDoc} */
@Override public void prepareUnmarshal(MarshallingContext ctx) throws IgniteCheckedException {
if (rows != null || mRows == null)
return;
rows = new ArrayList<>(mRows.size());
for (ValueMessage mRow : mRows) {
assert mRow != null;
mRow.prepareUnmarshal(ctx);
rows.add(mRow.value());
}
}
/** {@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("batchId", batchId))
return false;
writer.incrementState();
case 1:
if (!writer.writeLong("exchangeId", exchangeId))
return false;
writer.incrementState();
case 2:
if (!writer.writeLong("fragmentId", fragmentId))
return false;
writer.incrementState();
case 3:
if (!writer.writeBoolean("last", last))
return false;
writer.incrementState();
case 4:
if (!writer.writeCollection("mRows", mRows, MessageCollectionItemType.MSG))
return false;
writer.incrementState();
case 5:
if (!writer.writeUuid("queryId", qryId))
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:
batchId = reader.readInt("batchId");
if (!reader.isLastRead())
return false;
reader.incrementState();
case 1:
exchangeId = reader.readLong("exchangeId");
if (!reader.isLastRead())
return false;
reader.incrementState();
case 2:
fragmentId = reader.readLong("fragmentId");
if (!reader.isLastRead())
return false;
reader.incrementState();
case 3:
last = reader.readBoolean("last");
if (!reader.isLastRead())
return false;
reader.incrementState();
case 4:
mRows = reader.readCollection("mRows", MessageCollectionItemType.MSG);
if (!reader.isLastRead())
return false;
reader.incrementState();
case 5:
qryId = reader.readUuid("queryId");
if (!reader.isLastRead())
return false;
reader.incrementState();
}
return reader.afterMessageRead(QueryBatchMessage.class);
}
/** {@inheritDoc} */
@Override public MessageType type() {
return MessageType.QUERY_BATCH_MESSAGE;
}
/** {@inheritDoc} */
@Override public byte fieldsCount() {
return 6;
}
}
|
if (mRows != null || rows == null)
return;
mRows = new ArrayList<>(rows.size());
for (Object row : rows) {
ValueMessage mRow = CalciteMessageFactory.asMessage(row);
assert mRow != null;
mRow.prepareMarshal(ctx);
mRows.add(mRow);
}
| 1,351
| 99
| 1,450
|
<no_super_class>
|
apache_ignite
|
ignite/modules/calcite/src/main/java/org/apache/ignite/internal/processors/query/calcite/message/QueryCloseMessage.java
|
QueryCloseMessage
|
writeTo
|
class QueryCloseMessage implements CalciteMessage {
/** */
private UUID qryId;
/** */
public QueryCloseMessage() {
// No-op.
}
/** */
public QueryCloseMessage(UUID qryId) {
this.qryId = qryId;
}
/**
* @return Query ID.
*/
public UUID queryId() {
return qryId;
}
/** {@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:
qryId = reader.readUuid("queryId");
if (!reader.isLastRead())
return false;
reader.incrementState();
}
return reader.afterMessageRead(QueryCloseMessage.class);
}
/** {@inheritDoc} */
@Override public MessageType type() {
return MessageType.QUERY_CLOSE_MESSAGE;
}
/** {@inheritDoc} */
@Override public byte fieldsCount() {
return 1;
}
}
|
writer.setBuffer(buf);
if (!writer.isHeaderWritten()) {
if (!writer.writeHeader(directType(), fieldsCount()))
return false;
writer.onHeaderWritten();
}
switch (writer.state()) {
case 0:
if (!writer.writeUuid("queryId", qryId))
return false;
writer.incrementState();
}
return true;
| 350
| 114
| 464
|
<no_super_class>
|
apache_ignite
|
ignite/modules/calcite/src/main/java/org/apache/ignite/internal/processors/query/calcite/message/QueryStartResponse.java
|
QueryStartResponse
|
readFrom
|
class QueryStartResponse implements MarshalableMessage {
/** */
private UUID queryId;
/** */
private long fragmentId;
/** */
@GridDirectTransient
private Throwable error;
/** */
private byte[] errBytes;
/** */
public QueryStartResponse() {}
/** */
public QueryStartResponse(UUID queryId, long fragmentId) {
this(queryId, fragmentId, null);
}
/** */
public QueryStartResponse(UUID queryId, long fragmentId, Throwable error) {
this.queryId = queryId;
this.fragmentId = fragmentId;
this.error = error;
}
/**
* @return Query ID.
*/
public UUID queryId() {
return queryId;
}
/**
* @return Fragment ID.
*/
public long fragmentId() {
return fragmentId;
}
/**
* @return Error.
*/
public Throwable error() {
return error;
}
/** {@inheritDoc} */
@Override public void prepareMarshal(MarshallingContext ctx) throws IgniteCheckedException {
if (error != null)
errBytes = ctx.marshal(error);
}
/** {@inheritDoc} */
@Override public void prepareUnmarshal(MarshallingContext ctx) throws IgniteCheckedException {
if (errBytes != null)
error = ctx.unmarshal(errBytes);
}
/** {@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.writeByteArray("errBytes", errBytes))
return false;
writer.incrementState();
case 1:
if (!writer.writeLong("fragmentId", fragmentId))
return false;
writer.incrementState();
case 2:
if (!writer.writeUuid("queryId", queryId))
return false;
writer.incrementState();
}
return true;
}
/** {@inheritDoc} */
@Override public boolean readFrom(ByteBuffer buf, MessageReader reader) {<FILL_FUNCTION_BODY>}
/** {@inheritDoc} */
@Override public MessageType type() {
return MessageType.QUERY_START_RESPONSE;
}
/** {@inheritDoc} */
@Override public byte fieldsCount() {
return 3;
}
}
|
reader.setBuffer(buf);
if (!reader.beforeMessageRead())
return false;
switch (reader.state()) {
case 0:
errBytes = reader.readByteArray("errBytes");
if (!reader.isLastRead())
return false;
reader.incrementState();
case 1:
fragmentId = reader.readLong("fragmentId");
if (!reader.isLastRead())
return false;
reader.incrementState();
case 2:
queryId = reader.readUuid("queryId");
if (!reader.isLastRead())
return false;
reader.incrementState();
}
return reader.afterMessageRead(QueryStartResponse.class);
| 705
| 194
| 899
|
<no_super_class>
|
apache_ignite
|
ignite/modules/calcite/src/main/java/org/apache/ignite/internal/processors/query/calcite/metadata/FragmentMapping.java
|
FragmentMapping
|
writeTo
|
class FragmentMapping implements MarshalableMessage {
/** */
@GridDirectCollection(ColocationGroup.class)
private List<ColocationGroup> colocationGroups;
/** */
public FragmentMapping() {
}
/** */
private FragmentMapping(ColocationGroup colocationGroup) {
this(F.asList(colocationGroup));
}
/** */
private FragmentMapping(List<ColocationGroup> colocationGroups) {
this.colocationGroups = colocationGroups;
}
/** */
public static FragmentMapping create() {
return new FragmentMapping(Collections.emptyList());
}
/** */
public static FragmentMapping create(UUID nodeId) {
return new FragmentMapping(ColocationGroup.forNodes(Collections.singletonList(nodeId)));
}
/** */
public static FragmentMapping create(long sourceId) {
return new FragmentMapping(ColocationGroup.forSourceId(sourceId));
}
/** */
public static FragmentMapping create(long sourceId, ColocationGroup group) {
try {
return new FragmentMapping(ColocationGroup.forSourceId(sourceId).colocate(group));
}
catch (ColocationMappingException e) {
throw new AssertionError(e); // Cannot happen
}
}
/** */
public boolean colocated() {
return colocationGroups.isEmpty() || colocationGroups.size() == 1;
}
/** */
public FragmentMapping combine(FragmentMapping other) {
return new FragmentMapping(Commons.combine(colocationGroups, other.colocationGroups));
}
/** */
public FragmentMapping colocate(FragmentMapping other) throws ColocationMappingException {
assert colocated() && other.colocated();
ColocationGroup first = F.first(colocationGroups);
ColocationGroup second = F.first(other.colocationGroups);
if (first == null && second == null)
return this;
else if (first == null || second == null)
return new FragmentMapping(U.firstNotNull(first, second));
else
return new FragmentMapping(first.colocate(second));
}
/** */
public FragmentMapping local(UUID nodeId) throws ColocationMappingException {
if (colocationGroups.isEmpty())
return create(nodeId).colocate(this);
return new FragmentMapping(Commons.transform(colocationGroups, c -> c.local(nodeId)));
}
/** */
public List<UUID> nodeIds() {
return colocationGroups.stream()
.flatMap(g -> g.nodeIds().stream())
.distinct().collect(Collectors.toList());
}
/** */
public List<ColocationGroup> colocationGroups() {
return Collections.unmodifiableList(colocationGroups);
}
/** */
public FragmentMapping finalizeMapping(Supplier<List<UUID>> nodesSource) {
if (colocationGroups.isEmpty())
return this;
List<ColocationGroup> colocationGrps = this.colocationGroups;
colocationGrps = Commons.transform(colocationGrps, ColocationGroup::finalizeMapping);
List<UUID> nodes = nodeIds(), nodes0 = nodes.isEmpty() ? nodesSource.get() : nodes;
colocationGrps = Commons.transform(colocationGrps, g -> g.mapToNodes(nodes0));
return new FragmentMapping(colocationGrps);
}
/** */
public FragmentMapping filterByPartitions(int[] parts) throws ColocationMappingException {
List<ColocationGroup> colocationGrps = this.colocationGroups;
if (!F.isEmpty(parts) && colocationGrps.size() > 1)
throw new ColocationMappingException("Execution of non-collocated query with partition parameter is not possible");
colocationGrps = Commons.transform(colocationGrps, g -> g.filterByPartitions(parts));
return new FragmentMapping(colocationGrps);
}
/** */
public @NotNull ColocationGroup findGroup(long sourceId) {
List<ColocationGroup> grps = colocationGroups.stream()
.filter(c -> c.belongs(sourceId))
.collect(Collectors.toList());
if (grps.isEmpty())
throw new IllegalStateException("Failed to find group with given id. [sourceId=" + sourceId + "]");
else if (grps.size() > 1)
throw new IllegalStateException("Multiple groups with the same id found. [sourceId=" + sourceId + "]");
return F.first(grps);
}
/** {@inheritDoc} */
@Override public void prepareMarshal(MarshallingContext ctx) {
colocationGroups.forEach(g -> g.prepareMarshal(ctx));
}
/** {@inheritDoc} */
@Override public void prepareUnmarshal(MarshallingContext ctx) {
colocationGroups.forEach(g -> g.prepareUnmarshal(ctx));
}
/** {@inheritDoc} */
@Override public MessageType type() {
return MessageType.FRAGMENT_MAPPING;
}
/** {@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:
colocationGroups = reader.readCollection("colocationGroups", MessageCollectionItemType.MSG);
if (!reader.isLastRead())
return false;
reader.incrementState();
}
return reader.afterMessageRead(FragmentMapping.class);
}
/** {@inheritDoc} */
@Override public byte fieldsCount() {
return 1;
}
}
|
writer.setBuffer(buf);
if (!writer.isHeaderWritten()) {
if (!writer.writeHeader(directType(), fieldsCount()))
return false;
writer.onHeaderWritten();
}
switch (writer.state()) {
case 0:
if (!writer.writeCollection("colocationGroups", colocationGroups, MessageCollectionItemType.MSG))
return false;
writer.incrementState();
}
return true;
| 1,526
| 123
| 1,649
|
<no_super_class>
|
apache_ignite
|
ignite/modules/calcite/src/main/java/org/apache/ignite/internal/processors/query/calcite/metadata/IgniteMdCumulativeCost.java
|
IgniteMdCumulativeCost
|
getCumulativeCost
|
class IgniteMdCumulativeCost implements MetadataHandler<BuiltInMetadata.CumulativeCost> {
/** */
public static final RelMetadataProvider SOURCE = ReflectiveRelMetadataProvider.reflectiveSource(
BuiltInMethod.CUMULATIVE_COST.method, new IgniteMdCumulativeCost());
/** {@inheritDoc} */
@Override public MetadataDef<BuiltInMetadata.CumulativeCost> getDef() {
return BuiltInMetadata.CumulativeCost.DEF;
}
/** */
public RelOptCost getCumulativeCost(RelSubset rel, RelMetadataQuery mq) {
return VolcanoUtils.bestCost(rel);
}
/** */
public RelOptCost getCumulativeCost(RelNode rel, RelMetadataQuery mq) {
RelOptCost cost = nonCumulativeCost(rel, mq);
if (cost.isInfinite())
return cost;
for (RelNode input : rel.getInputs()) {
RelOptCost inputCost = mq.getCumulativeCost(input);
if (inputCost.isInfinite())
return inputCost;
cost = cost.plus(inputCost);
}
return cost;
}
/** */
public RelOptCost getCumulativeCost(IgniteCorrelatedNestedLoopJoin rel, RelMetadataQuery mq) {<FILL_FUNCTION_BODY>}
/** */
private static RelOptCost nonCumulativeCost(RelNode rel, RelMetadataQuery mq) {
RelOptCost cost = mq.getNonCumulativeCost(rel);
if (cost.isInfinite())
return cost;
RelOptCostFactory costFactory = rel.getCluster().getPlanner().getCostFactory();
if (rel.getConvention() == Convention.NONE || distribution(rel) == any())
return costFactory.makeInfiniteCost();
return costFactory.makeZeroCost().isLt(cost) ? cost : costFactory.makeTinyCost();
}
}
|
RelOptCost cost = nonCumulativeCost(rel, mq);
if (cost.isInfinite())
return cost;
RelNode left = rel.getLeft();
RelNode right = rel.getRight();
Set<CorrelationId> corIds = rel.getVariablesSet();
RelOptCost leftCost = mq.getCumulativeCost(left);
if (leftCost.isInfinite())
return leftCost;
RelOptCost rightCost = mq.getCumulativeCost(right);
if (rightCost.isInfinite())
return rightCost;
return cost.plus(leftCost).plus(rightCost.multiplyBy(left.estimateRowCount(mq) / corIds.size()));
| 515
| 190
| 705
|
<no_super_class>
|
apache_ignite
|
ignite/modules/calcite/src/main/java/org/apache/ignite/internal/processors/query/calcite/metadata/IgniteMdPredicates.java
|
IgniteMdPredicates
|
getPredicates
|
class IgniteMdPredicates extends RelMdPredicates {
/** */
public static final RelMetadataProvider SOURCE = ReflectiveRelMetadataProvider
.reflectiveSource(BuiltInMethod.PREDICATES.method, new IgniteMdPredicates());
/**
* See {@link RelMdPredicates#getPredicates(org.apache.calcite.rel.RelNode, org.apache.calcite.rel.metadata.RelMetadataQuery)}
*/
public RelOptPredicateList getPredicates(ProjectableFilterableTableScan rel, RelMetadataQuery mq) {<FILL_FUNCTION_BODY>}
}
|
RexNode predicate = rel.pushUpPredicate();
if (predicate == null)
return RelOptPredicateList.EMPTY;
return RelOptPredicateList.of(RexUtils.builder(rel),
RexUtil.retainDeterministic(RelOptUtil.conjunctions(predicate)));
| 162
| 83
| 245
|
<no_super_class>
|
apache_ignite
|
ignite/modules/calcite/src/main/java/org/apache/ignite/internal/processors/query/calcite/metadata/MappingServiceImpl.java
|
MappingServiceImpl
|
executionNodes
|
class MappingServiceImpl extends AbstractService implements MappingService {
/** */
private GridDiscoveryManager discoveryManager;
/**
* @param ctx Kernal.
*/
public MappingServiceImpl(GridKernalContext ctx) {
super(ctx);
}
/**
* @param discoveryManager Discovery manager.
*/
public void discoveryManager(GridDiscoveryManager discoveryManager) {
this.discoveryManager = discoveryManager;
}
/** {@inheritDoc} */
@Override public void onStart(GridKernalContext ctx) {
discoveryManager(ctx.discovery());
}
/** {@inheritDoc} */
@Override public List<UUID> executionNodes(@NotNull AffinityTopologyVersion topVer, boolean single,
@Nullable Predicate<ClusterNode> nodeFilter) {<FILL_FUNCTION_BODY>}
}
|
List<ClusterNode> nodes = new ArrayList<>(discoveryManager.discoCache(topVer).serverNodes());
if (nodeFilter != null)
nodes = nodes.stream().filter(nodeFilter).collect(Collectors.toList());
if (single && nodes.size() > 1)
nodes = F.asList(nodes.get(ThreadLocalRandom.current().nextInt(nodes.size())));
if (F.isEmpty(nodes))
throw new IllegalStateException("failed to map query to execution nodes. Nodes list is empty.");
return Commons.transform(nodes, ClusterNode::id);
| 217
| 152
| 369
|
<methods>public void onStart(org.apache.ignite.internal.GridKernalContext) ,public void onStop() <variables>protected final non-sealed org.apache.ignite.IgniteLogger log
|
apache_ignite
|
ignite/modules/calcite/src/main/java/org/apache/ignite/internal/processors/query/calcite/metadata/RelMetadataQueryEx.java
|
RelMetadataQueryEx
|
create
|
class RelMetadataQueryEx extends RelMetadataQuery {
static {
ConfigurationBuilder cfg = new ConfigurationBuilder()
.forPackages("org.apache.ignite.internal.processors.query.calcite.rel")
.addClassLoaders(U.gridClassLoader())
.addScanners(new SubTypesScanner());
List<Class<? extends RelNode>> types = new Reflections(cfg)
.getSubTypesOf(IgniteRel.class).stream()
.filter(type -> !type.isInterface())
.filter(type -> !Modifier.isAbstract(type.getModifiers()))
.collect(Collectors.toList());
JaninoRelMetadataProvider.DEFAULT.register(types);
}
/** */
private static final IgniteMetadata.FragmentMappingMetadata.Handler SOURCE_DISTRIBUTION_INITIAL_HANDLER =
initialHandler(IgniteMetadata.FragmentMappingMetadata.Handler.class);
/** */
private IgniteMetadata.FragmentMappingMetadata.Handler sourceDistributionHandler;
/**
* Factory method.
*
* @return return Metadata query instance.
*/
public static RelMetadataQueryEx create() {
return create(IgniteMetadata.METADATA_PROVIDER);
}
/**
* Factory method.
*
* @return return Metadata query instance.
*/
public static RelMetadataQueryEx create(RelMetadataProvider metadataProvider) {<FILL_FUNCTION_BODY>}
/** */
private RelMetadataQueryEx() {
sourceDistributionHandler = SOURCE_DISTRIBUTION_INITIAL_HANDLER;
}
/**
* Calculates data location mapping for a query fragment the given relation node is a root of.
*
* @param rel Relational node.
* @return Fragment meta information.
*/
public FragmentMapping fragmentMapping(RelNode rel, MappingQueryContext ctx) {
for (;;) {
try {
return sourceDistributionHandler.fragmentMapping(rel, this, ctx);
}
catch (JaninoRelMetadataProvider.NoHandler e) {
sourceDistributionHandler = revise(e.relClass, IgniteMetadata.FragmentMappingMetadata.DEF);
}
}
}
}
|
THREAD_PROVIDERS.set(JaninoRelMetadataProvider.of(metadataProvider));
try {
return new RelMetadataQueryEx();
}
finally {
THREAD_PROVIDERS.remove();
}
| 567
| 59
| 626
|
<no_super_class>
|
apache_ignite
|
ignite/modules/calcite/src/main/java/org/apache/ignite/internal/processors/query/calcite/prepare/CacheKey.java
|
CacheKey
|
equals
|
class CacheKey {
/** */
private final String schemaName;
/** */
private final String query;
/** */
private final Object contextKey;
/** */
private final Class<?>[] paramTypes;
/**
* @param schemaName Schema name.
* @param query Query string.
* @param contextKey Optional context key to differ queries with and without/different flags, having an impact
* on result plan (like LOCAL flag)
* @param params Dynamic parameters.
*/
public CacheKey(String schemaName, String query, Object contextKey, Object[] params) {
this.schemaName = schemaName;
this.query = query;
this.contextKey = contextKey;
paramTypes = params.length == 0 ? null :
Arrays.stream(params).map(p -> (p != null) ? p.getClass() : Void.class).toArray(Class[]::new);
}
/**
* @param schemaName Schema name.
* @param query Query string.
*/
public CacheKey(String schemaName, String query) {
this(schemaName, query, null, X.EMPTY_OBJECT_ARRAY);
}
/** {@inheritDoc} */
@Override public boolean equals(Object o) {<FILL_FUNCTION_BODY>}
/** {@inheritDoc} */
@Override public int hashCode() {
int result = schemaName.hashCode();
result = 31 * result + query.hashCode();
result = 31 * result + (contextKey != null ? contextKey.hashCode() : 0);
result = 31 * result + Arrays.deepHashCode(paramTypes);
return result;
}
}
|
if (this == o)
return true;
if (o == null || getClass() != o.getClass())
return false;
CacheKey cacheKey = (CacheKey)o;
if (!schemaName.equals(cacheKey.schemaName))
return false;
if (!query.equals(cacheKey.query))
return false;
if (!Objects.equals(contextKey, cacheKey.contextKey))
return false;
return Arrays.deepEquals(paramTypes, cacheKey.paramTypes);
| 437
| 135
| 572
|
<no_super_class>
|
apache_ignite
|
ignite/modules/calcite/src/main/java/org/apache/ignite/internal/processors/query/calcite/prepare/PlanExtractor.java
|
SensitiveDataAwarePlanWriter
|
removeSensitive
|
class SensitiveDataAwarePlanWriter extends RelWriterImpl {
/** */
public SensitiveDataAwarePlanWriter(PrintWriter pw) {
super(pw, SqlExplainLevel.ALL_ATTRIBUTES, false);
}
/** {@inheritDoc} */
@Override public RelWriter item(String term, @Nullable Object val) {
return super.item(term, removeSensitive(val));
}
/** */
private Object removeSensitive(Object val) {<FILL_FUNCTION_BODY>}
/** {@inheritDoc} */
@Override public boolean nest() {
// Don't try to expand some values by rel nodes, use original values.
return true;
}
}
|
if (val instanceof RexNode)
return LiteralRemoveShuttle.INSTANCE.apply((RexNode)val);
else if (val instanceof Collection)
return F.transform((Collection<?>)val, this::removeSensitive);
else if (val instanceof SearchBounds)
return ((SearchBounds)val).transform(LiteralRemoveShuttle.INSTANCE::apply);
return val;
| 181
| 101
| 282
|
<no_super_class>
|
apache_ignite
|
ignite/modules/calcite/src/main/java/org/apache/ignite/internal/processors/query/calcite/rel/AbstractIndexScan.java
|
AbstractIndexScan
|
computeSelfCost
|
class AbstractIndexScan extends ProjectableFilterableTableScan {
/** */
protected final String idxName;
/** */
protected final List<SearchBounds> searchBounds;
/**
* Constructor used for deserialization.
*
* @param input Serialized representation.
*/
protected AbstractIndexScan(RelInput input) {
super(input);
idxName = input.getString("index");
searchBounds = ((RelInputEx)input).getSearchBounds("searchBounds");
}
/** */
protected AbstractIndexScan(
RelOptCluster cluster,
RelTraitSet traitSet,
RelOptTable table,
String idxName,
@Nullable List<RexNode> proj,
@Nullable RexNode cond,
@Nullable List<SearchBounds> searchBounds,
@Nullable ImmutableBitSet reqColumns
) {
super(cluster, traitSet, Collections.emptyList(), table, proj, cond, reqColumns);
this.idxName = idxName;
this.searchBounds = searchBounds;
}
/** {@inheritDoc} */
@Override protected RelWriter explainTerms0(RelWriter pw) {
pw = pw.item("index", idxName);
pw = super.explainTerms0(pw);
pw = pw.itemIf("searchBounds", searchBounds, searchBounds != null);
if (pw.getDetailLevel() == SqlExplainLevel.ALL_ATTRIBUTES)
pw = pw.item("inlineScan", isInlineScan());
return pw;
}
/**
*
*/
public String indexName() {
return idxName;
}
/** */
public boolean isInlineScan() {
IgniteTable tbl = table.unwrap(IgniteTable.class);
IgniteIndex idx = tbl.getIndex(idxName);
if (idx != null)
return idx.isInlineScanPossible(requiredColumns);
return false;
}
/** {@inheritDoc} */
@Override public RelOptCost computeSelfCost(RelOptPlanner planner, RelMetadataQuery mq) {<FILL_FUNCTION_BODY>}
/** */
public List<SearchBounds> searchBounds() {
return searchBounds;
}
}
|
double rows = table.getRowCount();
double cost;
IgniteTable tbl = table.unwrap(IgniteTable.class);
IgniteIndex idx = tbl.getIndex(idxName);
double inlineReward = (idx != null && isInlineScan()) ?
(0.5d + 0.5d * idx.collation().getFieldCollations().size() / table.getRowType().getFieldCount()) : 1d;
if (condition == null)
cost = rows * IgniteCost.ROW_PASS_THROUGH_COST * inlineReward;
else {
RexBuilder builder = getCluster().getRexBuilder();
double selectivity = 1;
cost = 0;
if (searchBounds != null) {
selectivity = mq.getSelectivity(this, RexUtil.composeConjunction(builder,
Commons.transform(searchBounds, b -> b == null ? null : b.condition())));
cost = Math.log(rows) * IgniteCost.ROW_COMPARISON_COST;
}
rows *= selectivity;
if (rows <= 0)
rows = 1;
cost += rows * (IgniteCost.ROW_COMPARISON_COST + IgniteCost.ROW_PASS_THROUGH_COST * inlineReward);
}
// additional tiny cost for preventing equality with table scan.
return planner.getCostFactory().makeCost(rows, cost, 0).plus(planner.getCostFactory().makeTinyCost());
| 584
| 394
| 978
|
<methods>public RelColumnOrigin columnOriginsByRelLocalRef(int) ,public RelOptCost computeSelfCost(RelOptPlanner, RelMetadataQuery) ,public RexNode condition() ,public RelNode copy(RelTraitSet, List<RelNode>) ,public RelDataType deriveRowType() ,public double estimateRowCount(RelMetadataQuery) ,public RelWriter explainTerms(RelWriter) ,public List<RexNode> projects() ,public RexNode pushUpPredicate() ,public ImmutableBitSet requiredColumns() <variables>protected final non-sealed RexNode condition,protected final non-sealed List<RexNode> projects,protected final non-sealed ImmutableBitSet requiredColumns
|
apache_ignite
|
ignite/modules/calcite/src/main/java/org/apache/ignite/internal/processors/query/calcite/rel/IgniteAggregate.java
|
IgniteAggregate
|
estimateMemoryForGroup
|
class IgniteAggregate extends Aggregate implements IgniteRel {
/** */
protected IgniteAggregate(
RelOptCluster cluster,
RelTraitSet traitSet,
RelNode input,
ImmutableBitSet groupSet,
List<ImmutableBitSet> groupSets,
List<AggregateCall> aggCalls
) {
super(cluster, traitSet, ImmutableList.of(), input, groupSet, groupSets, aggCalls);
}
/** */
protected IgniteAggregate(RelInput input) {
super(changeTraits(input, IgniteConvention.INSTANCE));
}
/** {@inheritDoc} */
@Override public double estimateRowCount(RelMetadataQuery mq) {
Double grpsCnt = mq.getDistinctRowCount(getInput(), groupSet, null);
if (grpsCnt != null)
return grpsCnt;
// Estimation of the groups count is not available.
// Use heuristic estimation for result rows count.
return super.estimateRowCount(mq);
}
/** */
public double estimateMemoryForGroup(RelMetadataQuery mq) {<FILL_FUNCTION_BODY>}
/** */
public RelOptCost computeSelfCostHash(RelOptPlanner planner, RelMetadataQuery mq) {
IgniteCostFactory costFactory = (IgniteCostFactory)planner.getCostFactory();
double inRows = mq.getRowCount(getInput());
double grps = estimateRowCount(mq);
return costFactory.makeCost(
inRows,
inRows * IgniteCost.ROW_PASS_THROUGH_COST,
0,
grps * estimateMemoryForGroup(mq),
0
);
}
/** */
public RelOptCost computeSelfCostSort(RelOptPlanner planner, RelMetadataQuery mq) {
IgniteCostFactory costFactory = (IgniteCostFactory)planner.getCostFactory();
double inRows = mq.getRowCount(getInput());
return costFactory.makeCost(
inRows,
inRows * IgniteCost.ROW_PASS_THROUGH_COST,
0,
estimateMemoryForGroup(mq),
0
);
}
}
|
double mem = groupSet.cardinality() * IgniteCost.AVERAGE_FIELD_SIZE;
if (!aggCalls.isEmpty()) {
double grps = estimateRowCount(mq);
double rows = input.estimateRowCount(mq);
for (AggregateCall aggCall : aggCalls) {
if (aggCall.isDistinct())
mem += IgniteCost.AGG_CALL_MEM_COST * rows / grps;
else
mem += IgniteCost.AGG_CALL_MEM_COST;
}
}
return mem;
| 582
| 153
| 735
|
<no_super_class>
|
apache_ignite
|
ignite/modules/calcite/src/main/java/org/apache/ignite/internal/processors/query/calcite/rel/IgniteHashIndexSpool.java
|
IgniteHashIndexSpool
|
computeSelfCost
|
class IgniteHashIndexSpool extends Spool implements IgniteRel {
/** Search row. */
private final List<RexNode> searchRow;
/** Keys (number of the columns at the input row) to build hash index. */
private final ImmutableBitSet keys;
/** Filters. */
private final RexNode cond;
/** Allow NULL values. */
private final boolean allowNulls;
/** */
public IgniteHashIndexSpool(
RelOptCluster cluster,
RelTraitSet traits,
RelNode input,
List<RexNode> searchRow,
RexNode cond,
boolean allowNulls
) {
super(cluster, traits, input, Type.LAZY, Type.EAGER);
assert !F.isEmpty(searchRow);
this.searchRow = searchRow;
this.cond = cond;
this.allowNulls = allowNulls;
keys = ImmutableBitSet.of(RexUtils.notNullKeys(searchRow));
}
/**
* Constructor used for deserialization.
*
* @param input Serialized representation.
*/
public IgniteHashIndexSpool(RelInput input) {
this(input.getCluster(),
input.getTraitSet().replace(IgniteConvention.INSTANCE),
input.getInputs().get(0),
input.getExpressionList("searchRow"),
input.getExpression("condition"),
input.getBoolean("allowNulls", false)
);
}
/** {@inheritDoc} */
@Override public <T> T accept(IgniteRelVisitor<T> visitor) {
return visitor.visit(this);
}
/** */
@Override public IgniteRel clone(RelOptCluster cluster, List<IgniteRel> inputs) {
return new IgniteHashIndexSpool(cluster, getTraitSet(), inputs.get(0), searchRow, cond, allowNulls);
}
/** {@inheritDoc} */
@Override protected Spool copy(RelTraitSet traitSet, RelNode input, Type readType, Type writeType) {
return new IgniteHashIndexSpool(getCluster(), traitSet, input, searchRow, cond, allowNulls);
}
/** {@inheritDoc} */
@Override public boolean isEnforcer() {
return true;
}
/** */
@Override public RelWriter explainTerms(RelWriter pw) {
RelWriter writer = super.explainTerms(pw);
return writer
.item("searchRow", searchRow)
.item("condition", cond)
.item("allowNulls", allowNulls);
}
/** {@inheritDoc} */
@Override public RelOptCost computeSelfCost(RelOptPlanner planner, RelMetadataQuery mq) {<FILL_FUNCTION_BODY>}
/** {@inheritDoc} */
@Override public double estimateRowCount(RelMetadataQuery mq) {
return mq.getRowCount(getInput()) * mq.getSelectivity(this, null);
}
/** */
public List<RexNode> searchRow() {
return searchRow;
}
/** */
public ImmutableBitSet keys() {
return keys;
}
/** */
public RexNode condition() {
return cond;
}
/** */
public boolean allowNulls() {
return allowNulls;
}
}
|
double rowCnt = mq.getRowCount(getInput());
double bytesPerRow = getRowType().getFieldCount() * IgniteCost.AVERAGE_FIELD_SIZE;
double totalBytes = rowCnt * bytesPerRow;
double cpuCost = IgniteCost.HASH_LOOKUP_COST;
IgniteCostFactory costFactory = (IgniteCostFactory)planner.getCostFactory();
return costFactory.makeCost(rowCnt, cpuCost, 0, totalBytes, 0);
| 870
| 133
| 1,003
|
<no_super_class>
|
apache_ignite
|
ignite/modules/calcite/src/main/java/org/apache/ignite/internal/processors/query/calcite/rel/IgniteSender.java
|
IgniteSender
|
explainTerms
|
class IgniteSender extends SingleRel implements IgniteRel {
/** */
private final long exchangeId;
/** */
private final long targetFragmentId;
/** */
private final IgniteDistribution distribution;
/**
* Creates a Sender.
* @param cluster Cluster that this relational expression belongs to
* @param traits Traits of this relational expression
* @param input input relational expression
* @param exchangeId Exchange ID.
* @param targetFragmentId Target fragment ID.
*/
public IgniteSender(RelOptCluster cluster, RelTraitSet traits, RelNode input, long exchangeId,
long targetFragmentId, IgniteDistribution distribution) {
super(cluster, traits, input);
assert traitSet.containsIfApplicable(distribution)
: "traits=" + traitSet + ", distribution" + distribution;
assert distribution != RelDistributions.ANY;
this.exchangeId = exchangeId;
this.targetFragmentId = targetFragmentId;
this.distribution = distribution;
}
/**
* @param input Input.
*/
public IgniteSender(RelInput input) {
this(
input.getCluster(),
input.getTraitSet()
.replace(input.getDistribution())
.replace(IgniteConvention.INSTANCE),
input.getInput(),
((Number)input.get("exchangeId")).longValue(),
((Number)input.get("targetFragmentId")).longValue(),
(IgniteDistribution)input.getDistribution());
}
/** */
public long exchangeId() {
return exchangeId;
}
/** */
public long targetFragmentId() {
return targetFragmentId;
}
/** {@inheritDoc} */
@Override public RelNode copy(RelTraitSet traitSet, List<RelNode> inputs) {
return new IgniteSender(getCluster(), traitSet, sole(inputs), exchangeId, targetFragmentId, distribution);
}
/** {@inheritDoc} */
@Override public <T> T accept(IgniteRelVisitor<T> visitor) {
return visitor.visit(this);
}
/** {@inheritDoc} */
@Override public IgniteDistribution distribution() {
return distribution;
}
/**
* @return Node distribution.
*/
public IgniteDistribution sourceDistribution() {
return input.getTraitSet().getTrait(DistributionTraitDef.INSTANCE);
}
/** {@inheritDoc} */
@Override public RelWriter explainTerms(RelWriter pw) {<FILL_FUNCTION_BODY>}
/** {@inheritDoc} */
@Override public Pair<RelTraitSet, List<RelTraitSet>> passThroughTraits(
RelTraitSet required) {
throw new RuntimeException(getClass().getName()
+ "#passThroughTraits() is not implemented.");
}
/** {@inheritDoc} */
@Override public Pair<RelTraitSet, List<RelTraitSet>> deriveTraits(
RelTraitSet childTraits, int childId) {
throw new RuntimeException(getClass().getName()
+ "#deriveTraits() is not implemented.");
}
/** {@inheritDoc} */
@Override public IgniteRel clone(RelOptCluster cluster, List<IgniteRel> inputs) {
return new IgniteSender(cluster, getTraitSet(), sole(inputs), exchangeId(), targetFragmentId(), distribution());
}
}
|
RelWriter writer = super.explainTerms(pw);
if (pw.getDetailLevel() != SqlExplainLevel.ALL_ATTRIBUTES)
return writer;
return writer
.item("exchangeId", exchangeId)
.item("targetFragmentId", targetFragmentId)
.item("distribution", distribution());
| 890
| 89
| 979
|
<no_super_class>
|
apache_ignite
|
ignite/modules/calcite/src/main/java/org/apache/ignite/internal/processors/query/calcite/rel/IgniteTableModify.java
|
IgniteTableModify
|
copy
|
class IgniteTableModify extends TableModify implements IgniteRel {
/**
* Creates a {@code TableModify}.
*
* <p>The UPDATE operation has format like this:
* <blockquote>
* <pre>UPDATE table SET iden1 = exp1, ident2 = exp2 WHERE condition</pre>
* </blockquote>
*
* @param cluster Cluster this relational expression belongs to.
* @param traitSet Traits of this relational expression.
* @param table Target table to modify.
* @param input Sub-query or filter condition.
* @param operation Modify operation (INSERT, UPDATE, DELETE, MERGE).
* @param updateColumnList List of column identifiers to be updated (e.g. ident1, ident2); null if not UPDATE.
* @param sourceExpressionList List of value expressions to be set (e.g. exp1, exp2); null if not UPDATE.
* @param flattened Whether set flattens the input row type.
*/
public IgniteTableModify(
RelOptCluster cluster,
RelTraitSet traitSet,
RelOptTable table,
RelNode input,
Operation operation,
List<String> updateColumnList,
List<RexNode> sourceExpressionList,
boolean flattened
) {
super(cluster, traitSet, table, Commons.context(cluster).catalogReader(),
input, operation, updateColumnList,
sourceExpressionList, flattened);
}
/**
* Creates a {@code TableModify} from serialized {@link RelInput input}.
*
* @param input The input to create node from.
*/
public IgniteTableModify(RelInput input) {
this(
input.getCluster(),
input.getTraitSet().replace(IgniteConvention.INSTANCE),
input.getTable("table"),
input.getInput(),
input.getEnum("operation", Operation.class),
input.getStringList("updateColumnList"),
input.getExpressionList("sourceExpressionList"),
input.getBoolean("flattened", true)
);
}
/** {@inheritDoc} */
@Override public RelNode copy(RelTraitSet traitSet, List<RelNode> inputs) {<FILL_FUNCTION_BODY>}
/** {@inheritDoc} */
@Override public <T> T accept(IgniteRelVisitor<T> visitor) {
return visitor.visit(this);
}
/** {@inheritDoc} */
@Override public IgniteRel clone(RelOptCluster cluster, List<IgniteRel> inputs) {
return new IgniteTableModify(cluster, getTraitSet(), getTable(), sole(inputs),
getOperation(), getUpdateColumnList(), getSourceExpressionList(), isFlattened());
}
}
|
return new IgniteTableModify(
getCluster(),
traitSet,
getTable(),
sole(inputs),
getOperation(),
getUpdateColumnList(),
getSourceExpressionList(),
isFlattened());
| 708
| 63
| 771
|
<no_super_class>
|
apache_ignite
|
ignite/modules/calcite/src/main/java/org/apache/ignite/internal/processors/query/calcite/rel/IgniteTableScan.java
|
IgniteTableScan
|
clone
|
class IgniteTableScan extends ProjectableFilterableTableScan implements SourceAwareIgniteRel {
/** */
private final long sourceId;
/**
* Constructor used for deserialization.
*
* @param input Serialized representation.
*/
public IgniteTableScan(RelInput input) {
super(changeTraits(input, IgniteConvention.INSTANCE));
Object srcIdObj = input.get("sourceId");
if (srcIdObj != null)
sourceId = ((Number)srcIdObj).longValue();
else
sourceId = -1;
}
/**
* Creates a TableScan.
* @param cluster Cluster that this relational expression belongs to
* @param traits Traits of this relational expression
* @param tbl Table definition.
*/
public IgniteTableScan(
RelOptCluster cluster,
RelTraitSet traits,
RelOptTable tbl
) {
this(cluster, traits, tbl, null, null, null);
}
/**
* Creates a TableScan.
* @param cluster Cluster that this relational expression belongs to
* @param traits Traits of this relational expression
* @param tbl Table definition.
* @param proj Projects.
* @param cond Filters.
* @param requiredColunms Participating colunms.
*/
public IgniteTableScan(
RelOptCluster cluster,
RelTraitSet traits,
RelOptTable tbl,
@Nullable List<RexNode> proj,
@Nullable RexNode cond,
@Nullable ImmutableBitSet requiredColunms
) {
this(-1L, cluster, traits, tbl, proj, cond, requiredColunms);
}
/**
* Creates a TableScan.
* @param cluster Cluster that this relational expression belongs to
* @param traits Traits of this relational expression
* @param tbl Table definition.
* @param proj Projects.
* @param cond Filters.
* @param requiredColunms Participating colunms.
*/
private IgniteTableScan(
long sourceId,
RelOptCluster cluster,
RelTraitSet traits,
RelOptTable tbl,
@Nullable List<RexNode> proj,
@Nullable RexNode cond,
@Nullable ImmutableBitSet requiredColunms
) {
super(cluster, traits, ImmutableList.of(), tbl, proj, cond, requiredColunms);
this.sourceId = sourceId;
}
/** */
@Override public long sourceId() {
return sourceId;
}
/** */
@Override protected RelWriter explainTerms0(RelWriter pw) {
return super.explainTerms0(pw)
.itemIf("sourceId", sourceId, sourceId != -1);
}
/** {@inheritDoc} */
@Override public <T> T accept(IgniteRelVisitor<T> visitor) {
return visitor.visit(this);
}
/** {@inheritDoc} */
@Override public IgniteRel clone(long sourceId) {<FILL_FUNCTION_BODY>}
/** {@inheritDoc} */
@Override public IgniteRel clone(RelOptCluster cluster, List<IgniteRel> inputs) {
return new IgniteTableScan(sourceId, cluster, getTraitSet(), getTable(), projects, condition, requiredColumns);
}
}
|
return new IgniteTableScan(sourceId, getCluster(), getTraitSet(), getTable(), projects, condition, requiredColumns);
| 875
| 33
| 908
|
<methods>public RelColumnOrigin columnOriginsByRelLocalRef(int) ,public RelOptCost computeSelfCost(RelOptPlanner, RelMetadataQuery) ,public RexNode condition() ,public RelNode copy(RelTraitSet, List<RelNode>) ,public RelDataType deriveRowType() ,public double estimateRowCount(RelMetadataQuery) ,public RelWriter explainTerms(RelWriter) ,public List<RexNode> projects() ,public RexNode pushUpPredicate() ,public ImmutableBitSet requiredColumns() <variables>protected final non-sealed RexNode condition,protected final non-sealed List<RexNode> projects,protected final non-sealed ImmutableBitSet requiredColumns
|
apache_ignite
|
ignite/modules/calcite/src/main/java/org/apache/ignite/internal/processors/query/calcite/rel/IgniteTableSpool.java
|
IgniteTableSpool
|
computeSelfCost
|
class IgniteTableSpool extends Spool implements IgniteRel {
/** */
public IgniteTableSpool(
RelOptCluster cluster,
RelTraitSet traits,
Spool.Type readType,
RelNode input
) {
super(cluster, traits, input, readType, Type.EAGER);
}
/**
* Constructor used for deserialization.
*
* @param input Serialized representation.
*/
public IgniteTableSpool(RelInput input) {
this(
input.getCluster(),
input.getTraitSet().replace(IgniteConvention.INSTANCE),
input.getEnum("readType", Spool.Type.class),
input.getInput()
);
}
/** {@inheritDoc} */
@Override public <T> T accept(IgniteRelVisitor<T> visitor) {
return visitor.visit(this);
}
/** */
@Override public IgniteRel clone(RelOptCluster cluster, List<IgniteRel> inputs) {
return new IgniteTableSpool(cluster, getTraitSet(), readType, inputs.get(0));
}
/** {@inheritDoc} */
@Override protected Spool copy(RelTraitSet traitSet, RelNode input, Type readType, Type writeType) {
return new IgniteTableSpool(getCluster(), traitSet, readType, input);
}
/** {@inheritDoc} */
@Override public boolean isEnforcer() {
return true;
}
/** {@inheritDoc} */
@Override public RelOptCost computeSelfCost(RelOptPlanner planner, RelMetadataQuery mq) {<FILL_FUNCTION_BODY>}
}
|
double rowCnt = mq.getRowCount(getInput());
double bytesPerRow = getRowType().getFieldCount() * IgniteCost.AVERAGE_FIELD_SIZE;
double totalBytes = rowCnt * bytesPerRow;
double cpuCost = rowCnt * IgniteCost.ROW_PASS_THROUGH_COST;
IgniteCostFactory costFactory = (IgniteCostFactory)planner.getCostFactory();
return costFactory.makeCost(rowCnt, cpuCost, 0, totalBytes, 0);
| 432
| 139
| 571
|
<no_super_class>
|
apache_ignite
|
ignite/modules/calcite/src/main/java/org/apache/ignite/internal/processors/query/calcite/rel/agg/IgniteColocatedAggregateBase.java
|
IgniteColocatedAggregateBase
|
deriveDistribution
|
class IgniteColocatedAggregateBase extends IgniteAggregate implements TraitsAwareIgniteRel {
/** */
protected IgniteColocatedAggregateBase(
RelOptCluster cluster,
RelTraitSet traitSet,
RelNode input,
ImmutableBitSet groupSet,
List<ImmutableBitSet> groupSets,
List<AggregateCall> aggCalls
) {
super(cluster, traitSet, input, groupSet, groupSets, aggCalls);
}
/** */
protected IgniteColocatedAggregateBase(RelInput input) {
super(TraitUtils.changeTraits(input, IgniteConvention.INSTANCE));
}
/** {@inheritDoc} */
@Override public Pair<RelTraitSet, List<RelTraitSet>> passThroughDistribution(
RelTraitSet nodeTraits,
List<RelTraitSet> inTraits
) {
IgniteDistribution distr = TraitUtils.distribution(nodeTraits);
if (distr == IgniteDistributions.single() || distr.function().correlated())
return Pair.of(nodeTraits, Commons.transform(inTraits, t -> t.replace(distr)));
return null;
}
/** {@inheritDoc} */
@Override public List<Pair<RelTraitSet, List<RelTraitSet>>> deriveRewindability(
RelTraitSet nodeTraits,
List<RelTraitSet> inputTraits
) {
return ImmutableList.of(Pair.of(nodeTraits, ImmutableList.of(inputTraits.get(0))));
}
/** {@inheritDoc} */
@Override public List<Pair<RelTraitSet, List<RelTraitSet>>> deriveDistribution(
RelTraitSet nodeTraits,
List<RelTraitSet> inputTraits
) {<FILL_FUNCTION_BODY>}
/** {@inheritDoc} */
@Override public List<Pair<RelTraitSet, List<RelTraitSet>>> deriveCorrelation(
RelTraitSet nodeTraits,
List<RelTraitSet> inTraits
) {
return ImmutableList.of(Pair.of(nodeTraits.replace(TraitUtils.correlation(inTraits.get(0))),
inTraits));
}
}
|
IgniteDistribution inDistribution = TraitUtils.distribution(inputTraits.get(0));
if (inDistribution.satisfies(IgniteDistributions.single()))
return ImmutableList.of(Pair.of(nodeTraits.replace(IgniteDistributions.single()), inputTraits));
if (inDistribution.getType() == RelDistribution.Type.HASH_DISTRIBUTED) {
for (Integer key : inDistribution.getKeys()) {
if (!groupSet.get(key))
return ImmutableList.of();
}
// Group set contains all distribution keys, shift distribution keys according to used columns.
IgniteDistribution outDistribution = inDistribution.apply(Commons.mapping(groupSet, rowType.getFieldCount()));
return ImmutableList.of(Pair.of(nodeTraits.replace(outDistribution), inputTraits));
}
return ImmutableList.of();
| 592
| 235
| 827
|
<methods>public RelOptCost computeSelfCostHash(RelOptPlanner, RelMetadataQuery) ,public RelOptCost computeSelfCostSort(RelOptPlanner, RelMetadataQuery) ,public double estimateMemoryForGroup(RelMetadataQuery) ,public double estimateRowCount(RelMetadataQuery) <variables>
|
apache_ignite
|
ignite/modules/calcite/src/main/java/org/apache/ignite/internal/processors/query/calcite/rel/logical/IgniteLogicalTableScan.java
|
IgniteLogicalTableScan
|
create
|
class IgniteLogicalTableScan extends ProjectableFilterableTableScan {
/** Creates a IgniteLogicalTableScan. */
public static IgniteLogicalTableScan create(
RelOptCluster cluster,
RelTraitSet traits,
RelOptTable tbl,
@Nullable List<RelHint> hints,
@Nullable List<RexNode> proj,
@Nullable RexNode cond,
@Nullable ImmutableBitSet requiredColumns
) {<FILL_FUNCTION_BODY>}
/**
* Creates a IgniteLogicalTableScan.
* @param cluster Cluster that this relational expression belongs to.
* @param traits Traits of this relational expression.
* @param tbl Table definition.
* @param hints Hints.
* @param proj Projects.
* @param cond Filters.
* @param requiredColunms Participating colunms.
*/
private IgniteLogicalTableScan(
RelOptCluster cluster,
RelTraitSet traits,
RelOptTable tbl,
List<RelHint> hints,
@Nullable List<RexNode> proj,
@Nullable RexNode cond,
@Nullable ImmutableBitSet requiredColunms
) {
super(cluster, traits, hints, tbl, proj, cond, requiredColunms);
}
/** {@inheritDoc} */
@Override public IgniteLogicalTableScan withHints(List<RelHint> hints) {
return new IgniteLogicalTableScan(getCluster(), getTraitSet(), getTable(), hints, projects(), condition(),
requiredColumns());
}
}
|
return new IgniteLogicalTableScan(cluster, traits, tbl, hints == null ? ImmutableList.of() : hints, proj, cond,
requiredColumns);
| 406
| 44
| 450
|
<methods>public RelColumnOrigin columnOriginsByRelLocalRef(int) ,public RelOptCost computeSelfCost(RelOptPlanner, RelMetadataQuery) ,public RexNode condition() ,public RelNode copy(RelTraitSet, List<RelNode>) ,public RelDataType deriveRowType() ,public double estimateRowCount(RelMetadataQuery) ,public RelWriter explainTerms(RelWriter) ,public List<RexNode> projects() ,public RexNode pushUpPredicate() ,public ImmutableBitSet requiredColumns() <variables>protected final non-sealed RexNode condition,protected final non-sealed List<RexNode> projects,protected final non-sealed ImmutableBitSet requiredColumns
|
apache_ignite
|
ignite/modules/calcite/src/main/java/org/apache/ignite/internal/processors/query/calcite/rel/set/IgniteIntersect.java
|
IgniteIntersect
|
estimateRowCount
|
class IgniteIntersect extends Intersect implements IgniteSetOp {
/** */
IgniteIntersect(RelOptCluster cluster, RelTraitSet traits, List<RelNode> inputs, boolean all) {
super(cluster, traits, inputs, all);
}
/** */
protected IgniteIntersect(RelInput input) {
super(TraitUtils.changeTraits(input, IgniteConvention.INSTANCE));
}
/** {@inheritDoc} */
@Override public double estimateRowCount(RelMetadataQuery mq) {<FILL_FUNCTION_BODY>}
/** {@inheritDoc} */
@Override public RelOptCost computeSelfCost(RelOptPlanner planner, RelMetadataQuery mq) {
return computeSetOpCost(planner, mq);
}
/** {@inheritDoc} */
@Override public boolean all() {
return all;
}
}
|
final List<RelNode> inputs = getInputs();
double rows = mq.getRowCount(inputs.get(0));
for (int i = 1; i < inputs.size(); i++)
rows = 0.5 * Math.min(rows, mq.getRowCount(inputs.get(i)));
return rows;
| 224
| 90
| 314
|
<no_super_class>
|
apache_ignite
|
ignite/modules/calcite/src/main/java/org/apache/ignite/internal/processors/query/calcite/rule/CorrelatedNestedLoopJoinRule.java
|
CorrelatedNestedLoopJoinRule
|
convert
|
class CorrelatedNestedLoopJoinRule extends AbstractIgniteJoinConverterRule {
/** */
public static final RelOptRule INSTANCE = new CorrelatedNestedLoopJoinRule(1);
/** TODO: https://issues.apache.org/jira/browse/IGNITE-14757 */
public static final RelOptRule INSTANCE_BATCHED = new CorrelatedNestedLoopJoinRule(100);
/** */
private final int batchSize;
/** */
public CorrelatedNestedLoopJoinRule(int batchSize) {
super("CorrelatedNestedLoopJoin", HintDefinition.CNL_JOIN);
this.batchSize = batchSize;
}
/** {@inheritDoc} */
@Override protected PhysicalNode convert(RelOptPlanner planner, RelMetadataQuery mq, LogicalJoin rel) {<FILL_FUNCTION_BODY>}
/** {@inheritDoc} */
@Override public boolean matchesJoin(RelOptRuleCall call) {
LogicalJoin join = call.rel(0);
return supportedJoinType(join.getJoinType());
}
/** */
private static boolean supportedJoinType(JoinRelType type) {
return type == JoinRelType.INNER || type == JoinRelType.LEFT;
}
}
|
final int leftFieldCnt = rel.getLeft().getRowType().getFieldCount();
final RelOptCluster cluster = rel.getCluster();
final RexBuilder rexBuilder = cluster.getRexBuilder();
final RelBuilder relBuilder = relBuilderFactory.create(rel.getCluster(), null);
final Set<CorrelationId> correlationIds = new HashSet<>();
final ArrayList<RexNode> corrVar = new ArrayList<>();
if (corrVar.isEmpty()) {
for (int i = 0; i < batchSize; i++) {
CorrelationId correlationId = cluster.createCorrel();
correlationIds.add(correlationId);
corrVar.add(rexBuilder.makeCorrel(rel.getLeft().getRowType(), correlationId));
}
}
// Generate first condition
final RexNode condition = rel.getCondition().accept(new RexShuttle() {
@Override public RexNode visitInputRef(RexInputRef input) {
int field = input.getIndex();
if (field >= leftFieldCnt)
return rexBuilder.makeInputRef(input.getType(), input.getIndex() - leftFieldCnt);
return rexBuilder.makeFieldAccess(corrVar.get(0), field);
}
});
List<RexNode> conditionList = new ArrayList<>();
conditionList.add(condition);
// Add batchSize-1 other conditions
for (int i = 1; i < batchSize; i++) {
final int corrIdx = i;
final RexNode condition2 = condition.accept(new RexShuttle() {
@Override public RexNode visitCorrelVariable(RexCorrelVariable variable) {
return corrVar.get(corrIdx);
}
});
conditionList.add(condition2);
}
RelTraitSet filterInTraits = rel.getRight().getTraitSet();
// Push a filter with batchSize disjunctions
relBuilder
.push(rel.getRight().copy(filterInTraits, rel.getRight().getInputs()))
.filter(relBuilder.or(conditionList));
RelNode right = relBuilder.build();
JoinRelType joinType = rel.getJoinType();
RelTraitSet outTraits = cluster.traitSetOf(IgniteConvention.INSTANCE);
RelTraitSet leftInTraits = cluster.traitSetOf(IgniteConvention.INSTANCE);
CorrelationTrait corrTrait = CorrelationTrait.correlations(correlationIds);
RelTraitSet rightInTraits = cluster.traitSetOf(IgniteConvention.INSTANCE)
.replace(RewindabilityTrait.REWINDABLE)
.replace(corrTrait);
RelNode left = convert(rel.getLeft(), leftInTraits);
right = convert(right, rightInTraits);
return
new IgniteCorrelatedNestedLoopJoin(
cluster,
outTraits,
left,
right,
rel.getCondition(),
correlationIds,
joinType
);
| 321
| 788
| 1,109
|
<methods>public final boolean matches(RelOptRuleCall) <variables>private static final non-sealed org.apache.ignite.internal.processors.query.calcite.hint.HintDefinition[] ALL_HINTS,private static final EnumMap<org.apache.ignite.internal.processors.query.calcite.hint.HintDefinition,org.apache.ignite.internal.processors.query.calcite.hint.HintDefinition> HINTS,private final non-sealed org.apache.ignite.internal.processors.query.calcite.hint.HintDefinition knownDisableHint,private final non-sealed org.apache.ignite.internal.processors.query.calcite.hint.HintDefinition knownForceHint
|
apache_ignite
|
ignite/modules/calcite/src/main/java/org/apache/ignite/internal/processors/query/calcite/rule/FilterConverterRule.java
|
FilterConverterRule
|
convert
|
class FilterConverterRule extends AbstractIgniteConverterRule<LogicalFilter> {
/** */
public static final RelOptRule INSTANCE = new FilterConverterRule();
/** */
public FilterConverterRule() {
super(LogicalFilter.class, "FilterConverterRule");
}
/** {@inheritDoc} */
@Override protected PhysicalNode convert(RelOptPlanner planner, RelMetadataQuery mq, LogicalFilter rel) {<FILL_FUNCTION_BODY>}
}
|
RelOptCluster cluster = rel.getCluster();
RelTraitSet traits = cluster
.traitSetOf(IgniteConvention.INSTANCE)
.replace(IgniteDistributions.single());
Set<CorrelationId> corrIds = RexUtils.extractCorrelationIds(rel.getCondition());
if (!corrIds.isEmpty()) {
traits = traits
.replace(CorrelationTrait.correlations(corrIds))
.replace(RewindabilityTrait.REWINDABLE);
}
return new IgniteFilter(
cluster,
traits,
convert(rel.getInput(), traits.replace(CorrelationTrait.UNCORRELATED)),
rel.getCondition()
);
| 120
| 187
| 307
|
<methods>public final RelNode convert(RelNode) <variables>
|
apache_ignite
|
ignite/modules/calcite/src/main/java/org/apache/ignite/internal/processors/query/calcite/rule/FilterSpoolMergeToSortedIndexSpoolRule.java
|
FilterSpoolMergeToSortedIndexSpoolRule
|
onMatch
|
class FilterSpoolMergeToSortedIndexSpoolRule extends RelRule<FilterSpoolMergeToSortedIndexSpoolRule.Config> {
/** Instance. */
public static final RelOptRule INSTANCE = Config.DEFAULT.toRule();
/** */
private FilterSpoolMergeToSortedIndexSpoolRule(Config cfg) {
super(cfg);
}
/** {@inheritDoc} */
@Override public void onMatch(RelOptRuleCall call) {<FILL_FUNCTION_BODY>}
/** */
@SuppressWarnings("ClassNameSameAsAncestorName")
@Value.Immutable
public interface Config extends RelRule.Config {
/** */
Config DEFAULT = ImmutableFilterSpoolMergeToSortedIndexSpoolRule.Config.of()
.withDescription("FilterSpoolMergeToSortedIndexSpoolRule")
.withOperandFor(IgniteFilter.class, IgniteTableSpool.class);
/** Defines an operand tree for the given classes. */
default Config withOperandFor(Class<? extends Filter> filterClass, Class<? extends Spool> spoolClass) {
return withOperandSupplier(
o0 -> o0.operand(filterClass)
.oneInput(o1 -> o1.operand(spoolClass)
.anyInputs()
)
)
.as(Config.class);
}
/** {@inheritDoc} */
@Override default FilterSpoolMergeToSortedIndexSpoolRule toRule() {
return new FilterSpoolMergeToSortedIndexSpoolRule(this);
}
}
}
|
final IgniteFilter filter = call.rel(0);
final IgniteTableSpool spool = call.rel(1);
RelOptCluster cluster = spool.getCluster();
RelTraitSet trait = spool.getTraitSet();
CorrelationTrait filterCorr = TraitUtils.correlation(filter);
if (filterCorr.correlated())
trait = trait.replace(filterCorr);
RelNode input = spool.getInput();
RelCollation inCollation = TraitUtils.collation(input);
List<SearchBounds> bounds = RexUtils.buildSortedSearchBounds(
cluster,
inCollation,
filter.getCondition(),
spool.getRowType(),
null
);
if (F.isEmpty(bounds))
return;
RelCollation traitCollation;
RelCollation searchCollation;
if (inCollation == null || inCollation.isDefault()) {
// Create collation by index bounds.
List<Integer> equalsFields = new ArrayList<>(bounds.size());
List<Integer> otherFields = new ArrayList<>(bounds.size());
// First, add all equality filters to collation, then add other fields.
for (int i = 0; i < bounds.size(); i++) {
if (bounds.get(i) != null)
(bounds.get(i).type() == SearchBounds.Type.EXACT ? equalsFields : otherFields).add(i);
}
searchCollation = traitCollation = TraitUtils.createCollation(F.concat(true, equalsFields, otherFields));
}
else {
// Create search collation as a prefix of input collation.
traitCollation = inCollation;
Set<Integer> searchKeys = Ord.zip(bounds).stream()
.filter(v -> v.e != null)
.map(v -> v.i)
.collect(Collectors.toSet());
List<RelFieldCollation> collationFields = inCollation.getFieldCollations().subList(0, searchKeys.size());
assert searchKeys.containsAll(collationFields.stream().map(RelFieldCollation::getFieldIndex)
.collect(Collectors.toSet())) : "Search condition should be a prefix of collation [searchKeys=" +
searchKeys + ", collation=" + inCollation + ']';
searchCollation = RelCollations.of(collationFields);
}
RelNode res = new IgniteSortedIndexSpool(
cluster,
trait.replace(traitCollation),
convert(input, input.getTraitSet().replace(traitCollation)),
searchCollation,
filter.getCondition(),
bounds
);
call.transformTo(res);
| 415
| 713
| 1,128
|
<no_super_class>
|
apache_ignite
|
ignite/modules/calcite/src/main/java/org/apache/ignite/internal/processors/query/calcite/rule/NestedLoopJoinConverterRule.java
|
NestedLoopJoinConverterRule
|
convert
|
class NestedLoopJoinConverterRule extends AbstractIgniteJoinConverterRule {
/** */
public static final RelOptRule INSTANCE = new NestedLoopJoinConverterRule();
/**
* Creates a converter.
*/
public NestedLoopJoinConverterRule() {
super("NestedLoopJoinConverter", HintDefinition.NL_JOIN);
}
/** {@inheritDoc} */
@Override protected PhysicalNode convert(RelOptPlanner planner, RelMetadataQuery mq, LogicalJoin rel) {<FILL_FUNCTION_BODY>}
}
|
RelOptCluster cluster = rel.getCluster();
RelTraitSet outTraits = cluster.traitSetOf(IgniteConvention.INSTANCE);
RelTraitSet leftInTraits = cluster.traitSetOf(IgniteConvention.INSTANCE);
RelTraitSet rightInTraits = cluster.traitSetOf(IgniteConvention.INSTANCE);
RelNode left = convert(rel.getLeft(), leftInTraits);
RelNode right = convert(rel.getRight(), rightInTraits);
return new IgniteNestedLoopJoin(cluster, outTraits, left, right, rel.getCondition(), rel.getVariablesSet(), rel.getJoinType());
| 139
| 168
| 307
|
<methods>public final boolean matches(RelOptRuleCall) <variables>private static final non-sealed org.apache.ignite.internal.processors.query.calcite.hint.HintDefinition[] ALL_HINTS,private static final EnumMap<org.apache.ignite.internal.processors.query.calcite.hint.HintDefinition,org.apache.ignite.internal.processors.query.calcite.hint.HintDefinition> HINTS,private final non-sealed org.apache.ignite.internal.processors.query.calcite.hint.HintDefinition knownDisableHint,private final non-sealed org.apache.ignite.internal.processors.query.calcite.hint.HintDefinition knownForceHint
|
apache_ignite
|
ignite/modules/calcite/src/main/java/org/apache/ignite/internal/processors/query/calcite/rule/SortAggregateConverterRule.java
|
MapReduceSortAggregateConverterRule
|
convert
|
class MapReduceSortAggregateConverterRule extends AbstractIgniteConverterRule<LogicalAggregate> {
/** */
MapReduceSortAggregateConverterRule() {
super(LogicalAggregate.class, "MapReduceSortAggregateConverterRule");
}
/** {@inheritDoc} */
@Override protected PhysicalNode convert(RelOptPlanner planner, RelMetadataQuery mq,
LogicalAggregate agg) {<FILL_FUNCTION_BODY>}
}
|
// Applicable only for GROUP BY or SELECT DISTINCT
if (F.isEmpty(agg.getGroupSet()) || agg.getGroupSets().size() > 1)
return null;
if (HintUtils.isExpandDistinctAggregate(agg))
return null;
RelOptCluster cluster = agg.getCluster();
RelNode input = agg.getInput();
RelCollation collation = TraitUtils.createCollation(agg.getGroupSet().asList());
RelTraitSet inTrait = cluster.traitSetOf(IgniteConvention.INSTANCE).replace(collation);
RelTraitSet outTrait = cluster.traitSetOf(IgniteConvention.INSTANCE).replace(collation);
RelNode map = new IgniteMapSortAggregate(
cluster,
outTrait.replace(IgniteDistributions.random()),
convert(input, inTrait),
agg.getGroupSet(),
agg.getGroupSets(),
agg.getAggCallList(),
collation
);
return new IgniteReduceSortAggregate(
cluster,
outTrait.replace(IgniteDistributions.single()),
convert(map, inTrait.replace(IgniteDistributions.single())),
agg.getGroupSet(),
agg.getGroupSets(),
agg.getAggCallList(),
agg.getRowType(),
collation
);
| 119
| 368
| 487
|
<no_super_class>
|
apache_ignite
|
ignite/modules/calcite/src/main/java/org/apache/ignite/internal/processors/query/calcite/rule/UnionConverterRule.java
|
UnionConverterRule
|
onMatch
|
class UnionConverterRule extends RelRule<UnionConverterRule.Config> {
/** Instance. */
public static final RelOptRule INSTANCE = Config.DEFAULT.toRule();
/** */
public UnionConverterRule(Config cfg) {
super(cfg);
}
/** {@inheritDoc} */
@Override public void onMatch(RelOptRuleCall call) {<FILL_FUNCTION_BODY>}
/**
*
*/
@Value.Immutable
public interface Config extends RelRule.Config {
/** */
UnionConverterRule.Config DEFAULT = ImmutableUnionConverterRule.Config.of()
.withDescription("UnionConverterRule")
.withOperandFor(LogicalUnion.class);
/** Defines an operand tree for the given classes. */
default UnionConverterRule.Config withOperandFor(Class<? extends LogicalUnion> union) {
return withOperandSupplier(
o0 -> o0.operand(union).anyInputs()
)
.as(UnionConverterRule.Config.class);
}
/** {@inheritDoc} */
@Override default UnionConverterRule toRule() {
return new UnionConverterRule(this);
}
}
}
|
final LogicalUnion union = call.rel(0);
RelOptCluster cluster = union.getCluster();
RelTraitSet traits = cluster.traitSetOf(IgniteConvention.INSTANCE);
List<RelNode> inputs = Commons.transform(union.getInputs(), input -> convert(input, traits));
RelNode res = new IgniteUnionAll(cluster, traits, inputs);
if (!union.all) {
final RelBuilder relBuilder = relBuilderFactory.create(union.getCluster(), null);
relBuilder
.push(res)
.aggregate(relBuilder.groupKey(ImmutableBitSet.range(union.getRowType().getFieldCount())));
res = convert(relBuilder.build(), union.getTraitSet());
}
call.transformTo(res);
| 311
| 208
| 519
|
<no_super_class>
|
apache_ignite
|
ignite/modules/calcite/src/main/java/org/apache/ignite/internal/processors/query/calcite/rule/logical/LogicalOrToUnionRule.java
|
LogicalOrToUnionRule
|
onMatch
|
class LogicalOrToUnionRule extends RelRule<LogicalOrToUnionRule.Config> {
/** Rule instance to replace table scans with condition. */
public static final RelOptRule INSTANCE = new LogicalOrToUnionRule(Config.SCAN);
/**
* Constructor.
*
* @param config Rule configuration.
*/
private LogicalOrToUnionRule(Config config) {
super(config);
}
/** {@inheritDoc} */
@Override public void onMatch(RelOptRuleCall call) {<FILL_FUNCTION_BODY>}
/** */
private RexNode getCondition(RelOptRuleCall call) {
final IgniteLogicalTableScan rel = call.rel(0);
return rel.condition();
}
/** */
private RelNode getInput(RelOptRuleCall call) {
return call.rel(0);
}
/**
* @param call Set of appropriate RelNode.
* @param operands Operands fron OR expression.
*
* Compares intersection (currently begining position) of condition and index fields.
* This rule need to be triggered only if appropriate indexes will be found otherwise it`s not applicable.
*/
private boolean idxCollationCheck(RelOptRuleCall call, List<RexNode> operands) {
final IgniteLogicalTableScan scan = call.rel(0);
IgniteTable tbl = scan.getTable().unwrap(IgniteTable.class);
IgniteTypeFactory typeFactory = Commons.typeFactory(scan.getCluster());
int fieldCnt = tbl.getRowType(typeFactory).getFieldCount();
BitSet idxsFirstFields = new BitSet(fieldCnt);
for (IgniteIndex idx : tbl.indexes().values()) {
List<RelFieldCollation> fieldCollations = idx.collation().getFieldCollations();
if (!F.isEmpty(fieldCollations))
idxsFirstFields.set(fieldCollations.get(0).getFieldIndex());
}
Mappings.TargetMapping mapping = scan.requiredColumns() == null ? null :
Commons.inverseMapping(scan.requiredColumns(), fieldCnt);
for (RexNode op : operands) {
BitSet conditionFields = new BitSet(fieldCnt);
new RexShuttle() {
@Override public RexNode visitLocalRef(RexLocalRef inputRef) {
conditionFields.set(mapping == null ? inputRef.getIndex() :
mapping.getSourceOpt(inputRef.getIndex()));
return inputRef;
}
}.apply(op);
if (!conditionFields.intersects(idxsFirstFields))
return false;
}
return true;
}
/** */
private static @Nullable List<RexNode> getOrOperands(RexBuilder rexBuilder, RexNode condition) {
RexNode dnf = RexUtil.toDnf(rexBuilder, condition);
if (!dnf.isA(SqlKind.OR))
return null;
List<RexNode> operands = RelOptUtil.disjunctions(dnf);
if (operands.size() != 2 || RexUtil.find(SqlKind.IS_NULL).anyContain(operands))
return null;
return operands;
}
/** */
private void buildInput(RelBuilder relBldr, RelNode input, RexNode condition) {
IgniteLogicalTableScan scan = (IgniteLogicalTableScan)input;
// Set default traits, real traits will be calculated for physical node.
RelTraitSet trait = scan.getCluster().traitSet();
relBldr.push(IgniteLogicalTableScan.create(
scan.getCluster(),
trait,
scan.getTable(),
scan.getHints(),
scan.projects(),
condition,
scan.requiredColumns()
));
}
/**
* Creates 'UnionAll' for conditions.
*
* @param cluster The cluster UnionAll expression will belongs to.
* @param input Input.
* @param op1 First filter condition.
* @param op2 Second filter condition.
* @return UnionAll expression.
*/
private RelNode createUnionAll(RelOptCluster cluster, RelNode input, RexNode op1, RexNode op2) {
RelBuilder relBldr = relBuilderFactory.create(cluster, null);
buildInput(relBldr, input, op1);
buildInput(relBldr, input, relBldr.and(op2, relBldr.or(relBldr.isNull(op1), relBldr.not(op1))));
return relBldr
.union(true)
.build();
}
/** */
@SuppressWarnings("ClassNameSameAsAncestorName")
@Value.Immutable(singleton = false)
public interface Config extends RuleFactoryConfig<Config> {
/** */
Config SCAN = ImmutableLogicalOrToUnionRule.Config.builder()
.withRuleFactory(LogicalOrToUnionRule::new)
.withDescription("ScanLogicalOrToUnionRule")
.withOperandSupplier(o -> o.operand(IgniteLogicalTableScan.class)
.predicate(scan -> scan.condition() != null)
.noInputs())
.build();
}
}
|
final RelOptCluster cluster = call.rel(0).getCluster();
List<RexNode> operands = getOrOperands(cluster.getRexBuilder(), getCondition(call));
if (operands == null)
return;
if (!idxCollationCheck(call, operands))
return;
RelNode input = getInput(call);
RelNode rel0 = createUnionAll(cluster, input, operands.get(0), operands.get(1));
RelNode rel1 = createUnionAll(cluster, input, operands.get(1), operands.get(0));
call.transformTo(rel0, ImmutableMap.of(rel1, rel0));
| 1,382
| 178
| 1,560
|
<no_super_class>
|
apache_ignite
|
ignite/modules/calcite/src/main/java/org/apache/ignite/internal/processors/query/calcite/sql/IgniteSqlCreateTable.java
|
IgniteSqlCreateTable
|
unparse
|
class IgniteSqlCreateTable extends SqlCreate {
/** */
private final SqlIdentifier name;
/** */
private final @Nullable SqlNodeList columnList;
/** */
private final @Nullable SqlNode qry;
/** */
private final @Nullable SqlNodeList createOptionList;
/** */
private static final SqlOperator OPERATOR = new SqlSpecialOperator("CREATE TABLE", SqlKind.CREATE_TABLE) {
/**
* Required to override this method to correctly copy SQL nodes on SqlShuttle.
*/
@Override public SqlCall createCall(
@Nullable SqlLiteral functionQualifier,
SqlParserPos pos,
@Nullable SqlNode... operands
) {
assert operands != null && operands.length == 4 : operands;
return new IgniteSqlCreateTable(pos, false, (SqlIdentifier)operands[0],
(SqlNodeList)operands[1], operands[2], (SqlNodeList)operands[3]);
}
};
/** Creates a SqlCreateTable. */
public IgniteSqlCreateTable(SqlParserPos pos, boolean ifNotExists, SqlIdentifier name,
@Nullable SqlNodeList columnList, @Nullable SqlNode qry, @Nullable SqlNodeList createOptionList) {
super(OPERATOR, pos, false, ifNotExists);
this.name = Objects.requireNonNull(name, "name");
this.columnList = columnList;
this.qry = qry;
this.createOptionList = createOptionList;
}
/** {@inheritDoc} */
@SuppressWarnings("nullness")
@Override public List<SqlNode> getOperandList() {
return ImmutableNullableList.of(name, columnList, qry, createOptionList);
}
/** {@inheritDoc} */
@Override public void unparse(SqlWriter writer, int leftPrec, int rightPrec) {<FILL_FUNCTION_BODY>}
/**
* @return Name of the table.
*/
public SqlIdentifier name() {
return name;
}
/**
* @return List of the specified columns and constraints.
*/
public SqlNodeList columnList() {
return columnList;
}
/**
* @return Query of "CREATE TABLE AS query" statement.
*/
public SqlNode query() {
return qry;
}
/**
* @return List of the specified options to create table with.
*/
public SqlNodeList createOptionList() {
return createOptionList;
}
/**
* @return Whether the IF NOT EXISTS is specified.
*/
public boolean ifNotExists() {
return ifNotExists;
}
}
|
writer.keyword("CREATE");
writer.keyword("TABLE");
if (ifNotExists)
writer.keyword("IF NOT EXISTS");
name.unparse(writer, leftPrec, rightPrec);
if (columnList != null) {
SqlWriter.Frame frame = writer.startList("(", ")");
for (SqlNode c : columnList) {
writer.sep(",");
c.unparse(writer, 0, 0);
}
writer.endList(frame);
}
if (createOptionList != null) {
writer.keyword("WITH");
createOptionList.unparse(writer, 0, 0);
}
if (qry != null) {
writer.keyword("AS");
writer.newlineAndIndent();
qry.unparse(writer, 0, 0);
}
| 681
| 223
| 904
|
<no_super_class>
|
apache_ignite
|
ignite/modules/calcite/src/main/java/org/apache/ignite/internal/processors/query/calcite/sql/generated/ParseException.java
|
ParseException
|
getMessage
|
class ParseException extends Exception {
/**
* This constructor is used by the method "generateParseException"
* in the generated parser. Calling this constructor generates
* a new object of this type with the fields "currentToken",
* "expectedTokenSequences", and "tokenImage" set. The boolean
* flag "specialConstructor" is also set to true to indicate that
* this constructor was used to create this object.
* This constructor calls its super class with the empty string
* to force the "toString" method of parent class "Throwable" to
* print the error message in the form:
* ParseException: <result of getMessage>
*/
public ParseException(Token currentTokenVal,
int[][] expectedTokenSequencesVal,
String[] tokenImageVal
)
{
super("");
specialConstructor = true;
currentToken = currentTokenVal;
expectedTokenSequences = expectedTokenSequencesVal;
tokenImage = tokenImageVal;
}
/**
* The following constructors are for use by you for whatever
* purpose you can think of. Constructing the exception in this
* manner makes the exception behave in the normal way - i.e., as
* documented in the class "Throwable". The fields "errorToken",
* "expectedTokenSequences", and "tokenImage" do not contain
* relevant information. The JavaCC generated code does not use
* these constructors.
*/
public ParseException() {
super();
specialConstructor = false;
}
public ParseException(String message) {
super(message);
specialConstructor = false;
}
/**
* This variable determines which constructor was used to create
* this object and thereby affects the semantics of the
* "getMessage" method (see below).
*/
protected boolean specialConstructor;
/**
* This is the last token that has been consumed successfully. If
* this object has been created due to a parse error, the token
* followng this token will (therefore) be the first error token.
*/
public Token currentToken;
/**
* Each entry in this array is an array of integers. Each array
* of integers represents a sequence of tokens (by their ordinal
* values) that is expected at this point of the parse.
*/
public int[][] expectedTokenSequences;
/**
* This is a reference to the "tokenImage" array of the generated
* parser within which the parse error occurred. This array is
* defined in the generated ...Constants interface.
*/
public String[] tokenImage;
/**
* This method has the standard behavior when this object has been
* created using the standard constructors. Otherwise, it uses
* "currentToken" and "expectedTokenSequences" to generate a parse
* error message and returns it. If this object has been created
* due to a parse error, and you do not catch it (it gets thrown
* from the parser), then this method is called during the printing
* of the final stack trace, and hence the correct error message
* gets displayed.
*/
public String getMessage() {<FILL_FUNCTION_BODY>}
/**
* The end of line string for this machine.
*/
protected String eol = System.getProperty("line.separator", "\n");
/**
* Used to convert raw characters to their escaped version
* when these raw version cannot be used as part of an ASCII
* string literal.
*/
protected String add_escapes(String str) {
StringBuffer retval = new StringBuffer();
char ch;
for (int i = 0; i < str.length(); i++) {
switch (str.charAt(i))
{
case 0 :
continue;
case '\b':
retval.append("\\b");
continue;
case '\t':
retval.append("\\t");
continue;
case '\n':
retval.append("\\n");
continue;
case '\f':
retval.append("\\f");
continue;
case '\r':
retval.append("\\r");
continue;
case '\"':
retval.append("\\\"");
continue;
case '\'':
retval.append("\\\'");
continue;
case '\\':
retval.append("\\\\");
continue;
default:
if ((ch = str.charAt(i)) < 0x20 || ch > 0x7e) {
String s = "0000" + Integer.toString(ch, 16);
retval.append("\\u" + s.substring(s.length() - 4, s.length()));
} else {
retval.append(ch);
}
continue;
}
}
return retval.toString();
}
}
|
if (!specialConstructor) {
return super.getMessage();
}
StringBuffer expected = new StringBuffer();
int maxSize = 0;
for (int i = 0; i < expectedTokenSequences.length; i++) {
if (maxSize < expectedTokenSequences[i].length) {
maxSize = expectedTokenSequences[i].length;
}
for (int j = 0; j < expectedTokenSequences[i].length; j++) {
expected.append(tokenImage[expectedTokenSequences[i][j]]).append(" ");
}
if (expectedTokenSequences[i][expectedTokenSequences[i].length - 1] != 0) {
expected.append("...");
}
expected.append(eol).append(" ");
}
String retval = "Encountered \"";
Token tok = currentToken.next;
for (int i = 0; i < maxSize; i++) {
if (i != 0) retval += " ";
if (tok.kind == 0) {
retval += tokenImage[0];
break;
}
retval += add_escapes(tok.image);
tok = tok.next;
}
retval += "\" at line " + currentToken.next.beginLine + ", column " + currentToken.next.beginColumn;
retval += "." + eol;
if (expectedTokenSequences.length == 1) {
retval += "Was expecting:" + eol + " ";
} else {
retval += "Was expecting one of:" + eol + " ";
}
retval += expected.toString();
return retval;
| 1,234
| 428
| 1,662
|
<methods>public void <init>() ,public void <init>(java.lang.String) ,public void <init>(java.lang.Throwable) ,public void <init>(java.lang.String, java.lang.Throwable) <variables>static final long serialVersionUID
|
apache_ignite
|
ignite/modules/calcite/src/main/java/org/apache/ignite/internal/processors/query/calcite/sql/generated/TokenMgrError.java
|
TokenMgrError
|
LexicalError
|
class TokenMgrError extends Error
{
/*
* Ordinals for various reasons why an Error of this type can be thrown.
*/
/**
* Lexical error occured.
*/
static final int LEXICAL_ERROR = 0;
/**
* An attempt wass made to create a second instance of a static token manager.
*/
static final int STATIC_LEXER_ERROR = 1;
/**
* Tried to change to an invalid lexical state.
*/
static final int INVALID_LEXICAL_STATE = 2;
/**
* Detected (and bailed out of) an infinite loop in the token manager.
*/
static final int LOOP_DETECTED = 3;
/**
* Indicates the reason why the exception is thrown. It will have
* one of the above 4 values.
*/
int errorCode;
/**
* Replaces unprintable characters by their espaced (or unicode escaped)
* equivalents in the given string
*/
protected static final String addEscapes(String str) {
StringBuffer retval = new StringBuffer();
char ch;
for (int i = 0; i < str.length(); i++) {
switch (str.charAt(i))
{
case 0 :
continue;
case '\b':
retval.append("\\b");
continue;
case '\t':
retval.append("\\t");
continue;
case '\n':
retval.append("\\n");
continue;
case '\f':
retval.append("\\f");
continue;
case '\r':
retval.append("\\r");
continue;
case '\"':
retval.append("\\\"");
continue;
case '\'':
retval.append("\\\'");
continue;
case '\\':
retval.append("\\\\");
continue;
default:
if ((ch = str.charAt(i)) < 0x20 || ch > 0x7e) {
String s = "0000" + Integer.toString(ch, 16);
retval.append("\\u" + s.substring(s.length() - 4, s.length()));
} else {
retval.append(ch);
}
continue;
}
}
return retval.toString();
}
/**
* Returns a detailed message for the Error when it is thrown by the
* token manager to indicate a lexical error.
* Parameters :
* EOFSeen : indicates if EOF caused the lexicl error
* curLexState : lexical state in which this error occured
* errorLine : line number when the error occured
* errorColumn : column number when the error occured
* errorAfter : prefix that was seen before this error occured
* curchar : the offending character
* Note: You can customize the lexical error message by modifying this method.
*/
protected static String LexicalError(boolean EOFSeen, int lexState, int errorLine, int errorColumn, String errorAfter, char curChar) {<FILL_FUNCTION_BODY>}
/**
* You can also modify the body of this method to customize your error messages.
* For example, cases like LOOP_DETECTED and INVALID_LEXICAL_STATE are not
* of end-users concern, so you can return something like :
*
* "Internal Error : Please file a bug report .... "
*
* from this method for such cases in the release version of your parser.
*/
public String getMessage() {
return super.getMessage();
}
/*
* Constructors of various flavors follow.
*/
public TokenMgrError() {
}
public TokenMgrError(String message, int reason) {
super(message);
errorCode = reason;
}
public TokenMgrError(boolean EOFSeen, int lexState, int errorLine, int errorColumn, String errorAfter, char curChar, int reason) {
this(LexicalError(EOFSeen, lexState, errorLine, errorColumn, errorAfter, curChar), reason);
}
}
|
return("Lexical error at line " +
errorLine + ", column " +
errorColumn + ". Encountered: " +
(EOFSeen ? "<EOF> " : ("\"" + addEscapes(String.valueOf(curChar)) + "\"") + " (" + (int)curChar + "), ") +
"after : \"" + addEscapes(errorAfter) + "\"");
| 1,090
| 104
| 1,194
|
<methods>public void <init>() ,public void <init>(java.lang.String) ,public void <init>(java.lang.Throwable) ,public void <init>(java.lang.String, java.lang.Throwable) <variables>static final long serialVersionUID
|
apache_ignite
|
ignite/modules/calcite/src/main/java/org/apache/ignite/internal/processors/query/calcite/trait/DistributionFunction.java
|
RandomDistribution
|
destination
|
class RandomDistribution extends DistributionFunction {
/** */
public static final DistributionFunction INSTANCE = new RandomDistribution();
/** {@inheritDoc} */
@Override public RelDistribution.Type type() {
return RelDistribution.Type.RANDOM_DISTRIBUTED;
}
/** {@inheritDoc} */
@Override public <Row> Destination<Row> destination(ExecutionContext<Row> ctx, AffinityService affinityService,
ColocationGroup m, ImmutableIntList k) {<FILL_FUNCTION_BODY>}
}
|
assert m != null && !F.isEmpty(m.nodeIds());
return new RandomNode<>(m.nodeIds());
| 143
| 35
| 178
|
<no_super_class>
|
apache_ignite
|
ignite/modules/calcite/src/main/java/org/apache/ignite/internal/processors/query/calcite/trait/RewindabilityTrait.java
|
RewindabilityTrait
|
satisfies
|
class RewindabilityTrait implements RelMultipleTrait {
/** */
public static final RewindabilityTrait ONE_WAY = canonize(new RewindabilityTrait(false));
/** */
public static final RewindabilityTrait REWINDABLE = canonize(new RewindabilityTrait(true));
/** */
private final boolean rewindable;
/** */
private RewindabilityTrait(boolean rewindable) {
this.rewindable = rewindable;
}
/** */
public boolean rewindable() {
return rewindable;
}
/** {@inheritDoc} */
@Override public boolean isTop() {
return !rewindable();
}
/** {@inheritDoc} */
@Override public int compareTo(@NotNull RelMultipleTrait o) {
RewindabilityTrait that = (RewindabilityTrait)o;
return Boolean.compare(that.rewindable, rewindable);
}
/** {@inheritDoc} */
@Override public boolean equals(Object o) {
if (!(o instanceof RewindabilityTrait))
return false;
return compareTo((RewindabilityTrait)o) == 0;
}
/** {@inheritDoc} */
@Override public int hashCode() {
return (rewindable ? 1 : 0);
}
/** {@inheritDoc} */
@Override public String toString() {
return rewindable ? "rewindable" : "one-way";
}
/** {@inheritDoc} */
@Override public RelTraitDef<RewindabilityTrait> getTraitDef() {
return RewindabilityTraitDef.INSTANCE;
}
/** {@inheritDoc} */
@Override public boolean satisfies(RelTrait trait) {<FILL_FUNCTION_BODY>}
/** {@inheritDoc} */
@Override public void register(RelOptPlanner planner) {
// no-op
}
/** */
private static RewindabilityTrait canonize(RewindabilityTrait trait) {
return RewindabilityTraitDef.INSTANCE.canonize(trait);
}
}
|
if (this == trait)
return true;
if (!(trait instanceof RewindabilityTrait))
return false;
RewindabilityTrait trait0 = (RewindabilityTrait)trait;
return !trait0.rewindable() || rewindable();
| 567
| 80
| 647
|
<no_super_class>
|
apache_ignite
|
ignite/modules/calcite/src/main/java/org/apache/ignite/internal/processors/query/calcite/util/ListFieldsQueryCursor.java
|
ListFieldsQueryCursor
|
getAll
|
class ListFieldsQueryCursor<Row> implements FieldsQueryCursor<List<?>>, QueryCursorEx<List<?>> {
/** */
private final Iterator<List<?>> it;
/** */
private final List<GridQueryFieldMetadata> fieldsMeta;
/** */
private final boolean isQry;
/**
* @param plan Query plan.
* @param it Iterator.
* @param ectx Row converter.
*/
public ListFieldsQueryCursor(MultiStepPlan plan, Iterator<List<?>> it, ExecutionContext<Row> ectx) {
FieldsMetadata metadata0 = plan.fieldsMetadata();
assert metadata0 != null;
fieldsMeta = metadata0.queryFieldsMetadata(ectx.getTypeFactory());
isQry = plan.type() == QueryPlan.Type.QUERY;
this.it = it;
}
/** {@inheritDoc} */
@NotNull @Override public Iterator<List<?>> iterator() {
return it;
}
/** {@inheritDoc} */
@Override public List<List<?>> getAll() {
ArrayList<List<?>> res = new ArrayList<>();
try {
getAll(res::add);
}
catch (IgniteCheckedException e) {
throw U.convertException(e);
}
return res;
}
/** {@inheritDoc} */
@Override public void getAll(Consumer<List<?>> c) throws IgniteCheckedException {<FILL_FUNCTION_BODY>}
/** {@inheritDoc} */
@Override public List<GridQueryFieldMetadata> fieldsMeta() {
return fieldsMeta;
}
/** {@inheritDoc} */
@Override public String getFieldName(int idx) {
return fieldsMeta.get(idx).fieldName();
}
/** {@inheritDoc} */
@Override public int getColumnsCount() {
return fieldsMeta.size();
}
/** {@inheritDoc} */
@Override public boolean isQuery() {
return isQry;
}
/** {@inheritDoc} */
@Override public void close() {
Commons.closeQuiet(it);
}
}
|
try {
while (it.hasNext())
c.consume(it.next());
}
finally {
close();
}
| 553
| 41
| 594
|
<no_super_class>
|
apache_ignite
|
ignite/modules/control-utility/src/main/java/org/apache/ignite/internal/commandline/CliCommandInvoker.java
|
CliCommandInvoker
|
client
|
class CliCommandInvoker<A extends IgniteDataTransferObject> extends CommandInvoker<A> implements AutoCloseable {
/** Client configuration. */
private GridClientConfiguration clientCfg;
/** Client. */
private GridClient client;
/** @param cmd Command to execute. */
public CliCommandInvoker(Command<A, ?> cmd, A arg, GridClientConfiguration clientCfg) {
super(cmd, arg, null);
this.clientCfg = clientCfg;
}
/**
* @return Message text to show user for. {@code null} means that confirmantion is not required.
*/
public String confirmationPrompt() {
return cmd.confirmationPrompt(arg);
}
/** */
public <R> R invokeBeforeNodeStart(Consumer<String> printer) throws Exception {
try (GridClientBeforeNodeStart client = startClientBeforeNodeStart(clientCfg)) {
return ((BeforeNodeStartCommand<A, R>)cmd).execute(client, arg, printer);
}
catch (GridClientDisconnectedException e) {
throw new GridClientException(e.getCause());
}
}
/** {@inheritDoc} */
@Override protected GridClientNode defaultNode() throws GridClientException {
GridClientNode node;
// Prefer node from connect string.
final String cfgAddr = clientCfg.getServers().iterator().next();
String[] parts = cfgAddr.split(":");
if (DFLT_HOST.equals(parts[0])) {
InetAddress addr;
try {
addr = IgniteUtils.getLocalHost();
}
catch (IOException e) {
throw new GridClientException("Can't get localhost name.", e);
}
if (addr.isLoopbackAddress())
throw new GridClientException("Can't find localhost name.");
String origAddr = addr.getHostName() + ":" + parts[1];
node = listHosts(client()).filter(tuple -> origAddr.equals(tuple.get2())).findFirst().map(IgniteBiTuple::get1).orElse(null);
if (node == null)
node = listHostsByClientNode(client()).filter(tuple -> tuple.get2().size() == 1 && cfgAddr.equals(tuple.get2().get(0))).
findFirst().map(IgniteBiTuple::get1).orElse(null);
}
else
node = listHosts(client()).filter(tuple -> cfgAddr.equals(tuple.get2())).findFirst().map(IgniteBiTuple::get1).orElse(null);
// Otherwise choose random node.
if (node == null)
node = balancedNode(client().compute());
return node;
}
/** {@inheritDoc} */
@Override protected GridClient client() throws GridClientException {<FILL_FUNCTION_BODY>}
/** {@inheritDoc} */
@Override public void close() {
if (client != null)
client.close();
}
/**
* Method to create thin client for communication with node before it starts.
* If node has already started, there will be an error.
*
* @param clientCfg Thin client configuration.
* @return Grid thin client instance which is already connected to node before it starts.
* @throws Exception If error occur.
*/
private static GridClientBeforeNodeStart startClientBeforeNodeStart(
GridClientConfiguration clientCfg
) throws Exception {
GridClientBeforeNodeStart client = GridClientFactory.startBeforeNodeStart(clientCfg);
// If connection is unsuccessful, fail before doing any operations:
if (!client.connected()) {
GridClientException lastErr = client.checkLastError();
try {
client.close();
}
catch (Throwable e) {
lastErr.addSuppressed(e);
}
throw lastErr;
}
return client;
}
/**
* @param client Client.
* @return List of hosts.
*/
private static Stream<IgniteBiTuple<GridClientNode, String>> listHosts(GridClient client) throws GridClientException {
return client.compute()
.nodes(GridClientNode::connectable)
.stream()
.flatMap(node -> Stream.concat(
node.tcpAddresses() == null ? Stream.empty() : node.tcpAddresses().stream(),
node.tcpHostNames() == null ? Stream.empty() : node.tcpHostNames().stream()
).map(addr -> new IgniteBiTuple<>(node, addr + ":" + node.tcpPort())));
}
/**
* @param client Client.
* @return List of hosts.
*/
private static Stream<IgniteBiTuple<GridClientNode, List<String>>> listHostsByClientNode(
GridClient client
) throws GridClientException {
return client.compute().nodes(GridClientNode::connectable).stream()
.map(
node -> new IgniteBiTuple<>(
node,
Stream.concat(
node.tcpAddresses() == null ? Stream.empty() : node.tcpAddresses().stream(),
node.tcpHostNames() == null ? Stream.empty() : node.tcpHostNames().stream()
)
.map(addr -> addr + ":" + node.tcpPort()).collect(Collectors.toList())
)
);
}
/**
* @param compute instance
* @return balanced node
*/
private static GridClientNode balancedNode(GridClientCompute compute) throws GridClientException {
Collection<GridClientNode> nodes = compute.nodes(GridClientNode::connectable);
if (F.isEmpty(nodes))
throw new GridClientDisconnectedException("Connectable node not found", null);
return compute.balancer().balancedNode(nodes);
}
/** */
public void clientConfiguration(GridClientConfiguration clientCfg) {
this.clientCfg = clientCfg;
}
/** */
public GridClientConfiguration clientConfiguration() {
return clientCfg;
}
}
|
if (client != null && client.connected())
return client;
client = GridClientFactory.start(clientCfg);
// If connection is unsuccessful, fail before doing any operations:
if (!client.connected()) {
GridClientException lastErr = client.checkLastError();
try {
client.close();
}
catch (Throwable e) {
lastErr.addSuppressed(e);
}
throw lastErr;
}
return client;
| 1,547
| 129
| 1,676
|
<methods>public void <init>(Command<A,?>, A, org.apache.ignite.internal.IgniteEx) ,public R invoke(Consumer<java.lang.String>, boolean) throws org.apache.ignite.internal.client.GridClientException,public boolean prepare(Consumer<java.lang.String>) throws org.apache.ignite.internal.client.GridClientException<variables>protected final non-sealed A arg,protected final non-sealed Command<A,?> cmd,private final non-sealed org.apache.ignite.internal.IgniteEx ignite
|
apache_ignite
|
ignite/modules/control-utility/src/main/java/org/apache/ignite/internal/commandline/argument/parser/CLIArgument.java
|
CLIArgument
|
optionalArg
|
class CLIArgument<T> {
/** */
private final BiConsumer<String, T> EMPTY = (name, val) -> {};
/** */
private final String name;
/** */
private final String usage;
/** */
private final boolean isOptional;
/** */
private final Class<T> type;
/** */
private final Function<CLIArgumentParser, T> dfltValSupplier;
/** */
private final BiConsumer<String, T> validator;
/** */
public static <T> CLIArgument<T> optionalArg(String name, String usage, Class<T> type) {
return new CLIArgument<>(name, usage, true, type, null, null);
}
/** */
public static <T> CLIArgument<T> optionalArg(String name, String usage, Class<T> type, Supplier<T> dfltValSupplier) {<FILL_FUNCTION_BODY>}
/** */
public static <T> CLIArgument<T> optionalArg(
String name,
String usage,
Class<T> type,
Function<CLIArgumentParser, T> dfltValSupplier,
BiConsumer<String, T> validator
) {
return new CLIArgument<>(name, usage, true, type, dfltValSupplier, validator);
}
/** */
public static <T> CLIArgument<T> mandatoryArg(String name, String usage, Class<T> type) {
return new CLIArgument<>(name, usage, false, type, null, null);
}
/** */
public CLIArgument(
String name,
String usage,
boolean isOptional,
Class<T> type,
Function<CLIArgumentParser, T> dfltValSupplier,
BiConsumer<String, T> validator
) {
this.name = name;
this.usage = usage;
this.isOptional = isOptional;
this.type = type;
this.dfltValSupplier = dfltValSupplier == null
? (type.equals(Boolean.class) ? p -> (T)Boolean.FALSE : p -> null)
: dfltValSupplier;
this.validator = validator;
}
/** */
public String name() {
return name;
}
/** */
public String usage() {
return usage;
}
/** */
public boolean optional() {
return isOptional;
}
/** */
public Class<T> type() {
return type;
}
/** */
public Function<CLIArgumentParser, T> defaultValueSupplier() {
return dfltValSupplier;
}
/** */
public BiConsumer<String, T> validator() {
return validator == null ? EMPTY : validator;
}
}
|
return new CLIArgument<>(name, usage, true, type, p -> dfltValSupplier.get(), null);
| 740
| 34
| 774
|
<no_super_class>
|
apache_ignite
|
ignite/modules/core/src/main/java/org/apache/ignite/IgniteJdbcThinDriver.java
|
IgniteJdbcThinDriver
|
getPropertyInfo
|
class IgniteJdbcThinDriver implements Driver {
/** Driver instance. */
private static final Driver INSTANCE = new IgniteJdbcThinDriver();
/** Registered flag. */
private static volatile boolean registered;
static {
register();
}
/** Major version. */
private static final int MAJOR_VER = IgniteVersionUtils.VER.major();
/** Minor version. */
private static final int MINOR_VER = IgniteVersionUtils.VER.minor();
/** {@inheritDoc} */
@Override public Connection connect(String url, Properties props) throws SQLException {
if (!acceptsURL(url))
return null;
ConnectionPropertiesImpl connProps = new ConnectionPropertiesImpl();
connProps.init(url, props);
return new JdbcThinConnection(connProps);
}
/** {@inheritDoc} */
@Override public boolean acceptsURL(String url) throws SQLException {
return url.startsWith(JdbcThinUtils.URL_PREFIX);
}
/** {@inheritDoc} */
@Override public DriverPropertyInfo[] getPropertyInfo(String url, Properties info) throws SQLException {<FILL_FUNCTION_BODY>}
/** {@inheritDoc} */
@Override public int getMajorVersion() {
return MAJOR_VER;
}
/** {@inheritDoc} */
@Override public int getMinorVersion() {
return MINOR_VER;
}
/** {@inheritDoc} */
@Override public boolean jdbcCompliant() {
return false;
}
/** {@inheritDoc} */
@Override public Logger getParentLogger() throws SQLFeatureNotSupportedException {
throw new SQLFeatureNotSupportedException("java.util.logging is not used.");
}
/**
* @return Driver instance.
*/
public static synchronized Driver register() {
try {
if (!registered) {
DriverManager.registerDriver(INSTANCE);
registered = true;
}
}
catch (SQLException e) {
throw new RuntimeException("Failed to register Ignite JDBC thin driver.", e);
}
return INSTANCE;
}
}
|
ConnectionPropertiesImpl connProps = new ConnectionPropertiesImpl();
connProps.init(url, info);
return connProps.getDriverPropertyInfo();
| 555
| 40
| 595
|
<no_super_class>
|
apache_ignite
|
ignite/modules/core/src/main/java/org/apache/ignite/binary/BinaryBasicNameMapper.java
|
BinaryBasicNameMapper
|
simplifyDotNetGenerics
|
class BinaryBasicNameMapper implements BinaryNameMapper {
/** Default use simple name flag setting. */
public static final boolean DFLT_SIMPLE_NAME = false;
/** */
private boolean isSimpleName = DFLT_SIMPLE_NAME;
/**
* Default constructor.
*/
public BinaryBasicNameMapper() {
// No-op.
}
/**
* @param isSimpleName Whether to use simple (no package) name of class or not.
* <p>
* Defaults to {@link #DFLT_SIMPLE_NAME}.
*/
public BinaryBasicNameMapper(boolean isSimpleName) {
this.isSimpleName = isSimpleName;
}
/**
* Gets whether to use simple name of class or not.
*
* @return Whether to use simple name of class or not.
*/
public boolean isSimpleName() {
return isSimpleName;
}
/**
* Sets whether to use simple name of class or not.
*
* @param isSimpleName Whether to use simple name of class or not.
* @return {@code this} for chaining.
*/
public BinaryBasicNameMapper setSimpleName(boolean isSimpleName) {
this.isSimpleName = isSimpleName;
return this;
}
/** {@inheritDoc} */
@Override public String typeName(String clsName) {
A.notNull(clsName, "clsName");
return isSimpleName ? simpleName(clsName) : clsName;
}
/** {@inheritDoc} */
@Override public String fieldName(String fieldName) {
A.notNull(fieldName, "fieldName");
return fieldName;
}
/**
* @param clsName Class name.
* @return Type name.
*/
private static String simpleName(String clsName) {
assert clsName != null;
clsName = simplifyDotNetGenerics(clsName);
int idx = clsName.lastIndexOf('$');
if (idx == clsName.length() - 1)
// This is a regular (not inner) class name that ends with '$'. Common use case for Scala classes.
idx = -1;
else if (idx >= 0) {
String typeName = clsName.substring(idx + 1);
try {
Integer.parseInt(typeName);
// This is an anonymous class. Don't cut off enclosing class name for it.
idx = -1;
}
catch (NumberFormatException ignore) {
// This is a lambda class.
if (clsName.indexOf("$$Lambda$") > 0)
idx = -1;
else
return typeName;
}
}
if (idx < 0)
idx = clsName.lastIndexOf('+'); // .NET inner class.
if (idx < 0)
idx = clsName.lastIndexOf('.');
return idx >= 0 ? clsName.substring(idx + 1) : clsName;
}
/**
* Converts .NET generic type arguments to a simple form (without namespaces and outer classes classes).
*
* @param clsName Class name.
* @return Simplified class name.
*/
private static String simplifyDotNetGenerics(String clsName) {<FILL_FUNCTION_BODY>}
/** {@inheritDoc} */
@Override public boolean equals(Object o) {
if (this == o)
return true;
if (!(o instanceof BinaryBasicNameMapper))
return false;
BinaryBasicNameMapper mapper = (BinaryBasicNameMapper)o;
if (isSimpleName != mapper.isSimpleName)
return false;
return true;
}
/** {@inheritDoc} */
@Override public int hashCode() {
return (isSimpleName ? 1 : 0);
}
/** {@inheritDoc} */
@Override public String toString() {
return "BinaryBaseNameMapper [isSimpleName=" + isSimpleName + ']';
}
}
|
// .NET generic part starts with [[ (not valid for Java class name). Clean up every generic part recursively.
// Example: Foo.Bar`1[[Baz.Qux`2[[System.String],[System.Int32]]]]
int genericIdx = clsName.indexOf("[[");
if (genericIdx > 0)
clsName = clsName.substring(0, genericIdx + 2) + simpleName(clsName.substring(genericIdx + 2));
genericIdx = clsName.indexOf("],[", genericIdx);
if (genericIdx > 0)
clsName = clsName.substring(0, genericIdx + 3) + simpleName(clsName.substring(genericIdx + 3));
return clsName;
| 1,057
| 200
| 1,257
|
<no_super_class>
|
apache_ignite
|
ignite/modules/core/src/main/java/org/apache/ignite/cache/CacheKeyConfiguration.java
|
CacheKeyConfiguration
|
equals
|
class CacheKeyConfiguration implements Serializable {
/** */
private static final long serialVersionUID = 0L;
/** Type name. */
private String typeName;
/** Affinity key field name. */
private String affKeyFieldName;
/**
* Creates an empty cache key configuration that should be populated via setters.
*/
public CacheKeyConfiguration() {
// Convenience no-op constructor.
}
/**
* @param keyCls Key class.
*/
public CacheKeyConfiguration(Class keyCls) {
typeName = keyCls.getName();
for (; keyCls != Object.class && keyCls != null; keyCls = keyCls.getSuperclass()) {
for (Field f : keyCls.getDeclaredFields()) {
if (f.getAnnotation(AffinityKeyMapped.class) != null) {
affKeyFieldName = f.getName();
return;
}
}
}
}
/**
* Creates cache key configuration with given type name and affinity field name.
*
* @param typeName Type name.
* @param affKeyFieldName Affinity field name.
*/
public CacheKeyConfiguration(String typeName, String affKeyFieldName) {
this.typeName = typeName;
this.affKeyFieldName = affKeyFieldName;
}
/**
* Sets type name for which affinity field name is being defined.
*
* @return Type name.
*/
public String getTypeName() {
return typeName;
}
/**
* @param typeName Type name for which affinity field name is being defined.
* @return {@code this} for chaining.
*/
public CacheKeyConfiguration setTypeName(String typeName) {
this.typeName = typeName;
return this;
}
/**
* Gets affinity key field name.
*
* @return Affinity key field name.
*/
public String getAffinityKeyFieldName() {
return affKeyFieldName;
}
/**
* Sets affinity key field name.
*
* @param affKeyFieldName Affinity key field name.
* @return {@code this} for chaining.
*/
public CacheKeyConfiguration setAffinityKeyFieldName(String affKeyFieldName) {
this.affKeyFieldName = affKeyFieldName;
return this;
}
/** {@inheritDoc} */
@Override public boolean equals(Object o) {<FILL_FUNCTION_BODY>}
/** {@inheritDoc} */
@Override public int hashCode() {
int result = typeName != null ? typeName.hashCode() : 0;
result = 31 * result + (affKeyFieldName != null ? affKeyFieldName.hashCode() : 0);
return result;
}
/** {@inheritDoc} */
@Override public String toString() {
return S.toString(CacheKeyConfiguration.class, this);
}
}
|
if (this == o)
return true;
if (o == null || getClass() != o.getClass())
return false;
CacheKeyConfiguration that = (CacheKeyConfiguration)o;
if (!Objects.equals(typeName, that.typeName))
return false;
return Objects.equals(affKeyFieldName, that.affKeyFieldName);
| 774
| 98
| 872
|
<no_super_class>
|
apache_ignite
|
ignite/modules/core/src/main/java/org/apache/ignite/cache/CachingProvider.java
|
CachingProvider
|
removeClosedManager
|
class CachingProvider implements javax.cache.spi.CachingProvider {
/** */
private static final URI DEFAULT_URI;
/**
*
*/
static {
URI uri = null;
try {
URL dfltCfgURL = U.resolveIgniteUrl(IgnitionEx.DFLT_CFG);
if (dfltCfgURL != null)
uri = dfltCfgURL.toURI();
}
catch (URISyntaxException ignored) {
// No-op.
}
if (uri == null)
uri = URI.create("ignite://default");
DEFAULT_URI = uri;
}
/** */
public static final Properties DFLT_PROPS = new Properties();
/** */
private final Map<ClassLoader, Map<URI, GridFutureAdapter<CacheManager>>> cacheManagers = new WeakHashMap<>();
/** {@inheritDoc} */
@Override public javax.cache.CacheManager getCacheManager(@Nullable URI uri, ClassLoader clsLdr, Properties props)
throws CacheException {
if (uri == null)
uri = getDefaultURI();
if (clsLdr == null)
clsLdr = getDefaultClassLoader();
GridFutureAdapter<CacheManager> fut;
boolean needStartMgr = false;
Map<URI, GridFutureAdapter<CacheManager>> uriMap;
synchronized (cacheManagers) {
uriMap = cacheManagers.get(clsLdr);
if (uriMap == null) {
uriMap = new HashMap<>();
cacheManagers.put(clsLdr, uriMap);
}
fut = uriMap.get(uri);
if (fut == null) {
needStartMgr = true;
fut = new GridFutureAdapter<>();
uriMap.put(uri, fut);
}
}
if (needStartMgr) {
try {
CacheManager mgr = new CacheManager(uri, this, clsLdr, props);
fut.onDone(mgr);
return mgr;
}
catch (Throwable e) {
synchronized (cacheManagers) {
uriMap.remove(uri);
}
fut.onDone(e);
if (e instanceof Error)
throw (Error)e;
throw CU.convertToCacheException(U.cast(e));
}
}
else {
try {
return fut.get();
}
catch (IgniteCheckedException e) {
throw CU.convertToCacheException(e);
}
}
}
/** {@inheritDoc} */
@Override public ClassLoader getDefaultClassLoader() {
return getClass().getClassLoader();
}
/** {@inheritDoc} */
@Override public URI getDefaultURI() {
return DEFAULT_URI;
}
/** {@inheritDoc} */
@Override public Properties getDefaultProperties() {
return DFLT_PROPS;
}
/** {@inheritDoc} */
@Override public javax.cache.CacheManager getCacheManager(URI uri, ClassLoader clsLdr) {
return getCacheManager(uri, clsLdr, getDefaultProperties());
}
/** {@inheritDoc} */
@Override public javax.cache.CacheManager getCacheManager() {
return getCacheManager(getDefaultURI(), getDefaultClassLoader());
}
/**
* @param ignite Ignite.
* @return Cache manager implementation.
*/
public javax.cache.CacheManager findManager(Ignite ignite) {
synchronized (cacheManagers) {
for (Map<URI, GridFutureAdapter<CacheManager>> map : cacheManagers.values()) {
for (GridFutureAdapter<CacheManager> fut : map.values()) {
if (fut.isDone()) {
assert !fut.isFailed();
try {
CacheManager mgr = fut.get();
if (mgr.unwrap(Ignite.class) == ignite)
return mgr;
}
catch (IgniteCheckedException e) {
throw CU.convertToCacheException(e);
}
}
}
}
}
return null;
}
/** {@inheritDoc} */
@Override public void close() {
Collection<GridFutureAdapter<CacheManager>> futs = new ArrayList<>();
synchronized (cacheManagers) {
for (Map<URI, GridFutureAdapter<CacheManager>> uriMap : cacheManagers.values())
futs.addAll(uriMap.values());
cacheManagers.clear();
}
closeManagers(futs);
}
/** {@inheritDoc} */
@Override public void close(ClassLoader clsLdr) {
Map<URI, GridFutureAdapter<CacheManager>> uriMap;
synchronized (cacheManagers) {
uriMap = cacheManagers.remove(clsLdr);
}
if (uriMap == null)
return;
closeManagers(uriMap.values());
}
/**
* @param futs Futs.
*/
private void closeManagers(Collection<GridFutureAdapter<CacheManager>> futs) {
for (GridFutureAdapter<CacheManager> fut : futs) {
try {
CacheManager mgr = fut.get();
mgr.close();
}
catch (Exception ignored) {
// No-op.
}
}
}
/**
* @param mgr Manager.
*/
protected void removeClosedManager(CacheManager mgr) {<FILL_FUNCTION_BODY>}
/** {@inheritDoc} */
@Override public void close(URI uri, ClassLoader clsLdr) {
GridFutureAdapter<CacheManager> fut;
synchronized (cacheManagers) {
Map<URI, GridFutureAdapter<CacheManager>> uriMap = cacheManagers.get(clsLdr);
if (uriMap == null)
return;
fut = uriMap.remove(uri);
}
if (fut != null) {
CacheManager mgr;
try {
mgr = fut.get();
}
catch (Exception ignored) {
return;
}
mgr.close();
}
}
/** {@inheritDoc} */
@Override public boolean isSupported(OptionalFeature optionalFeature) {
return false;
}
}
|
synchronized (cacheManagers) {
Map<URI, GridFutureAdapter<CacheManager>> uriMap = cacheManagers.get(mgr.getClassLoader());
GridFutureAdapter<CacheManager> fut = uriMap.get(mgr.getURI());
if (fut != null && fut.isDone() && !fut.isFailed()) {
try {
CacheManager cachedMgr = fut.get();
if (cachedMgr == mgr)
uriMap.remove(mgr.getURI());
}
catch (IgniteCheckedException e) {
throw CU.convertToCacheException(e);
}
}
}
| 1,638
| 168
| 1,806
|
<no_super_class>
|
apache_ignite
|
ignite/modules/core/src/main/java/org/apache/ignite/cache/affinity/AffinityKey.java
|
AffinityKey
|
affinityKey
|
class AffinityKey<K> implements Externalizable {
/** */
private static final long serialVersionUID = 0L;
/** Key. */
@GridToStringInclude(sensitive = true)
private K key;
/** Affinity key. */
@AffinityKeyMapped
@GridToStringInclude(sensitive = true)
private Object affKey;
/**
* Empty constructor.
*/
public AffinityKey() {
// No-op.
}
/**
* Initializes key wrapper for a given key. If affinity key
* is not initialized, then this key will be used for affinity.
*
* @param key Key.
*/
public AffinityKey(K key) {
A.notNull(key, "key");
this.key = key;
}
/**
* Initializes key together with its affinity key counter-part.
*
* @param key Key.
* @param affKey Affinity key.
*/
public AffinityKey(K key, Object affKey) {
A.notNull(key, "key");
this.key = key;
this.affKey = affKey;
}
/**
* Gets wrapped key.
*
* @return Wrapped key.
*/
public K key() {
return key;
}
/**
* Sets wrapped key.
*
* @param key Wrapped key.
*/
public void key(K key) {
this.key = key;
}
/**
* Gets affinity key to use for affinity mapping. If affinity key is not provided,
* then {@code key} value will be returned.
* <p>
* This method is annotated with {@link AffinityKeyMapped} and will be picked up
* by {@link GridCacheDefaultAffinityKeyMapper} automatically.
*
* @param <T> Type of affinity key.
*
* @return Affinity key to use for affinity mapping.
*/
public <T> T affinityKey() {<FILL_FUNCTION_BODY>}
/**
* Sets affinity key to use for affinity mapping. If affinity key is not provided,
* then {@code key} value will be returned.
*
* @param affKey Affinity key to use for affinity mapping.
*/
public void affinityKey(Object affKey) {
this.affKey = affKey;
}
/** {@inheritDoc} */
@Override public void writeExternal(ObjectOutput out) throws IOException {
out.writeObject(key);
out.writeObject(affKey);
}
/** {@inheritDoc} */
@Override public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException {
key = (K)in.readObject();
affKey = in.readObject();
}
/**
* Hash code implementation which delegates to the underlying {@link #key()}. Note, however,
* that different subclasses of {@link AffinityKey} will produce different hash codes.
* <p>
* Users should override this method if different behavior is desired.
*
* @return Hash code.
*/
@Override public int hashCode() {
A.notNull(key, "key");
return 31 * key.hashCode() + getClass().getName().hashCode();
}
/**
* Equality check which delegates to the underlying key equality. Note, however, that
* different subclasses of {@link AffinityKey} will never be equal.
* <p>
* Users should override this method if different behavior is desired.
*
* @param obj Object to check for equality.
* @return {@code True} if objects are equal.
*/
@Override public boolean equals(Object obj) {
A.notNull(key, "key");
return obj != null && getClass() == obj.getClass() && key.equals(((AffinityKey)obj).key);
}
/** {@inheritDoc} */
@Override public String toString() {
return S.toString(AffinityKey.class, this);
}
}
|
A.notNull(key, "key");
return (T)(affKey == null ? key : affKey);
| 1,051
| 32
| 1,083
|
<no_super_class>
|
apache_ignite
|
ignite/modules/core/src/main/java/org/apache/ignite/cache/eviction/AbstractEvictionPolicyFactory.java
|
AbstractEvictionPolicyFactory
|
setBatchSize
|
class AbstractEvictionPolicyFactory<T> implements Factory<T> {
/** */
private int maxSize = DFLT_CACHE_SIZE;
/** */
private int batchSize = 1;
/** */
private long maxMemSize;
/**
* Sets maximum allowed size of cache before entry will start getting evicted.
*
* @param max Maximum allowed size of cache before entry will start getting evicted.
* @return {@code this} for chaining.
*/
public AbstractEvictionPolicyFactory setMaxSize(int max) {
A.ensure(max >= 0, "max >= 0");
this.maxSize = max;
return this;
}
/**
* Gets maximum allowed size of cache before entry will start getting evicted.
*
* @return Maximum allowed size of cache before entry will start getting evicted.
*/
public int getMaxSize() {
return maxSize;
}
/**
* Sets batch size.
*
* @param batchSize Batch size.
* @return {@code this} for chaining.
*/
public AbstractEvictionPolicyFactory setBatchSize(int batchSize) {<FILL_FUNCTION_BODY>}
/**
* Gets batch size.
*
* @return batch size.
*/
public int getBatchSize() {
return batchSize;
}
/**
* Sets maximum allowed cache size in bytes.
*
* @param maxMemSize Maximum allowed cache size in bytes.
* @return {@code this} for chaining.
*/
public AbstractEvictionPolicyFactory setMaxMemorySize(long maxMemSize) {
A.ensure(maxMemSize >= 0, "maxMemSize >= 0");
this.maxMemSize = maxMemSize;
return this;
}
/**
* Gets maximum allowed cache size in bytes.
*
* @return maximum allowed cache size in bytes.
*/
public long getMaxMemorySize() {
return maxMemSize;
}
}
|
A.ensure(batchSize > 0, "batchSize > 0");
this.batchSize = batchSize;
return this;
| 517
| 37
| 554
|
<no_super_class>
|
apache_ignite
|
ignite/modules/core/src/main/java/org/apache/ignite/cache/eviction/fifo/FifoEvictionPolicyFactory.java
|
FifoEvictionPolicyFactory
|
create
|
class FifoEvictionPolicyFactory<K, V> extends AbstractEvictionPolicyFactory<FifoEvictionPolicy<K, V>> {
/** */
private static final long serialVersionUID = 0L;
/** Constructor. */
public FifoEvictionPolicyFactory() {
}
/**
* Constructor.
*
* @param maxSize Maximum allowed size of cache before entry will start getting evicted.
*/
public FifoEvictionPolicyFactory(int maxSize) {
setMaxSize(maxSize);
}
/**
* @param maxSize Maximum allowed size of cache before entry will start getting evicted.
* @param batchSize Batch size.
* @param maxMemSize Sets maximum allowed cache size in bytes.
*/
public FifoEvictionPolicyFactory(int maxSize, int batchSize, long maxMemSize) {
setMaxSize(maxSize);
setBatchSize(batchSize);
setMaxMemorySize(maxMemSize);
}
/** {@inheritDoc} */
@Override public FifoEvictionPolicy<K, V> create() {<FILL_FUNCTION_BODY>}
}
|
FifoEvictionPolicy<K, V> plc = new FifoEvictionPolicy<>();
plc.setBatchSize(getBatchSize());
plc.setMaxMemorySize(getMaxMemorySize());
plc.setMaxSize(getMaxSize());
return plc;
| 292
| 77
| 369
|
<methods>public non-sealed void <init>() ,public int getBatchSize() ,public long getMaxMemorySize() ,public int getMaxSize() ,public AbstractEvictionPolicyFactory#RAW setBatchSize(int) ,public AbstractEvictionPolicyFactory#RAW setMaxMemorySize(long) ,public AbstractEvictionPolicyFactory#RAW setMaxSize(int) <variables>private int batchSize,private long maxMemSize,private int maxSize
|
apache_ignite
|
ignite/modules/core/src/main/java/org/apache/ignite/cache/eviction/lru/LruEvictionPolicy.java
|
LruEvictionPolicy
|
touch
|
class LruEvictionPolicy<K, V> extends AbstractEvictionPolicy<K, V> implements IgniteMBeanAware {
/** */
private static final long serialVersionUID = 0L;
/** Queue. */
private final ConcurrentLinkedDeque8<EvictableEntry<K, V>> queue =
new ConcurrentLinkedDeque8<>();
/**
* Constructs LRU eviction policy with all defaults.
*/
public LruEvictionPolicy() {
// No-op.
}
/**
* Constructs LRU eviction policy with maximum size.
*
* @param max Maximum allowed size of cache before entry will start getting evicted.
*/
public LruEvictionPolicy(int max) {
setMaxSize(max);
}
/** {@inheritDoc} */
@Override public int getCurrentSize() {
return queue.sizex();
}
/** {@inheritDoc} */
@Override public LruEvictionPolicy<K, V> setMaxMemorySize(long maxMemSize) {
super.setMaxMemorySize(maxMemSize);
return this;
}
/** {@inheritDoc} */
@Override public LruEvictionPolicy<K, V> setMaxSize(int max) {
super.setMaxSize(max);
return this;
}
/** {@inheritDoc} */
@Override public LruEvictionPolicy<K, V> setBatchSize(int batchSize) {
super.setBatchSize(batchSize);
return this;
}
/**
* Gets read-only view on internal {@code FIFO} queue in proper order.
*
* @return Read-only view ono internal {@code 'FIFO'} queue.
*/
public Collection<EvictableEntry<K, V>> queue() {
return Collections.unmodifiableCollection(queue);
}
/** {@inheritDoc} */
@Override protected boolean removeMeta(Object meta) {
return queue.unlinkx((Node<EvictableEntry<K, V>>)meta);
}
/**
* @param entry Entry to touch.
* @return {@code True} if new node has been added to queue by this call.
*/
@Override protected boolean touch(EvictableEntry<K, V> entry) {<FILL_FUNCTION_BODY>}
/**
* Tries to remove one item from queue.
*
* @return number of bytes that was free. {@code -1} if queue is empty.
*/
@Override protected int shrink0() {
EvictableEntry<K, V> entry = queue.poll();
if (entry == null)
return -1;
int size = 0;
Node<EvictableEntry<K, V>> meta = entry.removeMeta();
if (meta != null) {
size = entry.size();
memSize.add(-size);
if (!entry.evict())
touch(entry);
}
return size;
}
/** {@inheritDoc} */
@Override public Object getMBean() {
return new LruEvictionPolicyMBeanImpl();
}
/** {@inheritDoc} */
@Override public String toString() {
return S.toString(LruEvictionPolicy.class, this, "size", getCurrentSize());
}
/**
* MBean implementation for LruEvictionPolicy.
*/
private class LruEvictionPolicyMBeanImpl implements LruEvictionPolicyMBean {
/** {@inheritDoc} */
@Override public long getCurrentMemorySize() {
return LruEvictionPolicy.this.getCurrentMemorySize();
}
/** {@inheritDoc} */
@Override public int getCurrentSize() {
return LruEvictionPolicy.this.getCurrentSize();
}
/** {@inheritDoc} */
@Override public int getMaxSize() {
return LruEvictionPolicy.this.getMaxSize();
}
/** {@inheritDoc} */
@Override public void setMaxSize(int max) {
LruEvictionPolicy.this.setMaxSize(max);
}
/** {@inheritDoc} */
@Override public int getBatchSize() {
return LruEvictionPolicy.this.getBatchSize();
}
/** {@inheritDoc} */
@Override public void setBatchSize(int batchSize) {
LruEvictionPolicy.this.setBatchSize(batchSize);
}
/** {@inheritDoc} */
@Override public long getMaxMemorySize() {
return LruEvictionPolicy.this.getMaxMemorySize();
}
/** {@inheritDoc} */
@Override public void setMaxMemorySize(long maxMemSize) {
LruEvictionPolicy.this.setMaxMemorySize(maxMemSize);
}
}
}
|
Node<EvictableEntry<K, V>> node = entry.meta();
// Entry has not been enqueued yet.
if (node == null) {
while (true) {
node = queue.offerLastx(entry);
if (entry.putMetaIfAbsent(node) != null) {
// Was concurrently added, need to clear it from queue.
removeMeta(node);
// Queue has not been changed.
return false;
}
else if (node.item() != null) {
if (!entry.isCached()) {
// Was concurrently evicted, need to clear it from queue.
removeMeta(node);
return false;
}
memSize.add(entry.size());
return true;
}
// If node was unlinked by concurrent shrink() call, we must repeat the whole cycle.
else if (!entry.removeMeta(node))
return false;
}
}
else if (removeMeta(node)) {
// Move node to tail.
Node<EvictableEntry<K, V>> newNode = queue.offerLastx(entry);
if (!entry.replaceMeta(node, newNode))
// Was concurrently added, need to clear it from queue.
removeMeta(newNode);
}
// Entry is already in queue.
return false;
| 1,226
| 351
| 1,577
|
<methods>public non-sealed void <init>() ,public int getBatchSize() ,public long getCurrentMemorySize() ,public long getMaxMemorySize() ,public int getMaxSize() ,public void onEntryAccessed(boolean, EvictableEntry<K,V>) ,public void readExternal(java.io.ObjectInput) throws java.io.IOException, java.lang.ClassNotFoundException,public AbstractEvictionPolicy<K,V> setBatchSize(int) ,public AbstractEvictionPolicy<K,V> setMaxMemorySize(long) ,public AbstractEvictionPolicy<K,V> setMaxSize(int) ,public void writeExternal(java.io.ObjectOutput) throws java.io.IOException<variables>private volatile int batchSize,private volatile int max,private volatile long maxMemSize,protected final java.util.concurrent.atomic.LongAdder memSize,private static final long serialVersionUID
|
apache_ignite
|
ignite/modules/core/src/main/java/org/apache/ignite/cache/query/AbstractContinuousQuery.java
|
AbstractContinuousQuery
|
setTimeInterval
|
class AbstractContinuousQuery<K, V> extends Query<Cache.Entry<K, V>> {
/**
* Default page size. Size of {@code 1} means that all entries
* will be sent to master node immediately (buffering is disabled).
*/
public static final int DFLT_PAGE_SIZE = 1;
/** Maximum default time interval after which buffer will be flushed (if buffering is enabled). */
public static final long DFLT_TIME_INTERVAL = 0;
/**
* Default value for automatic unsubscription flag. Remote filters
* will be unregistered by default if master node leaves topology.
*/
public static final boolean DFLT_AUTO_UNSUBSCRIBE = true;
/** Initial query. */
private Query<Cache.Entry<K, V>> initQry;
/** Remote filter factory. */
private Factory<? extends CacheEntryEventFilter<K, V>> rmtFilterFactory;
/** Time interval. */
private long timeInterval = DFLT_TIME_INTERVAL;
/** Automatic unsubscription flag. */
private boolean autoUnsubscribe = DFLT_AUTO_UNSUBSCRIBE;
/** Whether to notify about {@link EventType#EXPIRED} events. */
private boolean includeExpired;
/**
* Sets initial query.
* <p>
* This query will be executed before continuous listener is registered
* which allows to iterate through entries which already existed at the
* time continuous query is executed.
*
* @param initQry Initial query.
* @return {@code this} for chaining.
*/
public AbstractContinuousQuery<K, V> setInitialQuery(Query<Cache.Entry<K, V>> initQry) {
this.initQry = initQry;
return this;
}
/**
* Gets initial query.
*
* @return Initial query.
*/
public Query<Cache.Entry<K, V>> getInitialQuery() {
return initQry;
}
/**
* Sets optional key-value filter factory. This factory produces filter is called before entry is
* sent to the master node.
* <p>
* <b>WARNING:</b> all operations that involve any kind of JVM-local or distributed locking
* (e.g., synchronization or transactional cache operations), should be executed asynchronously
* without blocking the thread that called the filter. Otherwise, you can get deadlocks.
* <p>
* If remote filter are annotated with {@link IgniteAsyncCallback} then it is executed in async callback
* pool (see {@link IgniteConfiguration#getAsyncCallbackPoolSize()}) that allow to perform a cache operations.
*
* @param rmtFilterFactory Key-value filter factory.
* @return {@code this} for chaining.
* @see IgniteAsyncCallback
* @see IgniteConfiguration#getAsyncCallbackPoolSize()
*/
public AbstractContinuousQuery<K, V> setRemoteFilterFactory(
Factory<? extends CacheEntryEventFilter<K, V>> rmtFilterFactory) {
this.rmtFilterFactory = rmtFilterFactory;
return this;
}
/**
* Gets remote filter.
*
* @return Remote filter.
*/
public Factory<? extends CacheEntryEventFilter<K, V>> getRemoteFilterFactory() {
return rmtFilterFactory;
}
/**
* Sets time interval.
* <p>
* When a cache update happens, entry is first put into a buffer. Entries from buffer will
* be sent to the master node only if the buffer is full (its size can be provided via {@link #setPageSize(int)}
* method) or time provided via this method is exceeded.
* <p>
* Default time interval is {@code 0} which means that
* time check is disabled and entries will be sent only when buffer is full.
*
* @param timeInterval Time interval.
* @return {@code this} for chaining.
*/
public AbstractContinuousQuery<K, V> setTimeInterval(long timeInterval) {<FILL_FUNCTION_BODY>}
/**
* Gets time interval.
*
* @return Time interval.
*/
public long getTimeInterval() {
return timeInterval;
}
/**
* Sets automatic unsubscribe flag.
* <p>
* This flag indicates that query filters on remote nodes should be
* automatically unregistered if master node (node that initiated the query) leaves topology. If this flag is
* {@code false}, filters will be unregistered only when the query is cancelled from master node, and won't ever be
* unregistered if master node leaves grid.
* <p>
* Default value for this flag is {@code true}.
*
* @param autoUnsubscribe Automatic unsubscription flag.
* @return {@code this} for chaining.
*/
public AbstractContinuousQuery<K, V> setAutoUnsubscribe(boolean autoUnsubscribe) {
this.autoUnsubscribe = autoUnsubscribe;
return this;
}
/**
* Gets automatic unsubscription flag value.
*
* @return Automatic unsubscription flag.
*/
public boolean isAutoUnsubscribe() {
return autoUnsubscribe;
}
/**
* Sets the flag value defining whether to notify about {@link EventType#EXPIRED} events.
* If {@code true}, then the remote listener will get notifications about entries
* expired in cache. Otherwise, only {@link EventType#CREATED}, {@link EventType#UPDATED}
* and {@link EventType#REMOVED} events will be fired in the remote listener.
* <p>
* This flag is {@code false} by default, so {@link EventType#EXPIRED} events are disabled.
*
* @param includeExpired Whether to notify about {@link EventType#EXPIRED} events.
* @return {@code this} for chaining.
*/
public AbstractContinuousQuery<K, V> setIncludeExpired(boolean includeExpired) {
this.includeExpired = includeExpired;
return this;
}
/**
* Gets the flag value defining whether to notify about {@link EventType#EXPIRED} events.
*
* @return Whether to notify about {@link EventType#EXPIRED} events.
*/
public boolean isIncludeExpired() {
return includeExpired;
}
}
|
if (timeInterval < 0)
throw new IllegalArgumentException("Time interval can't be negative.");
this.timeInterval = timeInterval;
return this;
| 1,626
| 44
| 1,670
|
<no_super_class>
|
apache_ignite
|
ignite/modules/core/src/main/java/org/apache/ignite/cache/query/CacheEntryEventAdapter.java
|
CacheEntryEventAdapter
|
getValue
|
class CacheEntryEventAdapter<K, V> extends CacheEntryEvent<K, V> {
/** */
protected CacheEntryEventAdapter(Cache src, EventType evtType) {
super(src, evtType);
}
/** {@inheritDoc} */
@Override public V getValue() {<FILL_FUNCTION_BODY>}
/** {@inheritDoc} */
@Override public <T> T unwrap(Class<T> cls) {
if (cls.isAssignableFrom(getClass()))
return cls.cast(this);
throw new IllegalArgumentException("Unwrapping to class is not supported: " + cls);
}
/** */
protected abstract V getNewValue();
}
|
EventType evtType = getEventType();
return (evtType == EXPIRED || evtType == REMOVED) ? getOldValue() : getNewValue();
| 182
| 47
| 229
|
<no_super_class>
|
apache_ignite
|
ignite/modules/core/src/main/java/org/apache/ignite/cache/query/IndexQuery.java
|
IndexQuery
|
validateAndSetCriteria
|
class IndexQuery<K, V> extends Query<Cache.Entry<K, V>> {
/** */
private static final long serialVersionUID = 0L;
/** Cache Value type. Describes a table within a cache that runs a query. */
private final String valType;
/** Index name. */
private final @Nullable String idxName;
/** Limit */
private int limit;
/** Index query criteria. */
private @Nullable List<IndexQueryCriterion> criteria;
/** Partition to run IndexQuery over. */
private @Nullable Integer part;
/**
* Specify index with cache value class.
*
* @param valCls Cache value class.
*/
public IndexQuery(Class<?> valCls) {
this(valCls, null);
}
/**
* Specify index with cache value type.
*
* @param valType Cache value type.
*/
public IndexQuery(String valType) {
this(valType, null);
}
/** Cache entries filter. Applies remotely to a query result cursor. */
private IgniteBiPredicate<K, V> filter;
/**
* Specify index with cache value class and index name.
*
* @param valCls Cache value class.
* @param idxName Index name.
*/
public IndexQuery(Class<?> valCls, @Nullable String idxName) {
this(valCls.getName(), idxName);
}
/**
* Specify index with cache value type and index name.
*
* @param valType Cache value type.
* @param idxName Index name.
*/
public IndexQuery(String valType, @Nullable String idxName) {
A.notEmpty(valType, "valType");
A.nullableNotEmpty(idxName, "idxName");
this.valType = valType;
this.idxName = idxName;
}
/**
* Sets conjunction (AND) criteria for index query.
*
* @param criteria Criteria to set.
* @return {@code this} for chaining.
*/
public IndexQuery<K, V> setCriteria(IndexQueryCriterion... criteria) {
validateAndSetCriteria(Arrays.asList(criteria));
return this;
}
/**
* Sets conjunction (AND) criteria for index query.
*
* @param criteria Criteria to set.
* @return {@code this} for chaining.
*/
public IndexQuery<K, V> setCriteria(List<IndexQueryCriterion> criteria) {
validateAndSetCriteria(new ArrayList<>(criteria));
return this;
}
/**
* Index query criteria.
*
* @return List of criteria for this index query.
*/
public List<IndexQueryCriterion> getCriteria() {
return criteria;
}
/**
* Cache Value type.
*
* @return Cache Value type.
*/
public String getValueType() {
return valType;
}
/**
* Index name.
*
* @return Index name.
*/
public String getIndexName() {
return idxName;
}
/**
* Gets limit to response records count.
*
* @return Limit value.
*/
public int getLimit() {
return limit;
}
/**
* Sets limit to response records count.
*
* @param limit POsitive limit to set.
* @return {@code this} For chaining.
*/
public IndexQuery<K, V> setLimit(int limit) {
A.ensure(limit > 0, "Limit must be positive.");
this.limit = limit;
return this;
}
/**
* Sets remote cache entries filter.
*
* @param filter Predicate for remote filtering of query result cursor.
* @return {@code this} for chaining.
*/
public IndexQuery<K, V> setFilter(IgniteBiPredicate<K, V> filter) {
A.notNull(filter, "filter");
this.filter = filter;
return this;
}
/**
* Gets remote cache entries filter.
*
* @return Filter.
*/
public IgniteBiPredicate<K, V> getFilter() {
return filter;
}
/**
* Sets partition number over which this query should iterate. If {@code null}, query will iterate over
* all partitions in the cache. Must be in the range [0, N) where N is partition number in the cache.
*
* @param part Partition number over which this query should iterate.
* @return {@code this} for chaining.
*/
public IndexQuery<K, V> setPartition(@Nullable Integer part) {
A.ensure(part == null || part >= 0,
"Specified partition must be in the range [0, N) where N is partition number in the cache.");
this.part = part;
return this;
}
/**
* Gets partition number over which this query should iterate. Will return {@code null} if partition was not
* set. In this case query will iterate over all partitions in the cache.
*
* @return Partition number or {@code null}.
*/
@Nullable public Integer getPartition() {
return part;
}
/** */
private void validateAndSetCriteria(List<IndexQueryCriterion> criteria) {<FILL_FUNCTION_BODY>}
}
|
if (F.isEmpty(criteria))
return;
for (IndexQueryCriterion c: criteria)
A.notNull(c, "criteria");
this.criteria = Collections.unmodifiableList(criteria);
| 1,413
| 64
| 1,477
|
<no_super_class>
|
apache_ignite
|
ignite/modules/core/src/main/java/org/apache/ignite/cache/store/jdbc/JdbcTypeDefaultHasher.java
|
JdbcTypeDefaultHasher
|
hashCode
|
class JdbcTypeDefaultHasher implements JdbcTypeHasher {
/** */
private static final long serialVersionUID = 0L;
/** Singleton instance to use. */
public static final JdbcTypeHasher INSTANCE = new JdbcTypeDefaultHasher();
/** {@inheritDoc} */
@Override public int hashCode(Collection<?> values) {<FILL_FUNCTION_BODY>}
}
|
int hash = 0;
for (Object val : values)
hash = 31 * hash + (val != null ? val.hashCode() : 0);
return hash;
| 104
| 50
| 154
|
<no_super_class>
|
apache_ignite
|
ignite/modules/core/src/main/java/org/apache/ignite/cache/store/jdbc/JdbcTypesDefaultTransformer.java
|
JdbcTypesDefaultTransformer
|
getColumnValue
|
class JdbcTypesDefaultTransformer implements JdbcTypesTransformer {
/** */
private static final long serialVersionUID = 0L;
/** Singleton instance to use. */
public static final JdbcTypesDefaultTransformer INSTANCE = new JdbcTypesDefaultTransformer();
/** {@inheritDoc} */
@Override public Object getColumnValue(ResultSet rs, int colIdx, Class<?> type) throws SQLException {<FILL_FUNCTION_BODY>}
}
|
if (type == String.class)
return rs.getString(colIdx);
if (type == int.class || type == Integer.class) {
int res = rs.getInt(colIdx);
return rs.wasNull() && type == Integer.class ? null : res;
}
if (type == long.class || type == Long.class) {
long res = rs.getLong(colIdx);
return rs.wasNull() && type == Long.class ? null : res;
}
if (type == double.class || type == Double.class) {
double res = rs.getDouble(colIdx);
return rs.wasNull() && type == Double.class ? null : res;
}
if (type == Date.class || type == java.util.Date.class)
return rs.getDate(colIdx);
if (type == Timestamp.class)
return rs.getTimestamp(colIdx);
if (type == Time.class)
return rs.getTime(colIdx);
if (type == boolean.class || type == Boolean.class) {
boolean res = rs.getBoolean(colIdx);
return rs.wasNull() && type == Boolean.class ? null : res;
}
if (type == byte.class || type == Byte.class) {
byte res = rs.getByte(colIdx);
return rs.wasNull() && type == Byte.class ? null : res;
}
if (type == short.class || type == Short.class) {
short res = rs.getShort(colIdx);
return rs.wasNull() && type == Short.class ? null : res;
}
if (type == float.class || type == Float.class) {
float res = rs.getFloat(colIdx);
return rs.wasNull() && type == Float.class ? null : res;
}
if (type == BigDecimal.class)
return rs.getBigDecimal(colIdx);
if (type == UUID.class) {
Object res = rs.getObject(colIdx);
if (res instanceof UUID)
return res;
if (res instanceof byte[]) {
ByteBuffer bb = ByteBuffer.wrap((byte[])res);
long most = bb.getLong();
long least = bb.getLong();
return new UUID(most, least);
}
if (res instanceof String)
return UUID.fromString((String)res);
}
if (type == byte[].class)
return rs.getBytes(colIdx);
if (type.isEnum()) {
if (NUMERIC_TYPES.contains(rs.getMetaData().getColumnType(colIdx))) {
int ordinal = rs.getInt(colIdx);
Object[] values = type.getEnumConstants();
return rs.wasNull() || ordinal >= values.length ? null : values[ordinal];
}
String str = rs.getString(colIdx);
try {
return rs.wasNull() ? null : Enum.valueOf((Class<? extends Enum>)type, str.trim());
}
catch (IllegalArgumentException ignore) {
return null;
}
}
return rs.getObject(colIdx);
| 119
| 879
| 998
|
<no_super_class>
|
apache_ignite
|
ignite/modules/core/src/main/java/org/apache/ignite/cache/store/jdbc/dialect/DB2Dialect.java
|
DB2Dialect
|
mergeQuery
|
class DB2Dialect extends BasicJdbcDialect {
/** */
private static final long serialVersionUID = 0L;
/** {@inheritDoc} */
@Override public String loadCacheSelectRangeQuery(String fullTblName, Collection<String> keyCols) {
String cols = mkString(keyCols, ",");
return String.format(
"SELECT %1$s FROM (SELECT %1$s, ROW_NUMBER() OVER(ORDER BY %1$s) AS rn FROM %2$s) WHERE mod(rn, ?) = 0 ORDER BY %1$s",
cols,
fullTblName
);
}
/** {@inheritDoc} */
@Override public boolean hasMerge() {
return true;
}
/** {@inheritDoc} */
@Override public String mergeQuery(String fullTblName, Collection<String> keyCols, Collection<String> uniqCols) {<FILL_FUNCTION_BODY>}
}
|
Collection<String> cols = F.concat(false, keyCols, uniqCols);
String colsLst = mkString(cols, ", ");
String match = mkString(keyCols, new C1<String, String>() {
@Override public String apply(String col) {
return String.format("t.%s=v.%s", col, col);
}
}, "", ", ", "");
String setCols = mkString(uniqCols, new C1<String, String>() {
@Override public String apply(String col) {
return String.format("t.%s = v.%s", col, col);
}
}, "", ", ", "");
String valuesCols = mkString(cols, new C1<String, String>() {
@Override public String apply(String col) {
return "v." + col;
}
}, "", ", ", "");
return String.format("MERGE INTO %s t" +
" USING (VALUES(%s)) AS v (%s)" +
" ON %s" +
" WHEN MATCHED THEN" +
" UPDATE SET %s" +
" WHEN NOT MATCHED THEN" +
" INSERT (%s) VALUES (%s)", fullTblName, repeat("?", cols.size(), "", ",", ""), colsLst,
match, setCols, colsLst, valuesCols);
| 249
| 368
| 617
|
<methods>public non-sealed void <init>() ,public java.lang.String escape(java.lang.String) ,public int getFetchSize() ,public int getMaxParameterCount() ,public boolean hasMerge() ,public java.lang.String insertQuery(java.lang.String, Collection<java.lang.String>, Collection<java.lang.String>) ,public java.lang.String loadCacheQuery(java.lang.String, Iterable<java.lang.String>) ,public java.lang.String loadCacheRangeQuery(java.lang.String, Collection<java.lang.String>, Iterable<java.lang.String>, boolean, boolean) ,public java.lang.String loadCacheSelectRangeQuery(java.lang.String, Collection<java.lang.String>) ,public java.lang.String loadQuery(java.lang.String, Collection<java.lang.String>, Iterable<java.lang.String>, int) ,public java.lang.String mergeQuery(java.lang.String, Collection<java.lang.String>, Collection<java.lang.String>) ,public java.lang.String removeQuery(java.lang.String, Iterable<java.lang.String>) ,public void setFetchSize(int) ,public void setMaxParameterCount(int) ,public java.lang.String updateQuery(java.lang.String, Collection<java.lang.String>, Iterable<java.lang.String>) <variables>protected static final int DFLT_MAX_PARAMS_CNT,protected int fetchSize,protected int maxParamsCnt,private static final long serialVersionUID
|
apache_ignite
|
ignite/modules/core/src/main/java/org/apache/ignite/configuration/BinaryConfiguration.java
|
BinaryConfiguration
|
setClassNames
|
class BinaryConfiguration implements Serializable {
/** Serial version uid. */
private static final long serialVersionUID = 0L;
/** Default compact footer flag setting. */
public static final boolean DFLT_COMPACT_FOOTER = true;
/** ID mapper. */
private BinaryIdMapper idMapper;
/** Name mapper. */
private BinaryNameMapper nameMapper;
/** Serializer. */
private BinarySerializer serializer;
/** Types. */
private Collection<BinaryTypeConfiguration> typeCfgs;
/** Compact footer flag. */
private boolean compactFooter = DFLT_COMPACT_FOOTER;
/**
* Sets class names of binary objects explicitly.
*
* @param clsNames Class names.
* @return {@code this} for chaining.
*/
public BinaryConfiguration setClassNames(Collection<String> clsNames) {<FILL_FUNCTION_BODY>}
/**
* Gets ID mapper.
*
* @return ID mapper.
*/
public BinaryIdMapper getIdMapper() {
return idMapper;
}
/**
* Sets ID mapper.
*
* @param idMapper ID mapper.
* @return {@code this} for chaining.
*/
public BinaryConfiguration setIdMapper(BinaryIdMapper idMapper) {
this.idMapper = idMapper;
return this;
}
/**
* Gets name mapper.
*
* @return Name mapper.
*/
public BinaryNameMapper getNameMapper() {
return nameMapper;
}
/**
* Sets name mapper.
*
* @param nameMapper Name mapper.
* @return {@code this} for chaining.
*/
public BinaryConfiguration setNameMapper(BinaryNameMapper nameMapper) {
this.nameMapper = nameMapper;
return this;
}
/**
* Gets serializer.
*
* @return Serializer.
*/
public BinarySerializer getSerializer() {
return serializer;
}
/**
* Sets serializer.
*
* @param serializer Serializer.
* @return {@code this} for chaining.
*/
public BinaryConfiguration setSerializer(BinarySerializer serializer) {
this.serializer = serializer;
return this;
}
/**
* Gets types configuration.
*
* @return Types configuration.
*/
public Collection<BinaryTypeConfiguration> getTypeConfigurations() {
return typeCfgs;
}
/**
* Sets type configurations.
*
* @param typeCfgs Type configurations.
* @return {@code this} for chaining.
*/
public BinaryConfiguration setTypeConfigurations(Collection<BinaryTypeConfiguration> typeCfgs) {
this.typeCfgs = typeCfgs;
return this;
}
/**
* Get whether to write footers in compact form. When enabled, Ignite will not write fields metadata
* when serializing objects, because internally {@code BinaryMarshaller} already distribute metadata inside
* cluster. This increases serialization performance.
* <p>
* <b>WARNING!</b> This mode should be disabled when already serialized data can be taken from some external
* sources (e.g. cache store which stores data in binary form, data center replication, etc.). Otherwise binary
* objects without any associated metadata could appear in the cluster and Ignite will not be able to deserialize
* it.
* <p>
* Defaults to {@link #DFLT_COMPACT_FOOTER}.
*
* @return Whether to write footers in compact form.
*/
public boolean isCompactFooter() {
return compactFooter;
}
/**
* Set whether to write footers in compact form. See {@link #isCompactFooter()} for more info.
*
* @param compactFooter Whether to write footers in compact form.
* @return {@code this} for chaining.
*/
public BinaryConfiguration setCompactFooter(boolean compactFooter) {
this.compactFooter = compactFooter;
return this;
}
/** {@inheritDoc} */
@Override public String toString() {
return S.toString(BinaryConfiguration.class, this);
}
}
|
if (typeCfgs == null)
typeCfgs = new ArrayList<>(clsNames.size());
for (String clsName : clsNames)
typeCfgs.add(new BinaryTypeConfiguration(clsName));
return this;
| 1,118
| 68
| 1,186
|
<no_super_class>
|
apache_ignite
|
ignite/modules/core/src/main/java/org/apache/ignite/configuration/SqlConfiguration.java
|
SqlConfiguration
|
setDefaultQueryTimeout
|
class SqlConfiguration {
/** Default SQL query history size. */
public static final int DFLT_SQL_QUERY_HISTORY_SIZE = 1000;
/** Default query timeout. */
public static final long DFLT_QRY_TIMEOUT = 0;
/** Default timeout after which long query warning will be printed. */
public static final long DFLT_LONG_QRY_WARN_TIMEOUT = 3000;
/** */
private long longQryWarnTimeout = DFLT_LONG_QRY_WARN_TIMEOUT;
/** Default query timeout. */
private long dfltQryTimeout = DFLT_QRY_TIMEOUT;
/** SQL schemas to be created on node start. */
private String[] sqlSchemas;
/** SQL query history size. */
private int sqlQryHistSize = DFLT_SQL_QUERY_HISTORY_SIZE;
/** Enable validation of key & values against sql schema. */
private boolean validationEnabled;
/** SQL query engines configuration. */
private QueryEngineConfiguration[] enginesConfiguration;
/**
* Defines the default query timeout.
*
* Defaults to {@link #DFLT_QRY_TIMEOUT}.
* {@code 0} means there is no timeout (this is a default value)
*
* @return Default query timeout.
* @deprecated Since 2.9. Please use distributed default query timeout.
*/
@Deprecated
public long getDefaultQueryTimeout() {
return dfltQryTimeout;
}
/**
* Sets timeout in milliseconds for default query timeout.
* {@code 0} means there is no timeout (this is a default value)
*
* @param dfltQryTimeout Timeout in milliseconds.
* @return {@code this} for chaining.
* @deprecated Since 2.9. Please use distributed default query timeout.
*/
@Deprecated
public SqlConfiguration setDefaultQueryTimeout(long dfltQryTimeout) {<FILL_FUNCTION_BODY>}
/**
* Number of SQL query history elements to keep in memory. If not provided, then default value {@link
* #DFLT_SQL_QUERY_HISTORY_SIZE} is used. If provided value is less or equals 0, then gathering SQL query history
* will be switched off.
*
* @return SQL query history size.
*/
public int getSqlQueryHistorySize() {
return sqlQryHistSize;
}
/**
* Sets number of SQL query history elements kept in memory. If not explicitly set, then default value is {@link
* #DFLT_SQL_QUERY_HISTORY_SIZE}.
*
* @param size Number of SQL query history elements kept in memory.
* @return {@code this} for chaining.
*/
public SqlConfiguration setSqlQueryHistorySize(int size) {
sqlQryHistSize = size;
return this;
}
/**
* Gets SQL schemas to be created on node startup.
* <p>
* See {@link #setSqlSchemas(String...)} for more information.
*
* @return SQL schemas to be created on node startup.
*/
public String[] getSqlSchemas() {
return sqlSchemas;
}
/**
* Sets SQL schemas to be created on node startup. Schemas are created on local node only and are not propagated
* to other cluster nodes. Created schemas cannot be dropped.
* <p>
* By default schema names are case-insensitive, i.e. {@code my_schema} and {@code My_Schema} represents the same
* object. Use quotes to enforce case sensitivity (e.g. {@code "My_Schema"}).
* <p>
* Property is ignored if {@code ignite-indexing} module is not in classpath.
*
* @param sqlSchemas SQL schemas to be created on node startup.
* @return {@code this} for chaining.
*/
public SqlConfiguration setSqlSchemas(String... sqlSchemas) {
this.sqlSchemas = sqlSchemas;
return this;
}
/**
* Gets timeout in milliseconds after which long query warning will be printed.
*
* @return Timeout in milliseconds.
*/
public long getLongQueryWarningTimeout() {
return longQryWarnTimeout;
}
/**
* Sets timeout in milliseconds after which long query warning will be printed.
*
* @param longQryWarnTimeout Timeout in milliseconds.
* @return {@code this} for chaining.
*/
public SqlConfiguration setLongQueryWarningTimeout(long longQryWarnTimeout) {
this.longQryWarnTimeout = longQryWarnTimeout;
return this;
}
/**
* Is key & value validation enabled.
*
* @return {@code true} When key & value shall be validated against SQL schema.
*/
public boolean isValidationEnabled() {
return validationEnabled;
}
/**
* Enable/disable key & value validation.
*
* @param validationEnabled {@code true} When key & value shall be validated against SQL schema.
* Default value is {@code false}.
* @return {@code this} for chaining.
*/
public SqlConfiguration setValidationEnabled(boolean validationEnabled) {
this.validationEnabled = validationEnabled;
return this;
}
/**
* Sets query engines configuration.
* <p>
* There are several engines to execute SQL queries can be configured. If configured more than one engine, exact
* engine to execute the query can be chosen in run-time by {@code queryEngine} JDBC connection property or by
* {@code QUERY_ENGINE('engineName')} SQL query hint. If no query engine is explicitly chosen, default query engine
* will be used (see {@link QueryEngineConfiguration#setDefault(boolean)}).
* <p>
* When this property is not set, the query engine cannot be chosen in run-time, and the engine provided by the
* ignite-indexing module will be used for all queries.
*
* @param enginesConfiguration Query engines configuration.
* @return {@code this} for chaining.
*/
public SqlConfiguration setQueryEnginesConfiguration(QueryEngineConfiguration... enginesConfiguration) {
this.enginesConfiguration = enginesConfiguration == null ? null : enginesConfiguration.clone();
return this;
}
/**
* Gets query engines configuration.
*
* @return Query engines configuration.
*/
public QueryEngineConfiguration[] getQueryEnginesConfiguration() {
return enginesConfiguration == null ? null : enginesConfiguration.clone();
}
/** {@inheritDoc} */
@Override public String toString() {
return S.toString(SqlConfiguration.class, this);
}
}
|
A.ensure(dfltQryTimeout >= 0 && dfltQryTimeout <= Integer.MAX_VALUE,
"default query timeout value should be valid Integer.");
this.dfltQryTimeout = dfltQryTimeout;
return this;
| 1,721
| 68
| 1,789
|
<no_super_class>
|
apache_ignite
|
ignite/modules/core/src/main/java/org/apache/ignite/events/CacheRebalancingEvent.java
|
CacheRebalancingEvent
|
shortDisplay
|
class CacheRebalancingEvent extends EventAdapter {
/** */
private static final long serialVersionUID = 0L;
/** Cache name. */
private String cacheName;
/** Partition for the event. */
private int part;
/** Discovery node. */
private ClusterNode discoNode;
/** Discovery event type. */
private int discoEvtType;
/** Discovery event time. */
private long discoTs;
/**
* Constructs cache event.
*
* @param cacheName Cache name.
* @param node Event node.
* @param msg Event message.
* @param type Event type.
* @param part Partition for the event (usually the partition the key belongs to).
* @param discoNode Node that triggered this rebalancing event.
* @param discoEvtType Discovery event type that triggered this rebalancing event.
* @param discoTs Timestamp of discovery event that triggered this rebalancing event.
*/
public CacheRebalancingEvent(
String cacheName,
ClusterNode node,
String msg,
int type,
int part,
ClusterNode discoNode,
int discoEvtType,
long discoTs
) {
super(node, msg, type);
this.cacheName = cacheName;
this.part = part;
this.discoNode = discoNode;
this.discoEvtType = discoEvtType;
this.discoTs = discoTs;
}
/**
* Gets cache name.
*
* @return Cache name.
*/
public String cacheName() {
return cacheName;
}
/**
* Gets partition for the event.
*
* @return Partition for the event.
*/
public int partition() {
return part;
}
/**
* Gets shadow of the node that triggered this rebalancing event.
*
* @return Shadow of the node that triggered this rebalancing event.
*/
public ClusterNode discoveryNode() {
return discoNode;
}
/**
* Gets type of discovery event that triggered this rebalancing event.
*
* @return Type of discovery event that triggered this rebalancing event.
* @see DiscoveryEvent#type()
*/
public int discoveryEventType() {
return discoEvtType;
}
/**
* Gets name of discovery event that triggered this rebalancing event.
*
* @return Name of discovery event that triggered this rebalancing event.
* @see DiscoveryEvent#name()
*/
public String discoveryEventName() {
return U.gridEventName(discoEvtType);
}
/**
* Gets timestamp of discovery event that caused this rebalancing event.
*
* @return Timestamp of discovery event that caused this rebalancing event.
*/
public long discoveryTimestamp() {
return discoTs;
}
/** {@inheritDoc} */
@Override public String shortDisplay() {<FILL_FUNCTION_BODY>}
/** {@inheritDoc} */
@Override public String toString() {
return S.toString(CacheRebalancingEvent.class, this,
"discoEvtName", discoveryEventName(),
"nodeId8", U.id8(node().id()),
"msg", message(),
"type", name(),
"tstamp", timestamp());
}
}
|
return name() + ": cache=" + CU.mask(cacheName) + ", cause=" +
discoveryEventName();
| 887
| 34
| 921
|
<methods>public void <init>() ,public void <init>(org.apache.ignite.cluster.ClusterNode, java.lang.String, int) ,public int compareTo(org.apache.ignite.events.Event) ,public boolean equals(java.lang.Object) ,public int hashCode() ,public org.apache.ignite.lang.IgniteUuid id() ,public long localOrder() ,public void message(java.lang.String) ,public java.lang.String message() ,public java.lang.String name() ,public void node(org.apache.ignite.cluster.ClusterNode) ,public org.apache.ignite.cluster.ClusterNode node() ,public java.lang.String shortDisplay() ,public long timestamp() ,public java.lang.String toString() ,public void type(int) ,public int type() <variables>private final org.apache.ignite.lang.IgniteUuid id,private long locId,private java.lang.String msg,private org.apache.ignite.cluster.ClusterNode node,private static final long serialVersionUID,private final long tstamp,private int type
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.