proj_name
stringclasses
230 values
relative_path
stringlengths
33
262
class_name
stringlengths
1
68
func_name
stringlengths
1
60
masked_class
stringlengths
66
10.4k
func_body
stringlengths
0
7.99k
len_input
int64
27
2.03k
len_output
int64
1
1.87k
total
int64
32
2.05k
index
int64
3
70.5k
crate_crate
crate/server/src/main/java/io/crate/expression/symbol/FieldsVisitor.java
FieldsVisitor
visitField
class FieldsVisitor extends DefaultTraversalSymbolVisitor<Consumer<? super ScopedSymbol>, Void> { private static final FieldsVisitor FIELDS_VISITOR = new FieldsVisitor(); private FieldsVisitor() { super(); } @Override public Void visitField(ScopedSymbol field, Consumer<? super ScopedSymbol> context) {<FILL_FUNCTION_BODY>} public static void visitFields(Symbol symbolTree, Consumer<? super ScopedSymbol> consumer) { symbolTree.accept(FIELDS_VISITOR, consumer); } }
context.accept(field); return null;
160
16
176
16,445
dromara_dynamic-tp
dynamic-tp/starter/starter-adapter/starter-adapter-grpc/src/main/java/org/dromara/dynamictp/starter/adapter/grpc/autoconfigure/GrpcTpAutoConfiguration.java
GrpcTpAutoConfiguration
grpcDtpAdapter
class GrpcTpAutoConfiguration { @Bean @ConditionalOnMissingBean public GrpcDtpAdapter grpcDtpAdapter() {<FILL_FUNCTION_BODY>} }
return new GrpcDtpAdapter();
51
13
64
17,787
lilishop_lilishop
lilishop/consumer/src/main/java/cn/lili/event/impl/VerificationOrderExecute.java
VerificationOrderExecute
orderChange
class VerificationOrderExecute implements OrderStatusChangeEvent { @Autowired private OrderService orderService; @Autowired private OrderItemService orderItemService; @Override public void orderChange(OrderMessage orderMessage) {<FILL_FUNCTION_BODY>} /** * 获取随机数 * 判断当前店铺下是否使用验证码,如果已使用则重新获取 * * @param storeId 店铺ID * @return */ private String getCode(String storeId) { //获取八位验证码 String code = Long.toString(RandomUtil.randomLong(10000000, 99999999)); LambdaQueryWrapper lambdaQueryWrapper = new LambdaQueryWrapper<Order>() .eq(Order::getVerificationCode, code) .eq(Order::getStoreId, storeId); if (orderService.getOne(lambdaQueryWrapper) == null) { return code; } else { return this.getCode(storeId); } } }
//订单状态为待核验,添加订单添加核验码 if (orderMessage.getNewStatus().equals(OrderStatusEnum.TAKE) || orderMessage.getNewStatus().equals(OrderStatusEnum.STAY_PICKED_UP)) { //获取订单信息 Order order = orderService.getBySn(orderMessage.getOrderSn()); //获取随机数,判定是否存在 String code = getCode(order.getStoreId()); //设置订单验证码 orderService.update(new LambdaUpdateWrapper<Order>() .set(Order::getVerificationCode, code) .eq(Order::getSn, orderMessage.getOrderSn())); //修改虚拟订单货物可以进行售后、投诉 orderItemService.update(new LambdaUpdateWrapper<OrderItem>().eq(OrderItem::getOrderSn, orderMessage.getOrderSn()) .set(OrderItem::getAfterSaleStatus, OrderItemAfterSaleStatusEnum.ALREADY_APPLIED) .set(OrderItem::getComplainStatus, OrderComplaintStatusEnum.COMPLETE)); }
278
282
560
30,349
elunez_eladmin
eladmin/eladmin-system/src/main/java/me/zhengjie/modules/security/security/TokenFilter.java
TokenFilter
doFilter
class TokenFilter extends GenericFilterBean { private static final Logger log = LoggerFactory.getLogger(TokenFilter.class); private final TokenProvider tokenProvider; private final SecurityProperties properties; private final OnlineUserService onlineUserService; private final UserCacheManager userCacheManager; /** * @param tokenProvider Token * @param properties JWT * @param onlineUserService 用户在线 * @param userCacheManager 用户缓存工具 */ public TokenFilter(TokenProvider tokenProvider, SecurityProperties properties, OnlineUserService onlineUserService, UserCacheManager userCacheManager) { this.properties = properties; this.onlineUserService = onlineUserService; this.tokenProvider = tokenProvider; this.userCacheManager = userCacheManager; } @Override public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {<FILL_FUNCTION_BODY>} /** * 初步检测Token * * @param request / * @return / */ private String resolveToken(HttpServletRequest request) { String bearerToken = request.getHeader(properties.getHeader()); if (StringUtils.hasText(bearerToken) && bearerToken.startsWith(properties.getTokenStartWith())) { // 去掉令牌前缀 return bearerToken.replace(properties.getTokenStartWith(), ""); } else { log.debug("非法Token:{}", bearerToken); } return null; } }
HttpServletRequest httpServletRequest = (HttpServletRequest) servletRequest; String token = resolveToken(httpServletRequest); // 对于 Token 为空的不需要去查 Redis if (StrUtil.isNotBlank(token)) { OnlineUserDto onlineUserDto = null; boolean cleanUserCache = false; try { String loginKey = tokenProvider.loginKey(token); onlineUserDto = onlineUserService.getOne(loginKey); } catch (ExpiredJwtException e) { log.error(e.getMessage()); cleanUserCache = true; } finally { if (cleanUserCache || Objects.isNull(onlineUserDto)) { userCacheManager.cleanUserCache(String.valueOf(tokenProvider.getClaims(token).get(TokenProvider.AUTHORITIES_KEY))); } } if (onlineUserDto != null && StringUtils.hasText(token)) { Authentication authentication = tokenProvider.getAuthentication(token); SecurityContextHolder.getContext().setAuthentication(authentication); // Token 续期 tokenProvider.checkRenewal(token); } } filterChain.doFilter(servletRequest, servletResponse);
408
313
721
81
springdoc_springdoc-openapi
springdoc-openapi/springdoc-openapi-starter-webmvc-api/src/main/java/org/springdoc/webmvc/core/configuration/MultipleOpenApiSupportConfiguration.java
MultipleOpenApiSupportConfiguration
multipleOpenApiResource
class MultipleOpenApiSupportConfiguration { /** * Multiple open api resource multiple open api resource. * * @param groupedOpenApis the grouped open apis * @param defaultOpenAPIBuilder the default open api builder * @param requestBuilder the request builder * @param responseBuilder the response builder * @param operationParser the operation parser * @param springDocConfigProperties the spring doc config properties * @param springDocProviders the spring doc providers * @param springDocCustomizers the spring doc customizers * @return the multiple open api resource */ @Bean @ConditionalOnMissingBean @ConditionalOnProperty(name = SPRINGDOC_USE_MANAGEMENT_PORT, havingValue = "false", matchIfMissing = true) @Lazy(false) MultipleOpenApiWebMvcResource multipleOpenApiResource(List<GroupedOpenApi> groupedOpenApis, ObjectFactory<OpenAPIService> defaultOpenAPIBuilder, AbstractRequestService requestBuilder, GenericResponseService responseBuilder, OperationService operationParser, SpringDocConfigProperties springDocConfigProperties, SpringDocProviders springDocProviders, SpringDocCustomizers springDocCustomizers) {<FILL_FUNCTION_BODY>} /** * The type Spring doc web mvc actuator different configuration. * @author bnasslashen */ @ConditionalOnClass(WebMvcEndpointHandlerMapping.class) @ConditionalOnManagementPort(ManagementPortType.DIFFERENT) static class SpringDocWebMvcActuatorDifferentConfiguration { /** * Multiple open api actuator resource multiple open api actuator resource. * * @param groupedOpenApis the grouped open apis * @param defaultOpenAPIBuilder the default open api builder * @param requestBuilder the request builder * @param responseBuilder the response builder * @param operationParser the operation parser * @param springDocConfigProperties the spring doc config properties * @param springDocProviders the spring doc providers * @param springDocCustomizers the spring doc customizers * @return the multiple open api actuator resource */ @Bean @ConditionalOnMissingBean @ConditionalOnProperty(SPRINGDOC_USE_MANAGEMENT_PORT) @Lazy(false) MultipleOpenApiActuatorResource multipleOpenApiActuatorResource(List<GroupedOpenApi> groupedOpenApis, ObjectFactory<OpenAPIService> defaultOpenAPIBuilder, AbstractRequestService requestBuilder, GenericResponseService responseBuilder, OperationService operationParser, SpringDocConfigProperties springDocConfigProperties, SpringDocProviders springDocProviders, SpringDocCustomizers springDocCustomizers) { return new MultipleOpenApiActuatorResource(groupedOpenApis, defaultOpenAPIBuilder, requestBuilder, responseBuilder, operationParser, springDocConfigProperties, springDocProviders, springDocCustomizers); } } }
return new MultipleOpenApiWebMvcResource(groupedOpenApis, defaultOpenAPIBuilder, requestBuilder, responseBuilder, operationParser, springDocConfigProperties, springDocProviders, springDocCustomizers);
735
63
798
43,904
pmd_pmd
pmd/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/ast/ASTTypeParameters.java
ASTTypeParameters
acceptVisitor
class ASTTypeParameters extends ASTNonEmptyList<ASTTypeParameter> { ASTTypeParameters(int id) { super(id, ASTTypeParameter.class); } @Override protected <P, R> R acceptVisitor(JavaVisitor<? super P, ? extends R> visitor, P data) {<FILL_FUNCTION_BODY>} }
return visitor.visit(this, data);
98
15
113
37,761
decaywood_XueQiuSuperSpider
XueQiuSuperSpider/src/main/java/org/decaywood/entity/selectorQuota/MarketQuotationsQuota.java
MarketQuotationsQuota
setVolavg30
class MarketQuotationsQuota extends AbstractQuotaNode { private String current = "ALL"; //当前价 private String pct = "ALL"; //本日涨跌幅(%) private String pct5 = "ALL"; //前5日涨跌幅(%) private String pct10 = "ALL"; //前10日涨跌幅(%) private String pct20 = "ALL"; //前20日涨跌幅(%) private String pct1m = "ALL"; //近1月涨跌幅(%) private String chgpct = "ALL"; //本日振幅(%) private String chgpct5 = "ALL"; //前5日振幅(%) private String chgpct10 = "ALL"; //前10日振幅(%) private String chgpct20 = "ALL"; //前20日振幅(%) private String chgpct1m = "ALL"; //近1月振幅(%) private String volume = "ALL"; //本日成交量(万) private String volavg30 = "ALL"; //30日均量(万) private String amount = "ALL"; //成交额(万) private String tr = "ALL"; // 本日换手率(%) private String tr5 = "ALL"; //前5日换手率(%) private String tr10 = "ALL"; // 前10日换手率(%) private String tr20 = "ALL"; //前20日换手率(%) private String tr1m = "ALL"; //近1月换手率(%) //设置当前价范围 public void setCurrent(double from, double to) { this.current = from + "_" + to; } //设置本日涨跌幅范围 public void setPct(double from, double to) { this.pct = from + "_" + to; } //设置前5日涨跌幅范围 public void setPct5(double from, double to) { this.pct5 = from + "_" + to; } //设置前10日涨跌幅范围 public void setPct10(double from, double to) { this.pct10 = from + "_" + to; } //设置前20日涨跌幅范围 public void setPct20(double from, double to) { this.pct20 = from + "_" + to; } //设置近1月涨跌幅范围 public void setPct1m(double from, double to) { this.pct1m = from + "_" + to; } //设置本日振幅范围 public void setChgpct(double from, double to) { this.chgpct = from + "_" + to; } //设置前5日振幅范围 public void setChgpct5(double from, double to) { this.chgpct5 = from + "_" + to; } //设置前10日振幅范围 public void setChgpct10(double from, double to) { this.chgpct10 = from + "_" + to; } //设置前20日振幅范围 public void setChgpct20(double from, double to) { this.chgpct20 = from + "_" + to; } //设置前1月振幅范围 public void setChgpct1m(double from, double to) { this.chgpct1m = from + "_" + to; } //设置本日成交量范围 public void setVolume(double from, double to) { this.volume = from + "_" + to; } //设置前30日均量范围 public void setVolavg30(double from, double to) {<FILL_FUNCTION_BODY>} //设置成交额范围 public void setAmount(double from, double to) { this.amount = from + "_" + to; } //设置本日换手率范围 public void setTr(double from, double to) { this.tr = from + "_" + to; } //设置前5日换手率范围 public void setTr5(double from, double to) { this.tr5 = from + "_" + to; } //设置前10日换手率范围 public void setTr10(double from, double to) { this.tr10 = from + "_" + to; } //设置前20日换手率范围 public void setTr20(double from, double to) { this.tr20 = from + "_" + to; } //设置前1月换手率范围 public void setTr1m(double from, double to) { this.tr1m = from + "_" + to; } @Override StringBuilder builderSelf() { StringBuilder builder = new StringBuilder(); append(builder, "current", current); append(builder, "pct", pct); append(builder, "pct5", pct5); append(builder, "pct10", pct10); append(builder, "pct20", pct20); append(builder, "pct1m", pct1m); append(builder, "chgpct", chgpct); append(builder, "chgpct5", chgpct5); append(builder, "chgpct10", chgpct10); append(builder, "chgpct20", chgpct20); append(builder, "chgpct1m", chgpct1m); append(builder, "volume", volume); append(builder, "volavg30", volavg30); append(builder, "amount", amount); append(builder, "tr", tr); append(builder, "tr5", tr5); append(builder, "tr10", tr10); append(builder, "tr20", tr20); append(builder, "tr1m", tr1m); return builder; } }
this.volavg30 = from + "_" + to;
1,569
20
1,589
16,640
dromara_dynamic-tp
dynamic-tp/common/src/main/java/org/dromara/dynamictp/common/util/DingSignUtil.java
DingSignUtil
dingSign
class DingSignUtil { private DingSignUtil() { } /** * The default encoding */ private static final Charset DEFAULT_ENCODING = StandardCharsets.UTF_8; /** * Signature method */ private static final String ALGORITHM = "HmacSHA256"; public static String dingSign(String secret, long timestamp) {<FILL_FUNCTION_BODY>} }
String stringToSign = timestamp + "\n" + secret; try { Mac mac = Mac.getInstance(ALGORITHM); mac.init(new SecretKeySpec(secret.getBytes(DEFAULT_ENCODING), ALGORITHM)); byte[] signData = mac.doFinal(stringToSign.getBytes(DEFAULT_ENCODING)); return URLEncoder.encode(new String(Base64.encodeBase64(signData)), DEFAULT_ENCODING.name()); } catch (Exception e) { log.error("DynamicTp, cal ding sign error", e); return ""; }
118
161
279
17,534
confluentinc_ksql
ksql/ksqldb-engine/src/main/java/io/confluent/ksql/execution/scalablepush/PushPhysicalPlanBuilder.java
PushPhysicalPlanBuilder
buildPushPhysicalPlan
class PushPhysicalPlanBuilder { // CHECKSTYLE_RULES.ON: ClassDataAbstractionCoupling private static final String REGISTRY_NOT_FOUND_ERROR_MESSAGE = "Scalable push registry cannot be found. " + "Make sure that ksql.query.push.v2.registry.installed is set to true."; private final ProcessingLogContext processingLogContext; private final PersistentQueryMetadata persistentQueryMetadata; private final Stacker contextStacker; private final QueryId queryId; private QuerySourceType querySourceType; public PushPhysicalPlanBuilder( final ProcessingLogContext processingLogContext, final PersistentQueryMetadata persistentQueryMetadata ) { this.processingLogContext = Objects.requireNonNull( processingLogContext, "processingLogContext"); this.persistentQueryMetadata = Objects.requireNonNull( persistentQueryMetadata, "persistentQueryMetadata"); this.contextStacker = new Stacker(); queryId = uniqueQueryId(); } /** * Visits the logical plan top-down to build the physical plan. * @param logicalPlanNode the logical plan root node * @return the root node of the tree of physical operators */ public PushPhysicalPlan buildPushPhysicalPlan( final LogicalPlanNode logicalPlanNode, final Context context, final Optional<PushOffsetRange> offsetRange, final Optional<String> catchupConsumerGroup ) {<FILL_FUNCTION_BODY>} private ProjectOperator translateProjectNode(final QueryProjectNode logicalNode) { final ProcessingLogger logger = processingLogContext .getLoggerFactory() .getLogger( QueryLoggerUtil.queryLoggerName( QueryType.PULL_QUERY, contextStacker.push("PROJECT").getQueryContext()) ); return new ProjectOperator( logger, logicalNode ); } private SelectOperator translateFilterNode(final QueryFilterNode logicalNode) { final ProcessingLogger logger = processingLogContext .getLoggerFactory() .getLogger( QueryLoggerUtil.queryLoggerName( QueryType.PULL_QUERY, contextStacker.push("SELECT").getQueryContext()) ); return new SelectOperator(logicalNode, logger); } private AbstractPhysicalOperator translateDataSourceNode( final DataSourceNode logicalNode, final Optional<PushOffsetRange> offsetRange, final String catchupConsumerGroupId ) { final ScalablePushRegistry scalablePushRegistry = persistentQueryMetadata.getScalablePushRegistry() .orElseThrow(() -> new IllegalStateException(REGISTRY_NOT_FOUND_ERROR_MESSAGE)); querySourceType = logicalNode.isWindowed() ? QuerySourceType.WINDOWED : QuerySourceType.NON_WINDOWED; final Optional<CatchupMetadata> catchupMetadata = offsetRange.map(or -> new CatchupMetadata(or, catchupConsumerGroupId)); return new PeekStreamOperator(scalablePushRegistry, logicalNode, queryId, catchupMetadata); } private String getConsumerGroupId(final Optional<String> catchupConsumerGroupFromSource) { final ScalablePushRegistry scalablePushRegistry = persistentQueryMetadata.getScalablePushRegistry() .orElseThrow(() -> new IllegalStateException(REGISTRY_NOT_FOUND_ERROR_MESSAGE)); return catchupConsumerGroupFromSource.orElse( scalablePushRegistry.getCatchupConsumerId(UUID.randomUUID().toString())); } private QueryId uniqueQueryId() { return new QueryId("SCALABLE_PUSH_QUERY_" + UUID.randomUUID()); } }
final String catchupConsumerGroupId = getConsumerGroupId(catchupConsumerGroup); PushDataSourceOperator dataSourceOperator = null; final OutputNode outputNode = logicalPlanNode.getNode() .orElseThrow(() -> new IllegalArgumentException("Need an output node to build a plan")); if (!(outputNode instanceof KsqlBareOutputNode)) { throw new KsqlException("Push queries expect the root of the logical plan to be a " + "KsqlBareOutputNode."); } // We skip KsqlBareOutputNode in the translation since it only applies the LIMIT PlanNode currentLogicalNode = outputNode.getSource(); AbstractPhysicalOperator prevPhysicalOp = null; AbstractPhysicalOperator rootPhysicalOp = null; while (true) { AbstractPhysicalOperator currentPhysicalOp = null; if (currentLogicalNode instanceof QueryProjectNode) { currentPhysicalOp = translateProjectNode((QueryProjectNode)currentLogicalNode); } else if (currentLogicalNode instanceof QueryFilterNode) { currentPhysicalOp = translateFilterNode((QueryFilterNode) currentLogicalNode); } else if (currentLogicalNode instanceof DataSourceNode) { currentPhysicalOp = translateDataSourceNode( (DataSourceNode) currentLogicalNode, offsetRange, catchupConsumerGroupId); dataSourceOperator = (PushDataSourceOperator) currentPhysicalOp; } else { throw new KsqlException(String.format( "Error in translating logical to physical plan for scalable push queries:" + " unrecognized logical node %s.", currentLogicalNode)); } if (prevPhysicalOp == null) { rootPhysicalOp = currentPhysicalOp; } else { prevPhysicalOp.addChild(currentPhysicalOp); } prevPhysicalOp = currentPhysicalOp; // Exit the loop when a leaf node is reached if (currentLogicalNode.getSources().isEmpty()) { break; } if (currentLogicalNode.getSources().size() > 1) { throw new KsqlException("Push queries do not support joins or nested sub-queries yet."); } currentLogicalNode = currentLogicalNode.getSources().get(0); } if (dataSourceOperator == null) { throw new IllegalStateException("DataSourceOperator cannot be null in Push physical plan"); } return new PushPhysicalPlan( rootPhysicalOp, (rootPhysicalOp).getLogicalNode().getSchema(), queryId, catchupConsumerGroupId, dataSourceOperator.getScalablePushRegistry(), dataSourceOperator, context, querySourceType);
948
674
1,622
15,379
liquibase_liquibase
liquibase/liquibase-standard/src/main/java/liquibase/sqlgenerator/core/AddPrimaryKeyGenerator.java
AddPrimaryKeyGenerator
generateSql
class AddPrimaryKeyGenerator extends AbstractSqlGenerator<AddPrimaryKeyStatement> { @Override public boolean supports(AddPrimaryKeyStatement statement, Database database) { return (!(database instanceof SQLiteDatabase)); } @Override public ValidationErrors validate(AddPrimaryKeyStatement addPrimaryKeyStatement, Database database, SqlGeneratorChain sqlGeneratorChain) { ValidationErrors validationErrors = new ValidationErrors(); validationErrors.checkRequiredField("columnNames", addPrimaryKeyStatement.getColumnNames()); validationErrors.checkRequiredField("tableName", addPrimaryKeyStatement.getTableName()); if (addPrimaryKeyStatement.isClustered() != null) { if (database instanceof PostgresDatabase) { if (addPrimaryKeyStatement.isClustered() && addPrimaryKeyStatement.getConstraintName() == null) { validationErrors.addError("Postgresql requires constraintName on addPrimaryKey when clustered=true"); } } else if (database instanceof MSSQLDatabase || database instanceof MockDatabase) { //clustered is fine } else if (addPrimaryKeyStatement.isClustered()) { validationErrors.addError("Cannot specify clustered=true on "+database.getShortName()); } } if (!((database instanceof OracleDatabase) || (database instanceof AbstractDb2Database) || (database instanceof PostgresDatabase))) { validationErrors.checkDisallowedField("forIndexName", addPrimaryKeyStatement.getForIndexName(), database); } return validationErrors; } @Override public Sql[] generateSql(AddPrimaryKeyStatement statement, Database database, SqlGeneratorChain sqlGeneratorChain) {<FILL_FUNCTION_BODY>} protected PrimaryKey getAffectedPrimaryKey(AddPrimaryKeyStatement statement) { return new PrimaryKey().setTable((Table) new Table().setName(statement.getTableName()).setSchema(statement.getCatalogName(), statement.getSchemaName())); } }
String sql; if ((statement.getConstraintName() == null) || (database instanceof MySQLDatabase) || (database instanceof SybaseASADatabase)) { sql = "ALTER TABLE " + database.escapeTableName(statement.getCatalogName(), statement.getSchemaName(), statement.getTableName()) + " ADD PRIMARY KEY (" + database.escapeColumnNameList(statement.getColumnNames()) + ")"; } else { sql = "ALTER TABLE " + database.escapeTableName(statement.getCatalogName(), statement.getSchemaName(), statement.getTableName()) + " ADD CONSTRAINT " + database.escapeConstraintName(statement.getConstraintName())+" PRIMARY KEY"; if ((database instanceof MSSQLDatabase) && (statement.isClustered() != null)) { if (statement.isClustered()) { sql += " CLUSTERED"; } else { sql += " NONCLUSTERED"; } } sql += " (" + database.escapeColumnNameList(statement.getColumnNames()) + ")"; } if ((StringUtil.trimToNull(statement.getTablespace()) != null) && database.supportsTablespaces()) { if (database instanceof MSSQLDatabase) { sql += " ON "+statement.getTablespace(); } else if ((database instanceof AbstractDb2Database) || (database instanceof SybaseASADatabase)) { //not supported } else { sql += " USING INDEX TABLESPACE "+statement.getTablespace(); } } if ((database instanceof OracleDatabase) && (statement.getForIndexName() != null)) { sql += " USING INDEX "+database.escapeObjectName(statement.getForIndexCatalogName(), statement.getForIndexSchemaName(), statement.getForIndexName(), Index.class); } if (database instanceof OracleDatabase) { sql += !statement.shouldValidate() ? " ENABLE NOVALIDATE " : ""; } if ((database instanceof PostgresDatabase) && (statement.isClustered() != null) && statement.isClustered() && (statement.getConstraintName() != null)) { return new Sql[] { new UnparsedSql(sql, getAffectedPrimaryKey(statement)), new UnparsedSql("CLUSTER "+database.escapeTableName(statement.getCatalogName(), statement.getSchemaName(), statement.getTableName())+" USING "+database.escapeObjectName(statement.getConstraintName(), PrimaryKey.class)) }; } else { return new Sql[] { new UnparsedSql(sql, getAffectedPrimaryKey(statement)) }; }
474
659
1,133
31,205
pmd_pmd
pmd/pmd-core/src/main/java/net/sourceforge/pmd/renderers/AbstractAccumulatingRenderer.java
AbstractAccumulatingRenderer
close
class AbstractAccumulatingRenderer extends AbstractRenderer { public AbstractAccumulatingRenderer(String name, String description) { super(name, description); } @Override public void start() throws IOException { // do nothing } @Override public void end() throws IOException { // do nothing } @Override public void startFileAnalysis(TextFile dataSource) { Objects.requireNonNull(dataSource); } /** * {@inheritDoc} * * @implNote The implementation in this class does nothing. All the reported violations and * errors are accumulated and can be rendered once with {@link #outputReport(Report)} in the * end. Subclasses of {@link AbstractAccumulatingRenderer} cannot override this method * anymore. */ @Override public final void renderFileReport(Report report) throws IOException { // do nothing, final because it will never be called by the listener Objects.requireNonNull(report); } /** * Output the report, called once at the end of the analysis. * * {@inheritDoc} */ protected abstract void outputReport(Report report) throws IOException; @Override public GlobalAnalysisListener newListener() throws IOException { try (TimedOperation ignored = TimeTracker.startOperation(TimedOperationCategory.REPORTING)) { this.start(); } return new GlobalAnalysisListener() { final GlobalReportBuilderListener reportBuilder = new GlobalReportBuilderListener(); @Override public FileAnalysisListener startFileAnalysis(TextFile file) { AbstractAccumulatingRenderer.this.startFileAnalysis(file); return reportBuilder.startFileAnalysis(file); } @Override public void onConfigError(ConfigurationError error) { reportBuilder.onConfigError(error); } @Override public void close() throws Exception {<FILL_FUNCTION_BODY>} }; } }
reportBuilder.close(); try (TimedOperation ignored = TimeTracker.startOperation(TimedOperationCategory.REPORTING)) { outputReport(reportBuilder.getResult()); end(); flush(); }
495
58
553
37,885
YunaiV_ruoyi-vue-pro
ruoyi-vue-pro/yudao-framework/yudao-spring-boot-starter-web/src/main/java/cn/iocoder/yudao/framework/xss/core/json/XssStringJsonDeserializer.java
XssStringJsonDeserializer
deserialize
class XssStringJsonDeserializer extends StringDeserializer { /** * 属性 */ private final XssProperties properties; /** * 路径匹配器 */ private final PathMatcher pathMatcher; private final XssCleaner xssCleaner; @Override public String deserialize(JsonParser p, DeserializationContext ctxt) throws IOException {<FILL_FUNCTION_BODY>} }
// 1. 白名单 URL 的处理 HttpServletRequest request = ServletUtils.getRequest(); if (request != null) { String uri = ServletUtils.getRequest().getRequestURI(); if (properties.getExcludeUrls().stream().anyMatch(excludeUrl -> pathMatcher.match(excludeUrl, uri))) { return p.getText(); } } // 2. 真正使用 xssCleaner 进行过滤 if (p.hasToken(JsonToken.VALUE_STRING)) { return xssCleaner.clean(p.getText()); } JsonToken t = p.currentToken(); // [databind#381] if (t == JsonToken.START_ARRAY) { return _deserializeFromArray(p, ctxt); } // need to gracefully handle byte[] data, as base64 if (t == JsonToken.VALUE_EMBEDDED_OBJECT) { Object ob = p.getEmbeddedObject(); if (ob == null) { return null; } if (ob instanceof byte[]) { return ctxt.getBase64Variant().encode((byte[]) ob, false); } // otherwise, try conversion using toString()... return ob.toString(); } // 29-Jun-2020, tatu: New! "Scalar from Object" (mostly for XML) if (t == JsonToken.START_OBJECT) { return ctxt.extractScalarFromObject(p, this, _valueClass); } if (t.isScalarValue()) { String text = p.getValueAsString(); return xssCleaner.clean(text); } return (String) ctxt.handleUnexpectedToken(_valueClass, p);
118
466
584
4,472
DependencyTrack_dependency-track
dependency-track/src/main/java/org/dependencytrack/model/FindingAttribution.java
FindingAttribution
setComponent
class FindingAttribution implements Serializable { private static final long serialVersionUID = -2609603709255246845L; @PrimaryKey @Persistent(valueStrategy = IdGeneratorStrategy.NATIVE) @JsonIgnore private long id; @Persistent @Column(name = "ATTRIBUTED_ON", allowsNull = "false") @NotNull private Date attributedOn; @Persistent @Column(name = "ANALYZERIDENTITY", allowsNull = "false") private AnalyzerIdentity analyzerIdentity; @Persistent(defaultFetchGroup = "true") @Column(name = "COMPONENT_ID", allowsNull = "false") @NotNull private Component component; @Persistent(defaultFetchGroup = "false") @Column(name = "PROJECT_ID", allowsNull = "false") @NotNull private Project project; @Persistent(defaultFetchGroup = "true") @Column(name = "VULNERABILITY_ID", allowsNull = "false") @NotNull private Vulnerability vulnerability; @Persistent @Column(name = "ALT_ID", allowsNull = "true") private String alternateIdentifier; @Persistent @Column(name = "REFERENCE_URL", allowsNull = "true") private String referenceUrl; @Persistent(customValueStrategy = "uuid") @Unique(name = "FINDINGATTRIBUTION_UUID_IDX") @Column(name = "UUID", jdbcType = "VARCHAR", length = 36, allowsNull = "false") @NotNull private UUID uuid; public FindingAttribution() {} public FindingAttribution(Component component, Vulnerability vulnerability, AnalyzerIdentity analyzerIdentity, String alternateIdentifier, String referenceUrl) { this.component = component; this.project = component.getProject(); this.vulnerability = vulnerability; this.analyzerIdentity = analyzerIdentity; this.attributedOn = new Date(); this.alternateIdentifier = alternateIdentifier; this.referenceUrl = referenceUrl; } public long getId() { return id; } public void setId(long id) { this.id = id; } public Date getAttributedOn() { return attributedOn; } public void setAttributedOn(Date attributedOn) { this.attributedOn = attributedOn; } public AnalyzerIdentity getAnalyzerIdentity() { return analyzerIdentity; } public void setAnalyzerIdentity(AnalyzerIdentity analyzerIdentity) { this.analyzerIdentity = analyzerIdentity; } public Component getComponent() { return component; } public void setComponent(Component component) {<FILL_FUNCTION_BODY>} public Vulnerability getVulnerability() { return vulnerability; } public void setVulnerability(Vulnerability vulnerability) { this.vulnerability = vulnerability; } public String getAlternateIdentifier() { return alternateIdentifier; } public void setAlternateIdentifier(String alternateIdentifier) { this.alternateIdentifier = alternateIdentifier; } public String getReferenceUrl() { return referenceUrl; } public void setReferenceUrl(String referenceUrl) { this.referenceUrl = referenceUrl; } public UUID getUuid() { return uuid; } public void setUuid(UUID uuid) { this.uuid = uuid; } }
this.component = component; this.project = component.getProject();
944
22
966
16,732
graphhopper_graphhopper
graphhopper/core/src/main/java/com/graphhopper/routing/util/countryrules/europe/AlbaniaCountryRule.java
AlbaniaCountryRule
getToll
class AlbaniaCountryRule implements CountryRule { @Override public Toll getToll(ReaderWay readerWay, Toll currentToll) {<FILL_FUNCTION_BODY>} }
if (currentToll != Toll.MISSING) { return currentToll; } return Toll.NO;
53
39
92
21,109
graphhopper_graphhopper
graphhopper/core/src/main/java/com/graphhopper/routing/util/countryrules/europe/PolandCountryRule.java
PolandCountryRule
getToll
class PolandCountryRule implements CountryRule { @Override public Toll getToll(ReaderWay readerWay, Toll currentToll) {<FILL_FUNCTION_BODY>} }
if (currentToll != Toll.MISSING) { return currentToll; } RoadClass roadClass = RoadClass.find(readerWay.getTag("highway", "")); if (RoadClass.MOTORWAY == roadClass) return Toll.HGV; return currentToll;
52
89
141
21,138
redis_lettuce
lettuce/src/main/java/io/lettuce/core/StaticRedisCredentials.java
StaticRedisCredentials
equals
class StaticRedisCredentials implements RedisCredentials { private final String username; private final char[] password; StaticRedisCredentials(String username, char[] password) { this.username = username; this.password = password != null ? Arrays.copyOf(password, password.length) : null; } @Override public String getUsername() { return username; } @Override public boolean hasUsername() { return username != null; } @Override public char[] getPassword() { return hasPassword() ? Arrays.copyOf(password, password.length) : null; } @Override public boolean hasPassword() { return password != null; } @Override public boolean equals(Object o) {<FILL_FUNCTION_BODY>} @Override public int hashCode() { int result = username != null ? username.hashCode() : 0; result = 31 * result + Arrays.hashCode(password); return result; } }
if (this == o) { return true; } if (!(o instanceof RedisCredentials)) { return false; } RedisCredentials that = (RedisCredentials) o; if (username != null ? !username.equals(that.getUsername()) : that.getUsername() != null) { return false; } return Arrays.equals(password, that.getPassword());
283
114
397
39,227
languagetool-org_languagetool
languagetool/languagetool-core/src/main/java/org/languagetool/languagemodel/bert/RemoteLanguageModel.java
Request
score
class Request { public String text; public int start; public int end; public List<String> candidates; public Request(String text, int start, int end, List<String> candidates) { this.text = text; this.start = start; this.end = end; this.candidates = candidates; } public ScoreRequest convert() { List<Mask> masks = Arrays.asList(Mask.newBuilder() .setStart(start) .setEnd(end) .addAllCandidates(candidates) .build()); return ScoreRequest.newBuilder().setText(text).addAllMask(masks).build(); } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Request request = (Request) o; return start == request.start && end == request.end && text.equals(request.text) && candidates.equals(request.candidates); } @Override public int hashCode() { return Objects.hash(text, start, end, candidates); } } public RemoteLanguageModel(String host, int port, boolean useSSL, @Nullable String clientPrivateKey, @Nullable String clientCertificate, @Nullable String rootCertificate) throws SSLException { // TODO configure deadline/retries/... here? channel = getChannel(host, port, useSSL, clientPrivateKey, clientCertificate, rootCertificate); model = BertLmGrpc.newBlockingStub(channel); } private ManagedChannel getChannel(String host, int port, boolean useSSL, @Nullable String clientPrivateKey, @Nullable String clientCertificate, @Nullable String rootCertificate) throws SSLException { NettyChannelBuilder channelBuilder = NettyChannelBuilder.forAddress(host, port); if (useSSL) { SslContextBuilder sslContextBuilder = GrpcSslContexts.forClient(); if (rootCertificate != null) { sslContextBuilder.trustManager(new File(rootCertificate)); } if (clientCertificate != null && clientPrivateKey != null) { sslContextBuilder.keyManager(new File(clientCertificate), new File(clientPrivateKey)); } channelBuilder = channelBuilder.negotiationType(NegotiationType.TLS).sslContext(sslContextBuilder.build()); } else { channelBuilder = channelBuilder.usePlaintext(); } return channelBuilder.build(); } public void shutdown() { if (channel != null) { channel.shutdownNow(); } } public List<List<Double>> batchScore(List<Request> requests, long timeoutMilliseconds) throws TimeoutException { Map<Request, List<Double>> cachedRequests = new HashMap<>(); List<Request> uncachedRequests = new ArrayList<>(); for (Request request : requests) { List<Double> result = cache.getIfPresent(request); if (result == null) { uncachedRequests.add(request); } else { cachedRequests.put(request, result); } } BatchScoreRequest batch = BatchScoreRequest.newBuilder().addAllRequests( uncachedRequests.stream().map(Request::convert).collect(Collectors.toList()) ).build(); // TODO multiple masks List<List<Double>> nonCacheResult; try { BertLmBlockingStub stub; if (timeoutMilliseconds > 0) { stub = model.withDeadlineAfter(timeoutMilliseconds, TimeUnit.MILLISECONDS); } else { stub = model; } nonCacheResult = stub.batchScore(batch) .getResponsesList().stream().map(r -> r.getScoresList().get(0).getScoreList()).collect(Collectors.toList()); } catch (StatusRuntimeException e) { if (e.getStatus().getCode() == Status.DEADLINE_EXCEEDED.getCode()) { throw new TimeoutException(e.getMessage()); } else { throw e; } } // List<List<Double>> allResults = new ArrayList<>(); int i = 0; for (Request request : requests) { List<Double> result = cachedRequests.get(request); if (result != null) { //System.out.println("Adding result from cache"); allResults.add(result); } else { //System.out.println("Adding result from remote"); allResults.add(nonCacheResult.get(i++)); } } int j = 0; for (List<Double> re : nonCacheResult) { // a CacheLoader doesn't work with batching, so add manually: //System.out.println("Adding request to cache"); cache.put(uncachedRequests.get(j), re); j++; } return allResults; } public List<Double> score(Request req) {<FILL_FUNCTION_BODY>
// TODO deal with max seq length, extract windows // TODO mask multiple tokens in a sentence // TODO multiple masks return model.score(req.convert()).getScoresList().get(0).getScoreList();
1,330
58
1,388
1,572
apache_dubbo
dubbo/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/zookeeper/AbstractZookeeperTransporter.java
AbstractZookeeperTransporter
getURLBackupAddress
class AbstractZookeeperTransporter implements ZookeeperTransporter { private static final Logger logger = LoggerFactory.getLogger(ZookeeperTransporter.class); private final Map<String, ZookeeperClient> zookeeperClientMap = new ConcurrentHashMap<>(); /** * share connect for registry, metadata, etc.. * <p> * Make sure the connection is connected. * * @param url * @return */ @Override public ZookeeperClient connect(URL url) { ZookeeperClient zookeeperClient; // address format: {[username:password@]address} List<String> addressList = getURLBackupAddress(url); // The field define the zookeeper server , including protocol, host, port, username, password if ((zookeeperClient = fetchAndUpdateZookeeperClientCache(addressList)) != null && zookeeperClient.isConnected()) { logger.info("find valid zookeeper client from the cache for address: " + url); return zookeeperClient; } // avoid creating too many connections, so add lock synchronized (zookeeperClientMap) { if ((zookeeperClient = fetchAndUpdateZookeeperClientCache(addressList)) != null && zookeeperClient.isConnected()) { logger.info("find valid zookeeper client from the cache for address: " + url); return zookeeperClient; } zookeeperClient = createZookeeperClient(url); logger.info("No valid zookeeper client found from cache, therefore create a new client for url. " + url); writeToClientMap(addressList, zookeeperClient); } return zookeeperClient; } /** * @param url the url that will create zookeeper connection . * The url in AbstractZookeeperTransporter#connect parameter is rewritten by this one. * such as: zookeeper://127.0.0.1:2181/org.apache.dubbo.remoting.zookeeper.ZookeeperTransporter * @return */ protected abstract ZookeeperClient createZookeeperClient(URL url); /** * get the ZookeeperClient from cache, the ZookeeperClient must be connected. * <p> * It is not private method for unit test. * * @param addressList * @return */ public ZookeeperClient fetchAndUpdateZookeeperClientCache(List<String> addressList) { ZookeeperClient zookeeperClient = null; for (String address : addressList) { if ((zookeeperClient = zookeeperClientMap.get(address)) != null && zookeeperClient.isConnected()) { break; } } // mapping new backup address if (zookeeperClient != null && zookeeperClient.isConnected()) { writeToClientMap(addressList, zookeeperClient); } return zookeeperClient; } /** * get all zookeeper urls (such as zookeeper://127.0.0.1:2181?backup=127.0.0.1:8989,127.0.0.1:9999) * * @param url such as zookeeper://127.0.0.1:2181?backup=127.0.0.1:8989,127.0.0.1:9999 * @return such as 127.0.0.1:2181,127.0.0.1:8989,127.0.0.1:9999 */ public List<String> getURLBackupAddress(URL url) {<FILL_FUNCTION_BODY>} /** * write address-ZookeeperClient relationship to Map * * @param addressList * @param zookeeperClient */ void writeToClientMap(List<String> addressList, ZookeeperClient zookeeperClient) { for (String address : addressList) { zookeeperClientMap.put(address, zookeeperClient); } } /** * redefine the url for zookeeper. just keep protocol, username, password, host, port, and individual parameter. * * @param url * @return */ URL toClientURL(URL url) { Map<String, String> parameterMap = new HashMap<>(); // for CuratorZookeeperClient if (url.getParameter(TIMEOUT_KEY) != null) { parameterMap.put(TIMEOUT_KEY, url.getParameter(TIMEOUT_KEY)); } if (url.getParameter(RemotingConstants.BACKUP_KEY) != null) { parameterMap.put(RemotingConstants.BACKUP_KEY, url.getParameter(RemotingConstants.BACKUP_KEY)); } return new ServiceConfigURL( url.getProtocol(), url.getUsername(), url.getPassword(), url.getHost(), url.getPort(), ZookeeperTransporter.class.getName(), parameterMap); } /** * for unit test * * @return */ public Map<String, ZookeeperClient> getZookeeperClientMap() { return zookeeperClientMap; } @Override public void destroy() { // only destroy zk clients here for (ZookeeperClient client : zookeeperClientMap.values()) { client.close(); } zookeeperClientMap.clear(); } }
List<String> addressList = new ArrayList<>(); addressList.add(url.getAddress()); addressList.addAll(url.getParameter(RemotingConstants.BACKUP_KEY, Collections.emptyList())); String authPrefix = null; if (StringUtils.isNotEmpty(url.getUsername())) { StringBuilder buf = new StringBuilder(); buf.append(url.getUsername()); if (StringUtils.isNotEmpty(url.getPassword())) { buf.append(':'); buf.append(url.getPassword()); } buf.append('@'); authPrefix = buf.toString(); } if (StringUtils.isNotEmpty(authPrefix)) { List<String> authedAddressList = new ArrayList<>(addressList.size()); for (String addr : addressList) { authedAddressList.add(authPrefix + addr); } return authedAddressList; } return addressList;
1,491
246
1,737
66,951
questdb_questdb
questdb/core/src/main/java/io/questdb/griffin/engine/functions/conditional/NullIfDoubleFunctionFactory.java
NullIfDoubleFunction
getDouble
class NullIfDoubleFunction extends DoubleFunction implements BinaryFunction { private final Function doubleFunc1; private final Function doubleFunc2; public NullIfDoubleFunction(Function doubleFunc1, Function doubleFunc2) { this.doubleFunc1 = doubleFunc1; this.doubleFunc2 = doubleFunc2; } @Override public double getDouble(Record rec) {<FILL_FUNCTION_BODY>} @Override public Function getLeft() { return doubleFunc1; } @Override public Function getRight() { return doubleFunc2; } @Override public void toPlan(PlanSink sink) { sink.val("nullif(").val(doubleFunc1).val(',').val(doubleFunc2).val(')'); } }
return Numbers.equals(doubleFunc1.getDouble(rec), doubleFunc2.getDouble(rec)) ? Double.NaN : doubleFunc1.getDouble(rec);
207
45
252
61,466
houbb_sensitive-word
sensitive-word/src/main/java/com/github/houbb/sensitive/word/support/result/WordResultHandlerWordTags.java
WordResultHandlerWordTags
doHandle
class WordResultHandlerWordTags extends AbstractWordResultHandler<WordTagsDto> { @Override protected WordTagsDto doHandle(IWordResult wordResult, IWordContext wordContext, String originalText) {<FILL_FUNCTION_BODY>} }
// 截取 String word = InnerWordCharUtils.getString(originalText.toCharArray(), wordResult); // 标签 WordTagsDto dto = new WordTagsDto(); dto.setWord(word); // 获取 tags Set<String> wordTags = wordContext.wordTag().getTag(word); dto.setTags(wordTags); return dto;
66
107
173
22,638
AsyncHttpClient_async-http-client
async-http-client/client/src/main/java/org/asynchttpclient/channel/DefaultKeepAliveStrategy.java
DefaultKeepAliveStrategy
keepAlive
class DefaultKeepAliveStrategy implements KeepAliveStrategy { /** * Implemented in accordance with RFC 7230 section 6.1 <a href="https://tools.ietf.org/html/rfc7230#section-6.1">...</a> */ @Override public boolean keepAlive(InetSocketAddress remoteAddress, Request ahcRequest, HttpRequest request, HttpResponse response) {<FILL_FUNCTION_BODY>} }
return HttpUtil.isKeepAlive(response) && HttpUtil.isKeepAlive(request) && // support non-standard Proxy-Connection !response.headers().contains("Proxy-Connection", CLOSE, true);
123
60
183
13,202
shopizer-ecommerce_shopizer
shopizer/sm-core/src/main/java/com/salesmanager/core/business/services/reference/loader/ConfigurationModulesLoader.java
ConfigurationModulesLoader
loadIntegrationConfigurations
class ConfigurationModulesLoader { @SuppressWarnings("unused") private static final Logger LOGGER = LoggerFactory.getLogger(ConfigurationModulesLoader.class); public static String toJSONString(Map<String,IntegrationConfiguration> configurations) throws Exception { StringBuilder jsonModules = new StringBuilder(); jsonModules.append("["); int count = 0; for(Object key : configurations.keySet()) { String k = (String)key; IntegrationConfiguration c = configurations.get(k); String jsonString = c.toJSONString(); jsonModules.append(jsonString); count ++; if(count<configurations.size()) { jsonModules.append(","); } } jsonModules.append("]"); return jsonModules.toString(); } @SuppressWarnings({ "rawtypes", "unchecked" }) public static Map<String,IntegrationConfiguration> loadIntegrationConfigurations(String value) throws Exception {<FILL_FUNCTION_BODY>} }
Map<String,IntegrationConfiguration> modules = new HashMap<String,IntegrationConfiguration>(); ObjectMapper mapper = new ObjectMapper(); try { Map[] objects = mapper.readValue(value, Map[].class); for (Map object : objects) { IntegrationConfiguration configuration = new IntegrationConfiguration(); String moduleCode = (String) object.get("moduleCode"); if (object.get("active") != null) { configuration.setActive((Boolean) object.get("active")); } if (object.get("defaultSelected") != null) { configuration.setDefaultSelected((Boolean) object.get("defaultSelected")); } if (object.get("environment") != null) { configuration.setEnvironment((String) object.get("environment")); } configuration.setModuleCode(moduleCode); modules.put(moduleCode, configuration); if (object.get("integrationKeys") != null) { Map<String, String> confs = (Map<String, String>) object.get("integrationKeys"); configuration.setIntegrationKeys(confs); } if (object.get("integrationKeys") != null) { Map<String, List<String>> options = (Map<String, List<String>>) object.get("integrationOptions"); configuration.setIntegrationOptions(options); } } return modules; } catch (Exception e) { throw new ServiceException(e); }
288
417
705
40,320
RipMeApp_ripme
ripme/src/main/java/com/rarchives/ripme/ripper/rippers/ReadcomicRipper.java
ReadcomicRipper
getGID
class ReadcomicRipper extends ViewcomicRipper { public ReadcomicRipper(URL url) throws IOException { super(url); } @Override public String getHost() { return "read-comic"; } @Override public String getDomain() { return "read-comic.com"; } @Override public String getGID(URL url) throws MalformedURLException {<FILL_FUNCTION_BODY>} @Override public List<String> getURLsFromPage(Document doc) { List<String> result = new ArrayList<String>(); for (Element el : doc.select("div.pinbin-copy > a > img")) { result.add(el.attr("src")); } return result; } }
Pattern p = Pattern.compile("https?://read-comic.com/([a-zA-Z1-9_-]*)/?$"); Matcher m = p.matcher(url.toExternalForm()); if (m.matches()) { return m.group(1); } throw new MalformedURLException("Expected view-comic URL format: " + "read-comic.com/COMIC_NAME - got " + url + " instead");
216
122
338
39,688
apache_hertzbeat
hertzbeat/common/src/main/java/org/apache/hertzbeat/common/util/LruHashMap.java
LruHashMap
removeEldestEntry
class LruHashMap<K, V> extends LinkedHashMap<K, V> { private final int threshold; public LruHashMap(int threshold) { super(16, 0.75f, true); this.threshold = threshold; } @Override protected boolean removeEldestEntry(Map.Entry eldest) {<FILL_FUNCTION_BODY>} }
return size() > threshold;
107
11
118
7,153
YunaiV_ruoyi-vue-pro
ruoyi-vue-pro/yudao-module-system/yudao-module-system-biz/src/main/java/cn/iocoder/yudao/module/system/service/errorcode/ErrorCodeServiceImpl.java
ErrorCodeServiceImpl
getErrorCodeList
class ErrorCodeServiceImpl implements ErrorCodeService { @Resource private ErrorCodeMapper errorCodeMapper; @Override public Long createErrorCode(ErrorCodeSaveReqVO createReqVO) { // 校验 code 重复 validateCodeDuplicate(createReqVO.getCode(), null); // 插入 ErrorCodeDO errorCode = BeanUtils.toBean(createReqVO, ErrorCodeDO.class) .setType(ErrorCodeTypeEnum.MANUAL_OPERATION.getType()); errorCodeMapper.insert(errorCode); // 返回 return errorCode.getId(); } @Override public void updateErrorCode(ErrorCodeSaveReqVO updateReqVO) { // 校验存在 validateErrorCodeExists(updateReqVO.getId()); // 校验 code 重复 validateCodeDuplicate(updateReqVO.getCode(), updateReqVO.getId()); // 更新 ErrorCodeDO updateObj = BeanUtils.toBean(updateReqVO, ErrorCodeDO.class) .setType(ErrorCodeTypeEnum.MANUAL_OPERATION.getType()); errorCodeMapper.updateById(updateObj); } @Override public void deleteErrorCode(Long id) { // 校验存在 validateErrorCodeExists(id); // 删除 errorCodeMapper.deleteById(id); } /** * 校验错误码的唯一字段是否重复 * * 是否存在相同编码的错误码 * * @param code 错误码编码 * @param id 错误码编号 */ @VisibleForTesting public void validateCodeDuplicate(Integer code, Long id) { ErrorCodeDO errorCodeDO = errorCodeMapper.selectByCode(code); if (errorCodeDO == null) { return; } // 如果 id 为空,说明不用比较是否为相同 id 的错误码 if (id == null) { throw exception(ERROR_CODE_DUPLICATE); } if (!errorCodeDO.getId().equals(id)) { throw exception(ERROR_CODE_DUPLICATE); } } @VisibleForTesting void validateErrorCodeExists(Long id) { if (errorCodeMapper.selectById(id) == null) { throw exception(ERROR_CODE_NOT_EXISTS); } } @Override public ErrorCodeDO getErrorCode(Long id) { return errorCodeMapper.selectById(id); } @Override public PageResult<ErrorCodeDO> getErrorCodePage(ErrorCodePageReqVO pageReqVO) { return errorCodeMapper.selectPage(pageReqVO); } @Override @Transactional public void autoGenerateErrorCodes(List<ErrorCodeAutoGenerateReqDTO> autoGenerateDTOs) { if (CollUtil.isEmpty(autoGenerateDTOs)) { return; } // 获得错误码 List<ErrorCodeDO> errorCodeDOs = errorCodeMapper.selectListByCodes( convertSet(autoGenerateDTOs, ErrorCodeAutoGenerateReqDTO::getCode)); Map<Integer, ErrorCodeDO> errorCodeDOMap = convertMap(errorCodeDOs, ErrorCodeDO::getCode); // 遍历 autoGenerateBOs 数组,逐个插入或更新。考虑到每次量级不大,就不走批量了 autoGenerateDTOs.forEach(autoGenerateDTO -> { ErrorCodeDO errorCode = errorCodeDOMap.get(autoGenerateDTO.getCode()); // 不存在,则进行新增 if (errorCode == null) { errorCode = BeanUtils.toBean(autoGenerateDTO, ErrorCodeDO.class) .setType(ErrorCodeTypeEnum.AUTO_GENERATION.getType()); errorCodeMapper.insert(errorCode); return; } // 存在,则进行更新。更新有三个前置条件: // 条件 1. 只更新自动生成的错误码,即 Type 为 ErrorCodeTypeEnum.AUTO_GENERATION if (!ErrorCodeTypeEnum.AUTO_GENERATION.getType().equals(errorCode.getType())) { return; } // 条件 2. 分组 applicationName 必须匹配,避免存在错误码冲突的情况 if (!autoGenerateDTO.getApplicationName().equals(errorCode.getApplicationName())) { log.error("[autoGenerateErrorCodes][自动创建({}/{}) 错误码失败,数据库中已经存在({}/{})]", autoGenerateDTO.getCode(), autoGenerateDTO.getApplicationName(), errorCode.getCode(), errorCode.getApplicationName()); return; } // 条件 3. 错误提示语存在差异 if (autoGenerateDTO.getMessage().equals(errorCode.getMessage())) { return; } // 最终匹配,进行更新 errorCodeMapper.updateById(new ErrorCodeDO().setId(errorCode.getId()).setMessage(autoGenerateDTO.getMessage())); }); } @Override public List<ErrorCodeRespDTO> getErrorCodeList(String applicationName, LocalDateTime minUpdateTime) {<FILL_FUNCTION_BODY>} }
List<ErrorCodeDO> list = errorCodeMapper.selectListByApplicationNameAndUpdateTimeGt( applicationName, minUpdateTime); return BeanUtils.toBean(list, ErrorCodeRespDTO.class);
1,368
58
1,426
4,627
apache_dubbo
dubbo/dubbo-common/src/main/java/org/apache/dubbo/rpc/executor/DefaultExecutorSupport.java
DefaultExecutorSupport
getExecutor
class DefaultExecutorSupport implements ExecutorSupport { private final ExecutorRepository executorRepository; private final URL url; public DefaultExecutorSupport(URL url) { this.url = url; this.executorRepository = ExecutorRepository.getInstance(url.getOrDefaultApplicationModel()); } @Override public Executor getExecutor(Object data) {<FILL_FUNCTION_BODY>} }
return executorRepository.getExecutor(url);
104
15
119
66,974
zhkl0228_unidbg
unidbg/unidbg-ios/src/main/java/com/github/unidbg/ios/kevent/KEvent.java
KEvent
processChangeList
class KEvent extends BaseDarwinFileIO { private static final Log log = LogFactory.getLog(KEvent.class); private static final short EVFILT_SIGNAL = (-6); /* attached to struct proc */ private static final short EVFILT_MACHPORT = (-8); /* Mach portsets */ private static final short EVFILT_USER = (-10); /* User events */ private static final short EVFILT_VM = (-12); /* Virtual memory events */ private final Map<Integer, KEvent64> registerMap = new HashMap<>(); final List<KEvent64> pendingEventList = new ArrayList<>(); public KEvent(int oflags) { super(oflags); } private static final int EV_ADD = 0x0001; /* add event to kq (implies enable) */ private static final int EV_DELETE = 0x0002; /* delete event from kq */ public static final int EV_ENABLE = 0x0004; /* enable event */ public static final int EV_DISABLE = 0x0008; /* disable event (not reported) */ private static final int EV_RECEIPT = 0x0040; /* force EV_ERROR on success, data == 0 */ /* * On input, NOTE_TRIGGER causes the event to be triggered for output. */ private static final int NOTE_TRIGGER = 0x01000000; private void processKev(KEvent64 kev) { switch (kev.filter) { case EVFILT_USER: { if ((kev.fflags & NOTE_TRIGGER) != 0) { KEvent64 reg = registerMap.get(kev.hashCode()); if (reg == null) { throw new IllegalStateException(); } else { pendingEventList.add(reg); } } else { if ((kev.flags & EV_ADD) != 0) { registerMap.put(kev.hashCode(), kev); } if ((kev.flags & EV_DELETE) != 0) { throw new UnsupportedOperationException(); } if ((kev.flags & EV_ENABLE) != 0) { throw new UnsupportedOperationException(); } if ((kev.flags & EV_DISABLE) != 0) { throw new UnsupportedOperationException(); } if ((kev.flags & EV_RECEIPT) != 0) { throw new UnsupportedOperationException(); } } break; } case EVFILT_VM: case EVFILT_MACHPORT: { if ((kev.flags & EV_ADD) != 0) { registerMap.put(kev.hashCode(), kev); } if ((kev.flags & EV_DELETE) != 0) { throw new UnsupportedOperationException(); } if (kev.isEnabled() && kev.isDisabled()) { throw new UnsupportedOperationException(); } break; } case EVFILT_SIGNAL: default: throw new UnsupportedOperationException("filter=" + kev.filter); } } public void processChangeList(Pointer changelist, int nchanges) {<FILL_FUNCTION_BODY>} @Override public void close() { registerMap.clear(); pendingEventList.clear(); } }
int size = UnidbgStructure.calculateSize(KEvent64.class); Pointer ptr = changelist; for (int i = 0; i < nchanges; i++, ptr = ptr.share(size)) { KEvent64 kev = new KEvent64(ptr); kev.unpack(); if (log.isDebugEnabled()) { log.debug("processChangeList i=" + i + ", kev=" + kev); } processKev(kev); }
896
139
1,035
48,508
apache_incubator-streampark
incubator-streampark/streampark-flink/streampark-flink-sql-gateway/streampark-flink-sql-gateway-flink-v1/src/main/java/org/apache/streampark/gateway/flink/FlinkSqlGatewayServiceFactory.java
FlinkSqlGatewayServiceFactory
createSqlGatewayService
class FlinkSqlGatewayServiceFactory implements SqlGatewayServiceFactory { @Override public String factoryIdentifier() { return "flink-v1"; } @Override public Set<ConfigOption<?>> requiredOptions() { Set<ConfigOption<?>> options = new HashSet<>(); options.add(BASE_URI); return options; } @Override public Set<ConfigOption<?>> optionalOptions() { return Collections.emptySet(); } @Override public SqlGatewayService createSqlGatewayService(Context context) {<FILL_FUNCTION_BODY>} public static final ConfigOption<String> BASE_URI = ConfigOption.key("base-uri") .stringType() .noDefaultValue() .withDescription("The base uri of the flink cluster."); }
SqlGatewayServiceFactoryUtils.EndpointFactoryHelper helper = SqlGatewayServiceFactoryUtils.createEndpointFactoryHelper(this, context); helper.validate(); String baseUri = context.getGateWayServiceOptions().get(BASE_URI.getKey()); return new FlinkSqlGatewayImpl(baseUri);
221
83
304
52,990
apache_incubator-seata
incubator-seata/rm-datasource/src/main/java/org/apache/seata/rm/datasource/xa/StatementProxyXA.java
StatementProxyXA
isCloseOnCompletion
class StatementProxyXA implements Statement { protected AbstractConnectionProxyXA connectionProxyXA; protected Statement targetStatement; public StatementProxyXA(AbstractConnectionProxyXA connectionProxyXA, Statement targetStatement) { this.connectionProxyXA = connectionProxyXA; this.targetStatement = targetStatement; } @Override public int executeUpdate(String sql) throws SQLException { return ExecuteTemplateXA.execute(connectionProxyXA, (statement, args) -> statement.executeUpdate( (String)args[0]), targetStatement, sql); } @Override public int executeUpdate(String sql, int autoGeneratedKeys) throws SQLException { return ExecuteTemplateXA.execute(connectionProxyXA, (statement, args) -> statement.executeUpdate((String)args[0], (int)args[1]), targetStatement, sql, autoGeneratedKeys); } @Override public int executeUpdate(String sql, int[] columnIndexes) throws SQLException { return ExecuteTemplateXA.execute(connectionProxyXA, (statement, args) -> statement.executeUpdate((String)args[0], (int[])args[1]), targetStatement, sql, columnIndexes); } @Override public int executeUpdate(String sql, String[] columnNames) throws SQLException { return ExecuteTemplateXA.execute(connectionProxyXA, (statement, args) -> statement.executeUpdate((String)args[0], (String[])args[1]), targetStatement, sql, columnNames); } @Override public boolean execute(String sql, int autoGeneratedKeys) throws SQLException { return ExecuteTemplateXA.execute(connectionProxyXA, (statement, args) -> statement.execute((String)args[0], (int)args[1]), targetStatement, sql, autoGeneratedKeys); } @Override public boolean execute(String sql, int[] columnIndexes) throws SQLException { return ExecuteTemplateXA.execute(connectionProxyXA, (statement, args) -> statement.execute((String)args[0], (int[])args[1]), targetStatement, sql, columnIndexes); } @Override public boolean execute(String sql, String[] columnNames) throws SQLException { return ExecuteTemplateXA.execute(connectionProxyXA, (statement, args) -> statement.execute((String)args[0], (String[])args[1]), targetStatement, sql, columnNames); } @Override public boolean execute(String sql) throws SQLException { return ExecuteTemplateXA.execute(connectionProxyXA, (statement, args) -> statement.execute((String)args[0]), targetStatement, sql); } @Override public ResultSet executeQuery(String sql) throws SQLException { return ExecuteTemplateXA.execute(connectionProxyXA, (statement, args) -> statement.executeQuery((String)args[0]), targetStatement, sql); } @Override public int[] executeBatch() throws SQLException { return ExecuteTemplateXA.execute(connectionProxyXA, (statement, args) -> statement.executeBatch(), targetStatement); } @Override public void close() throws SQLException { targetStatement.close(); } @Override public int getMaxFieldSize() throws SQLException { return targetStatement.getMaxFieldSize(); } @Override public void setMaxFieldSize(int max) throws SQLException { targetStatement.setMaxFieldSize(max); } @Override public int getMaxRows() throws SQLException { return targetStatement.getMaxRows(); } @Override public void setMaxRows(int max) throws SQLException { targetStatement.setMaxFieldSize(max); } @Override public void setEscapeProcessing(boolean enable) throws SQLException { targetStatement.setEscapeProcessing(enable); } @Override public int getQueryTimeout() throws SQLException { return targetStatement.getQueryTimeout(); } @Override public void setQueryTimeout(int seconds) throws SQLException { targetStatement.setQueryTimeout(seconds); } @Override public void cancel() throws SQLException { targetStatement.cancel(); } @Override public SQLWarning getWarnings() throws SQLException { return targetStatement.getWarnings(); } @Override public void clearWarnings() throws SQLException { targetStatement.clearWarnings(); } @Override public void setCursorName(String name) throws SQLException { targetStatement.setCursorName(name); } @Override public ResultSet getResultSet() throws SQLException { return targetStatement.getResultSet(); } @Override public int getUpdateCount() throws SQLException { return targetStatement.getUpdateCount(); } @Override public boolean getMoreResults() throws SQLException { return targetStatement.getMoreResults(); } @Override public void setFetchDirection(int direction) throws SQLException { targetStatement.setFetchDirection(direction); } @Override public int getFetchDirection() throws SQLException { return targetStatement.getFetchDirection(); } @Override public void setFetchSize(int rows) throws SQLException { targetStatement.setFetchSize(rows); } @Override public int getFetchSize() throws SQLException { return targetStatement.getFetchSize(); } @Override public int getResultSetConcurrency() throws SQLException { return targetStatement.getResultSetConcurrency(); } @Override public int getResultSetType() throws SQLException { return targetStatement.getResultSetType(); } @Override public void addBatch(String sql) throws SQLException { targetStatement.addBatch(sql); } @Override public void clearBatch() throws SQLException { targetStatement.clearBatch(); } @Override public Connection getConnection() throws SQLException { return targetStatement.getConnection(); } @Override public boolean getMoreResults(int current) throws SQLException { return targetStatement.getMoreResults(current); } @Override public ResultSet getGeneratedKeys() throws SQLException { return targetStatement.getGeneratedKeys(); } @Override public int getResultSetHoldability() throws SQLException { return targetStatement.getResultSetHoldability(); } @Override public boolean isClosed() throws SQLException { return targetStatement.isClosed(); } @Override public void setPoolable(boolean poolable) throws SQLException { targetStatement.setPoolable(poolable); } @Override public boolean isPoolable() throws SQLException { return targetStatement.isPoolable(); } @Override public void closeOnCompletion() throws SQLException { targetStatement.closeOnCompletion(); } @Override public boolean isCloseOnCompletion() throws SQLException {<FILL_FUNCTION_BODY>} @Override public <T> T unwrap(Class<T> iface) throws SQLException { return targetStatement.unwrap(iface); } @Override public boolean isWrapperFor(Class<?> iface) throws SQLException { return targetStatement.isWrapperFor(iface); } }
return targetStatement.isCloseOnCompletion();
1,898
15
1,913
52,432
spring-cloud_spring-cloud-kubernetes
spring-cloud-kubernetes/spring-cloud-kubernetes-client-config/src/main/java/org/springframework/cloud/kubernetes/client/config/KubernetesClientConfigMapPropertySource.java
KubernetesClientConfigMapPropertySource
getSourceData
class KubernetesClientConfigMapPropertySource extends SourceDataEntriesProcessor { private static final EnumMap<NormalizedSourceType, KubernetesClientContextToSourceData> STRATEGIES = new EnumMap<>( NormalizedSourceType.class); static { STRATEGIES.put(NormalizedSourceType.NAMED_CONFIG_MAP, namedConfigMap()); STRATEGIES.put(NormalizedSourceType.LABELED_CONFIG_MAP, labeledConfigMap()); } public KubernetesClientConfigMapPropertySource(KubernetesClientConfigContext context) { super(getSourceData(context)); } private static SourceData getSourceData(KubernetesClientConfigContext context) {<FILL_FUNCTION_BODY>} private static KubernetesClientContextToSourceData namedConfigMap() { return new NamedConfigMapContextToSourceDataProvider().get(); } private static KubernetesClientContextToSourceData labeledConfigMap() { return new LabeledConfigMapContextToSourceDataProvider().get(); } }
NormalizedSourceType type = context.normalizedSource().type(); return Optional.ofNullable(STRATEGIES.get(type)).map(x -> x.apply(context)) .orElseThrow(() -> new IllegalArgumentException("no strategy found for : " + type));
261
71
332
43,490
LibrePDF_OpenPDF
OpenPDF/openpdf/src/main/java/com/lowagie/text/pdf/CFFFont.java
DictNumberItem
emit
class DictNumberItem extends Item { public final int value; public int size = 5; public DictNumberItem(int value) { this.value = value; } public void increment(int[] currentOffset) { super.increment(currentOffset); currentOffset[0] += size; } // this is incomplete! public void emit(byte[] buffer) {<FILL_FUNCTION_BODY>} }
if (size == 5) { buffer[myOffset] = 29; buffer[myOffset + 1] = (byte) ((value >>> 24) & 0xff); buffer[myOffset + 2] = (byte) ((value >>> 16) & 0xff); buffer[myOffset + 3] = (byte) ((value >>> 8) & 0xff); buffer[myOffset + 4] = (byte) ((value >>> 0) & 0xff); }
119
132
251
29,634
newbee-ltd_newbee-mall
newbee-mall/src/main/java/ltd/newbee/mall/util/PatternUtil.java
PatternUtil
validKeyword
class PatternUtil { /** * 匹配邮箱正则 */ private static final Pattern VALID_EMAIL_ADDRESS_REGEX = Pattern.compile("^[A-Z0-9._%+-]+@[A-Z0-9.-]+\\.[A-Z]{2,6}$", Pattern.CASE_INSENSITIVE); /** * 验证只包含中英文和数字的字符串 * * @param keyword * @return */ public static Boolean validKeyword(String keyword) {<FILL_FUNCTION_BODY>} /** * 判断是否是邮箱 * * @param emailStr * @return */ public static boolean isEmail(String emailStr) { Matcher matcher = VALID_EMAIL_ADDRESS_REGEX.matcher(emailStr); return matcher.find(); } /** * 判断是否是网址 * * @param urlString * @return */ public static boolean isURL(String urlString) { String regex = "^([hH][tT]{2}[pP]:/*|[hH][tT]{2}[pP][sS]:/*|[fF][tT][pP]:/*)(([A-Za-z0-9-~]+).)+([A-Za-z0-9-~\\/])+(\\?{0,1}(([A-Za-z0-9-~]+\\={0,1})([A-Za-z0-9-~]*)\\&{0,1})*)$"; Pattern pattern = Pattern.compile(regex); if (pattern.matcher(urlString).matches()) { return true; } else { return false; } } }
String regex = "^[a-zA-Z0-9\u4E00-\u9FA5]+$"; Pattern pattern = Pattern.compile(regex); Matcher match = pattern.matcher(keyword); return match.matches();
476
68
544
3,083
apache_dubbo
dubbo/dubbo-spring-boot/dubbo-spring-boot-compatible/actuator/src/main/java/org/apache/dubbo/spring/boot/actuate/endpoint/metadata/AbstractDubboMetadata.java
AbstractDubboMetadata
resolveBeanMetadata
class AbstractDubboMetadata implements ApplicationContextAware, EnvironmentAware { protected ApplicationContext applicationContext; protected ConfigurableEnvironment environment; private static boolean isSimpleType(Class<?> type) { return isPrimitiveOrWrapper(type) || type == String.class || type == BigDecimal.class || type == BigInteger.class || type == Date.class || type == URL.class || type == Class.class; } @Override public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { this.applicationContext = applicationContext; } @Override public void setEnvironment(Environment environment) { if (environment instanceof ConfigurableEnvironment) { this.environment = (ConfigurableEnvironment) environment; } } protected Map<String, Object> resolveBeanMetadata(final Object bean) {<FILL_FUNCTION_BODY>} protected Map<String, ServiceBean> getServiceBeansMap() { return beansOfTypeIncludingAncestors(applicationContext, ServiceBean.class); } protected ReferenceAnnotationBeanPostProcessor getReferenceAnnotationBeanPostProcessor() { return DubboBeanUtils.getReferenceAnnotationBeanPostProcessor(applicationContext); } protected Map<String, ProtocolConfig> getProtocolConfigsBeanMap() { return beansOfTypeIncludingAncestors(applicationContext, ProtocolConfig.class); } }
final Map<String, Object> beanMetadata = new LinkedHashMap<>(); try { BeanInfo beanInfo = Introspector.getBeanInfo(bean.getClass()); PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors(); for (PropertyDescriptor propertyDescriptor : propertyDescriptors) { Method readMethod = propertyDescriptor.getReadMethod(); if (readMethod != null && isSimpleType(propertyDescriptor.getPropertyType())) { String name = Introspector.decapitalize(propertyDescriptor.getName()); Object value = readMethod.invoke(bean); if (value != null) { beanMetadata.put(name, value); } } } } catch (Exception e) { throw new RuntimeException(e); } return beanMetadata;
358
212
570
67,340
spring-io_initializr
initializr/initializr-generator-spring/src/main/java/io/spring/initializr/generator/spring/code/groovy/GroovyProjectGenerationConfiguration.java
GroovyProjectGenerationConfiguration
mainGroovySourceCodeProjectContributor
class GroovyProjectGenerationConfiguration { private final ProjectDescription description; private final IndentingWriterFactory indentingWriterFactory; public GroovyProjectGenerationConfiguration(ProjectDescription description, IndentingWriterFactory indentingWriterFactory) { this.description = description; this.indentingWriterFactory = indentingWriterFactory; } @Bean public MainSourceCodeProjectContributor<GroovyTypeDeclaration, GroovyCompilationUnit, GroovySourceCode> mainGroovySourceCodeProjectContributor( ObjectProvider<MainApplicationTypeCustomizer<?>> mainApplicationTypeCustomizers, ObjectProvider<MainCompilationUnitCustomizer<?, ?>> mainCompilationUnitCustomizers, ObjectProvider<MainSourceCodeCustomizer<?, ?, ?>> mainSourceCodeCustomizers) {<FILL_FUNCTION_BODY>} @Bean public TestSourceCodeProjectContributor<GroovyTypeDeclaration, GroovyCompilationUnit, GroovySourceCode> testGroovySourceCodeProjectContributor( ObjectProvider<TestApplicationTypeCustomizer<?>> testApplicationTypeCustomizers, ObjectProvider<TestSourceCodeCustomizer<?, ?, ?>> testSourceCodeCustomizers) { return new TestSourceCodeProjectContributor<>(this.description, GroovySourceCode::new, new GroovySourceCodeWriter(this.indentingWriterFactory), testApplicationTypeCustomizers, testSourceCodeCustomizers); } }
return new MainSourceCodeProjectContributor<>(this.description, GroovySourceCode::new, new GroovySourceCodeWriter(this.indentingWriterFactory), mainApplicationTypeCustomizers, mainCompilationUnitCustomizers, mainSourceCodeCustomizers);
366
68
434
43,959
AxonFramework_AxonFramework
AxonFramework/messaging/src/main/java/org/axonframework/commandhandling/callbacks/FutureCallback.java
FutureCallback
getResult
class FutureCallback<C, R> extends CompletableFuture<CommandResultMessage<? extends R>> implements CommandCallback<C, R> { @Override public void onResult(@Nonnull CommandMessage<? extends C> commandMessage, @Nonnull CommandResultMessage<? extends R> commandResultMessage) { super.complete(commandResultMessage); } /** * Waits if necessary for the command handling to complete, and then returns its result. * <p/> * Unlike {@link #get(long, java.util.concurrent.TimeUnit)}, this method will throw the original exception. Only * checked exceptions are wrapped in a {@link CommandExecutionException}. * <p/> * If the thread is interrupted while waiting, the interrupt flag is set back on the thread, and {@code null} * is returned. To distinguish between an interrupt and a {@code null} result, use the {@link #isDone()} * method. * * @return the result of the command handler execution. * @see #get() */ public CommandResultMessage<? extends R> getResult() {<FILL_FUNCTION_BODY>} /** * Waits if necessary for at most the given time for the command handling to complete, and then retrieves its * result, if available. * <p/> * Unlike {@link #get(long, java.util.concurrent.TimeUnit)}, this method will report the original exception from * within a CommandResultMessage, rather than throwing an {@link ExecutionException}. * <p/> * If the timeout expired or the thread is interrupted before completion, the returned {@link CommandResultMessage} * will contain an {@link InterruptedException} or {@link TimeoutException}. In case of * an interrupt, the interrupt flag will have been set back on the thread. * * @param timeout the maximum time to wait * @param unit the time unit of the timeout argument * @return the result of the command handler execution. */ public CommandResultMessage<? extends R> getResult(long timeout, TimeUnit unit) { try { return get(timeout, unit); } catch (InterruptedException e) { Thread.currentThread().interrupt(); return new GenericCommandResultMessage<>(e); } catch (ExecutionException e) { return asCommandResultMessage(e.getCause()); } catch (Exception e) { return asCommandResultMessage(e); } } /** * Wait for completion of the command, or for the timeout to expire. * * @param timeout The amount of time to wait for command processing to complete * @param unit The unit in which the timeout is expressed * @return {@code true} if command processing completed before the timeout expired, otherwise * {@code false}. */ public boolean awaitCompletion(long timeout, TimeUnit unit) { try { get(timeout, unit); return true; } catch (InterruptedException e) { Thread.currentThread().interrupt(); return false; } catch (ExecutionException e) { return true; } catch (TimeoutException e) { return false; } } }
try { return get(); } catch (InterruptedException e) { Thread.currentThread().interrupt(); return new GenericCommandResultMessage<>((R) null); } catch (ExecutionException e) { return asCommandResultMessage(e.getCause()); } catch (Exception e) { return asCommandResultMessage(e); }
793
94
887
54,839
apache_incubator-hugegraph
incubator-hugegraph/hugegraph-server/hugegraph-core/src/main/java/org/apache/hugegraph/util/collection/IntSet.java
IntSetByFixedAddr4Unsigned
add
class IntSetByFixedAddr4Unsigned implements IntSet { private final long[] bits; private final int numBits; private final AtomicInteger size; @SuppressWarnings("static-access") private static final int BASE_OFFSET = UNSAFE.ARRAY_LONG_BASE_OFFSET; @SuppressWarnings("static-access") private static final int MUL8 = 31 - Integer.numberOfLeadingZeros( UNSAFE.ARRAY_LONG_INDEX_SCALE); public IntSetByFixedAddr4Unsigned(int numBits) { this.numBits = numBits; this.bits = new long[IntSet.bits2words(numBits)]; this.size = new AtomicInteger(); } @Override public boolean add(int key) {<FILL_FUNCTION_BODY>} @Override public boolean contains(int key) { if (key >= this.numBits || key < 0) { return false; } long offset = this.offset(key); long bitmask = bitmaskOfKey(key); long value = UNSAFE.getLongVolatile(this.bits, offset); return (value & bitmask) != 0L; } @Override public boolean remove(int key) { long offset = this.offset(key); long bitmask = bitmaskOfKey(key); while (true) { long oldV = UNSAFE.getLongVolatile(this.bits, offset); long newV = oldV & ~bitmask; if (newV == oldV) { return false; } // this.bits[index] &= ~bitmask if (UNSAFE.compareAndSwapLong(this.bits, offset, oldV, newV)) { this.size.decrementAndGet(); return true; } } } @Override public void clear() { Arrays.fill(this.bits, 0); this.size.set(0); } @Override public int size() { return this.size.get(); } @Override public boolean concurrent() { return true; } public int nextKey(int key) { if (key < 0) { key = 0; } if (key >= this.numBits) { return key; } long offset = this.offset(key); int startBit = key & (int) MOD64; int bitsEachLong = 64; int bytesEachLong = 8; key -= startBit; // check the first long long value = UNSAFE.getLongVolatile(this.bits, offset); if (value != 0L) { for (int bit = startBit; bit < bitsEachLong; bit++) { long bitmask = 1L << bit; if ((value & bitmask) != 0L) { return key + bit; } } } offset += bytesEachLong; key += bitsEachLong; // check the remaining while (key < this.numBits) { value = UNSAFE.getLongVolatile(this.bits, offset); if (value != 0L) { for (int bit = 0; bit < bitsEachLong; bit++) { long bitmask = 1L << bit; if ((value & bitmask) != 0L) { return key + bit; } } } offset += bytesEachLong; key += bitsEachLong; } return key; } private long offset(int key) { if (key >= this.numBits || key < 0) { E.checkArgument(false, "The key %s is out of bound %s", key, this.numBits); } return bitOffsetToByteOffset(key); } private static long bitOffsetToByteOffset(long key) { // bits to long offset long index = key >> DIV64; // long offset to byte offset long offset = index << MUL8; // add the array base offset offset += BASE_OFFSET; return offset; } private static long bitmaskOfKey(long key) { long bitIndex = key & MOD64; long bitmask = 1L << bitIndex; return bitmask; } }
long offset = this.offset(key); long bitmask = bitmaskOfKey(key); while (true) { long oldV = UNSAFE.getLongVolatile(this.bits, offset); long newV = oldV | bitmask; if (newV == oldV) { return false; } // this.bits[index] |= bitmask; if (UNSAFE.compareAndSwapLong(this.bits, offset, oldV, newV)) { this.size.incrementAndGet(); return true; } }
1,158
150
1,308
8,740
dromara_liteflow
liteflow/liteflow-core/src/main/java/com/yomahub/liteflow/parser/el/ClassJsonFlowELParser.java
ClassJsonFlowELParser
parseMain
class ClassJsonFlowELParser extends JsonFlowELParser { @Override public void parseMain(List<String> pathList) throws Exception {<FILL_FUNCTION_BODY>} public abstract String parseCustom(); }
String content = parseCustom(); parse(content);
56
18
74
18,003
pac4j_pac4j
pac4j/pac4j-javaee/src/main/java/org/pac4j/jee/saml/metadata/Saml2MetadataFilter.java
Saml2MetadataFilter
internalFilter
class Saml2MetadataFilter extends AbstractConfigFilter { private String clientName; /** {@inheritDoc} */ @Override public void init(final FilterConfig filterConfig) throws ServletException { super.init(filterConfig); this.clientName = getStringParam(filterConfig, Pac4jConstants.CLIENT_NAME, this.clientName); } /** {@inheritDoc} */ @Override protected void internalFilter(final HttpServletRequest request, final HttpServletResponse response, final FilterChain chain) throws IOException, ServletException {<FILL_FUNCTION_BODY>} /** {@inheritDoc} */ @Override public void destroy() { } }
CommonHelper.assertNotNull("config", getSharedConfig()); CommonHelper.assertNotNull("clientName", clientName); SAML2Client client; val result = getSharedConfig().getClients().findClient(this.clientName); if (result.isPresent()) { client = (SAML2Client) result.get(); } else { throw new TechnicalException("No SAML2 client: " + this.clientName); } client.init(); response.getWriter().write(client.getServiceProviderMetadataResolver().getMetadata()); response.getWriter().flush();
176
153
329
36,930
apache_shenyu
shenyu/shenyu-admin/src/main/java/org/apache/shenyu/admin/model/query/PluginQueryCondition.java
PluginQueryCondition
setSwitchStatus
class PluginQueryCondition extends BaseExcludedSearchCondition implements SearchCondition, SwitchCondition { /** * search keyword: plugin name or role name. */ private String keyword; /** * switch status: plugin status[close or open]. */ private Boolean switchStatus; /** * get switchStatus. * * @return status */ @Override public Boolean getSwitchStatus() { return switchStatus; } /** * set switchStatus. * * @param switchStatus status */ public void setSwitchStatus(final Boolean switchStatus) {<FILL_FUNCTION_BODY>} /** * get keyword. * * @return keyword */ @Override public String getKeyword() { return keyword; } /** * set keyword. * * @param keyword keyword */ @Override public void setKeyword(final String keyword) { this.keyword = keyword; } }
this.switchStatus = switchStatus;
271
13
284
67,827
apache_rocketmq
rocketmq/remoting/src/main/java/org/apache/rocketmq/remoting/protocol/header/NotificationRequestHeader.java
NotificationRequestHeader
toString
class NotificationRequestHeader extends TopicQueueRequestHeader { @CFNotNull @RocketMQResource(ResourceType.GROUP) private String consumerGroup; @CFNotNull @RocketMQResource(ResourceType.TOPIC) private String topic; @CFNotNull private int queueId; @CFNotNull private long pollTime; @CFNotNull private long bornTime; private Boolean order = Boolean.FALSE; private String attemptId; @CFNotNull @Override public void checkFields() throws RemotingCommandException { } public long getPollTime() { return pollTime; } public void setPollTime(long pollTime) { this.pollTime = pollTime; } public String getConsumerGroup() { return consumerGroup; } public void setConsumerGroup(String consumerGroup) { this.consumerGroup = consumerGroup; } public long getBornTime() { return bornTime; } public void setBornTime(long bornTime) { this.bornTime = bornTime; } public String getTopic() { return topic; } public void setTopic(String topic) { this.topic = topic; } public Integer getQueueId() { if (queueId < 0) { return -1; } return queueId; } public void setQueueId(Integer queueId) { this.queueId = queueId; } public Boolean getOrder() { return order; } public void setOrder(Boolean order) { this.order = order; } public String getAttemptId() { return attemptId; } public void setAttemptId(String attemptId) { this.attemptId = attemptId; } @Override public String toString() {<FILL_FUNCTION_BODY>} }
return MoreObjects.toStringHelper(this) .add("consumerGroup", consumerGroup) .add("topic", topic) .add("queueId", queueId) .add("pollTime", pollTime) .add("bornTime", bornTime) .add("order", order) .add("attemptId", attemptId) .toString();
513
95
608
53,804
apache_rocketmq
rocketmq/remoting/src/main/java/org/apache/rocketmq/remoting/netty/RemotingCodeDistributionHandler.java
RemotingCodeDistributionHandler
snapshotToString
class RemotingCodeDistributionHandler extends ChannelDuplexHandler { private final ConcurrentMap<Integer, LongAdder> inboundDistribution; private final ConcurrentMap<Integer, LongAdder> outboundDistribution; public RemotingCodeDistributionHandler() { inboundDistribution = new ConcurrentHashMap<>(); outboundDistribution = new ConcurrentHashMap<>(); } private void countInbound(int requestCode) { LongAdder item = inboundDistribution.computeIfAbsent(requestCode, k -> new LongAdder()); item.increment(); } private void countOutbound(int responseCode) { LongAdder item = outboundDistribution.computeIfAbsent(responseCode, k -> new LongAdder()); item.increment(); } @Override public void channelRead(ChannelHandlerContext ctx, Object msg) { if (msg instanceof RemotingCommand) { RemotingCommand cmd = (RemotingCommand) msg; countInbound(cmd.getCode()); } ctx.fireChannelRead(msg); } @Override public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception { if (msg instanceof RemotingCommand) { RemotingCommand cmd = (RemotingCommand) msg; countOutbound(cmd.getCode()); } ctx.write(msg, promise); } private Map<Integer, Long> getDistributionSnapshot(Map<Integer, LongAdder> countMap) { Map<Integer, Long> map = new HashMap<>(countMap.size()); for (Map.Entry<Integer, LongAdder> entry : countMap.entrySet()) { map.put(entry.getKey(), entry.getValue().sumThenReset()); } return map; } private String snapshotToString(Map<Integer, Long> distribution) {<FILL_FUNCTION_BODY>} public String getInBoundSnapshotString() { return this.snapshotToString(this.getDistributionSnapshot(this.inboundDistribution)); } public String getOutBoundSnapshotString() { return this.snapshotToString(this.getDistributionSnapshot(this.outboundDistribution)); } }
if (null != distribution && !distribution.isEmpty()) { StringBuilder sb = new StringBuilder("{"); boolean first = true; for (Map.Entry<Integer, Long> entry : distribution.entrySet()) { if (0L == entry.getValue()) { continue; } sb.append(first ? "" : ", ").append(entry.getKey()).append(":").append(entry.getValue()); first = false; } if (first) { return null; } sb.append("}"); return sb.toString(); } return null;
559
153
712
53,693
assertj_assertj
assertj/assertj-core/src/main/java/org/assertj/core/description/JoinDescription.java
IndentedAppendable
changeIndentationBy
class IndentedAppendable implements Appendable { private final StringBuilder stringBuilder; private int currentIndentation; IndentedAppendable(StringBuilder stringBuilder) { this.stringBuilder = stringBuilder; this.currentIndentation = 0; } @Override public IndentedAppendable append(CharSequence charSequence) { stringBuilder.append(charSequence); return this; } @Override public IndentedAppendable append(CharSequence charSequence, int start, int end) { stringBuilder.append(charSequence, start, end); return this; } @Override public IndentedAppendable append(char c) { stringBuilder.append(c); return this; } /** * Adjusts the indentation size by {@code indentation}. * * @param indentation The indentation adjustment. * * @return a this instance. */ IndentedAppendable changeIndentationBy(int indentation) {<FILL_FUNCTION_BODY>} /** * Appends the indentation according to current size. * * @return a this instance. */ IndentedAppendable indent() { for (int i = 0; i < currentIndentation; i++) { stringBuilder.append(' '); } return this; } /** * Shortcut method from {@link #changeIndentationBy(int)} and {@link #indent()} * * @param indentation The indentation adjustment. * * @return a this instance. */ IndentedAppendable indentBy(int indentation) { return changeIndentationBy(indentation).indent(); } @Override public String toString() { return stringBuilder.toString(); } }
this.currentIndentation += indentation; return this;
477
21
498
12,668
alibaba_canal
canal/instance/spring/src/main/java/com/alibaba/otter/canal/instance/spring/SpringCanalInstanceGenerator.java
SpringCanalInstanceGenerator
generate
class SpringCanalInstanceGenerator implements CanalInstanceGenerator { private static final Logger logger = LoggerFactory.getLogger(SpringCanalInstanceGenerator.class); private String springXml; private String defaultName = "instance"; private BeanFactory beanFactory; public CanalInstance generate(String destination) {<FILL_FUNCTION_BODY>} private BeanFactory getBeanFactory(String springXml) { ApplicationContext applicationContext = new ClassPathXmlApplicationContext(springXml); return applicationContext; } public void setSpringXml(String springXml) { this.springXml = springXml; } }
synchronized (CanalEventParser.class) { try { // 设置当前正在加载的通道,加载spring查找文件时会用到该变量 System.setProperty("canal.instance.destination", destination); this.beanFactory = getBeanFactory(springXml); String beanName = destination; if (!beanFactory.containsBean(beanName)) { beanName = defaultName; } return (CanalInstance) beanFactory.getBean(beanName); } catch (Throwable e) { logger.error("generator instance failed.", e); throw new CanalException(e); } finally { System.setProperty("canal.instance.destination", ""); } }
164
186
350
49,464
sofastack_sofa-jraft
sofa-jraft/jraft-rheakv/rheakv-pd/src/main/java/com/alipay/sofa/jraft/rhea/PlacementDriverServer.java
PlacementDriverServer
createDefaultPdExecutor
class PlacementDriverServer implements Lifecycle<PlacementDriverServerOptions> { private static final Logger LOG = LoggerFactory.getLogger(PlacementDriverServer.class); private final ThreadPoolExecutor pdExecutor; private PlacementDriverService placementDriverService; private RheaKVStore rheaKVStore; private RegionEngine regionEngine; private boolean started; public PlacementDriverServer() { this(null); } public PlacementDriverServer(ThreadPoolExecutor pdExecutor) { this.pdExecutor = pdExecutor != null ? pdExecutor : createDefaultPdExecutor(); } @Override public synchronized boolean init(final PlacementDriverServerOptions opts) { if (this.started) { LOG.info("[PlacementDriverServer] already started."); return true; } Requires.requireNonNull(opts, "opts"); final RheaKVStoreOptions rheaOpts = opts.getRheaKVStoreOptions(); Requires.requireNonNull(rheaOpts, "opts.rheaKVStoreOptions"); this.rheaKVStore = new DefaultRheaKVStore(); this.placementDriverService = new DefaultPlacementDriverService(this.rheaKVStore); // Set up a listener before becoming a leader this.rheaKVStore.addLeaderStateListener(getPdReginId(rheaOpts), ((DefaultPlacementDriverService) this.placementDriverService)); if (!this.rheaKVStore.init(rheaOpts)) { LOG.error("Fail to init [RheaKVStore]."); return false; } if (!this.placementDriverService.init(opts)) { LOG.error("Fail to init [PlacementDriverService]."); return false; } final StoreEngine storeEngine = ((DefaultRheaKVStore) this.rheaKVStore).getStoreEngine(); Requires.requireNonNull(storeEngine, "storeEngine"); final List<RegionEngine> regionEngines = storeEngine.getAllRegionEngines(); if (regionEngines.isEmpty()) { throw new IllegalArgumentException("Non region for [PlacementDriverServer]"); } if (regionEngines.size() > 1) { throw new IllegalArgumentException("Only support single region for [PlacementDriverServer]"); } this.regionEngine = regionEngines.get(0); addPlacementDriverProcessor(storeEngine.getRpcServer()); LOG.info("[PlacementDriverServer] start successfully, options: {}.", opts); return this.started = true; } private long getPdReginId(final RheaKVStoreOptions rheaOpts) { StoreEngineOptions storeEngineOptions = rheaOpts.getStoreEngineOptions(); Requires.requireNonNull(storeEngineOptions, "storeEngineOptions"); List<RegionEngineOptions> rOptsList = storeEngineOptions.getRegionEngineOptionsList(); if (rOptsList == null || rOptsList.isEmpty()) { return Constants.DEFAULT_REGION_ID; } List<RegionEngineOptions> filteredOptsList = new ArrayList<>(); for (RegionEngineOptions rOpts : rOptsList) { if (inConfiguration(rOpts.getServerAddress().toString(), rOpts.getInitialServerList())) { filteredOptsList.add(rOpts); } } if (filteredOptsList.size() > 1) { throw new IllegalArgumentException("Only support single region for [PlacementDriverServer]"); } return rOptsList.get(0).getRegionId(); } private boolean inConfiguration(final String curr, final String all) { final PeerId currPeer = new PeerId(); if (!currPeer.parse(curr)) { return false; } final Configuration allConf = new Configuration(); if (!allConf.parse(all)) { return false; } return allConf.contains(currPeer) || allConf.getLearners().contains(currPeer); } @Override public synchronized void shutdown() { if (!this.started) { return; } if (this.rheaKVStore != null) { this.rheaKVStore.shutdown(); } if (this.placementDriverService != null) { this.placementDriverService.shutdown(); } ExecutorServiceHelper.shutdownAndAwaitTermination(this.pdExecutor); this.started = false; LOG.info("[PlacementDriverServer] shutdown successfully."); } public ThreadPoolExecutor getPdExecutor() { return pdExecutor; } public PlacementDriverService getPlacementDriverService() { return placementDriverService; } public RheaKVStore getRheaKVStore() { return rheaKVStore; } public RegionEngine getRegionEngine() { return regionEngine; } public boolean isLeader() { return this.regionEngine.isLeader(); } public PeerId getLeaderId() { return this.regionEngine.getLeaderId(); } public boolean awaitReady(final long timeoutMillis) { final PlacementDriverClient pdClient = this.rheaKVStore.getPlacementDriverClient(); final Endpoint endpoint = pdClient.getLeader(this.regionEngine.getRegion().getId(), true, timeoutMillis); return endpoint != null; } private void addPlacementDriverProcessor(final RpcServer rpcServer) { rpcServer.registerProcessor(new PlacementDriverProcessor<>(RegionHeartbeatRequest.class, this.placementDriverService, this.pdExecutor)); rpcServer.registerProcessor(new PlacementDriverProcessor<>(StoreHeartbeatRequest.class, this.placementDriverService, this.pdExecutor)); rpcServer.registerProcessor(new PlacementDriverProcessor<>(GetClusterInfoRequest.class, this.placementDriverService, this.pdExecutor)); rpcServer.registerProcessor(new PlacementDriverProcessor<>(GetStoreIdRequest.class, this.placementDriverService, this.pdExecutor)); rpcServer.registerProcessor(new PlacementDriverProcessor<>(GetStoreInfoRequest.class, this.placementDriverService, this.pdExecutor)); rpcServer.registerProcessor(new PlacementDriverProcessor<>(SetStoreInfoRequest.class, this.placementDriverService, this.pdExecutor)); rpcServer.registerProcessor(new PlacementDriverProcessor<>(CreateRegionIdRequest.class, this.placementDriverService, this.pdExecutor)); } private ThreadPoolExecutor createDefaultPdExecutor() {<FILL_FUNCTION_BODY>} }
final int corePoolSize = Math.max(Utils.cpus() << 2, 32); final String name = "rheakv-pd-executor"; return ThreadPoolUtil.newBuilder() // .poolName(name) // .enableMetric(true) // .coreThreads(corePoolSize) // .maximumThreads(corePoolSize << 2) // .keepAliveSeconds(120L) // .workQueue(new ArrayBlockingQueue<>(4096)) // .threadFactory(new NamedThreadFactory(name, true)) // .rejectedHandler(new CallerRunsPolicyWithReport(name, name)) // .build();
1,734
178
1,912
63,174
Nepxion_Discovery
Discovery/discovery-plugin-strategy/discovery-plugin-strategy-starter-gateway/src/main/java/com/nepxion/discovery/plugin/strategy/gateway/processor/GatewayStrategyRouteApolloProcessor.java
GatewayStrategyRouteApolloProcessor
getDataId
class GatewayStrategyRouteApolloProcessor extends ApolloProcessor { @Autowired private PluginAdapter pluginAdapter; @Autowired private GatewayStrategyRoute gatewayStrategyRoute; @Override public String getGroup() { return pluginAdapter.getGroup(); } @Override public String getDataId() {<FILL_FUNCTION_BODY>} @Override public String getDescription() { return DiscoveryConstant.SPRING_CLOUD_GATEWAY_DYNAMIC_ROUTE_DESCRIPTION; } @Override public void callbackConfig(String config) { gatewayStrategyRoute.updateAll(config); } }
return pluginAdapter.getServiceId() + "-" + DiscoveryConstant.DYNAMIC_ROUTE_KEY;
179
32
211
32,735
spring-cloud_spring-cloud-kubernetes
spring-cloud-kubernetes/spring-cloud-kubernetes-integration-tests/spring-cloud-kubernetes-k8s-client-reload/src/main/java/org/springframework/cloud/kubernetes/k8s/client/reload/Controller.java
Controller
witLabel
class Controller { private final LeftProperties leftProperties; private final RightProperties rightProperties; private final RightWithLabelsProperties rightWithLabelsProperties; private final ConfigMapProperties configMapProperties; public Controller(LeftProperties leftProperties, RightProperties rightProperties, RightWithLabelsProperties rightWithLabelsProperties, ConfigMapProperties configMapProperties) { this.leftProperties = leftProperties; this.rightProperties = rightProperties; this.rightWithLabelsProperties = rightWithLabelsProperties; this.configMapProperties = configMapProperties; } @GetMapping("/left") public String left() { return leftProperties.getValue(); } @GetMapping("/right") public String right() { return rightProperties.getValue(); } @GetMapping("/with-label") public String witLabel() {<FILL_FUNCTION_BODY>} @GetMapping("/mount") public String key() { return configMapProperties.getKey(); } }
return rightWithLabelsProperties.getValue();
241
14
255
43,696
j-easy_easy-rules
easy-rules/easy-rules-core/src/main/java/org/jeasy/rules/core/AbstractRulesEngine.java
AbstractRulesEngine
getRulesEngineListeners
class AbstractRulesEngine implements RulesEngine { RulesEngineParameters parameters; List<RuleListener> ruleListeners; List<RulesEngineListener> rulesEngineListeners; AbstractRulesEngine() { this(new RulesEngineParameters()); } AbstractRulesEngine(final RulesEngineParameters parameters) { this.parameters = parameters; this.ruleListeners = new ArrayList<>(); this.rulesEngineListeners = new ArrayList<>(); } /** * Return a copy of the rules engine parameters. * @return copy of the rules engine parameters */ @Override public RulesEngineParameters getParameters() { return new RulesEngineParameters( parameters.isSkipOnFirstAppliedRule(), parameters.isSkipOnFirstFailedRule(), parameters.isSkipOnFirstNonTriggeredRule(), parameters.getPriorityThreshold() ); } /** * Return an unmodifiable list of the registered rule listeners. * @return an unmodifiable list of the registered rule listeners */ @Override public List<RuleListener> getRuleListeners() { return Collections.unmodifiableList(ruleListeners); } /** * Return an unmodifiable list of the registered rules engine listeners * @return an unmodifiable list of the registered rules engine listeners */ @Override public List<RulesEngineListener> getRulesEngineListeners() {<FILL_FUNCTION_BODY>} public void registerRuleListener(RuleListener ruleListener) { ruleListeners.add(ruleListener); } public void registerRuleListeners(List<RuleListener> ruleListeners) { this.ruleListeners.addAll(ruleListeners); } public void registerRulesEngineListener(RulesEngineListener rulesEngineListener) { rulesEngineListeners.add(rulesEngineListener); } public void registerRulesEngineListeners(List<RulesEngineListener> rulesEngineListeners) { this.rulesEngineListeners.addAll(rulesEngineListeners); } }
return Collections.unmodifiableList(rulesEngineListeners);
514
19
533
24,773
jetlinks_jetlinks-community
jetlinks-community/jetlinks-components/notify-component/notify-sms/src/main/java/org/jetlinks/community/notify/sms/aliyun/AliyunSmsTemplate.java
AliyunSmsTemplate
getPhoneNumber
class AliyunSmsTemplate extends AbstractTemplate<AliyunSmsTemplate> { public static final String PHONE_NUMBER_KEY = "phoneNumber"; //签名名称 @NotBlank(message = "[signName]不能为空") private String signName; //模版编码 @NotBlank(message = "[code]不能为空") private String code; //为空时,则表示从变量中传入 // @NotBlank(message = "[phoneNumber]不能为空") private String phoneNumber; private Map<String, String> param; public String getCode(Map<String, Object> ctx) { //code不支持变量 return getCode(); } public Flux<String> getPhoneNumber(Map<String, Object> ctx) {<FILL_FUNCTION_BODY>} public String getSignName(Map<String, Object> ctx) { //签名不支持变量 return getSignName(); } public String createTtsParam(Map<String, Object> ctx) { Map<String, VariableDefinition> variables = getVariables(); return JSON.toJSONString(Maps.filterEntries( renderMap(ctx), e -> variables.containsKey(e.getKey()))); } @Override @Nonnull protected List<VariableDefinition> getEmbeddedVariables() { //指定了固定的收信人 if (StringUtils.hasText(phoneNumber)) { return Collections.emptyList(); } return Collections.singletonList( VariableDefinition .builder() .id(PHONE_NUMBER_KEY) .name("收信人") .description("收信人手机号码") .expand(NotifyVariableBusinessConstant.businessId, NotifyVariableBusinessConstant.NotifyVariableBusinessTypes.userType) .type(StringType.ID) .required(true) .build() ); } }
if (StringUtils.hasText(this.getPhoneNumber())) { return Flux.just(this.getPhoneNumber()); } //如果没有指定固定值,则从上下文中获取 return RelationUtils .resolve(PHONE_NUMBER_KEY, ctx, RelationConstants.UserProperty.telephone) .map(String::valueOf);
515
94
609
25,483
sohutv_cachecloud
cachecloud/cachecloud-web/src/main/java/com/sohu/cache/task/tasks/OffLineAppTask.java
OffLineAppTask
init
class OffLineAppTask extends BaseTask { private long appId; private AppDesc appDesc; private AppUser userInfo; private long auditId; @Autowired private AppService appService; @Autowired private InstanceDao instanceDao; @Resource(name = "appEmailUtil") private AppEmailUtil appEmailUtil; @Override public List<String> getTaskSteps() { List<String> taskStepList = Lists.newArrayList(); taskStepList.add(TaskConstants.INIT_METHOD_KEY); // 2. 执行应用下线处理 taskStepList.add("executeOffLineApp"); // 3. 更新应用信息 taskStepList.add("updateAppStatus"); return taskStepList; } /** * 初始化参数 * * @return */ @Override public TaskFlowStatusEnum init() {<FILL_FUNCTION_BODY>} /** * 2. 执行应用下线操作 * * @return */ public TaskFlowStatusEnum executeOffLineApp() { logger.info("executeOffLineApp"); if (auditId > 0) { appAuditDao.updateAppAuditUser(auditId, 2, userInfo.getId()); } List<InstanceInfo> instanceInfos = instanceDao.getInstListByAppId(appId); int type = appDesc.getType(); List<Boolean> isShutDownList = Lists.newArrayList(); if (instanceInfos != null) { isShutDownList = instanceInfos.parallelStream() .map(instanceInfo -> instanceOffline(instanceInfo, type)) .collect(Collectors.toList()); } if (isShutDownList.contains(false)) { appEmailUtil.noticeOfflineApp(userInfo, appId, false); return TaskFlowStatusEnum.ABORT; } return TaskFlowStatusEnum.SUCCESS; } private boolean instanceOffline(InstanceInfo instanceInfo, int type) { final String ip = instanceInfo.getIp(); final int port = instanceInfo.getPort(); boolean isShutdown = TypeUtil.isRedisType(type) ? redisCenter.shutdown(appId, ip, port) : true; if(isShutdown){ isShutdown = redisCenter.checkShutdownSuccess(instanceInfo); } if (isShutdown) { instanceInfo.setStatus(InstanceStatusEnum.OFFLINE_STATUS.getStatus()); instanceDao.update(instanceInfo); } else { logger.error("task {} appId {} {}:{} redis not shutdown!", taskId, appId, ip, port); return false; } return true; } /** * 3. 更新应用信息,发送邮件 * * @return */ public TaskFlowStatusEnum updateAppStatus() { logger.info("updateAppStatus"); appDesc.setStatus(AppStatusEnum.STATUS_OFFLINE.getStatus()); if (auditId > 0) { appAuditDao.updateAppAudit(auditId, 1); } int count = appService.update(appDesc); if (count > 0) { appEmailUtil.noticeOfflineApp(userInfo, appId, true); return TaskFlowStatusEnum.SUCCESS; } else { appEmailUtil.noticeOfflineApp(userInfo, appId, false); return TaskFlowStatusEnum.ABORT; } } }
TaskFlowStatusEnum taskFlowStatusEnum = super.init(); appId = MapUtils.getLongValue(paramMap, TaskConstants.APPID_KEY); if (appId <= 0) { logger.error(marker, "task {} appId {} is wrong", taskId, appId); taskFlowStatusEnum = TaskFlowStatusEnum.ABORT; } auditId = MapUtils.getLongValue(paramMap, TaskConstants.AUDIT_ID_KEY, -1); if (auditId <= 0) { logger.info(marker, "task {} auditId {} is wrong", taskId, auditId); } appDesc = appService.getByAppId(appId); if (appDesc == null) { logger.error(marker, "task {} appId {} appDesc is not exist", taskId, appId); taskFlowStatusEnum = TaskFlowStatusEnum.ABORT; } Object userObject = MapUtils.getObject(paramMap, TaskConstants.USER_INFO_KEY, null); if (userObject instanceof JSONObject) { JSONObject userJson = (JSONObject) userObject; userInfo = JSONObject.parseObject(JSON.toJSONString(userJson), AppUser.class); } if (userInfo == null) { logger.error(marker, "task {} appId {} userInfo is not exist", taskId, appId); taskFlowStatusEnum = TaskFlowStatusEnum.ABORT; } else { if (!ConstUtils.SUPER_MANAGER.contains(userInfo.getName())) { logger.error("task {} appId {} user {} who hope to offline hasn't privilege", taskId, appId, userInfo.getName()); taskFlowStatusEnum = TaskFlowStatusEnum.ABORT; } } if (taskFlowStatusEnum == TaskFlowStatusEnum.ABORT) { appEmailUtil.noticeOfflineApp(userInfo, appId, false); } return taskFlowStatusEnum;
927
495
1,422
3,678
shopizer-ecommerce_shopizer
shopizer/sm-shop/src/main/java/com/salesmanager/shop/utils/AdminAccessDeniedHandler.java
AdminAccessDeniedHandler
handle
class AdminAccessDeniedHandler implements AccessDeniedHandler { @Override public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException accessDeniedException) throws IOException, ServletException {<FILL_FUNCTION_BODY>} public String getAccessDeniedUrl() { return accessDeniedUrl; } public void setAccessDeniedUrl(String accessDeniedUrl) { this.accessDeniedUrl = accessDeniedUrl; } private String accessDeniedUrl = null; }
response.sendRedirect(request.getContextPath() + getAccessDeniedUrl());
138
26
164
40,840
Col-E_Recaf
Recaf/src/main/java/me/coley/recaf/config/FieldWrapper.java
FieldWrapper
set
class FieldWrapper { private final Configurable instance; private final Field field; private final Conf conf; /** * @param instance * Configurable object instance. * @param field * Field of configurable value. * @param conf * Annotation on field. */ public FieldWrapper(Configurable instance, Field field, Conf conf) { this.instance = instance; this.field = field; this.conf = conf; } /** * @return Translation key. */ public final String key() { return conf.value(); } /** * @return {@code true} when the config key is translatable. */ public final boolean isTranslatable() { return !conf.noTranslate(); } /** * @return Translated name. */ public final String name() { return LangUtil.translate(key() + ".name"); } /** * @return Translated description. */ public final String description() { return LangUtil.translate(key() + ".desc"); } /** * @return {@code true} if the field is not intended to be shown. */ public final boolean hidden() { return conf.hide(); } /** * @param <T> * Generic type of class. * * @return Declared type of the field. */ @SuppressWarnings("unchecked") public final <T> Class<T> type() { return (Class<T>) field.getType(); } /** * @param <T> * Field value type. * * @return Field value. */ @SuppressWarnings("unchecked") public final <T> T get() { try { return (T) field.get(instance); } catch(IllegalAccessException ex) { error(ex, "Failed to fetch field value: {}", key()); return null; } } /** * @param value * Value to set. */ public final void set(Object value) {<FILL_FUNCTION_BODY>} }
try { field.set(instance, value); } catch(IllegalAccessException ex) { error(ex, "Failed to set field value: {}", key()); }
549
52
601
14,102
assertj_assertj
assertj/assertj-core/src/main/java/org/assertj/core/error/ShouldHave.java
ShouldHave
shouldHave
class ShouldHave extends BasicErrorMessageFactory { /** * Creates a new <code>{@link ShouldHave}</code>. * @param <T> guarantees that the type of the actual value and the generic type of the {@code Condition} are the same. * @param actual the actual value in the failed assertion. * @param condition the {@code Condition}. * @return the created {@code ErrorMessageFactory}. */ public static <T> ErrorMessageFactory shouldHave(T actual, Condition<? super T> condition) {<FILL_FUNCTION_BODY>} private ShouldHave(Object actual, Condition<?> condition) { super("%nExpecting actual:%n %s%nto have %s", actual, condition); } private <T> ShouldHave(T actual, Join<? super T> join) { super("%n" + "Expecting actual:%n" + " %s%n" + // use concatenation to avoid the string to be double quoted later on "to have:%n" + join.conditionDescriptionWithStatus(actual), actual); } }
if (condition instanceof Join) return new ShouldHave(actual, (Join<? super T>) condition); return new ShouldHave(actual, condition);
284
39
323
12,840
pmd_pmd
pmd/pmd-javascript/src/main/java/net/sourceforge/pmd/lang/ecmascript/ast/ASTSwitchCase.java
ASTSwitchCase
getStatement
class ASTSwitchCase extends AbstractEcmascriptNode<SwitchCase> { ASTSwitchCase(SwitchCase switchCase) { super(switchCase); } @Override protected <P, R> R acceptJsVisitor(EcmascriptVisitor<? super P, ? extends R> visitor, P data) { return visitor.visit(this, data); } public boolean isDefault() { return node.isDefault(); } public EcmascriptNode<?> getExpression() { if (!isDefault()) { return (EcmascriptNode<?>) getChild(0); } else { return null; } } public int getNumStatements() { return node.getStatements() != null ? node.getStatements().size() : 0; } public EcmascriptNode<?> getStatement(int index) {<FILL_FUNCTION_BODY>} }
int statementIndex = index; if (!isDefault()) { statementIndex++; } return (EcmascriptNode<?>) getChild(statementIndex);
242
46
288
38,414
jetlinks_jetlinks-community
jetlinks-community/jetlinks-components/network-component/tcp-component/src/main/java/org/jetlinks/community/network/tcp/server/VertxTcpServer.java
VertxTcpServer
getType
class VertxTcpServer implements TcpServer { Collection<NetServer> tcpServers; private Supplier<PayloadParser> parserSupplier; @Setter private long keepAliveTimeout = Duration.ofMinutes(10).toMillis(); @Getter private final String id; private final Sinks.Many<TcpClient> sink = Reactors.createMany(Integer.MAX_VALUE,false); @Getter @Setter private String lastError; @Setter(AccessLevel.PACKAGE) private InetSocketAddress bind; public VertxTcpServer(String id) { this.id = id; } @Override public Flux<TcpClient> handleConnection() { return sink.asFlux(); } private void execute(Runnable runnable) { try { runnable.run(); } catch (Exception e) { log.warn("close tcp server error", e); } } @Override public InetSocketAddress getBindAddress() { return bind; } public void setParserSupplier(Supplier<PayloadParser> parserSupplier) { this.parserSupplier = parserSupplier; } public void setServer(Collection<NetServer> servers) { if (this.tcpServers != null && !this.tcpServers.isEmpty()) { shutdown(); } this.tcpServers = servers; for (NetServer tcpServer : this.tcpServers) { tcpServer.connectHandler(this::acceptTcpConnection); } } protected void acceptTcpConnection(NetSocket socket) { if (sink.currentSubscriberCount() == 0) { log.warn("not handler for tcp client[{}]", socket.remoteAddress()); socket.close(); return; } VertxTcpClient client = new VertxTcpClient(id + "_" + socket.remoteAddress()); client.setKeepAliveTimeoutMs(keepAliveTimeout); try { socket.exceptionHandler(err -> { log.error("tcp server client [{}] error", socket.remoteAddress(), err); }); client.setRecordParser(parserSupplier.get()); client.setSocket(socket); sink.emitNext(client, Reactors.emitFailureHandler()); log.debug("accept tcp client [{}] connection", socket.remoteAddress()); } catch (Exception e) { log.error("create tcp server client error", e); client.shutdown(); } } @Override public NetworkType getType() {<FILL_FUNCTION_BODY>} @Override public void shutdown() { if (null != tcpServers) { log.debug("close tcp server :[{}]", id); for (NetServer tcpServer : tcpServers) { execute(tcpServer::close); } tcpServers = null; } } @Override public boolean isAlive() { return tcpServers != null; } @Override public boolean isAutoReload() { return false; } }
return DefaultNetworkType.TCP_SERVER;
836
15
851
25,440
DerekYRC_mini-spring
mini-spring/src/main/java/org/springframework/aop/framework/adapter/AfterReturningAdviceInterceptor.java
AfterReturningAdviceInterceptor
invoke
class AfterReturningAdviceInterceptor implements MethodInterceptor, AfterAdvice { private AfterReturningAdvice advice; public AfterReturningAdviceInterceptor() { } public AfterReturningAdviceInterceptor(AfterReturningAdvice advice) { this.advice = advice; } @Override public Object invoke(MethodInvocation mi) throws Throwable {<FILL_FUNCTION_BODY>} }
Object retVal = mi.proceed(); this.advice.afterReturning(retVal, mi.getMethod(), mi.getArguments(), mi.getThis()); return retVal;
110
50
160
17,040
spring-projects_spring-batch
spring-batch/spring-batch-infrastructure/src/main/java/org/springframework/batch/item/support/PassThroughItemProcessor.java
PassThroughItemProcessor
process
class PassThroughItemProcessor<T> implements ItemProcessor<T, T> { /** * Just returns the item back to the caller. * @return the item * @see ItemProcessor#process(Object) */ @Nullable @Override public T process(T item) throws Exception {<FILL_FUNCTION_BODY>} }
return item;
88
8
96
44,696
google_error-prone
error-prone/core/src/main/java/com/google/errorprone/bugpatterns/NamedLikeContextualKeyword.java
NamedLikeContextualKeyword
matchClass
class NamedLikeContextualKeyword extends BugChecker implements ClassTreeMatcher, MethodTreeMatcher, MethodInvocationTreeMatcher { // Refer to JLS 19 §3.9. // Note that "non-sealed" is not a valid class name private static final ImmutableSet<String> DISALLOWED_CLASS_NAMES = ImmutableSet.of( "exports", "opens", "requires", "uses", "module", "permits", "sealed", "var", "provides", "to", "with", "open", "record", "transitive", "yield"); private static final Matcher<MethodTree> DISALLOWED_METHOD_NAME_MATCHER = allOf(not(methodIsConstructor()), methodIsNamed("yield")); private static final ImmutableSet<String> AUTO_PROCESSORS = ImmutableSet.of( "com.google.auto.value.processor.AutoValueProcessor", "com.google.auto.value.processor.AutoOneOfProcessor"); @Override public Description matchMethod(MethodTree tree, VisitorState state) { MethodSymbol methodSymbol = ASTHelpers.getSymbol(tree); // Don't alert if an @Auto... class (safe since reference always qualified). if (isInGeneratedAutoCode(state)) { return NO_MATCH; } // Don't alert if method is an override (this includes interfaces) if (!streamSuperMethods(methodSymbol, state.getTypes()).findAny().isPresent() && DISALLOWED_METHOD_NAME_MATCHER.matches(tree, state)) { return describeMatch(tree); } return NO_MATCH; } @Override public Description matchClass(ClassTree tree, VisitorState state) {<FILL_FUNCTION_BODY>} @Override public Description matchMethodInvocation(MethodInvocationTree tree, VisitorState state) { ExpressionTree select = tree.getMethodSelect(); if (!(select instanceof IdentifierTree)) { return NO_MATCH; } if (!((IdentifierTree) select).getName().contentEquals("yield")) { return NO_MATCH; } SuggestedFix.Builder fix = SuggestedFix.builder(); String qualifier = getQualifier(state, getSymbol(tree), fix); return describeMatch(tree, fix.prefixWith(select, qualifier + ".").build()); } private static String getQualifier( VisitorState state, MethodSymbol sym, SuggestedFix.Builder fix) { if (sym.isStatic()) { return qualifyType(state, fix, sym.owner.enclClass()); } TreePath path = findPathFromEnclosingNodeToTopLevel(state.getPath(), ClassTree.class); if (sym.isMemberOf(getSymbol((ClassTree) path.getLeaf()), state.getTypes())) { return "this"; } while (true) { path = findPathFromEnclosingNodeToTopLevel(path, ClassTree.class); ClassSymbol enclosingClass = getSymbol((ClassTree) path.getLeaf()); if (sym.isMemberOf(enclosingClass, state.getTypes())) { return qualifyType(state, fix, enclosingClass) + ".this"; } } } private static boolean isInGeneratedAutoCode(VisitorState state) { return !Collections.disjoint(ASTHelpers.getGeneratedBy(state), AUTO_PROCESSORS); } }
if (DISALLOWED_CLASS_NAMES.contains(tree.getSimpleName().toString())) { return describeMatch(tree); } return NO_MATCH;
915
48
963
57,228
redis_lettuce
lettuce/src/main/java/io/lettuce/core/dynamic/BatchTasks.java
BatchTasks
toArray
class BatchTasks implements Iterable<RedisCommand<?, ?, ?>> { public static final BatchTasks EMPTY = new BatchTasks(Collections.emptyList()); private final List<RedisCommand<?, ?, ?>> futures; BatchTasks(List<RedisCommand<?, ?, ?>> futures) { this.futures = futures; } @Override public Iterator<RedisCommand<?, ?, ?>> iterator() { return futures.iterator(); } @SuppressWarnings("rawtypes") public RedisCommand<?, ?, ?>[] toArray() {<FILL_FUNCTION_BODY>} }
return futures.toArray(new RedisCommand[0]);
177
19
196
39,315
soot-oss_soot
soot/src/main/java/soot/PolymorphicMethodRef.java
PolymorphicMethodRef
resolve
class PolymorphicMethodRef extends SootMethodRefImpl { public static final String METHODHANDLE_SIGNATURE = "java.lang.invoke.MethodHandle"; public static final String VARHANDLE_SIGNATURE = "java.lang.invoke.VarHandle"; public static final String POLYMORPHIC_SIGNATURE = "java/lang/invoke/MethodHandle$PolymorphicSignature"; /** * Check if the declaring class "has the rights" to declare polymorphic methods * {@see http://docs.oracle.com/javase/specs/jls/se11/html/jls-15.html#jls-15.12.4.4} * * @param declaringClass * the class to check * @return if the class is allowed according to the JVM Spec */ public static boolean handlesClass(SootClass declaringClass) { return handlesClass(declaringClass.getName()); } public static boolean handlesClass(String declaringClassName) { return PolymorphicMethodRef.METHODHANDLE_SIGNATURE.equals(declaringClassName) || PolymorphicMethodRef.VARHANDLE_SIGNATURE.equals(declaringClassName); } /** * Constructor. * * @param declaringClass * the declaring class. Must not be {@code null} * @param name * the method name. Must not be {@code null} * @param parameterTypes * the types of parameters. May be {@code null} * @param returnType * the type of return value. Must not be {@code null} * @param isStatic * the static modifier value * @throws IllegalArgumentException * is thrown when {@code declaringClass}, or {@code name}, or {@code returnType} is null */ public PolymorphicMethodRef(SootClass declaringClass, String name, List<Type> parameterTypes, Type returnType, boolean isStatic) { super(declaringClass, name, parameterTypes, returnType, isStatic); } @Override public SootMethod resolve() {<FILL_FUNCTION_BODY>} private SootMethod addPolyMorphicMethod(SootMethod originalPolyMorphicMethod) { SootMethod newMethod = new SootMethod(getName(), getParameterTypes(), getReturnType(), originalPolyMorphicMethod.modifiers); getDeclaringClass().addMethod(newMethod); return newMethod; } }
SootMethod method = getDeclaringClass().getMethodUnsafe(getName(), getParameterTypes(), getReturnType()); if (method != null) { return method; } // No method with matching parameter types or return types found for polymorphic methods, // we don't care about the return or parameter types. We just check if a method with the // name exists and has a polymorphic type signature. // Note(MB): We cannot use getMethodByName here since the method name is ambiguous after // adding the first method with same name and refined signature. for (SootMethod candidateMethod : getDeclaringClass().getMethods()) { if (candidateMethod.getName().equals(getName())) { Tag annotationsTag = candidateMethod.getTag(VisibilityAnnotationTag.NAME); if (annotationsTag != null) { for (AnnotationTag annotation : ((VisibilityAnnotationTag) annotationsTag).getAnnotations()) { // check the annotation's type if (('L' + POLYMORPHIC_SIGNATURE + ';').equals(annotation.getType())) { // The method is polymorphic, add a fitting method to the MethodHandle // or VarHandle class, as the JVM does on runtime. return addPolyMorphicMethod(candidateMethod); } } } } } return super.resolve();
647
347
994
42,072
jetlinks_jetlinks-community
jetlinks-community/jetlinks-components/rule-engine-component/src/main/java/org/jetlinks/community/rule/engine/executor/DeviceMessageSendTaskExecutorProvider.java
DeviceMessageSendTaskExecutor
reload
class DeviceMessageSendTaskExecutor extends FunctionTaskExecutor { private DeviceMessageSendConfig config; private Function<Map<String, Object>, Flux<DeviceOperator>> selector; public DeviceMessageSendTaskExecutor(ExecutionContext context) { super("发送设备消息", context); reload(); } protected Flux<DeviceOperator> selectDevice(Map<String, Object> ctx) { return selector.apply(ctx); } @Override protected Publisher<RuleData> apply(RuleData input) { Map<String, Object> ctx = RuleDataHelper.toContextMap(input); Flux<DeviceOperator> readySendDevice = "ignoreOffline".equals(config.getStateOperator()) ? selectDevice(ctx).filterWhen(DeviceOperator::isOnline) : selectDevice(ctx); return readySendDevice .switchIfEmpty(context.onError(() -> new DeviceOperationException(ErrorCode.SYSTEM_ERROR, "无可用设备"), input)) .flatMap(device -> config .doSend(ctx, context, device, input) .onErrorResume(error -> context.onError(error, input)) .subscribeOn(Schedulers.parallel()) ) .map(reply -> { RuleData data = context.newRuleData(input.newData(reply.toJson())); if (config.getResponseHeaders() != null) { config.getResponseHeaders().forEach(data::setHeader); } return data; }) ; } @Override public void validate() { if (CollectionUtils.isEmpty(context.getJob().getConfiguration())) { throw new IllegalArgumentException("配置不能为空"); } FastBeanCopier.copy(context.getJob().getConfiguration(), new DeviceMessageSendConfig()).validate(); } @Override public void reload() {<FILL_FUNCTION_BODY>} }
config = FastBeanCopier.copy(context.getJob().getConfiguration(), new DeviceMessageSendConfig()); config.validate(); if (config.getSelectorSpec() != null) { selector = selectorBuilder.createSelector(config.getSelectorSpec())::select; } else if (StringUtils.hasText(config.deviceId)) { selector = ctx -> registry.getDevice(config.getDeviceId()).flux(); } else if (StringUtils.hasText(config.productId)) { selector = selectorBuilder.createSelector(DeviceSelectorProviders.product(config.productId))::select; } else { if (config.isFixed() && MapUtils.isNotEmpty(config.getMessage())) { selector = ctx -> registry.getDevice(config.getDeviceIdInMessage(ctx)).flux(); } else { selector = ctx -> registry .getDevice((String) ctx .getOrDefault("deviceId", config.getMessage() == null ? null : config.getMessage().get("deviceId"))) .flux(); } }
489
275
764
25,558
zlt2000_microservices-platform
microservices-platform/zlt-demo/seata-demo/order-service/src/main/java/com/central/order/OrderServiceApplication.java
OrderServiceApplication
main
class OrderServiceApplication { public static void main(String[] args) {<FILL_FUNCTION_BODY>} }
SpringApplication.run(OrderServiceApplication.class, args);
32
18
50
48,822
apache_incubator-streampark
incubator-streampark/streampark-console/streampark-console-service/src/main/java/org/apache/streampark/console/system/controller/TeamController.java
TeamController
deleteTeam
class TeamController { @Autowired private TeamService teamService; @Operation(summary = "List teams") @PostMapping("list") public RestResponse teamList(RestRequest restRequest, Team team) { IPage<Team> teamList = teamService.getPage(team, restRequest); return RestResponse.success(teamList); } @Operation(summary = "Check the team name") @PostMapping("check/name") public RestResponse checkTeamName(@NotBlank(message = "{required}") String teamName) { Team result = this.teamService.getByName(teamName); return RestResponse.success(result == null); } @Operation(summary = "Create team") @PostMapping("post") @RequiresPermissions("team:add") public RestResponse addTeam(@Valid Team team) { this.teamService.createTeam(team); return RestResponse.success(); } @Operation(summary = "Delete team") @DeleteMapping("delete") @RequiresPermissions("team:delete") public RestResponse deleteTeam(Team team) {<FILL_FUNCTION_BODY>} @Operation(summary = "Update team") @PutMapping("update") @RequiresPermissions("team:update") public RestResponse updateTeam(Team team) { this.teamService.updateTeam(team); return RestResponse.success(); } }
this.teamService.removeById(team.getId()); return RestResponse.success();
364
25
389
52,951
javaparser_javaparser
javaparser/javaparser-symbol-solver-core/src/main/java/com/github/javaparser/symbolsolver/javaparsermodel/JavaParserFactory.java
JavaParserFactory
getSymbolDeclarator
class JavaParserFactory { public static Context getContext(Node node, TypeSolver typeSolver) { if (node == null) { throw new NullPointerException("Node should not be null"); } if (node instanceof ArrayAccessExpr) { return new ArrayAccessExprContext((ArrayAccessExpr) node, typeSolver); } if (node instanceof AnnotationDeclaration) { return new AnnotationDeclarationContext((AnnotationDeclaration) node, typeSolver); } if (node instanceof BinaryExpr) { return new BinaryExprContext((BinaryExpr) node, typeSolver); } if (node instanceof BlockStmt) { return new BlockStmtContext((BlockStmt) node, typeSolver); } if (node instanceof CompilationUnit) { return new CompilationUnitContext((CompilationUnit) node, typeSolver); } if (node instanceof EnclosedExpr) { return new EnclosedExprContext((EnclosedExpr) node, typeSolver); } if (node instanceof ForEachStmt) { return new ForEachStatementContext((ForEachStmt) node, typeSolver); } if (node instanceof ForStmt) { return new ForStatementContext((ForStmt) node, typeSolver); } if (node instanceof IfStmt) { return new IfStatementContext((IfStmt) node, typeSolver); } if (node instanceof InstanceOfExpr) { return new InstanceOfExprContext((InstanceOfExpr) node, typeSolver); } if (node instanceof LambdaExpr) { return new LambdaExprContext((LambdaExpr) node, typeSolver); } if (node instanceof MethodDeclaration) { return new MethodContext((MethodDeclaration) node, typeSolver); } if (node instanceof ConstructorDeclaration) { return new ConstructorContext((ConstructorDeclaration) node, typeSolver); } if (node instanceof ClassOrInterfaceDeclaration) { return new ClassOrInterfaceDeclarationContext((ClassOrInterfaceDeclaration) node, typeSolver); } if (node instanceof MethodCallExpr) { return new MethodCallExprContext((MethodCallExpr) node, typeSolver); } if (node instanceof MethodReferenceExpr) { return new MethodReferenceExprContext((MethodReferenceExpr) node, typeSolver); } if (node instanceof EnumDeclaration) { return new EnumDeclarationContext((EnumDeclaration) node, typeSolver); } if (node instanceof FieldAccessExpr) { return new FieldAccessContext((FieldAccessExpr) node, typeSolver); } if (node instanceof SwitchEntry) { return new SwitchEntryContext((SwitchEntry) node, typeSolver); } if (node instanceof TryStmt) { return new TryWithResourceContext((TryStmt) node, typeSolver); } if (node instanceof Statement) { return new StatementContext<>((Statement) node, typeSolver); } if (node instanceof CatchClause) { return new CatchClauseContext((CatchClause) node, typeSolver); } if (node instanceof UnaryExpr) { return new UnaryExprContext((UnaryExpr) node, typeSolver); } if (node instanceof VariableDeclarator) { return new VariableDeclaratorContext((VariableDeclarator) node, typeSolver); } if (node instanceof VariableDeclarationExpr) { return new VariableDeclarationExprContext((VariableDeclarationExpr) node, typeSolver); } if (node instanceof ObjectCreationExpr && ((ObjectCreationExpr) node).getAnonymousClassBody().isPresent()) { return new AnonymousClassDeclarationContext((ObjectCreationExpr) node, typeSolver); } if (node instanceof ObjectCreationExpr) { return new ObjectCreationContext((ObjectCreationExpr)node, typeSolver); } if (node instanceof NameExpr) { // to resolve a name when in a fieldAccess context, we can go up until we get a node other than FieldAccessExpr, // in order to prevent a infinite loop if the name is the same as the field (ie x.x, x.y.x, or x.y.z.x) if (node.getParentNode().isPresent() && node.getParentNode().get() instanceof FieldAccessExpr) { Node ancestor = node.getParentNode().get(); while (ancestor.getParentNode().isPresent()) { ancestor = ancestor.getParentNode().get(); if (!(ancestor instanceof FieldAccessExpr)) { break; } } return getContext(ancestor, typeSolver); } if (node.getParentNode().isPresent() && node.getParentNode().get() instanceof ObjectCreationExpr && node.getParentNode().get().getParentNode().isPresent()) { return getContext(node.getParentNode().get().getParentNode().get(), typeSolver); } } final Node parentNode = demandParentNode(node); if (node instanceof ClassOrInterfaceType && parentNode instanceof ClassOrInterfaceDeclaration) { ClassOrInterfaceDeclaration parentDeclaration = (ClassOrInterfaceDeclaration) parentNode; if (parentDeclaration.getImplementedTypes().contains(node) || parentDeclaration.getExtendedTypes().contains(node)) { // When resolving names in implements and extends the body of the declaration // should not be searched so use limited context. return new ClassOrInterfaceDeclarationExtendsContext(parentDeclaration, typeSolver); } } return getContext(parentNode, typeSolver); } public static SymbolDeclarator getSymbolDeclarator(Node node, TypeSolver typeSolver) {<FILL_FUNCTION_BODY>} }
if (node instanceof FieldDeclaration) { return new FieldSymbolDeclarator((FieldDeclaration) node, typeSolver); } if (node instanceof Parameter) { return new ParameterSymbolDeclarator((Parameter) node, typeSolver); } if (node instanceof PatternExpr) { return new PatternSymbolDeclarator((PatternExpr) node, typeSolver); } if (node instanceof ExpressionStmt) { ExpressionStmt expressionStmt = (ExpressionStmt) node; if (expressionStmt.getExpression() instanceof VariableDeclarationExpr) { return new VariableSymbolDeclarator((VariableDeclarationExpr) (expressionStmt.getExpression()), typeSolver); } return new NoSymbolDeclarator<>(expressionStmt, typeSolver); } if (node instanceof ForEachStmt) { ForEachStmt foreachStmt = (ForEachStmt) node; return new VariableSymbolDeclarator(foreachStmt.getVariable(), typeSolver); } return new NoSymbolDeclarator<>(node, typeSolver);
1,427
274
1,701
24,526
alibaba_nacos
nacos/naming/src/main/java/com/alibaba/nacos/naming/web/NamingConfig.java
NamingConfig
trafficReviseFilterRegistration
class NamingConfig { private static final String URL_PATTERNS = "/v1/ns/*"; private static final String URL_PATTERNS_V2 = "/v2/ns/*"; private static final String DISTRO_FILTER = "distroFilter"; private static final String SERVICE_NAME_FILTER = "serviceNameFilter"; private static final String TRAFFIC_REVISE_FILTER = "trafficReviseFilter"; private static final String CLIENT_ATTRIBUTES_FILTER = "clientAttributes_filter"; private static final String NAMING_PARAM_CHECK_FILTER = "namingparamCheckFilter"; @Bean public FilterRegistrationBean<DistroFilter> distroFilterRegistration() { FilterRegistrationBean<DistroFilter> registration = new FilterRegistrationBean<>(); registration.setFilter(distroFilter()); registration.addUrlPatterns(URL_PATTERNS); registration.setName(DISTRO_FILTER); registration.setOrder(7); return registration; } @Bean public FilterRegistrationBean<ServiceNameFilter> serviceNameFilterRegistration() { FilterRegistrationBean<ServiceNameFilter> registration = new FilterRegistrationBean<>(); registration.setFilter(serviceNameFilter()); registration.addUrlPatterns(URL_PATTERNS); registration.setName(SERVICE_NAME_FILTER); registration.setOrder(5); return registration; } @Bean public FilterRegistrationBean<TrafficReviseFilter> trafficReviseFilterRegistration() {<FILL_FUNCTION_BODY>} @Bean public FilterRegistrationBean<ClientAttributesFilter> clientAttributesFilterRegistration() { FilterRegistrationBean<ClientAttributesFilter> registration = new FilterRegistrationBean<>(); registration.setFilter(clientAttributesFilter()); registration.addUrlPatterns(URL_PATTERNS, URL_PATTERNS_V2); registration.setName(CLIENT_ATTRIBUTES_FILTER); registration.setOrder(8); return registration; } @Bean public DistroFilter distroFilter() { return new DistroFilter(); } @Bean public TrafficReviseFilter trafficReviseFilter() { return new TrafficReviseFilter(); } @Bean public ServiceNameFilter serviceNameFilter() { return new ServiceNameFilter(); } @Bean public ClientAttributesFilter clientAttributesFilter() { return new ClientAttributesFilter(); } }
FilterRegistrationBean<TrafficReviseFilter> registration = new FilterRegistrationBean<>(); registration.setFilter(trafficReviseFilter()); registration.addUrlPatterns(URL_PATTERNS); registration.setName(TRAFFIC_REVISE_FILTER); registration.setOrder(1); return registration;
663
88
751
51,625
648540858_wvp-GB28181-pro
wvp-GB28181-pro/src/main/java/com/genersoft/iot/vmp/vmanager/gb28181/sse/SseController.java
SseController
emit
class SseController { @Resource private AlarmEventListener alarmEventListener; /** * SSE 推送. * * @param response 响应 * @param browserId 浏览器ID * @throws IOException IOEXCEPTION * @author <a href="mailto:xiaoQQya@126.com">xiaoQQya</a> * @since 2023/11/06 */ @GetMapping("/emit") public void emit(HttpServletResponse response, @RequestParam String browserId) throws IOException, InterruptedException {<FILL_FUNCTION_BODY>} }
response.setContentType("text/event-stream"); response.setCharacterEncoding("utf-8"); PrintWriter writer = response.getWriter(); alarmEventListener.addSseEmitter(browserId, writer); while (!writer.checkError()) { Thread.sleep(1000); writer.write(":keep alive\n\n"); writer.flush(); } alarmEventListener.removeSseEmitter(browserId, writer);
172
120
292
5,335
iluwatar_java-design-patterns
java-design-patterns/hexagonal/src/main/java/com/iluwatar/hexagonal/administration/ConsoleAdministrationSrvImpl.java
ConsoleAdministrationSrvImpl
performLottery
class ConsoleAdministrationSrvImpl implements ConsoleAdministrationSrv { private final LotteryAdministration administration; private final Logger logger; /** * Constructor. */ public ConsoleAdministrationSrvImpl(LotteryAdministration administration, Logger logger) { this.administration = administration; this.logger = logger; } @Override public void getAllSubmittedTickets() { administration.getAllSubmittedTickets() .forEach((k, v) -> logger.info("Key: {}, Value: {}", k, v)); } @Override public void performLottery() {<FILL_FUNCTION_BODY>} @Override public void resetLottery() { administration.resetLottery(); logger.info("The lottery ticket database was cleared."); } }
var numbers = administration.performLottery(); logger.info("The winning numbers: {}", numbers.getNumbersAsString()); logger.info("Time to reset the database for next round, eh?");
221
55
276
544
soot-oss_soot
soot/src/main/java/soot/jimple/toolkits/annotation/arraycheck/MethodParameter.java
MethodParameter
hashCode
class MethodParameter { private SootMethod m; private int param; public MethodParameter(SootMethod m, int i) { this.m = m; this.param = i; } public Type getType() { return m.getParameterType(param); } public int hashCode() {<FILL_FUNCTION_BODY>} public SootMethod getMethod() { return m; } public int getIndex() { return param; } public boolean equals(Object other) { if (other instanceof MethodParameter) { MethodParameter another = (MethodParameter) other; return (m.equals(another.getMethod()) && param == another.getIndex()); } return false; } public String toString() { return "[" + m.getSignature() + " : P" + param + "]"; } }
return m.hashCode() + param;
237
14
251
42,361
RipMeApp_ripme
ripme/src/main/java/com/rarchives/ripme/ripper/rippers/MeituriRipper.java
MeituriRipper
getGID
class MeituriRipper extends AbstractHTMLRipper { public MeituriRipper(URL url) throws IOException { super(url); } @Override public String getHost() { return "meituri"; } @Override public String getDomain() { return "meituri.com"; } // To use in getting URLs String albumID = ""; @Override public String getGID(URL url) throws MalformedURLException {<FILL_FUNCTION_BODY>} @Override public Document getFirstPage() throws IOException { return Http.url(url).get(); } @Override public List<String> getURLsFromPage(Document doc) { List<String> imageURLs = new ArrayList<>(); // Get number of images from the page // Then generate links according to that int numOfImages = 1; Pattern p = Pattern.compile("^<p>图片数量: ([0-9]+)P</p>$"); for (Element para : doc.select("div.tuji > p")) { // <p>图片数量: 55P</p> Matcher m = p.matcher(para.toString()); if (m.matches()) { // 55 numOfImages = Integer.parseInt(m.group(1)); } } // Base URL: http://ii.hywly.com/a/1/albumid/imgnum.jpg String baseURL = "http://ii.hywly.com/a/1/" + albumID + "/"; // Loop through and add images to the URL list for (int i = 1; i <= numOfImages; i++) { imageURLs.add(baseURL + i + ".jpg"); } return imageURLs; } @Override public void downloadURL(URL url, int index) { addURLToDownload(url, getPrefix(index)); } }
// without escape // ^https?://[w.]*meituri\.com/a/([0-9]+)/([0-9]+\.html)*$ // https://www.meituri.com/a/14449/ // also matches https://www.meituri.com/a/14449/3.html etc. // group 1 is 14449 Pattern p = Pattern.compile("^https?://[w.]*meituri\\.com/a/([0-9]+)/([0-9]+\\.html)*$"); Matcher m = p.matcher(url.toExternalForm()); if (m.matches()) { albumID = m.group(1); return m.group(1); } throw new MalformedURLException( "Expected meituri.com URL format: " + "meituri.com/a/albumid/ - got " + url + "instead");
516
250
766
39,666
apache_incubator-seata
incubator-seata/sqlparser/seata-sqlparser-druid/src/main/java/org/apache/seata/sqlparser/druid/SupportSqlWhereMethod.java
SupportSqlWhereMethodHolder
getInstance
class SupportSqlWhereMethodHolder { private static final SupportSqlWhereMethod INSTANCE = new SupportSqlWhereMethod(); } public static SupportSqlWhereMethod getInstance() {<FILL_FUNCTION_BODY>
return SupportSqlWhereMethodHolder.INSTANCE;
54
15
69
52,732
fabric8io_kubernetes-client
kubernetes-client/extensions/istio/examples/src/main/java/io/fabric8/istio/api/examples/v1beta1/SidecarExample.java
SidecarExample
createResource
class SidecarExample { private static final String NAMESPACE = "test"; public static void main(String[] args) { try { IstioClient client = ClientFactory.newClient(args); createResource(client); System.exit(0); } catch (KubernetesClientException ex) { System.err.println("Failed with " + ex.getMessage()); System.exit(1); } } public static void createResource(IstioClient client) {<FILL_FUNCTION_BODY>} }
System.out.println("Creating a sidecar"); // Example from: https://istio.io/latest/docs/reference/config/networking/sidecar/ client.v1beta1().sidecars().inNamespace(NAMESPACE).create(new SidecarBuilder() .withNewMetadata() .withName("default") .endMetadata() .withNewSpec() .withEgress(new IstioEgressListenerBuilder() .withHosts("./*", "istio-system/*").build()) .endSpec() .build()); System.out.println("Listing sidecar instances:"); SidecarList list = client.v1beta1().sidecars().inNamespace(NAMESPACE).list(); list.getItems().forEach(b -> System.out.println(b.getMetadata().getName())); System.out.println("Done");
141
224
365
18,517
alibaba_fastjson2
fastjson2/example-spring-test/src/main/java/com/alibaba/fastjson2/example/springtest/controller/TestController.java
TestController
hello
class TestController { @GetMapping("/test") public User test(User user) { return user; } @GetMapping(value = "/hello", produces = "text/html") public void hello(HttpServletResponse response) {<FILL_FUNCTION_BODY>} }
//返回一个html测试页面 try (ServletOutputStream servletOutputStream = response.getOutputStream(); ) { ClassPathResource classPathResource = new ClassPathResource("hello.html"); servletOutputStream.write(classPathResource.readBytes()); } catch (IOException e) { throw new RuntimeException(e); }
77
86
163
6,277
apache_shenyu
shenyu/shenyu-plugin/shenyu-plugin-proxy/shenyu-plugin-rpc/shenyu-plugin-dubbo/shenyu-plugin-dubbo-common/src/main/java/org/apache/shenyu/plugin/dubbo/common/cache/DubboConfigCache.java
DubboConfigCache
parserToDubboParam
class DubboConfigCache { /** * parser the rpc ext to dubbo param. * * @param rpcExt the rpc ext * @return parsed dubbo param */ protected DubboParam parserToDubboParam(final String rpcExt) {<FILL_FUNCTION_BODY>} }
return GsonUtils.getInstance().fromJson(rpcExt, DubboParam.class);
85
25
110
68,141
apache_shenyu
shenyu/shenyu-web/src/main/java/org/apache/shenyu/web/loader/ShenyuExtPathPluginJarLoader.java
ShenyuExtPathPluginJarLoader
loadExtendPlugins
class ShenyuExtPathPluginJarLoader { private static volatile Set<String> pluginJarName = new HashSet<>(); /** * Load extend plugins list. * * @param path the path * @return the list * @throws IOException the io exception */ public static synchronized List<PluginJarParser.PluginJar> loadExtendPlugins(final String path) throws IOException {<FILL_FUNCTION_BODY>} }
File[] jarFiles = ShenyuPluginPathBuilder.getPluginFile(path).listFiles(file -> file.getName().endsWith(".jar")); if (Objects.isNull(jarFiles)) { return Collections.emptyList(); } List<PluginJarParser.PluginJar> uploadPluginJars = new ArrayList<>(); Set<String> currentPaths = new HashSet<>(); for (File file : jarFiles) { String absolutePath = file.getAbsolutePath(); currentPaths.add(absolutePath); if (pluginJarName.contains(absolutePath)) { continue; } byte[] pluginBytes = Files.readAllBytes(Paths.get(absolutePath)); PluginJarParser.PluginJar uploadPluginJar = PluginJarParser.parseJar(pluginBytes); uploadPluginJar.setAbsolutePath(absolutePath); uploadPluginJars.add(uploadPluginJar); } Sets.SetView<String> removePluginSet = Sets.difference(pluginJarName, currentPaths); for (String removePath : removePluginSet) { ShenyuPluginClassloaderHolder.getSingleton().removePluginClassLoader(removePath); } pluginJarName = currentPaths; return uploadPluginJars;
121
329
450
68,202
apache_incubator-kie-optaplanner
incubator-kie-optaplanner/optaplanner-persistence/optaplanner-persistence-jackson/src/main/java/org/optaplanner/persistence/jackson/api/score/PolymorphicScoreJacksonDeserializer.java
PolymorphicScoreJacksonDeserializer
deserialize
class PolymorphicScoreJacksonDeserializer extends JsonDeserializer<Score> { @Override public Score deserialize(JsonParser parser, DeserializationContext context) throws IOException {<FILL_FUNCTION_BODY>} }
parser.nextToken(); String scoreClassSimpleName = parser.getCurrentName(); parser.nextToken(); String scoreString = parser.getValueAsString(); if (scoreClassSimpleName.equals(SimpleScore.class.getSimpleName())) { return SimpleScore.parseScore(scoreString); } else if (scoreClassSimpleName.equals(SimpleLongScore.class.getSimpleName())) { return SimpleLongScore.parseScore(scoreString); } else if (scoreClassSimpleName.equals(SimpleBigDecimalScore.class.getSimpleName())) { return SimpleBigDecimalScore.parseScore(scoreString); } else if (scoreClassSimpleName.equals(HardSoftScore.class.getSimpleName())) { return HardSoftScore.parseScore(scoreString); } else if (scoreClassSimpleName.equals(HardSoftLongScore.class.getSimpleName())) { return HardSoftLongScore.parseScore(scoreString); } else if (scoreClassSimpleName.equals(HardSoftBigDecimalScore.class.getSimpleName())) { return HardSoftBigDecimalScore.parseScore(scoreString); } else if (scoreClassSimpleName.equals(HardMediumSoftScore.class.getSimpleName())) { return HardMediumSoftScore.parseScore(scoreString); } else if (scoreClassSimpleName.equals(HardMediumSoftLongScore.class.getSimpleName())) { return HardMediumSoftLongScore.parseScore(scoreString); } else if (scoreClassSimpleName.equals(HardMediumSoftBigDecimalScore.class.getSimpleName())) { return HardMediumSoftBigDecimalScore.parseScore(scoreString); } else if (scoreClassSimpleName.equals(BendableScore.class.getSimpleName())) { return BendableScore.parseScore(scoreString); } else if (scoreClassSimpleName.equals(BendableLongScore.class.getSimpleName())) { return BendableLongScore.parseScore(scoreString); } else if (scoreClassSimpleName.equals(BendableBigDecimalScore.class.getSimpleName())) { return BendableBigDecimalScore.parseScore(scoreString); } else { throw new IllegalArgumentException("Unrecognized scoreClassSimpleName (" + scoreClassSimpleName + ") for scoreString (" + scoreString + ")."); }
63
572
635
9,657
oracle_opengrok
opengrok/opengrok-indexer/src/main/java/org/opengrok/indexer/analysis/plain/DefinitionsTokenStream.java
DefinitionsTokenStream
initialize
class DefinitionsTokenStream extends TokenStream { /** * Defines the ultimate queue of tokens to be produced by * {@link #incrementToken()}. */ private final List<PendingToken> events = new ArrayList<>(); private final CharTermAttribute termAtt = addAttribute( CharTermAttribute.class); private final OffsetAttribute offsetAtt = addAttribute( OffsetAttribute.class); private final PositionIncrementAttribute posIncrAtt = addAttribute( PositionIncrementAttribute.class); private int offset; /** * Initializes the stream by merging {@code defs} with cross-referenced * line offsets read from {@code src}. * @param defs a defined instance * @param src a defined instance * @param wrapper an optional instance * @throws IOException if I/O error occurs */ public void initialize(Definitions defs, StreamSource src, ReaderWrapper wrapper) throws IOException {<FILL_FUNCTION_BODY>} /** * Publishes the next, pending token from * {@link #initialize(org.opengrok.indexer.analysis.Definitions, org.opengrok.indexer.analysis.StreamSource, * org.opengrok.indexer.util.ReaderWrapper)}, * if one is available. * @return false if no more tokens; otherwise true * @throws IOException in case of I/O error */ @Override public final boolean incrementToken() throws IOException { if (offset < events.size()) { PendingToken tok = events.get(offset++); setAttribs(tok); return true; } clearAttributes(); return false; } private void setAttribs(PendingToken tok) { clearAttributes(); this.posIncrAtt.setPositionIncrement(1); this.termAtt.setEmpty(); this.termAtt.append(tok.str); this.offsetAtt.setOffset(tok.start, tok.end); } private void createTokens(Definitions defs, LineBreaker brk) { for (Definitions.Tag tag : defs.getTags()) { // Shift from ctags's convention. int lineno = tag.line - 1; if (lineno >= 0 && lineno < brk.count() && tag.symbol != null && tag.text != null) { int lineoff = brk.getOffset(lineno); if (tag.lineStart >= 0) { PendingToken tok = new PendingToken(tag.symbol, lineoff + tag.lineStart, lineoff + tag.lineEnd); events.add(tok); } } } events.sort(PendingTokenOffsetsComparator.INSTANCE); } }
if (defs == null) { throw new IllegalArgumentException("`defs' is null"); } if (src == null) { throw new IllegalArgumentException("`src' is null"); } events.clear(); offset = 0; LineBreaker brk = new LineBreaker(); brk.reset(src, wrapper); createTokens(defs, brk);
722
105
827
35,108
apache_shenyu
shenyu/shenyu-register-center/shenyu-register-common/src/main/java/org/apache/shenyu/register/common/config/ShenyuClientConfig.java
ShenyuClientConfig
get
class ShenyuClientConfig { private Map<String, ClientPropertiesConfig> client = new HashMap<String, ClientPropertiesConfig>() { @Override public ClientPropertiesConfig get(final Object key) {<FILL_FUNCTION_BODY>} }; /** * Gets client. * * @return the client */ public Map<String, ClientPropertiesConfig> getClient() { return client; } /** * Sets client. * * @param client the client */ public void setClient(final Map<String, ClientPropertiesConfig> client) { this.client = client; } /** * this client properties config. */ public static class ClientPropertiesConfig extends PropertiesConfig { } }
ClientPropertiesConfig config = super.get(key); if (Objects.isNull(key) || Objects.isNull(config)) { throw new ShenyuException("key is null or invalid, you should checkout property of " + key); } return config;
203
71
274
67,917
macrozheng_mall-swarm
mall-swarm/mall-portal/src/main/java/com/macro/mall/portal/service/impl/AlipayServiceImpl.java
AlipayServiceImpl
query
class AlipayServiceImpl implements AlipayService { @Autowired private AlipayConfig alipayConfig; @Autowired private AlipayClient alipayClient; @Autowired private OmsOrderMapper orderMapper; @Autowired private OmsPortalOrderService portalOrderService; @Override public String pay(AliPayParam aliPayParam) { AlipayTradePagePayRequest request = new AlipayTradePagePayRequest(); if(StrUtil.isNotEmpty(alipayConfig.getNotifyUrl())){ //异步接收地址,公网可访问 request.setNotifyUrl(alipayConfig.getNotifyUrl()); } if(StrUtil.isNotEmpty(alipayConfig.getReturnUrl())){ //同步跳转地址 request.setReturnUrl(alipayConfig.getReturnUrl()); } //******必传参数****** JSONObject bizContent = new JSONObject(); //商户订单号,商家自定义,保持唯一性 bizContent.put("out_trade_no", aliPayParam.getOutTradeNo()); //支付金额,最小值0.01元 bizContent.put("total_amount", aliPayParam.getTotalAmount()); //订单标题,不可使用特殊符号 bizContent.put("subject", aliPayParam.getSubject()); //电脑网站支付场景固定传值FAST_INSTANT_TRADE_PAY bizContent.put("product_code", "FAST_INSTANT_TRADE_PAY"); request.setBizContent(bizContent.toString()); String formHtml = null; try { formHtml = alipayClient.pageExecute(request).getBody(); } catch (AlipayApiException e) { e.printStackTrace(); } return formHtml; } @Override public String notify(Map<String, String> params) { String result = "failure"; boolean signVerified = false; try { //调用SDK验证签名 signVerified = AlipaySignature.rsaCheckV1(params, alipayConfig.getAlipayPublicKey(), alipayConfig.getCharset(), alipayConfig.getSignType()); } catch (AlipayApiException e) { log.error("支付回调签名校验异常!",e); e.printStackTrace(); } if (signVerified) { String tradeStatus = params.get("trade_status"); if("TRADE_SUCCESS".equals(tradeStatus)){ result = "success"; log.info("notify方法被调用了,tradeStatus:{}",tradeStatus); String outTradeNo = params.get("out_trade_no"); portalOrderService.paySuccessByOrderSn(outTradeNo,1); }else{ log.warn("订单未支付成功,trade_status:{}",tradeStatus); } } else { log.warn("支付回调签名校验失败!"); } return result; } @Override public String query(String outTradeNo, String tradeNo) {<FILL_FUNCTION_BODY>} @Override public String webPay(AliPayParam aliPayParam) { AlipayTradeWapPayRequest request = new AlipayTradeWapPayRequest (); if(StrUtil.isNotEmpty(alipayConfig.getNotifyUrl())){ //异步接收地址,公网可访问 request.setNotifyUrl(alipayConfig.getNotifyUrl()); } if(StrUtil.isNotEmpty(alipayConfig.getReturnUrl())){ //同步跳转地址 request.setReturnUrl(alipayConfig.getReturnUrl()); } //******必传参数****** JSONObject bizContent = new JSONObject(); //商户订单号,商家自定义,保持唯一性 bizContent.put("out_trade_no", aliPayParam.getOutTradeNo()); //支付金额,最小值0.01元 bizContent.put("total_amount", aliPayParam.getTotalAmount()); //订单标题,不可使用特殊符号 bizContent.put("subject", aliPayParam.getSubject()); //手机网站支付默认传值FAST_INSTANT_TRADE_PAY bizContent.put("product_code", "QUICK_WAP_WAY"); request.setBizContent(bizContent.toString()); String formHtml = null; try { formHtml = alipayClient.pageExecute(request).getBody(); } catch (AlipayApiException e) { e.printStackTrace(); } return formHtml; } }
AlipayTradeQueryRequest request = new AlipayTradeQueryRequest(); //******必传参数****** JSONObject bizContent = new JSONObject(); //设置查询参数,out_trade_no和trade_no至少传一个 if(StrUtil.isNotEmpty(outTradeNo)){ bizContent.put("out_trade_no",outTradeNo); } if(StrUtil.isNotEmpty(tradeNo)){ bizContent.put("trade_no",tradeNo); } //交易结算信息: trade_settle_info String[] queryOptions = {"trade_settle_info"}; bizContent.put("query_options", queryOptions); request.setBizContent(bizContent.toString()); AlipayTradeQueryResponse response = null; try { response = alipayClient.execute(request); } catch (AlipayApiException e) { log.error("查询支付宝账单异常!",e); } if(response.isSuccess()){ log.info("查询支付宝账单成功!"); if("TRADE_SUCCESS".equals(response.getTradeStatus())){ portalOrderService.paySuccessByOrderSn(outTradeNo,1); } } else { log.error("查询支付宝账单失败!"); } //交易状态:WAIT_BUYER_PAY(交易创建,等待买家付款)、TRADE_CLOSED(未付款交易超时关闭,或支付完成后全额退款)、TRADE_SUCCESS(交易支付成功)、TRADE_FINISHED(交易结束,不可退款) return response.getTradeStatus();
1,241
458
1,699
3,000
flowable_flowable-engine
flowable-engine/modules/flowable-batch-service/src/main/java/org/flowable/batch/service/impl/persistence/entity/BatchPartEntityImpl.java
BatchPartEntityImpl
setBatchId
class BatchPartEntityImpl extends AbstractBatchServiceEntity implements BatchPartEntity, Serializable { private static final long serialVersionUID = 1L; protected static final String BATCH_RESULT_LABEL = "batchPartResult"; protected String type; protected String batchType; protected String batchId; protected String scopeId; protected String subScopeId; protected String scopeType; protected String searchKey; protected String searchKey2; protected String batchSearchKey; protected String batchSearchKey2; protected Date createTime; protected Date completeTime; protected String status; protected ByteArrayRef resultDocRefId; protected String tenantId; @Override public Object getPersistentState() { Map<String, Object> persistentState = new HashMap<>(); persistentState.put("batchId", batchId); persistentState.put("type", type); persistentState.put("scopeId", scopeId); persistentState.put("subScopeId", subScopeId); persistentState.put("scopeType", scopeType); persistentState.put("createTime", createTime); persistentState.put("completeTime", completeTime); persistentState.put("searchKey", searchKey); persistentState.put("searchKey2", searchKey2); persistentState.put("status", status); persistentState.put("tenantId", tenantId); if (resultDocRefId != null) { persistentState.put("resultDocRefId", resultDocRefId); } return persistentState; } @Override public String getType() { return type; } @Override public void setType(String type) { this.type = type; } @Override public String getBatchType() { return batchType; } @Override public void setBatchType(String batchType) { this.batchType = batchType; } @Override public String getBatchId() { return batchId; } @Override public void setBatchId(String batchId) {<FILL_FUNCTION_BODY>} @Override public Date getCreateTime() { return createTime; } @Override public void setCreateTime(Date time) { this.createTime = time; } @Override public Date getCompleteTime() { return completeTime; } @Override public void setCompleteTime(Date time) { this.completeTime = time; } @Override public boolean isCompleted() { return completeTime != null; } @Override public String getScopeId() { return scopeId; } @Override public void setScopeId(String scopeId) { this.scopeId = scopeId; } @Override public String getSubScopeId() { return subScopeId; } @Override public void setSubScopeId(String subScopeId) { this.subScopeId = subScopeId; } @Override public String getScopeType() { return scopeType; } @Override public void setScopeType(String scopeType) { this.scopeType = scopeType; } @Override public String getSearchKey() { return searchKey; } @Override public void setSearchKey(String searchKey) { this.searchKey = searchKey; } @Override public String getSearchKey2() { return searchKey2; } @Override public void setSearchKey2(String searchKey2) { this.searchKey2 = searchKey2; } @Override public String getBatchSearchKey() { return batchSearchKey; } @Override public void setBatchSearchKey(String batchSearchKey) { this.batchSearchKey = batchSearchKey; } @Override public String getBatchSearchKey2() { return batchSearchKey2; } @Override public void setBatchSearchKey2(String batchSearchKey2) { this.batchSearchKey2 = batchSearchKey2; } @Override public String getStatus() { return status; } @Override public void setStatus(String status) { this.status = status; } @Override public ByteArrayRef getResultDocRefId() { return resultDocRefId; } public void setResultDocRefId(ByteArrayRef resultDocRefId) { this.resultDocRefId = resultDocRefId; } @Override public String getResultDocumentJson(String engineType) { if (resultDocRefId != null) { byte[] bytes = resultDocRefId.getBytes(engineType); if (bytes != null) { return new String(bytes, StandardCharsets.UTF_8); } } return null; } @Override public void setResultDocumentJson(String resultDocumentJson, String engineType) { this.resultDocRefId = setByteArrayRef(this.resultDocRefId, BATCH_RESULT_LABEL, resultDocumentJson, engineType); } @Override public String getTenantId() { return tenantId; } @Override public void setTenantId(String tenantId) { this.tenantId = tenantId; } private static ByteArrayRef setByteArrayRef(ByteArrayRef byteArrayRef, String name, String value, String engineType) { if (byteArrayRef == null) { byteArrayRef = new ByteArrayRef(); } byte[] bytes = null; if (value != null) { bytes = value.getBytes(StandardCharsets.UTF_8); } byteArrayRef.setValue(name, bytes, engineType); return byteArrayRef; } }
this.batchId = batchId;
1,530
13
1,543
56,734
apache_shenyu
shenyu/shenyu-admin/src/main/java/org/apache/shenyu/admin/controller/ApiController.java
ApiController
deleteApis
class ApiController { private final ApiService apiService; public ApiController(final ApiService apiService) { this.apiService = apiService; } /** * query apis. * * @param apiPath api path. * @param state state. * @param tagId tagId. * @param currentPage current page. * @param pageSize page size. * @return {@linkplain ShenyuAdminResult} */ @GetMapping("") public ShenyuAdminResult queryApis(final String apiPath, final Integer state, final String tagId, @NotNull final Integer currentPage, @NotNull final Integer pageSize) { CommonPager<ApiVO> commonPager = apiService.listByPage(new ApiQuery(apiPath, state, tagId, new PageParameter(currentPage, pageSize))); return ShenyuAdminResult.success(ShenyuResultMessage.QUERY_SUCCESS, commonPager); } /** * detail plugin. * * @param id plugin id. * @return {@linkplain ShenyuAdminResult} */ @GetMapping("/{id}") public ShenyuAdminResult detailApi(@PathVariable("id") @Existed(message = "api is not existed", provider = ApiMapper.class) final String id) { ApiVO apiVO = apiService.findById(id); return ShenyuAdminResult.success(ShenyuResultMessage.DETAIL_SUCCESS, apiVO); } /** * create api. * * @param apiDTO api. * @return {@linkplain ShenyuAdminResult} */ @PostMapping("") @RequiresPermissions("system:api:add") public ShenyuAdminResult createApi(@Valid @RequestBody final ApiDTO apiDTO) { return ShenyuAdminResult.success(apiService.createOrUpdate(apiDTO)); } /** * update api. * * @param id primary key. * @param apiDTO api. * @return {@linkplain ShenyuAdminResult} */ @PutMapping("/{id}") @RequiresPermissions("system:api:edit") public ShenyuAdminResult updateApi(@PathVariable("id") @Existed(message = "api is not existed", provider = ApiMapper.class) final String id, @Valid @RequestBody final ApiDTO apiDTO) { apiDTO.setId(id); return ShenyuAdminResult.success(apiService.createOrUpdate(apiDTO)); } /** * delete apis. * * @param ids primary key. * @return {@linkplain ShenyuAdminResult} */ @DeleteMapping("/batch") @RequiresPermissions("system:api:delete") public ShenyuAdminResult deleteApis(@RequestBody @NotEmpty final List<@NotBlank String> ids) {<FILL_FUNCTION_BODY>} }
final String result = apiService.delete(ids); if (StringUtils.isNoneBlank(result)) { return ShenyuAdminResult.error(result); } return ShenyuAdminResult.success(ShenyuResultMessage.DELETE_SUCCESS);
806
74
880
68,230
knowm_XChange
XChange/xchange-bleutrade/src/main/java/org/knowm/xchange/bleutrade/dto/trade/BleutradeOpenOrdersReturn.java
BleutradeOpenOrdersReturn
setMessage
class BleutradeOpenOrdersReturn { @JsonProperty("success") private Boolean success; @JsonProperty("message") private String message; @JsonProperty("result") private List<BleutradeOpenOrder> result = new ArrayList<BleutradeOpenOrder>(); @JsonIgnore private Map<String, Object> additionalProperties = new HashMap<String, Object>(); /** * @return The success */ @JsonProperty("success") public Boolean getSuccess() { return success; } /** * @param success The success */ @JsonProperty("success") public void setSuccess(Boolean success) { this.success = success; } /** * @return The message */ @JsonProperty("message") public String getMessage() { return message; } /** * @param message The message */ @JsonProperty("message") public void setMessage(String message) {<FILL_FUNCTION_BODY>} /** * @return The result */ @JsonProperty("result") public List<BleutradeOpenOrder> getResult() { return result; } /** * @param result The result */ @JsonProperty("result") public void setResult(List<BleutradeOpenOrder> result) { this.result = result; } @JsonAnyGetter public Map<String, Object> getAdditionalProperties() { return this.additionalProperties; } @JsonAnySetter public void setAdditionalProperty(String name, Object value) { this.additionalProperties.put(name, value); } @Override public String toString() { return "BleutradeOpenOrdersReturn [success=" + success + ", message=" + message + ", result=" + result + ", additionalProperties=" + additionalProperties + "]"; } }
this.message = message;
527
12
539
27,550
apache_incubator-kie-optaplanner
incubator-kie-optaplanner/core/optaplanner-constraint-streams-bavet/src/main/java/org/optaplanner/constraint/streams/bavet/bi/Group0Mapping3CollectorBiNode.java
Group0Mapping3CollectorBiNode
updateOutTupleToResult
class Group0Mapping3CollectorBiNode<OldA, OldB, A, B, C, ResultContainerA_, ResultContainerB_, ResultContainerC_> extends AbstractGroupBiNode<OldA, OldB, TriTuple<A, B, C>, TriTupleImpl<A, B, C>, Void, Object, Triple<A, B, C>> { private final int outputStoreSize; public Group0Mapping3CollectorBiNode(int groupStoreIndex, int undoStoreIndex, BiConstraintCollector<OldA, OldB, ResultContainerA_, A> collectorA, BiConstraintCollector<OldA, OldB, ResultContainerB_, B> collectorB, BiConstraintCollector<OldA, OldB, ResultContainerC_, C> collectorC, TupleLifecycle<TriTuple<A, B, C>> nextNodesTupleLifecycle, int outputStoreSize, EnvironmentMode environmentMode) { super(groupStoreIndex, undoStoreIndex, null, mergeCollectors(collectorA, collectorB, collectorC), nextNodesTupleLifecycle, environmentMode); this.outputStoreSize = outputStoreSize; } static <OldA, OldB, A, B, C, ResultContainerA_, ResultContainerB_, ResultContainerC_> BiConstraintCollector<OldA, OldB, Object, Triple<A, B, C>> mergeCollectors( BiConstraintCollector<OldA, OldB, ResultContainerA_, A> collectorA, BiConstraintCollector<OldA, OldB, ResultContainerB_, B> collectorB, BiConstraintCollector<OldA, OldB, ResultContainerC_, C> collectorC) { return (BiConstraintCollector<OldA, OldB, Object, Triple<A, B, C>>) ConstraintCollectors.compose(collectorA, collectorB, collectorC, Triple::of); } @Override protected TriTupleImpl<A, B, C> createOutTuple(Void groupKey) { return new TriTupleImpl<>(null, null, null, outputStoreSize); } @Override protected void updateOutTupleToResult(TriTupleImpl<A, B, C> outTuple, Triple<A, B, C> result) {<FILL_FUNCTION_BODY>} }
outTuple.factA = result.getA(); outTuple.factB = result.getB(); outTuple.factC = result.getC();
576
45
621
9,964
dianping_cat
cat/cat-home/src/main/java/com/dianping/cat/system/page/login/JspViewer.java
JspViewer
getJspFilePath
class JspViewer extends BaseJspViewer<SystemPage, Action, Context, Model> { @Override protected String getJspFilePath(Context ctx, Model model) {<FILL_FUNCTION_BODY>} }
Action action = model.getAction(); switch (action) { case LOGIN: return JspFile.LOGIN.getPath(); case LOGOUT: return com.dianping.cat.report.page.home.JspFile.VIEW.getPath(); default: } throw new RuntimeException("Unknown action: " + action);
57
100
157
69,913
sofastack_sofa-jraft
sofa-jraft/jraft-core/src/main/java/com/alipay/sofa/jraft/util/FileOutputSignalHandler.java
FileOutputSignalHandler
makeDir
class FileOutputSignalHandler implements JRaftSignalHandler { protected File getOutputFile(final String path, final String baseFileName) throws IOException { makeDir(path); final String now = new SimpleDateFormat("yyyy-MM-dd_HH-mm-ss").format(new Date()); final String fileName = baseFileName + "." + now; final File file = Paths.get(path, fileName).toFile(); if (!file.exists() && !file.createNewFile()) { throw new IOException("Fail to create file: " + file); } return file; } private static void makeDir(final String path) throws IOException {<FILL_FUNCTION_BODY>} }
final File dir = Paths.get(path).toFile().getAbsoluteFile(); if (dir.exists()) { Requires.requireTrue(dir.isDirectory(), String.format("[%s] is not directory.", path)); } else { FileUtils.forceMkdir(dir); }
179
80
259
62,843
alibaba_Sentinel
Sentinel/sentinel-core/src/main/java/com/alibaba/csp/sentinel/slots/block/degrade/circuitbreaker/EventObserverRegistry.java
EventObserverRegistry
removeStateChangeObserver
class EventObserverRegistry { private final Map<String, CircuitBreakerStateChangeObserver> stateChangeObserverMap = new HashMap<>(); /** * Register a circuit breaker state change observer. * * @param name observer name * @param observer a valid observer */ public void addStateChangeObserver(String name, CircuitBreakerStateChangeObserver observer) { AssertUtil.notNull(name, "name cannot be null"); AssertUtil.notNull(observer, "observer cannot be null"); stateChangeObserverMap.put(name, observer); } public boolean removeStateChangeObserver(String name) {<FILL_FUNCTION_BODY>} /** * Get all registered state chane observers. * * @return all registered state chane observers */ public List<CircuitBreakerStateChangeObserver> getStateChangeObservers() { return new ArrayList<>(stateChangeObserverMap.values()); } public static EventObserverRegistry getInstance() { return InstanceHolder.instance; } private static class InstanceHolder { private static EventObserverRegistry instance = new EventObserverRegistry(); } EventObserverRegistry() {} }
AssertUtil.notNull(name, "name cannot be null"); return stateChangeObserverMap.remove(name) != null;
300
35
335
65,292
spring-projects_spring-batch
spring-batch/spring-batch-infrastructure/src/main/java/org/springframework/batch/item/database/HibernateCursorItemReader.java
HibernateCursorItemReader
setFetchSize
class HibernateCursorItemReader<T> extends AbstractItemCountingItemStreamItemReader<T> implements InitializingBean { private final HibernateItemReaderHelper<T> helper = new HibernateItemReaderHelper<>(); public HibernateCursorItemReader() { setName(ClassUtils.getShortName(HibernateCursorItemReader.class)); } private ScrollableResults<? extends T> cursor; private boolean initialized = false; private int fetchSize; private Map<String, Object> parameterValues; @Override public void afterPropertiesSet() throws Exception { Assert.state(fetchSize >= 0, "fetchSize must not be negative"); helper.afterPropertiesSet(); } /** * The parameter values to apply to a query (map of name:value). * @param parameterValues the parameter values to set */ public void setParameterValues(Map<String, Object> parameterValues) { this.parameterValues = parameterValues; } /** * A query name for an externalized query. Either this or the { * {@link #setQueryString(String) query string} or the { * {@link #setQueryProvider(HibernateQueryProvider) query provider} should be set. * @param queryName name of a hibernate named query */ public void setQueryName(String queryName) { helper.setQueryName(queryName); } /** * Fetch size used internally by Hibernate to limit amount of data fetched from * database per round trip. * @param fetchSize the fetch size to pass down to Hibernate */ public void setFetchSize(int fetchSize) {<FILL_FUNCTION_BODY>} /** * A query provider. Either this or the {{@link #setQueryString(String) query string} * or the {{@link #setQueryName(String) query name} should be set. * @param queryProvider Hibernate query provider */ public void setQueryProvider(HibernateQueryProvider<T> queryProvider) { helper.setQueryProvider(queryProvider); } /** * A query string in HQL. Either this or the { * {@link #setQueryProvider(HibernateQueryProvider) query provider} or the { * {@link #setQueryName(String) query name} should be set. * @param queryString HQL query string */ public void setQueryString(String queryString) { helper.setQueryString(queryString); } /** * The Hibernate SessionFactory to use the create a session. * @param sessionFactory the {@link SessionFactory} to set */ public void setSessionFactory(SessionFactory sessionFactory) { helper.setSessionFactory(sessionFactory); } /** * Can be set only in uninitialized state. * @param useStatelessSession <code>true</code> to use {@link StatelessSession} * <code>false</code> to use standard hibernate {@link Session} */ public void setUseStatelessSession(boolean useStatelessSession) { helper.setUseStatelessSession(useStatelessSession); } @Nullable @Override protected T doRead() throws Exception { if (cursor.next()) { return cursor.get(); } return null; } /** * Open hibernate session and create a forward-only cursor for the query. */ @Override protected void doOpen() throws Exception { Assert.state(!initialized, "Cannot open an already opened ItemReader, call close first"); cursor = helper.getForwardOnlyCursor(fetchSize, parameterValues); initialized = true; } /** * Update the context and clear the session if stateful. * @param executionContext the current {@link ExecutionContext} * @throws ItemStreamException if there is a problem */ @Override public void update(ExecutionContext executionContext) throws ItemStreamException { super.update(executionContext); helper.clear(); } /** * Wind forward through the result set to the item requested. Also clears the session * every now and then (if stateful) to avoid memory problems. The frequency of session * clearing is the larger of the fetch size (if set) and 100. * @param itemIndex the first item to read * @throws Exception if there is a problem * @see AbstractItemCountingItemStreamItemReader#jumpToItem(int) */ @Override protected void jumpToItem(int itemIndex) throws Exception { int flushSize = Math.max(fetchSize, 100); helper.jumpToItem(cursor, itemIndex, flushSize); } /** * Close the cursor and hibernate session. */ @Override protected void doClose() throws Exception { if (initialized) { if (cursor != null) { cursor.close(); } helper.close(); } initialized = false; } }
this.fetchSize = fetchSize;
1,253
13
1,266
44,561
Kong_unirest-java
unirest-java/unirest/src/main/java/kong/unirest/core/InputStreamPart.java
InputStreamPart
getFileName
class InputStreamPart extends BodyPart<InputStream> { private String fileName; InputStreamPart(String name, InputStream value, String contentType) { super(value, name, contentType); } InputStreamPart(String name, InputStream value, String contentType, String fileName) { super(value, name, contentType); this.fileName = fileName; } @Override public String getFileName() {<FILL_FUNCTION_BODY>} @Override public boolean isFile() { return true; } @Override public String toString() { return String.format("%s=%s", getName(), fileName); } }
return fileName;
181
9
190
28,440
lealone_Lealone
Lealone/lealone-net/src/main/java/com/lealone/net/NetBufferInputStream.java
NetBufferInputStream
close
class NetBufferInputStream extends InputStream { protected final NetBuffer buffer; protected final int size; protected int pos; public NetBufferInputStream(NetBuffer buffer) { this.buffer = buffer; size = buffer.length(); } @Override public int available() throws IOException { return size - pos; } @Override public int read() throws IOException { return buffer.getUnsignedByte(pos++); } @Override public void close() throws IOException {<FILL_FUNCTION_BODY>} }
// buffer中只有一个包时回收才安全 if (buffer.isOnlyOnePacket()) buffer.recycle();
146
35
181
29,219
vipshop_vjtools
vjtools/vjkit/src/main/java/com/vip/vjtools/vjkit/id/IdUtil.java
IdUtil
fastUUID
class IdUtil { /* * 返回使用ThreadLocalRandom的UUID,比默认的UUID性能更优 */ public static UUID fastUUID() {<FILL_FUNCTION_BODY>} }
ThreadLocalRandom random = ThreadLocalRandom.current(); return new UUID(random.nextLong(), random.nextLong());
53
33
86
64,145
sofastack_sofa-boot
sofa-boot/sofa-boot-project/sofa-boot-core/runtime-sofa-boot/src/main/java/com/alipay/sofa/runtime/ext/spring/parser/ExtensionBeanDefinitionParser.java
ExtensionBeanDefinitionParser
parserSubElement
class ExtensionBeanDefinitionParser extends AbstractExtBeanDefinitionParser { public static final String CONTENT = "content"; private static final ExtensionBeanDefinitionParser INSTANCE = new ExtensionBeanDefinitionParser(); public ExtensionBeanDefinitionParser() { } public static ExtensionBeanDefinitionParser getInstance() { return INSTANCE; } @Override protected Class<?> getBeanClass(Element element) { return ExtensionFactoryBean.class; } @Override protected void parserSubElement(Element element, ParserContext parserContext, BeanDefinitionBuilder builder) {<FILL_FUNCTION_BODY>} @Override public String supportTagName() { return "extension"; } }
NodeList nl = element.getChildNodes(); // parse all sub elements for (int i = 0; i < nl.getLength(); i++) { Node node = nl.item(i); if (node instanceof Element subElement) { // osgi:content if (CONTENT.equals(subElement.getLocalName())) { builder.addPropertyValue(CONTENT, subElement); } } }
183
116
299
41,195
Col-E_Recaf
Recaf/src/main/java/me/coley/recaf/parse/bytecode/parser/TypeInsnParser.java
TypeInsnParser
visit
class TypeInsnParser extends AbstractParser<TypeInsnAST> { @Override public TypeInsnAST visit(int lineNo, String line) throws ASTParseException {<FILL_FUNCTION_BODY>} @Override public List<String> suggest(ParseResult<RootAST> lastParse, String text) { if (text.contains(" ")) { String[] parts = text.split("\\s+"); return new TypeParser().suggest(lastParse, parts[parts.length - 1]); } return Collections.emptyList(); } }
try { String[] trim = line.trim().split("\\s+"); if (trim.length < 2) throw new ASTParseException(lineNo, "Not enough parameters"); int start = line.indexOf(trim[0]); // op OpcodeParser opParser = new OpcodeParser(); opParser.setOffset(line.indexOf(trim[0])); OpcodeAST op = opParser.visit(lineNo, trim[0]); // type TypeParser typeParser = new TypeParser(); typeParser.setOffset(line.indexOf(trim[1])); TypeAST type = typeParser.visit(lineNo, trim[1]); return new TypeInsnAST(lineNo, start, op, type); } catch(Exception ex) { throw new ASTParseException(ex, lineNo, "Bad format for type instruction"); }
139
228
367
14,240
brettwooldridge_HikariCP
HikariCP/src/main/java/com/zaxxer/hikari/pool/PoolBase.java
MetricsTrackerDelegate
recordConnectionCreated
class MetricsTrackerDelegate implements IMetricsTrackerDelegate { final IMetricsTracker tracker; MetricsTrackerDelegate(IMetricsTracker tracker) { this.tracker = tracker; } @Override public void recordConnectionUsage(final PoolEntry poolEntry) { tracker.recordConnectionUsageMillis(poolEntry.getMillisSinceBorrowed()); } @Override public void recordConnectionCreated(long connectionCreatedMillis) {<FILL_FUNCTION_BODY>} @Override public void recordBorrowTimeoutStats(long startTime) { tracker.recordConnectionAcquiredNanos(elapsedNanos(startTime)); } @Override public void recordBorrowStats(final PoolEntry poolEntry, final long startTime) { final var now = currentTime(); poolEntry.lastBorrowed = now; tracker.recordConnectionAcquiredNanos(elapsedNanos(startTime, now)); } @Override public void recordConnectionTimeout() { tracker.recordConnectionTimeout(); } @Override public void close() { tracker.close(); } }
tracker.recordConnectionCreatedMillis(connectionCreatedMillis);
318
19
337
68,840
alibaba_druid
druid/core/src/main/java/com/alibaba/druid/sql/ast/statement/SQLAlterTableDropColumnItem.java
SQLAlterTableDropColumnItem
accept0
class SQLAlterTableDropColumnItem extends SQLObjectImpl implements SQLAlterTableItem { private boolean ifExists; private List<SQLName> columns = new ArrayList<SQLName>(); private boolean restrict; private boolean cascade; public SQLAlterTableDropColumnItem() { } @Override protected void accept0(SQLASTVisitor visitor) {<FILL_FUNCTION_BODY>} public boolean isIfExists() { return ifExists; } public void setIfExists(boolean ifExists) { this.ifExists = ifExists; } public List<SQLName> getColumns() { return columns; } public void addColumn(SQLName column) { if (column != null) { column.setParent(this); } this.columns.add(column); } public boolean isRestrict() { return restrict; } public void setRestrict(boolean restrict) { this.restrict = restrict; } public boolean isCascade() { return cascade; } public void setCascade(boolean cascade) { this.cascade = cascade; } }
if (visitor.visit(this)) { acceptChild(visitor, columns); } visitor.endVisit(this);
314
38
352
50,416
apache_incubator-hugegraph
incubator-hugegraph/hugegraph-server/hugegraph-test/src/main/java/org/apache/hugegraph/api/BaseApiTest.java
RestClient
initPropertyKey
class RestClient { private final Client client; private final WebTarget target; public RestClient(String url) { this(url, true); } public RestClient(String url, Boolean enableAuth) { this.client = ClientBuilder.newClient(); this.client.register(EncodingFilter.class); this.client.register(GZipEncoder.class); if (enableAuth) { this.client.register(HttpAuthenticationFeature.basic(USERNAME, PASSWORD)); } this.target = this.client.target(url); } public void close() { this.client.close(); } public WebTarget target() { return this.target; } public WebTarget target(String url) { return this.client.target(url); } public Response get(String path) { return this.target.path(path).request().get(); } public Response get(String path, String id) { return this.target.path(path).path(id).request().get(); } public Response get(String path, MultivaluedMap<String, Object> headers) { return this.target.path(path).request().headers(headers).get(); } public Response get(String path, Multimap<String, Object> params) { WebTarget target = this.target.path(path); for (Map.Entry<String, Object> entries : params.entries()) { target = target.queryParam(entries.getKey(), entries.getValue()); } return target.request().get(); } public Response get(String path, Map<String, Object> params) { WebTarget target = this.target.path(path); for (Map.Entry<String, Object> i : params.entrySet()) { target = target.queryParam(i.getKey(), i.getValue()); } return target.request().get(); } public Response post(String path, String content) { return this.post(path, Entity.json(content)); } public Response post(String path, Entity<?> entity) { return this.target.path(path).request().post(entity); } public Response put(String path, String id, String content, Map<String, Object> params) { WebTarget target = this.target.path(path).path(id); for (Map.Entry<String, Object> i : params.entrySet()) { target = target.queryParam(i.getKey(), i.getValue()); } return target.request().put(Entity.json(content)); } public Response delete(String path, String id) { return this.target.path(path).path(id).request().delete(); } public Response delete(String path, Map<String, Object> params) { WebTarget target = this.target.path(path); for (Map.Entry<String, Object> i : params.entrySet()) { target = target.queryParam(i.getKey(), i.getValue()); } return target.request().delete(); } public Response delete(String path, MultivaluedMap<String, Object> headers) { WebTarget target = this.target.path(path); return target.request().headers(headers).delete(); } } /** * Utils method to init some properties */ protected static void initPropertyKey() {<FILL_FUNCTION_BODY>
String path = URL_PREFIX + SCHEMA_PKS; createAndAssert(path, "{\n" + "\"name\": \"name\",\n" + "\"data_type\": \"TEXT\",\n" + "\"cardinality\": \"SINGLE\",\n" + "\"check_exist\": false,\n" + "\"properties\":[]\n" + "}", 202); createAndAssert(path, "{\n" + "\"name\": \"age\",\n" + "\"data_type\": \"INT\",\n" + "\"cardinality\": \"SINGLE\",\n" + "\"check_exist\": false,\n" + "\"properties\":[]\n" + "}", 202); createAndAssert(path, "{\n" + "\"name\": \"city\",\n" + "\"data_type\": \"TEXT\",\n" + "\"cardinality\": \"SINGLE\",\n" + "\"check_exist\": false,\n" + "\"properties\":[]\n" + "}", 202); createAndAssert(path, "{\n" + "\"name\": \"lang\",\n" + "\"data_type\": \"TEXT\",\n" + "\"cardinality\": \"SINGLE\",\n" + "\"check_exist\": false,\n" + "\"properties\":[]\n" + "}", 202); createAndAssert(path, "{\n" + "\"name\": \"date\",\n" + "\"data_type\": \"TEXT\",\n" + "\"cardinality\": \"SINGLE\",\n" + "\"check_exist\": false,\n" + "\"properties\":[]\n" + "}", 202); createAndAssert(path, "{\n" + "\"name\": \"price\",\n" + "\"data_type\": \"INT\",\n" + "\"cardinality\": \"SINGLE\",\n" + "\"check_exist\": false,\n" + "\"properties\":[]\n" + "}", 202); createAndAssert(path, "{\n" + "\"name\": \"weight\",\n" + "\"data_type\": \"DOUBLE\",\n" + "\"cardinality\": \"SINGLE\",\n" + "\"check_exist\": false,\n" + "\"properties\":[]\n" + "}", 202);
888
723
1,611
8,825
alibaba_COLA
COLA/cola-samples/craftsman/craftsman-domain/src/main/java/com/alibaba/craftsman/domain/metrics/techinfluence/PaperMetric.java
PaperMetric
getWeight
class PaperMetric extends SubMetric { public PaperMetric(){ this.subMetricType = SubMetricType.Paper; } public PaperMetric(MainMetric parent) { this.parent = parent; parent.addSubMetric(this); this.subMetricType = SubMetricType.Paper; } @Override public double getWeight() {<FILL_FUNCTION_BODY>} }
return parent.getMetricOwner().getWeight().getUnanimousWeight();
113
22
135
49,671
lilishop_lilishop
lilishop/framework/src/main/java/cn/lili/modules/system/entity/dto/PointSettingItem.java
PointSettingItem
getPoint
class PointSettingItem implements Comparable<PointSettingItem>, Serializable { @ApiModelProperty(value = "签到天数") private Integer day; @ApiModelProperty(value = "赠送积分") private Integer point; public Integer getPoint() {<FILL_FUNCTION_BODY>} public void setPoint(Integer point) { this.point = point; } @Override public int compareTo(PointSettingItem pointSettingItem) { return this.day - pointSettingItem.getDay(); } }
if (point == null || point < 0) { return 0; } return point;
147
30
177
30,260
jitsi_jitsi
jitsi/modules/impl/gui/src/main/java/net/java/sip/communicator/impl/gui/main/chat/history/DatesPanel.java
DatesPanel
getNextDate
class DatesPanel extends SIPCommScrollPane implements ListSelectionListener { private final JList datesList = new JList(); /** * The <tt>ListModel</tt> of {@link #datesList} explicitly stored in order * to have it as a <tt>DefaultListModel</tt> instance. */ private final DefaultListModel listModel = new DefaultListModel(); private final HistoryWindow historyWindow; private int lastSelectedIndex = -1; /** * Creates an instance of <tt>DatesPanel</tt>. * * @param historyWindow the parent <tt>HistoryWindow</tt>, where * this panel is contained. */ public DatesPanel(HistoryWindow historyWindow) { this.historyWindow = historyWindow; this.setPreferredSize(new Dimension(100, 100)); this.setBorder(SIPCommBorders.getBoldRoundBorder()); this.setOpaque(false); this.datesList.setModel(listModel); this.datesList.setCellRenderer(new DatesListRenderer()); this.datesList.setFont(datesList.getFont().deriveFont(Font.BOLD)); this.datesList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); this.datesList.addListSelectionListener(this); JPanel listPanel = new TransparentPanel(new BorderLayout()); listPanel.add(datesList, BorderLayout.NORTH); this.setViewportView(listPanel); this.getVerticalScrollBar().setUnitIncrement(30); } /** * Returns the number of dates contained in this dates panel. * @return the number of dates contained in this dates panel */ public int getDatesNumber() { synchronized (listModel) { return listModel.size(); } } /** * Returns the date at the given index. * @param index the index of the date in the list model * @return the date at the given index */ public Date getDate(int index) { synchronized (listModel) { return (Date)listModel.get(index); } } /** * Returns the next date in the list. * @param date the date from which to start * @return the next date in the list */ public Date getNextDate(Date date) {<FILL_FUNCTION_BODY>} /** * Adds the given date to the list of dates. * @param date the date to add */ public void addDate(Date date) { synchronized (listModel) { int listSize = listModel.size(); boolean dateAdded = false; if(listSize > 0) { for(int i = 0; i < listSize; i ++) { Date dateFromList = (Date)listModel.get(i); if(dateFromList.after(date)) { listModel.add(i, date); dateAdded = true; break; } } if(!dateAdded) { listModel.addElement(date); } } else { listModel.addElement(date); } } } /** * Removes all dates contained in this list. */ public void removeAllDates() { synchronized (listModel) { listModel.removeAllElements(); } } /** * Checks whether the given date is contained in the list * of history dates. * @param date the date to search for * @return TRUE if the given date is contained in the list * of history dates, FALSE otherwise */ public boolean containsDate(Date date) { synchronized (listModel) { return listModel.contains(date); } } /** * Implements the <tt>ListSelectionListener.valueChanged</tt>. * Shows all history records for the selected date. */ public void valueChanged(ListSelectionEvent e) { synchronized (listModel) { int selectedIndex = this.datesList.getSelectedIndex(); if(selectedIndex != -1 && lastSelectedIndex != selectedIndex) { this.setLastSelectedIndex(selectedIndex); Date date = (Date)this.listModel.get(selectedIndex); this.historyWindow.showHistoryByPeriod( date, historyWindow.getNextDateFromHistory(date)); } } } /** * Selects the cell at the given index. * @param index the index of the cell to select */ public void setSelected(int index) { this.datesList.setSelectedIndex(index); } /** * Returns the model of the contained list. * @return the model of the contained list */ public ListModel getModel() { return listModel; } /** * Returns the index that was last selected. * @return the index that was last selected */ public int getLastSelectedIndex() { return lastSelectedIndex; } /** * Sets the last selected index. * @param lastSelectedIndex the last selected index */ public void setLastSelectedIndex(int lastSelectedIndex) { this.lastSelectedIndex = lastSelectedIndex; } }
synchronized (listModel) { Date nextDate; int dateIndex = listModel.indexOf(date); if(dateIndex < listModel.getSize() - 1) { nextDate = getDate(dateIndex + 1); } else { nextDate = new Date(System.currentTimeMillis()); } return nextDate; }
1,410
99
1,509
26,433
speedment_speedment
speedment/runtime-parent/runtime-compute/src/main/java/com/speedment/runtime/compute/internal/JoiningExpressionImpl.java
JoiningExpressionImpl
apply
class JoiningExpressionImpl<T> implements JoiningExpression<T> { private final CharSequence separator; private final CharSequence prefix; private final CharSequence suffix; private final List<ToString<T>> expressions; public JoiningExpressionImpl( final CharSequence separator, final CharSequence prefix, final CharSequence suffix, final List<ToString<T>> expressions) { this.separator = requireNonNull(separator); this.prefix = requireNonNull(prefix); this.suffix = requireNonNull(suffix); this.expressions = unmodifiableList(expressions); } @Override public List<ToString<T>> expressions() { return expressions; } @Override public CharSequence prefix() { return prefix; } @Override public CharSequence suffix() { return suffix; } @Override public CharSequence separator() { return separator; } @Override public String apply(T object) {<FILL_FUNCTION_BODY>} }
final StringJoiner joiner = new StringJoiner(separator, prefix, suffix); for (final ToString<T> expression : expressions) { joiner.add(expression.apply(object)); } return joiner.toString();
277
63
340
42,643
648540858_wvp-GB28181-pro
wvp-GB28181-pro/src/main/java/com/genersoft/iot/vmp/service/redisMsg/RedisPushStreamResponseListener.java
RedisPushStreamResponseListener
onMessage
class RedisPushStreamResponseListener implements MessageListener { private final static Logger logger = LoggerFactory.getLogger(RedisPushStreamResponseListener.class); private ConcurrentLinkedQueue<Message> taskQueue = new ConcurrentLinkedQueue<>(); @Qualifier("taskExecutor") @Autowired private ThreadPoolTaskExecutor taskExecutor; private Map<String, PushStreamResponseEvent> responseEvents = new ConcurrentHashMap<>(); public interface PushStreamResponseEvent{ void run(MessageForPushChannelResponse response); } @Override public void onMessage(Message message, byte[] bytes) {<FILL_FUNCTION_BODY>} public void addEvent(String app, String stream, PushStreamResponseEvent callback) { responseEvents.put(app + stream, callback); } public void removeEvent(String app, String stream) { responseEvents.remove(app + stream); } }
logger.info("[REDIS消息-请求推流结果]: {}", new String(message.getBody())); boolean isEmpty = taskQueue.isEmpty(); taskQueue.offer(message); if (isEmpty) { taskExecutor.execute(() -> { while (!taskQueue.isEmpty()) { Message msg = taskQueue.poll(); try { MessageForPushChannelResponse response = JSON.parseObject(new String(msg.getBody()), MessageForPushChannelResponse.class); if (response == null || ObjectUtils.isEmpty(response.getApp()) || ObjectUtils.isEmpty(response.getStream())){ logger.info("[REDIS消息-请求推流结果]:参数不全"); continue; } // 查看正在等待的invite消息 if (responseEvents.get(response.getApp() + response.getStream()) != null) { responseEvents.get(response.getApp() + response.getStream()).run(response); } }catch (Exception e) { logger.warn("[REDIS消息-请求推流结果] 发现未处理的异常, \r\n{}", JSON.toJSONString(message)); logger.error("[REDIS消息-请求推流结果] 异常内容: ", e); } } }); }
243
328
571
5,278
apache_incubator-streampark
incubator-streampark/streampark-console/streampark-console-service/src/main/java/org/apache/streampark/console/core/service/alert/impl/HttpCallbackAlertNotifyServiceImpl.java
HttpCallbackAlertNotifyServiceImpl
sendMessage
class HttpCallbackAlertNotifyServiceImpl implements AlertNotifyService { @Autowired private RestTemplate alertRestTemplate; @Autowired private ObjectMapper mapper; @Override public boolean doAlert(AlertConfigParams alertConfig, AlertTemplate alertTemplate) throws AlertException { AlertHttpCallbackParams alertHttpCallbackParams = alertConfig.getHttpCallbackParams(); String requestTemplate = alertHttpCallbackParams.getRequestTemplate(); if (!StringUtils.hasLength(requestTemplate)) { return false; } try { Template template = FreemarkerUtils.loadTemplateString(requestTemplate); String format = FreemarkerUtils.format(template, alertTemplate); Map<String, Object> body = mapper.readValue(format, new TypeReference<Map<String, Object>>() {}); sendMessage(alertHttpCallbackParams, body); return true; } catch (AlertException alertException) { throw alertException; } catch (Exception e) { throw new AlertException("Failed send httpCallback alert", e); } } private void sendMessage(AlertHttpCallbackParams params, Map<String, Object> body) throws AlertException {<FILL_FUNCTION_BODY>} @Nonnull private HttpHeaders getHttpHeaders(AlertHttpCallbackParams params) { HttpHeaders headers = new HttpHeaders(); String contentType = params.getContentType(); MediaType mediaType = MediaType.APPLICATION_JSON; if (StringUtils.hasLength(contentType)) { switch (contentType.toLowerCase()) { case MediaType.APPLICATION_FORM_URLENCODED_VALUE: mediaType = MediaType.APPLICATION_FORM_URLENCODED; break; case MediaType.MULTIPART_FORM_DATA_VALUE: mediaType = MediaType.MULTIPART_FORM_DATA; break; case MediaType.APPLICATION_JSON_VALUE: default: break; } } headers.setContentType(mediaType); return headers; } }
String url = params.getUrl(); HttpHeaders headers = getHttpHeaders(params); ResponseEntity<Object> response; try { HttpMethod httpMethod = HttpMethod.POST; String method = params.getMethod(); if (!StringUtils.hasLength(method)) { if (HttpMethod.PUT.name().equalsIgnoreCase(method)) { httpMethod = HttpMethod.PUT; } } HttpEntity<Map<String, Object>> entity = new HttpEntity<>(body, headers); RequestCallback requestCallback = alertRestTemplate.httpEntityCallback(entity, Object.class); ResponseExtractor<ResponseEntity<Object>> responseExtractor = alertRestTemplate.responseEntityExtractor(Object.class); response = alertRestTemplate.execute(url, httpMethod, requestCallback, responseExtractor); } catch (Exception e) { log.error("Failed to request httpCallback alert,\nurl:{}", url, e); throw new AlertException( String.format("Failed to request httpCallback alert,%nurl:%s", url), e); } if (response == null) { throw new AlertException(String.format("Failed to request httpCallback alert,%nurl:%s", url)); }
535
309
844
52,896
sannies_mp4parser
mp4parser/isoparser/src/main/java/org/mp4parser/boxes/samplegrouping/TemporalLevelEntry.java
TemporalLevelEntry
hashCode
class TemporalLevelEntry extends GroupEntry { public static final String TYPE = "tele"; private boolean levelIndependentlyDecodable; private short reserved; @Override public String getType() { return TYPE; } public boolean isLevelIndependentlyDecodable() { return levelIndependentlyDecodable; } public void setLevelIndependentlyDecodable(boolean levelIndependentlyDecodable) { this.levelIndependentlyDecodable = levelIndependentlyDecodable; } @Override public void parse(ByteBuffer byteBuffer) { final byte b = byteBuffer.get(); levelIndependentlyDecodable = ((b & 0x80) == 0x80); } @Override public ByteBuffer get() { ByteBuffer content = ByteBuffer.allocate(1); content.put((byte) (levelIndependentlyDecodable ? 0x80 : 0x00)); ((Buffer)content).rewind(); return content; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; TemporalLevelEntry that = (TemporalLevelEntry) o; if (levelIndependentlyDecodable != that.levelIndependentlyDecodable) return false; if (reserved != that.reserved) return false; return true; } @Override public int hashCode() {<FILL_FUNCTION_BODY>} @Override public String toString() { final StringBuilder sb = new StringBuilder(); sb.append("TemporalLevelEntry"); sb.append("{levelIndependentlyDecodable=").append(levelIndependentlyDecodable); sb.append('}'); return sb.toString(); } }
int result = (levelIndependentlyDecodable ? 1 : 0); result = 31 * result + (int) reserved; return result;
493
42
535
39,908