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
|
---|---|---|---|---|---|---|---|---|---|
sofastack_sofa-boot
|
sofa-boot/sofa-boot-project/sofa-boot-core/test-sofa-boot/src/main/java/com/alipay/sofa/test/mock/injector/definition/Definition.java
|
Definition
|
equals
|
class Definition {
private static final int MULTIPLIER = 31;
private final String name;
private final ResolvableType type;
private final String module;
private final String field;
private final MockReset reset;
private final QualifierDefinition qualifier;
private final ResolvableType mockType;
protected Object mockInstance;
public Definition(ResolvableType mockType, String name, ResolvableType type, String module,
String field, MockReset reset, QualifierDefinition qualifier) {
Assert.notNull(mockType, "MockType must not be null");
this.mockType = mockType;
this.type = type;
this.name = name;
this.module = module;
this.field = field;
this.reset = (reset != null) ? reset : MockReset.AFTER;
this.qualifier = qualifier;
}
public String getName() {
return name;
}
public ResolvableType getType() {
return type;
}
public String getModule() {
return module;
}
public String getField() {
return field;
}
public MockReset getReset() {
return reset;
}
public ResolvableType getMockType() {
return this.mockType;
}
public QualifierDefinition getQualifier() {
return qualifier;
}
public Object getMockInstance() {
return mockInstance;
}
public void resetMock() {
if (mockInstance != null) {
Mockito.reset(mockInstance);
}
}
@Override
public boolean equals(Object obj) {<FILL_FUNCTION_BODY>}
@Override
public int hashCode() {
int result = 1;
result = MULTIPLIER * result + ObjectUtils.nullSafeHashCode(this.mockType);
result = MULTIPLIER * result + ObjectUtils.nullSafeHashCode(this.name);
result = MULTIPLIER * result + ObjectUtils.nullSafeHashCode(this.type);
result = MULTIPLIER * result + ObjectUtils.nullSafeHashCode(this.module);
result = MULTIPLIER * result + ObjectUtils.nullSafeHashCode(this.field);
result = MULTIPLIER * result + ObjectUtils.nullSafeHashCode(this.reset);
result = MULTIPLIER * result + ObjectUtils.nullSafeHashCode(this.qualifier);
return result;
}
}
|
if (obj == this) {
return true;
}
if (obj == null || !getClass().isAssignableFrom(obj.getClass())) {
return false;
}
Definition other = (Definition) obj;
boolean result = true;
result = result && ObjectUtils.nullSafeEquals(this.mockType, other.mockType);
result = result && ObjectUtils.nullSafeEquals(this.name, other.name);
result = result && ObjectUtils.nullSafeEquals(this.type, other.type);
result = result && ObjectUtils.nullSafeEquals(this.module, other.module);
result = result && ObjectUtils.nullSafeEquals(this.field, other.field);
result = result && ObjectUtils.nullSafeEquals(this.reset, other.reset);
result = result && ObjectUtils.nullSafeEquals(this.qualifier, other.qualifier);
return result;
| 654 | 225 | 879 | 41,249 |
killme2008_aviatorscript
|
aviatorscript/src/main/java/com/googlecode/aviator/lexer/SymbolTable.java
|
SymbolTable
|
reserve
|
class SymbolTable implements Serializable {
private static final long serialVersionUID = -9019014977807517193L;
private final Map<String, Variable> table = new HashMap<>();
private static final Map<String, Variable> RESERVED = new HashMap<>();
private static void reserveKeyword(final Variable v) {
RESERVED.put(v.getLexeme(), v);
}
static {
reserveKeyword(Variable.TRUE);
reserveKeyword(Variable.FALSE);
reserveKeyword(Variable.NIL);
reserveKeyword(Variable.LAMBDA);
reserveKeyword(Variable.FN);
reserveKeyword(Variable.END);
reserveKeyword(Variable.IF);
reserveKeyword(Variable.ELSE);
reserveKeyword(Variable.FOR);
reserveKeyword(Variable.IN);
reserveKeyword(Variable.RETURN);
reserveKeyword(Variable.BREAK);
reserveKeyword(Variable.CONTINUE);
reserveKeyword(Variable.LET);
reserveKeyword(Variable.WHILE);
reserveKeyword(Variable.ELSIF);
reserveKeyword(Variable.TRY);
reserveKeyword(Variable.CATCH);
reserveKeyword(Variable.FINALLY);
reserveKeyword(Variable.THROW);
reserveKeyword(Variable.NEW);
reserveKeyword(Variable.USE);
}
public static boolean isReservedKeyword(final String name) {
return RESERVED.containsKey(name);
}
public static boolean isReservedKeyword(final Variable v) {
return isReservedKeyword(v.getLexeme());
}
/**
* Check variable has been reserved?
*
* @param name
* @return
*/
public boolean isReserved(final String name) {
return isReservedKeyword(name) || this.table.containsKey(name);
}
/**
* Try to reserve key word, return the reserved variable if success, otherwise return itself.
*
* @param var
* @return
*/
public static Variable tryReserveKeyword(final Variable var) {
Variable reserve = RESERVED.get(var.getLexeme());
return reserve != null ? reserve : var;
}
/**
* Get variable by name
*
* @param name
* @return
*/
public Variable getVariable(final String name) {
Variable var = RESERVED.get(name);
return var != null ? var : this.table.get(name);
}
public Variable reserve(final String lexeme) {<FILL_FUNCTION_BODY>}
public Token<?> reserve(final Variable variable) {
String lexeme = variable.getLexeme();
if (isReserved(lexeme)) {
Variable v = getVariable(lexeme);
if (v.getStartIndex() < 0) {
return v;
}
variable.setLexeme(v.getLexeme());
return variable;
} else {
final String name = lexeme;
this.table.put(name, variable);
return variable;
}
}
}
|
if (isReserved(lexeme)) {
return getVariable(lexeme);
} else {
final Variable var = new Variable(lexeme, 0, -1);
this.table.put(lexeme, var);
return var;
}
| 841 | 70 | 911 | 27,326 |
openzipkin_brave
|
brave/brave/src/main/java/brave/internal/InternalPropagation.java
|
InternalPropagation
|
sampled
|
class InternalPropagation {
/**
* A flags bitfield is used internally inside {@link TraceContext} as opposed to several booleans.
* This reduces the size of the object and allows us to set or check a couple states at once.
*/
public static final int FLAG_SAMPLED = 1 << 1;
public static final int FLAG_SAMPLED_SET = 1 << 2;
public static final int FLAG_DEBUG = 1 << 3;
public static final int FLAG_SHARED = 1 << 4;
public static final int FLAG_SAMPLED_LOCAL = 1 << 5;
public static final int FLAG_LOCAL_ROOT = 1 << 6;
public static InternalPropagation instance;
public abstract int flags(SamplingFlags flags);
public static int sampled(boolean sampled, int flags) {<FILL_FUNCTION_BODY>}
/**
* @param localRootId must be non-zero prior to instantiating {@link Span} or {@link ScopedSpan}
*/
public abstract TraceContext newTraceContext(
int flags,
long traceIdHigh,
long traceId,
long localRootId,
long parentId,
long spanId,
List<Object> extra
);
/**
* Allows you to decouple from the actual context, for example when it is a weak key. This is less
* allocations vs {@code context.toBuilder().build()}.
*/
public abstract TraceContext shallowCopy(TraceContext context);
/** {@link brave.propagation.TraceContext} is immutable so you need to read the result */
public abstract TraceContext withExtra(TraceContext context, List<Object> immutableExtra);
/** {@link brave.propagation.TraceContext} is immutable so you need to read the result */
public abstract TraceContext withFlags(TraceContext context, int flags);
}
|
if (sampled) {
flags |= FLAG_SAMPLED | FLAG_SAMPLED_SET;
} else {
flags |= FLAG_SAMPLED_SET;
flags &= ~FLAG_SAMPLED;
}
return flags;
| 477 | 72 | 549 | 34,732 |
spring-projects_spring-batch
|
spring-batch/spring-batch-samples/src/main/java/org/springframework/batch/samples/domain/trade/CustomerUpdate.java
|
CustomerUpdate
|
getOperation
|
class CustomerUpdate {
private final CustomerOperation operation;
private final String customerName;
private final BigDecimal credit;
public CustomerUpdate(CustomerOperation operation, String customerName, BigDecimal credit) {
this.operation = operation;
this.customerName = customerName;
this.credit = credit;
}
public CustomerOperation getOperation() {<FILL_FUNCTION_BODY>}
public String getCustomerName() {
return customerName;
}
public BigDecimal getCredit() {
return credit;
}
@Override
public String toString() {
return "Customer Update, name: [" + customerName + "], operation: [" + operation + "], credit: [" + credit
+ "]";
}
}
|
return operation;
| 186 | 8 | 194 | 44,821 |
soot-oss_soot
|
soot/src/main/java/soot/toolkits/graph/HashMutableEdgeLabelledDirectedGraph.java
|
DGEdge
|
equals
|
class DGEdge<N> {
final N from;
final N to;
public DGEdge(N from, N to) {
this.from = from;
this.to = to;
}
public N from() {
return from;
}
public N to() {
return to;
}
@Override
public boolean equals(Object o) {<FILL_FUNCTION_BODY>}
@Override
public int hashCode() {
return Arrays.hashCode(new Object[] { from, to });
}
}
|
if (o instanceof DGEdge) {
DGEdge<?> other = (DGEdge<?>) o;
return this.from.equals(other.from) && this.to.equals(other.to);
}
return false;
| 151 | 66 | 217 | 42,205 |
crate_crate
|
crate/server/src/main/java/org/elasticsearch/index/fielddata/SortableLongBitsToSortedNumericDoubleValues.java
|
SortableLongBitsToSortedNumericDoubleValues
|
docValueCount
|
class SortableLongBitsToSortedNumericDoubleValues extends SortedNumericDoubleValues {
private final SortedNumericDocValues values;
SortableLongBitsToSortedNumericDoubleValues(SortedNumericDocValues values) {
this.values = values;
}
@Override
public boolean advanceExact(int target) throws IOException {
return values.advanceExact(target);
}
@Override
public double nextValue() throws IOException {
return NumericUtils.sortableLongToDouble(values.nextValue());
}
@Override
public int docValueCount() {<FILL_FUNCTION_BODY>}
/** Return the wrapped values. */
public SortedNumericDocValues getLongValues() {
return values;
}
}
|
return values.docValueCount();
| 203 | 12 | 215 | 15,805 |
spring-cloud_spring-cloud-gateway
|
spring-cloud-gateway/spring-cloud-gateway-server/src/main/java/org/springframework/cloud/gateway/config/GatewayRedisAutoConfiguration.java
|
GatewayRedisAutoConfiguration
|
reactiveRedisRouteDefinitionTemplate
|
class GatewayRedisAutoConfiguration {
@Bean
@SuppressWarnings("unchecked")
public RedisScript redisRequestRateLimiterScript() {
DefaultRedisScript redisScript = new DefaultRedisScript<>();
redisScript.setScriptSource(
new ResourceScriptSource(new ClassPathResource("META-INF/scripts/request_rate_limiter.lua")));
redisScript.setResultType(List.class);
return redisScript;
}
@Bean
@ConditionalOnMissingBean
public RedisRateLimiter redisRateLimiter(ReactiveStringRedisTemplate redisTemplate,
@Qualifier(RedisRateLimiter.REDIS_SCRIPT_NAME) RedisScript<List<Long>> redisScript,
ConfigurationService configurationService) {
return new RedisRateLimiter(redisTemplate, redisScript, configurationService);
}
@Bean
@ConditionalOnProperty(value = "spring.cloud.gateway.redis-route-definition-repository.enabled",
havingValue = "true")
@ConditionalOnClass(ReactiveRedisTemplate.class)
public RedisRouteDefinitionRepository redisRouteDefinitionRepository(
ReactiveRedisTemplate<String, RouteDefinition> reactiveRedisTemplate) {
return new RedisRouteDefinitionRepository(reactiveRedisTemplate);
}
@Bean
public ReactiveRedisTemplate<String, RouteDefinition> reactiveRedisRouteDefinitionTemplate(
ReactiveRedisConnectionFactory factory) {<FILL_FUNCTION_BODY>}
}
|
StringRedisSerializer keySerializer = new StringRedisSerializer();
Jackson2JsonRedisSerializer<RouteDefinition> valueSerializer = new Jackson2JsonRedisSerializer<>(
RouteDefinition.class);
RedisSerializationContext.RedisSerializationContextBuilder<String, RouteDefinition> builder = RedisSerializationContext
.newSerializationContext(keySerializer);
RedisSerializationContext<String, RouteDefinition> context = builder.value(valueSerializer).build();
return new ReactiveRedisTemplate<>(factory, context);
| 386 | 132 | 518 | 43,298 |
oshi_oshi
|
oshi/oshi-core/src/main/java/oshi/software/common/AbstractOSProcess.java
|
AbstractOSProcess
|
toString
|
class AbstractOSProcess implements OSProcess {
private final Supplier<Double> cumulativeCpuLoad = memoize(this::queryCumulativeCpuLoad, defaultExpiration());
private int processID;
protected AbstractOSProcess(int pid) {
this.processID = pid;
}
@Override
public int getProcessID() {
return this.processID;
}
@Override
public double getProcessCpuLoadCumulative() {
return cumulativeCpuLoad.get();
}
private double queryCumulativeCpuLoad() {
return getUpTime() > 0d ? (getKernelTime() + getUserTime()) / (double) getUpTime() : 0d;
}
@Override
public double getProcessCpuLoadBetweenTicks(OSProcess priorSnapshot) {
if (priorSnapshot != null && this.processID == priorSnapshot.getProcessID()
&& getUpTime() > priorSnapshot.getUpTime()) {
return (getUserTime() - priorSnapshot.getUserTime() + getKernelTime() - priorSnapshot.getKernelTime())
/ (double) (getUpTime() - priorSnapshot.getUpTime());
}
return getProcessCpuLoadCumulative();
}
@Override
public String toString() {<FILL_FUNCTION_BODY>}
}
|
StringBuilder builder = new StringBuilder("OSProcess@");
builder.append(Integer.toHexString(hashCode()));
builder.append("[processID=").append(this.processID);
builder.append(", name=").append(getName()).append(']');
return builder.toString();
| 340 | 76 | 416 | 36,633 |
AdoptOpenJDK_jitwatch
|
jitwatch/ui/src/main/java/org/adoptopenjdk/jitwatch/ui/main/NothingMountedStage.java
|
NothingMountedStage
|
handle
|
class NothingMountedStage extends Stage
{
public NothingMountedStage(final JITWatchUI parent, final JITWatchConfig config)
{
initStyle(StageStyle.DECORATED);
VBox vbox = new VBox();
vbox.setSpacing(20);
vbox.setPadding(new Insets(10));
Scene scene = UserInterfaceUtil.getScene(vbox, 530, 200);
setTitle("No classes or sources mounted");
Label lblMsg1 = new Label("I see you've not configured any source or class locations?");
Text lblMsg2 = new Text("JITWatch will try and work out the classpath from the JIT log but if I miss\nanything then you might need to configure the paths manually!");
CheckBox cbShowWarning = new CheckBox("Don't show this warning again.");
cbShowWarning.setTooltip(new Tooltip("Don't show warning about no source or class files added."));
cbShowWarning.setSelected(false);
cbShowWarning.selectedProperty().addListener(new ChangeListener<Boolean>()
{
@Override
public void changed(ObservableValue<? extends Boolean> ov, Boolean oldVal, Boolean newVal)
{
config.setShowNothingMounted(!newVal);
config.saveConfig();
}
});
HBox hboxButtons = new HBox();
hboxButtons.setSpacing(20);
hboxButtons.setPadding(new Insets(10));
hboxButtons.setAlignment(Pos.CENTER);
Button btnOpenConfig = new Button("Open Config");
Button btnDismiss = new Button("Dismiss");
btnOpenConfig.setOnAction(new EventHandler<ActionEvent>()
{
@Override
public void handle(ActionEvent e)
{<FILL_FUNCTION_BODY>}
});
btnDismiss.setOnAction(StageManager.getCloseHandler(this));
hboxButtons.getChildren().add(btnDismiss);
hboxButtons.getChildren().add(btnOpenConfig);
vbox.getChildren().add(lblMsg1);
vbox.getChildren().add(lblMsg2);
//vbox.getChildren().add(lblMsg3);
vbox.getChildren().add(cbShowWarning);
vbox.getChildren().add(hboxButtons);
setScene(scene);
}
}
|
close();
parent.openConfigStage();
parent.handleStageClosed(NothingMountedStage.this);
| 650 | 42 | 692 | 49,072 |
AxonFramework_AxonFramework
|
AxonFramework/spring-boot-autoconfigure/src/main/java/org/axonframework/springboot/autoconfig/AxonDbSchedulerAutoConfiguration.java
|
AxonDbSchedulerAutoConfiguration
|
eventScheduler
|
class AxonDbSchedulerAutoConfiguration {
@Bean
@Qualifier("eventDataTask")
@ConditionalOnMissingQualifiedBean(beanClass = Task.class, qualifier = "eventDataTask")
public Task<DbSchedulerBinaryEventData> dbSchedulerEventDataTask(
ApplicationContext context
) {
return DbSchedulerEventScheduler.binaryTask(() -> context.getBean(DbSchedulerEventScheduler.class));
}
@Bean
@Qualifier("deadlineDetailsTask")
@ConditionalOnMissingQualifiedBean(beanClass = Task.class, qualifier = "deadlineDetailsTask")
public Task<DbSchedulerBinaryDeadlineDetails> dbSchedulerDeadlineDetailsTask(
ApplicationContext context
) {
return DbSchedulerDeadlineManager.binaryTask(() -> context.getBean(DbSchedulerDeadlineManager.class));
}
@Bean
@ConditionalOnMissingBean
public EventScheduler eventScheduler(
Scheduler scheduler,
@Qualifier("eventSerializer") Serializer serializer,
TransactionManager transactionManager,
EventBus eventBus) {<FILL_FUNCTION_BODY>}
@Bean
@ConditionalOnMissingBean
public DeadlineManager deadlineManager(
Scheduler scheduler,
Configuration configuration,
@Qualifier("eventSerializer") Serializer serializer,
TransactionManager transactionManager,
DeadlineManagerSpanFactory spanFactory) {
ScopeAwareProvider scopeAwareProvider = new ConfigurationScopeAwareProvider(configuration);
return DbSchedulerDeadlineManager.builder()
.scheduler(scheduler)
.scopeAwareProvider(scopeAwareProvider)
.serializer(serializer)
.transactionManager(transactionManager)
.spanFactory(spanFactory)
//Set to false, as a DbSchedulerStarter is expected to start the scheduler.
.startScheduler(false)
//Set to false as the auto config of DbScheduler manages this.
.stopScheduler(false)
.build();
}
}
|
return DbSchedulerEventScheduler.builder()
.scheduler(scheduler)
.serializer(serializer)
.transactionManager(transactionManager)
.eventBus(eventBus)
//Set to false, as a DbSchedulerStarter is expected to start the scheduler.
.startScheduler(false)
//Set to false, as autoconfiguration from the db scheduler will take care.
.stopScheduler(false)
.build();
| 524 | 120 | 644 | 55,266 |
apache_incubator-seata
|
incubator-seata/console/src/main/java/org/apache/seata/console/Application.java
|
Application
|
main
|
class Application {
/**
* The entry point of application.
*
* @param args the input arguments
*/
public static void main(String[] args) {<FILL_FUNCTION_BODY>}
}
|
SpringApplication.run(Application.class, args);
| 58 | 16 | 74 | 52,209 |
apache_incubator-streampark
|
incubator-streampark/streampark-flink/streampark-flink-sql-gateway/streampark-flink-sql-gateway-base/src/main/java/org/apache/streampark/gateway/ConfigOption.java
|
TypedConfigOptionBuilder
|
noDefaultValue
|
class TypedConfigOptionBuilder<T> {
private final String key;
private final Class<T> clazz;
TypedConfigOptionBuilder(String key, Class<T> clazz) {
this.key = key;
this.clazz = clazz;
}
/**
* Creates a ConfigOption with the given default value.
*
* @param value The default value for the config option
* @return The config option with the default value.
*/
public ConfigOption<T> defaultValue(T value) {
return new ConfigOption<>(key, value, ConfigOption.EMPTY_DESCRIPTION, clazz);
}
/**
* Creates a ConfigOption without a default value.
*
* @return The config option without a default value.
*/
public ConfigOption<T> noDefaultValue() {<FILL_FUNCTION_BODY>}
}
|
return new ConfigOption<>(key, null, ConfigOption.EMPTY_DESCRIPTION, clazz);
| 228 | 29 | 257 | 52,973 |
spring-projects_spring-batch
|
spring-batch/spring-batch-core/src/main/java/org/springframework/batch/core/configuration/support/MapJobRegistry.java
|
MapJobRegistry
|
getJob
|
class MapJobRegistry implements JobRegistry {
/**
* The map holding the registered job factories.
*/
// The "final" ensures that it is visible and initialized when the constructor
// resolves.
private final ConcurrentMap<String, JobFactory> map = new ConcurrentHashMap<>();
@Override
public void register(JobFactory jobFactory) throws DuplicateJobException {
Assert.notNull(jobFactory, "jobFactory is null");
String name = jobFactory.getJobName();
Assert.notNull(name, "Job configuration must have a name.");
JobFactory previousValue = map.putIfAbsent(name, jobFactory);
if (previousValue != null) {
throw new DuplicateJobException("A job configuration with this name [" + name + "] was already registered");
}
}
@Override
public void unregister(String name) {
Assert.notNull(name, "Job configuration must have a name.");
map.remove(name);
}
@Override
public Job getJob(@Nullable String name) throws NoSuchJobException {<FILL_FUNCTION_BODY>}
/**
* Provides an unmodifiable view of the job names.
*/
@Override
public Set<String> getJobNames() {
return Collections.unmodifiableSet(map.keySet());
}
}
|
JobFactory factory = map.get(name);
if (factory == null) {
throw new NoSuchJobException("No job configuration with the name [" + name + "] was registered");
}
else {
return factory.createJob();
}
| 329 | 68 | 397 | 44,344 |
bucket4j_bucket4j
|
bucket4j/bucket4j-ignite/src/main/java/io/github/bucket4j/grid/ignite/thin/compute/Bucket4jComputeTask.java
|
Bucket4jComputeTask
|
map
|
class Bucket4jComputeTask <K> extends ComputeTaskAdapter<Bucket4jComputeTaskParams<K>, byte[]> {
public static final String JOB_NAME = Bucket4jComputeTask.class.getName();
@IgniteInstanceResource
private Ignite ignite;
@Override
public Map<? extends ComputeJob, ClusterNode> map(List<ClusterNode> subgrid, Bucket4jComputeTaskParams<K> params) throws IgniteException {<FILL_FUNCTION_BODY>}
@Override
public byte[] reduce(List<ComputeJobResult> results) throws IgniteException {
return results.get(0).getData();
}
}
|
Bucket4jComputeJob<K> job = new Bucket4jComputeJob<>(params);
ClusterNode primaryNodeForKey = ignite.affinity(params.getCacheName()).mapKeyToNode(params.getKey());
for (ClusterNode clusterNode : subgrid) {
if (clusterNode == primaryNodeForKey) {
return Collections.singletonMap(job, clusterNode);
}
}
// should never come here, but if it happen let's execute Job on random node
int randomNode = ThreadLocalRandom.current().nextInt(subgrid.size());
return Collections.singletonMap(job, subgrid.get(randomNode));
| 178 | 170 | 348 | 13,735 |
lilishop_lilishop
|
lilishop/manager-api/src/main/java/cn/lili/controller/promotion/KanJiaActivityGoodsManagerController.java
|
KanJiaActivityGoodsManagerController
|
updatePointsGoods
|
class KanJiaActivityGoodsManagerController {
@Autowired
private KanjiaActivityGoodsService kanJiaActivityGoodsService;
@PostMapping
@ApiOperation(value = "添加砍价活动")
public ResultMessage<Object> add(@RequestBody KanjiaActivityGoodsOperationDTO kanJiaActivityGoodsOperationDTO) {
kanJiaActivityGoodsService.add(kanJiaActivityGoodsOperationDTO);
return ResultUtil.success();
}
@ApiOperation(value = "获取砍价活动分页")
@GetMapping
public ResultMessage<IPage<KanjiaActivityGoods>> getKanJiaActivityPage(KanjiaActivityGoodsParams kanJiaParams, PageVO page) {
return ResultUtil.data(kanJiaActivityGoodsService.pageFindAll(kanJiaParams, page));
}
@GetMapping("/{id}")
@ApiOperation(value = "获取积分商品详情")
public ResultMessage<Object> getPointsGoodsDetail(@PathVariable("id") String goodsId) {
KanjiaActivityGoodsDTO kanJiaActivityGoodsDTO = kanJiaActivityGoodsService.getKanjiaGoodsDetail(goodsId);
return ResultUtil.data(kanJiaActivityGoodsDTO);
}
@PutMapping
@ApiOperation(value = "修改砍价商品")
public ResultMessage<Object> updatePointsGoods(@RequestBody KanjiaActivityGoodsDTO kanJiaActivityGoodsDTO) {<FILL_FUNCTION_BODY>}
@DeleteMapping("/{ids}")
@ApiOperation(value = "删除砍价商品")
public ResultMessage<Object> delete(@PathVariable String ids) {
if (kanJiaActivityGoodsService.removePromotions(Arrays.asList(ids.split(",")))) {
return ResultUtil.success();
}
throw new ServiceException(ResultCode.KANJIA_GOODS_DELETE_ERROR);
}
}
|
if (!kanJiaActivityGoodsService.updateKanjiaActivityGoods(kanJiaActivityGoodsDTO)) {
return ResultUtil.error(ResultCode.KANJIA_GOODS_UPDATE_ERROR);
}
return ResultUtil.success();
| 529 | 69 | 598 | 29,968 |
hs-web_hsweb-framework
|
hsweb-framework/hsweb-authorization/hsweb-authorization-basic/src/main/java/org/hswebframework/web/authorization/basic/define/DefaultBasicAuthorizeDefinition.java
|
DefaultBasicAuthorizeDefinition
|
putAnnotation
|
class DefaultBasicAuthorizeDefinition implements AopAuthorizeDefinition {
@JsonIgnore
private Class<?> targetClass;
@JsonIgnore
private Method targetMethod;
private ResourcesDefinition resources = new ResourcesDefinition();
private DimensionsDefinition dimensions = new DimensionsDefinition();
private String message = "error.access_denied";
private Phased phased = Phased.before;
@Override
public boolean isEmpty() {
return false;
}
private static final Set<Class<? extends Annotation>> types = new HashSet<>(Arrays.asList(
Authorize.class,
DataAccess.class,
Dimension.class,
Resource.class,
ResourceAction.class,
DataAccessType.class
));
public static AopAuthorizeDefinition from(Class<?> targetClass, Method method) {
AopAuthorizeDefinitionParser parser = new AopAuthorizeDefinitionParser(targetClass, method);
return parser.parse();
}
public void putAnnotation(Authorize ann) {
if (!ann.merge()) {
getResources().getResources().clear();
getDimensions().getDimensions().clear();
}
setPhased(ann.phased());
getResources().setPhased(ann.phased());
for (Resource resource : ann.resources()) {
putAnnotation(resource);
}
for (Dimension dimension : ann.dimension()) {
putAnnotation(dimension);
}
}
public void putAnnotation(Dimension ann) {
if (ann.ignore()) {
getDimensions().getDimensions().clear();
return;
}
DimensionDefinition definition = new DimensionDefinition();
definition.setTypeId(ann.type());
definition.setDimensionId(new HashSet<>(Arrays.asList(ann.id())));
definition.setLogical(ann.logical());
getDimensions().addDimension(definition);
}
public void putAnnotation(Resource ann) {
ResourceDefinition resource = new ResourceDefinition();
resource.setId(ann.id());
resource.setName(ann.name());
resource.setLogical(ann.logical());
resource.setPhased(ann.phased());
resource.setDescription(String.join("\n", ann.description()));
for (ResourceAction action : ann.actions()) {
putAnnotation(resource, action);
}
resource.setGroup(new ArrayList<>(Arrays.asList(ann.group())));
setPhased(ann.phased());
getResources().setPhased(ann.phased());
resources.addResource(resource, ann.merge());
}
public ResourceActionDefinition putAnnotation(ResourceDefinition definition, ResourceAction ann) {<FILL_FUNCTION_BODY>}
public void putAnnotation(ResourceActionDefinition definition, DataAccess ann) {
if (ann.ignore()) {
return;
}
DataAccessTypeDefinition typeDefinition = new DataAccessTypeDefinition();
for (DataAccessType dataAccessType : ann.type()) {
if (dataAccessType.ignore()) {
continue;
}
typeDefinition.setId(dataAccessType.id());
typeDefinition.setName(dataAccessType.name());
typeDefinition.setController(dataAccessType.controller());
typeDefinition.setConfiguration(dataAccessType.configuration());
typeDefinition.setDescription(String.join("\n", dataAccessType.description()));
}
if (StringUtils.isEmpty(typeDefinition.getId())) {
return;
}
definition.getDataAccess()
.getDataAccessTypes()
.add(typeDefinition);
}
public void putAnnotation(ResourceActionDefinition definition, DataAccessType dataAccessType) {
if (dataAccessType.ignore()) {
return;
}
DataAccessTypeDefinition typeDefinition = new DataAccessTypeDefinition();
typeDefinition.setId(dataAccessType.id());
typeDefinition.setName(dataAccessType.name());
typeDefinition.setController(dataAccessType.controller());
typeDefinition.setConfiguration(dataAccessType.configuration());
typeDefinition.setDescription(String.join("\n", dataAccessType.description()));
definition.getDataAccess()
.getDataAccessTypes()
.add(typeDefinition);
}
}
|
ResourceActionDefinition actionDefinition = new ResourceActionDefinition();
actionDefinition.setId(ann.id());
actionDefinition.setName(ann.name());
actionDefinition.setDescription(String.join("\n", ann.description()));
for (DataAccess dataAccess : ann.dataAccess()) {
putAnnotation(actionDefinition, dataAccess);
}
definition.addAction(actionDefinition);
return actionDefinition;
| 1,066 | 103 | 1,169 | 22,719 |
PlexPt_chatgpt-java
|
chatgpt-java/src/main/java/com/plexpt/chatgpt/ChatGPTStream.java
|
ChatGPTStream
|
streamChatCompletion
|
class ChatGPTStream {
private String apiKey;
private List<String> apiKeyList;
private OkHttpClient okHttpClient;
/**
* 连接超时
*/
@Builder.Default
private long timeout = 90;
/**
* 网络代理
*/
@Builder.Default
private Proxy proxy = Proxy.NO_PROXY;
/**
* 反向代理
*/
@Builder.Default
private String apiHost = Api.DEFAULT_API_HOST;
/**
* 初始化
*/
public ChatGPTStream init() {
OkHttpClient.Builder client = new OkHttpClient.Builder();
client.connectTimeout(timeout, TimeUnit.SECONDS);
client.writeTimeout(timeout, TimeUnit.SECONDS);
client.readTimeout(timeout, TimeUnit.SECONDS);
if (Objects.nonNull(proxy)) {
client.proxy(proxy);
}
okHttpClient = client.build();
return this;
}
/**
* 流式输出
*/
public void streamChatCompletion(ChatCompletion chatCompletion,
EventSourceListener eventSourceListener) {<FILL_FUNCTION_BODY>}
/**
* 流式输出
*/
public void streamChatCompletion(List<Message> messages,
EventSourceListener eventSourceListener) {
ChatCompletion chatCompletion = ChatCompletion.builder()
.messages(messages)
.stream(true)
.build();
streamChatCompletion(chatCompletion, eventSourceListener);
}
}
|
chatCompletion.setStream(true);
try {
EventSource.Factory factory = EventSources.createFactory(okHttpClient);
ObjectMapper mapper = new ObjectMapper();
String requestBody = mapper.writeValueAsString(chatCompletion);
String key = apiKey;
if (apiKeyList != null && !apiKeyList.isEmpty()) {
key = RandomUtil.randomEle(apiKeyList);
}
Request request = new Request.Builder()
.url(apiHost + "v1/chat/completions")
.post(RequestBody.create(MediaType.parse(ContentType.JSON.getValue()),
requestBody))
.header("Authorization", "Bearer " + key)
.build();
factory.newEventSource(request, eventSourceListener);
} catch (Exception e) {
log.error("请求出错:{}", e);
}
| 414 | 232 | 646 | 37,626 |
alibaba_fastjson2
|
fastjson2/fastjson1-compatible/src/main/java/com/alibaba/fastjson/support/jaxrs/FastJsonFeature.java
|
FastJsonFeature
|
configure
|
class FastJsonFeature
implements Feature {
private static final String JSON_FEATURE = FastJsonFeature.class.getSimpleName();
@Override
public boolean configure(final FeatureContext context) {<FILL_FUNCTION_BODY>}
}
|
try {
final Configuration config = context.getConfiguration();
final String jsonFeature = CommonProperties.getValue(
config.getProperties(),
config.getRuntimeType(),
InternalProperties.JSON_FEATURE,
JSON_FEATURE,
String.class
);
// Other JSON providers registered.
if (!JSON_FEATURE.equalsIgnoreCase(jsonFeature)) {
return false;
}
// Disable other JSON providers.
context.property(
PropertiesHelper.getPropertyNameForRuntime(
InternalProperties.JSON_FEATURE,
config.getRuntimeType()
),
JSON_FEATURE
);
// Register FastJson.
if (!config.isRegistered(FastJsonProvider.class)) {
context.register(FastJsonProvider.class, MessageBodyReader.class, MessageBodyWriter.class);
}
} catch (NoSuchMethodError e) {
// skip
}
return true;
| 62 | 239 | 301 | 6,381 |
alibaba_fastjson2
|
fastjson2/core/src/main/java/com/alibaba/fastjson2/reader/ObjectReaderImplMapEntry.java
|
ObjectReaderImplMapEntry
|
readJSONBObject
|
class ObjectReaderImplMapEntry
extends ObjectReaderPrimitive {
final Type keyType;
final Type valueType;
volatile ObjectReader keyReader;
volatile ObjectReader valueReader;
public ObjectReaderImplMapEntry(Type keyType, Type valueType) {
super(Map.Entry.class);
this.keyType = keyType;
this.valueType = valueType;
}
@Override
public Object readJSONBObject(JSONReader jsonReader, Type fieldType, Object fieldName, long features) {<FILL_FUNCTION_BODY>}
@Override
public Object readObject(JSONReader jsonReader, Type fieldType, Object fieldName, long features) {
jsonReader.nextIfObjectStart();
Object key = jsonReader.readAny();
jsonReader.nextIfMatch(':');
Object value;
if (valueType == null) {
value = jsonReader.readAny();
} else {
if (valueReader == null) {
valueReader = jsonReader.getObjectReader(valueType);
}
value = valueReader.readObject(jsonReader, fieldType, fieldName, features);
}
jsonReader.nextIfObjectEnd();
jsonReader.nextIfComma();
return new AbstractMap.SimpleEntry(key, value);
}
}
|
int entryCnt = jsonReader.startArray();
if (entryCnt != 2) {
throw new JSONException(jsonReader.info("entryCnt must be 2, but " + entryCnt));
}
Object key;
if (keyType == null) {
key = jsonReader.readAny();
} else {
if (keyReader == null) {
keyReader = jsonReader.getObjectReader(keyType);
}
key = keyReader.readObject(jsonReader, fieldType, fieldName, features);
}
Object value;
if (valueType == null) {
value = jsonReader.readAny();
} else {
if (valueReader == null) {
valueReader = jsonReader.getObjectReader(valueType);
}
value = valueReader.readObject(jsonReader, fieldType, fieldName, features);
}
return new AbstractMap.SimpleEntry(key, value);
| 325 | 238 | 563 | 6,040 |
hs-web_hsweb-framework
|
hsweb-framework/hsweb-authorization/hsweb-authorization-api/src/main/java/org/hswebframework/web/authorization/simple/SimplePermission.java
|
SimplePermission
|
copy
|
class SimplePermission implements Permission {
private static final long serialVersionUID = 7587266693680162184L;
private String id;
private String name;
private Set<String> actions;
private Set<DataAccessConfig> dataAccesses;
private Map<String, Object> options;
public Set<String> getActions() {
if (actions == null) {
actions = new java.util.HashSet<>();
}
return actions;
}
public Set<DataAccessConfig> getDataAccesses() {
if (dataAccesses == null) {
dataAccesses = new java.util.HashSet<>();
}
return dataAccesses;
}
@Override
public Permission copy(Predicate<String> actionFilter,
Predicate<DataAccessConfig> dataAccessFilter) {<FILL_FUNCTION_BODY>}
public Permission copy() {
return copy(action -> true, conf -> true);
}
@Override
public String toString() {
return id + (CollectionUtils.isNotEmpty(actions) ? ":" + String.join(",", actions) : "");
}
}
|
SimplePermission permission = new SimplePermission();
permission.setId(id);
permission.setName(name);
permission.setActions(getActions().stream().filter(actionFilter).collect(Collectors.toSet()));
permission.setDataAccesses(getDataAccesses().stream().filter(dataAccessFilter).collect(Collectors.toSet()));
if (options != null) {
permission.setOptions(new HashMap<>(options));
}
return permission;
| 311 | 119 | 430 | 22,686 |
docker-java_docker-java
|
docker-java/docker-java-core/src/main/java/com/github/dockerjava/core/command/KillContainerCmdImpl.java
|
KillContainerCmdImpl
|
withSignal
|
class KillContainerCmdImpl extends AbstrDockerCmd<KillContainerCmd, Void> implements KillContainerCmd {
private String containerId, signal;
public KillContainerCmdImpl(KillContainerCmd.Exec exec, String containerId) {
super(exec);
withContainerId(containerId);
}
@Override
public String getContainerId() {
return containerId;
}
@Override
public String getSignal() {
return signal;
}
@Override
public KillContainerCmd withContainerId(String containerId) {
this.containerId = Objects.requireNonNull(containerId, "containerId was not specified");
return this;
}
@Override
public KillContainerCmd withSignal(String signal) {<FILL_FUNCTION_BODY>}
/**
* @throws NotFoundException
* No such container
*/
@Override
public Void exec() throws NotFoundException {
return super.exec();
}
}
|
this.signal = Objects.requireNonNull(signal, "signal was not specified");
return this;
| 259 | 29 | 288 | 17,298 |
crate_crate
|
crate/server/src/main/java/org/elasticsearch/monitor/fs/FsHealthService.java
|
FsHealthMonitor
|
run
|
class FsHealthMonitor implements Runnable {
static final String TEMP_FILE_NAME = ".es_temp_file";
private byte[] byteToWrite;
FsHealthMonitor() {
this.byteToWrite = UUIDs.randomBase64UUID().getBytes(StandardCharsets.UTF_8);
}
@Override
public void run() {<FILL_FUNCTION_BODY>}
private void monitorFSHealth() {
Set<Path> currentUnhealthyPaths = null;
for (Path path : nodeEnv.nodeDataPaths()) {
long executionStartTime = currentTimeMillisSupplier.getAsLong();
try {
if (Files.exists(path)) {
Path tempDataPath = path.resolve(TEMP_FILE_NAME);
Files.deleteIfExists(tempDataPath);
try (OutputStream os = Files.newOutputStream(tempDataPath, StandardOpenOption.CREATE_NEW)) {
os.write(byteToWrite);
IOUtils.fsync(tempDataPath, false);
}
Files.delete(tempDataPath);
final long elapsedTime = currentTimeMillisSupplier.getAsLong() - executionStartTime;
if (elapsedTime > slowPathLoggingThreshold.millis()) {
LOGGER.warn("health check of [{}] took [{}ms] which is above the warn threshold of [{}]",
path, elapsedTime, slowPathLoggingThreshold);
}
}
} catch (Exception ex) {
LOGGER.error(new ParameterizedMessage("health check of [{}] failed", path), ex);
if (currentUnhealthyPaths == null) {
currentUnhealthyPaths = new HashSet<>(1);
}
currentUnhealthyPaths.add(path);
}
}
unhealthyPaths = currentUnhealthyPaths;
}
}
|
try {
if (enabled) {
monitorFSHealth();
LOGGER.debug("health check succeeded");
}
} catch (Exception e) {
LOGGER.error("health check failed", e);
}
| 470 | 59 | 529 | 16,520 |
knowm_XChange
|
XChange/xchange-kraken/src/main/java/org/knowm/xchange/kraken/dto/account/WithdrawInfo.java
|
WithdrawInfo
|
getMethod
|
class WithdrawInfo {
/*
* method = name of the withdrawal method that will be used limit = maximum net amount that can be withdrawn right now fee = amount of fees that
* will be paid
*/
private final String method;
private final BigDecimal limit;
private final String fee;
public WithdrawInfo(
@JsonProperty("method") String method,
@JsonProperty("limit") BigDecimal limit,
@JsonProperty("fee") String fee) {
super();
this.method = method;
this.limit = limit;
this.fee = fee;
}
public String getMethod() {<FILL_FUNCTION_BODY>}
public BigDecimal getLimit() {
return limit;
}
public String getFee() {
return fee;
}
@Override
public String toString() {
return "WithdrawInfo [method=" + method + ", limit=" + limit + ", fee=" + fee + "]";
}
}
|
return method;
| 259 | 8 | 267 | 28,242 |
alibaba_Sentinel
|
Sentinel/sentinel-demo/sentinel-demo-apache-dubbo/src/main/java/com/alibaba/csp/sentinel/demo/apache/dubbo/FooProviderBootstrap.java
|
FooProviderBootstrap
|
main
|
class FooProviderBootstrap {
public static void main(String[] args) {<FILL_FUNCTION_BODY>}
}
|
// Users don't need to manually call this method.
// Only for eager initialization.
InitExecutor.doInit();
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();
context.register(ProviderConfiguration.class);
context.refresh();
System.out.println("Service provider is ready");
| 36 | 83 | 119 | 65,450 |
gephi_gephi
|
gephi/modules/PreviewExport/src/main/java/org/gephi/io/exporter/preview/PDFExporter.java
|
PDFExporter
|
setWorkspace
|
class PDFExporter implements ByteExporter, VectorExporter, LongTask {
private ProgressTicket progress;
private Workspace workspace;
private OutputStream stream;
private boolean cancel = false;
private PDFTarget target;
//Parameters
private float marginTop = 18f;
private float marginBottom = 18f;
private float marginLeft = 18f;
private float marginRight = 18f;
private boolean landscape = false;
private PDRectangle pageSize = PDRectangle.A4;
private boolean transparentBackground = false;
@Override
public boolean execute() {
Progress.start(progress);
PreviewController controller = Lookup.getDefault().lookup(PreviewController.class);
controller.getModel(workspace).getProperties().putValue(PreviewProperty.VISIBILITY_RATIO, 1.0);
controller.refreshPreview(workspace);
PreviewProperties props = controller.getModel(workspace).getProperties();
try (PDDocument doc = new PDDocument()) {
doc.setVersion(1.5f);
PDRectangle size = landscape ? new PDRectangle(pageSize.getHeight(), pageSize.getWidth()) : pageSize;
PDPage page = new PDPage(size);
doc.addPage(page);
try (PDPageContentStream contentStream = new PDPageContentStream(doc, page)) {
props.putValue(PDFTarget.LANDSCAPE, landscape);
props.putValue(PDFTarget.PAGESIZE, size);
props.putValue(PDFTarget.MARGIN_TOP, marginTop);
props.putValue(PDFTarget.MARGIN_LEFT, marginLeft);
props.putValue(PDFTarget.MARGIN_BOTTOM, marginBottom);
props.putValue(PDFTarget.MARGIN_RIGHT, marginRight);
props.putValue(PDFTarget.PDF_CONTENT_BYTE, contentStream);
props.putValue(PDFTarget.PDF_DOCUMENT, doc);
props.putValue(PDFTarget.TRANSPARENT_BACKGROUND, transparentBackground);
target = (PDFTarget) controller.getRenderTarget(RenderTarget.PDF_TARGET, workspace);
if (target instanceof LongTask) {
((LongTask) target).setProgressTicket(progress);
}
controller.render(target, workspace);
}
doc.save(stream);
} catch (Exception ex) {
Exceptions.printStackTrace(ex);
} finally {
Progress.finish(progress);
props.putValue(PDFTarget.PDF_CONTENT_BYTE, null);
props.putValue(PDFTarget.PAGESIZE, null);
props.putValue(PDFTarget.PDF_DOCUMENT, null);
}
return !cancel;
}
public boolean isLandscape() {
return landscape;
}
public void setLandscape(boolean landscape) {
this.landscape = landscape;
}
public float getMarginBottom() {
return marginBottom;
}
public void setMarginBottom(float marginBottom) {
this.marginBottom = marginBottom;
}
public float getMarginLeft() {
return marginLeft;
}
public void setMarginLeft(float marginLeft) {
this.marginLeft = marginLeft;
}
public float getMarginRight() {
return marginRight;
}
public void setMarginRight(float marginRight) {
this.marginRight = marginRight;
}
public float getMarginTop() {
return marginTop;
}
public void setMarginTop(float marginTop) {
this.marginTop = marginTop;
}
public PDRectangle getPageSize() {
return pageSize;
}
public void setPageSize(PDRectangle pageSize) {
this.pageSize = pageSize;
}
public boolean isTransparentBackground() {
return transparentBackground;
}
public void setTransparentBackground(boolean transparentBackground) {
this.transparentBackground = transparentBackground;
}
@Override
public void setOutputStream(OutputStream stream) {
this.stream = stream;
}
@Override
public Workspace getWorkspace() {
return workspace;
}
@Override
public void setWorkspace(Workspace workspace) {<FILL_FUNCTION_BODY>}
@Override
public boolean cancel() {
this.cancel = true;
if (target instanceof LongTask) {
((LongTask) target).cancel();
}
return true;
}
@Override
public void setProgressTicket(ProgressTicket progressTicket) {
this.progress = progressTicket;
}
}
|
this.workspace = workspace;
| 1,218 | 13 | 1,231 | 20,390 |
apache_shardingsphere-elasticjob
|
shardingsphere-elasticjob/restful/src/main/java/org/apache/shardingsphere/elasticjob/restful/pipeline/ContextInitializationInboundHandler.java
|
ContextInitializationInboundHandler
|
channelRead
|
class ContextInitializationInboundHandler extends ChannelInboundHandlerAdapter {
@Override
public void channelRead(final ChannelHandlerContext ctx, final Object msg) {<FILL_FUNCTION_BODY>}
}
|
log.debug("{}", msg);
FullHttpRequest httpRequest = (FullHttpRequest) msg;
FullHttpResponse httpResponse = new DefaultFullHttpResponse(httpRequest.protocolVersion(), HttpResponseStatus.NOT_FOUND, ctx.alloc().buffer());
HttpUtil.setContentLength(httpResponse, httpResponse.content().readableBytes());
ctx.fireChannelRead(new HandleContext<Handler>(httpRequest, httpResponse));
| 53 | 105 | 158 | 67,791 |
karatelabs_karate
|
karate/karate-demo/src/main/java/com/intuit/karate/demo/domain/FileInfo.java
|
FileInfo
|
getContentType
|
class FileInfo {
private String id;
private String filename;
private String message;
private String contentType;
public FileInfo() {
// zero arg constructor
}
public FileInfo(String id, String filename, String message, String contentType) {
this.id = id;
this.filename = filename;
this.message = message;
this.contentType = contentType;
}
public String getId() {
return id;
}
public String getFilename() {
return filename;
}
public String getMessage() {
return message;
}
public String getContentType() {<FILL_FUNCTION_BODY>}
}
|
return contentType;
| 190 | 9 | 199 | 59,684 |
Red5_red5-server
|
red5-server/io/src/main/java/org/red5/io/utils/HexCharset.java
|
Encoder
|
encodeLoop
|
class Encoder extends CharsetEncoder {
private boolean unpaired;
private int nyble;
private Encoder() {
super(HexCharset.this, 0.49f, 1f);
}
/**
* Flushes this encoder.
*
* <p>
* The default implementation of this method does nothing, and always returns {@link CoderResult#UNDERFLOW}. This method should be overridden by encoders that may need to write final bytes to the output buffer once the entire input sequence has been read.
* </p>
*
* @param out
* The output byte buffer
*
* @return A coder-result object, either {@link CoderResult#UNDERFLOW} or {@link CoderResult#OVERFLOW}
*/
@Override
protected java.nio.charset.CoderResult implFlush(java.nio.ByteBuffer out) {
if (!unpaired) {
implReset();
return CoderResult.UNDERFLOW;
} else
throw new IllegalArgumentException("Hex string must be an even number of digits");
}
/**
* Encodes one or more characters into one or more bytes.
*
* <p>
* This method encapsulates the basic encoding loop, encoding as many characters as possible until it either runs out of input, runs out of room in the output buffer, or encounters an encoding error. This method is invoked by the {@link #encode encode} method, which handles result interpretation and error recovery.
*
* <p>
* The buffers are read from, and written to, starting at their current positions. At most {@link Buffer#remaining in.remaining()} characters will be read, and at most {@link Buffer#remaining out.remaining()} bytes will be written. The buffers' positions will be advanced to reflect the characters read and the bytes written, but their marks and limits will not be modified.
*
* <p>
* This method returns a {@link CoderResult} object to describe its reason for termination, in the same manner as the {@link #encode encode} method. Most implementations of this method will handle encoding errors by returning an appropriate result object for interpretation by the {@link #encode encode} method. An optimized implementation may instead examine the relevant error action and implement that action
* itself.
*
* <p>
* An implementation of this method may perform arbitrary lookahead by returning {@link CoderResult#UNDERFLOW} until it receives sufficient input.
* </p>
*
* @param in
* The input character buffer
*
* @param out
* The output byte buffer
*
* @return A coder-result object describing the reason for termination
*/
@Override
public java.nio.charset.CoderResult encodeLoop(java.nio.CharBuffer in, java.nio.ByteBuffer out) {<FILL_FUNCTION_BODY>}
/**
* Clear state
*/
@Override
protected void implReset() {
unpaired = false;
nyble = 0;
}
}
|
while (in.remaining() > 0) {
if (out.remaining() <= 0)
return CoderResult.OVERFLOW;
char inch = in.get();
if (!Character.isWhitespace(inch)) {
int d = Character.digit(inch, 16);
if (d < 0)
throw new IllegalArgumentException("Bad hex character " + inch);
if (unpaired)
out.put((byte) (nyble | d));
else
nyble = d << 4;
unpaired = !unpaired;
}
}
return CoderResult.UNDERFLOW;
| 776 | 165 | 941 | 62,260 |
lukas-krecan_ShedLock
|
ShedLock/providers/jdbc/shedlock-provider-jdbc-template/src/main/java/net/javacrumbs/shedlock/provider/jdbctemplate/MySqlServerTimeStatementsSource.java
|
MySqlServerTimeStatementsSource
|
getUpdateStatement
|
class MySqlServerTimeStatementsSource extends SqlStatementsSource {
private static final String now = "UTC_TIMESTAMP(3)";
private static final String lockAtMostFor = "TIMESTAMPADD(MICROSECOND, :lockAtMostForMicros, " + now + ")";
MySqlServerTimeStatementsSource(JdbcTemplateLockProvider.Configuration configuration) {
super(configuration);
}
@Override
String getInsertStatement() {
return "INSERT IGNORE INTO " + tableName() + "(" + name() + ", " + lockUntil() + ", " + lockedAt() + ", "
+ lockedBy() + ") VALUES(:name, " + lockAtMostFor + ", " + now + ", :lockedBy)";
}
@Override
public String getUpdateStatement() {<FILL_FUNCTION_BODY>}
@Override
public String getUnlockStatement() {
String lockAtLeastFor = "TIMESTAMPADD(MICROSECOND, :lockAtLeastForMicros, " + lockedAt() + ")";
return "UPDATE " + tableName() + " SET " + lockUntil() + " = IF (" + lockAtLeastFor + " > " + now + " , "
+ lockAtLeastFor + ", " + now + ") WHERE " + name() + " = :name AND " + lockedBy() + " = :lockedBy";
}
@Override
public String getExtendStatement() {
return "UPDATE " + tableName() + " SET " + lockUntil() + " = " + lockAtMostFor + " WHERE " + name()
+ " = :name AND " + lockedBy() + " = :lockedBy AND " + lockUntil() + " > " + now;
}
@Override
@NonNull
Map<String, Object> params(@NonNull LockConfiguration lockConfiguration) {
return Map.of(
"name",
lockConfiguration.getName(),
"lockedBy",
configuration.getLockedByValue(),
"lockAtMostForMicros",
lockConfiguration.getLockAtMostFor().toNanos() / 1_000,
"lockAtLeastForMicros",
lockConfiguration.getLockAtLeastFor().toNanos() / 1_000);
}
}
|
return "UPDATE " + tableName() + " SET " + lockUntil() + " = " + lockAtMostFor + ", " + lockedAt() + " = " + now
+ ", " + lockedBy() + " = :lockedBy WHERE " + name() + " = :name AND " + lockUntil() + " <= " + now;
| 576 | 82 | 658 | 31,629 |
joelittlejohn_jsonschema2pojo
|
jsonschema2pojo/jsonschema2pojo-core/src/main/java/org/jsonschema2pojo/model/EnumDefinition.java
|
EnumDefinition
|
size
|
class EnumDefinition {
private final JType backingType;
private final ArrayList<EnumValueDefinition> enumValues;
private final String nodeName;
private final JsonNode enumNode;
private final EnumDefinitionExtensionType type;
public EnumDefinition(String nodeName,
JsonNode enumNode,
JType backingType,
ArrayList<EnumValueDefinition> enumValues,
EnumDefinitionExtensionType type) {
this.nodeName = nodeName;
this.enumNode = enumNode;
this.backingType = backingType;
this.enumValues = enumValues;
this.type = type;
}
public EnumDefinition(EnumDefinition enumDefinition) {
this(enumDefinition, enumDefinition.enumValues);
}
public EnumDefinition(EnumDefinition enumDefinition, ArrayList<EnumValueDefinition> enumValueDefinitions) {
this(enumDefinition.nodeName,
enumDefinition.enumNode,
enumDefinition.backingType,
enumValueDefinitions,
enumDefinition.type);
}
public JType getBackingType() {
return backingType;
}
public JsonNode getEnumNode() {
return enumNode;
}
public String getNodeName() {
return nodeName;
}
public EnumDefinitionExtensionType getType() {
return type;
}
public int size() {<FILL_FUNCTION_BODY>}
public Collection<EnumValueDefinition> values() {
if (enumValues != null) {
return Collections.unmodifiableCollection(enumValues);
} else {
return Collections.emptyList();
}
}
}
|
if (enumValues != null) {
return enumValues.size();
} else {
return 0;
}
| 417 | 36 | 453 | 26,901 |
crate_crate
|
crate/server/src/main/java/io/crate/types/StorageSupport.java
|
StorageSupport
|
supportsDocValuesOff
|
class StorageSupport<T> {
private final boolean docValuesDefault;
private final boolean supportsDocValuesOff;
@Nullable
private final EqQuery<T> eqQuery;
StorageSupport(boolean docValuesDefault,
boolean supportsDocValuesOff,
@Nullable EqQuery<T> eqQuery) {
this.docValuesDefault = docValuesDefault;
this.supportsDocValuesOff = supportsDocValuesOff;
this.eqQuery = eqQuery;
}
public boolean getComputedDocValuesDefault(@Nullable IndexType indexType) {
return docValuesDefault && indexType != IndexType.FULLTEXT;
}
/**
* @param getFieldType returns a {@link FieldType} for the column or null in
* case the column gets dynamically created.
*/
public abstract ValueIndexer<? super T> valueIndexer(
RelationName table,
Reference ref,
Function<String, FieldType> getFieldType,
Function<ColumnIdent, Reference> getRef);
public boolean docValuesDefault() {
return docValuesDefault;
}
public boolean supportsDocValuesOff() {<FILL_FUNCTION_BODY>}
@Nullable
public EqQuery<T> eqQuery() {
return eqQuery;
}
}
|
return supportsDocValuesOff;
| 323 | 11 | 334 | 16,142 |
alibaba_fastjson2
|
fastjson2/core/src/main/java/com/alibaba/fastjson2/writer/FieldWriterInt8ValField.java
|
FieldWriterInt8ValField
|
writeValue
|
class FieldWriterInt8ValField<T>
extends FieldWriterInt8<T> {
FieldWriterInt8ValField(
String name,
int ordinal,
long features,
String format,
String label,
Field field
) {
super(name, ordinal, features, format, label, byte.class, field, null);
}
@Override
public Object getFieldValue(T object) {
return getFieldValueByte(object);
}
public byte getFieldValueByte(T object) {
if (object == null) {
throw new JSONException("field.get error, " + fieldName);
}
try {
byte value;
if (fieldOffset != -1) {
value = UNSAFE.getByte(object, fieldOffset);
} else {
value = field.getByte(object);
}
return value;
} catch (IllegalArgumentException | IllegalAccessException e) {
throw new JSONException("field.get error, " + fieldName, e);
}
}
@Override
public boolean write(JSONWriter jsonWriter, T object) {
byte value = getFieldValueByte(object);
writeInt8(jsonWriter, value);
return true;
}
@Override
public void writeValue(JSONWriter jsonWriter, T object) {<FILL_FUNCTION_BODY>}
}
|
byte value = getFieldValueByte(object);
jsonWriter.writeInt32(value);
| 353 | 27 | 380 | 6,167 |
zendesk_maxwell
|
maxwell/src/main/java/com/zendesk/maxwell/row/HeartbeatRowMap.java
|
HeartbeatRowMap
|
toJSON
|
class HeartbeatRowMap extends RowMap {
public HeartbeatRowMap(String database, Position position, Position nextPosition) {
super("heartbeat", database, "heartbeats", position.getLastHeartbeatRead(), new ArrayList<String>(), position, nextPosition, null);
}
public static HeartbeatRowMap valueOf(String database, Position position, Position nextPosition) {
return new HeartbeatRowMap(database, position, nextPosition);
}
@Override
public String toJSON(MaxwellOutputConfig outputConfig) throws IOException {<FILL_FUNCTION_BODY>}
@Override
public String toJSON() throws IOException {
return null;
}
@Override
public boolean isTXCommit() {
return true;
}
@Override
public boolean shouldOutput(MaxwellOutputConfig outputConfig) {
return false;
}
}
|
return null;
| 206 | 8 | 214 | 64,819 |
lilishop_lilishop
|
lilishop/framework/src/main/java/cn/lili/modules/im/serviceimpl/QAServiceImpl.java
|
QAServiceImpl
|
getStoreQA
|
class QAServiceImpl extends ServiceImpl<QAMapper, QA> implements QAService {
@Override
public IPage<QA> getStoreQA(String word, PageVO pageVo) {<FILL_FUNCTION_BODY>}
}
|
LambdaQueryWrapper<QA> qaLambdaQueryWrapper = new LambdaQueryWrapper<>();
qaLambdaQueryWrapper.eq(QA::getTenantId, UserContext.getCurrentUser().getTenantId());
qaLambdaQueryWrapper.like(QA::getQuestion, word);
return this.page(PageUtil.initPage(pageVo), qaLambdaQueryWrapper);
| 66 | 97 | 163 | 30,340 |
modelmapper_modelmapper
|
modelmapper/core/src/main/java/org/modelmapper/internal/PropertyInfoRegistry.java
|
PropertyInfoKey
|
mutatorFor
|
class PropertyInfoKey {
private final Class<?> initialType;
private final String propertyName;
private final Configuration configuration;
PropertyInfoKey(Class<?> initialType, String propertyName, Configuration configuration) {
this.initialType = initialType;
this.propertyName = propertyName;
this.configuration = configuration;
}
@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (!(o instanceof PropertyInfoKey))
return false;
PropertyInfoKey other = (PropertyInfoKey) o;
return initialType.equals(other.initialType) && propertyName.equals(other.propertyName)
&& configuration.equals(other.configuration);
}
@Override
public int hashCode() {
int result = 31 + initialType.hashCode();
result = 31 * result + propertyName.hashCode();
result = 31 * result + configuration.hashCode();
return result;
}
}
/**
* Returns an accessor for the {@code accessorName}, else {@code null} if none exists.
*/
static Accessor accessorFor(Class<?> type, String accessorName, InheritingConfiguration configuration) {
PropertyInfoKey key = new PropertyInfoKey(type, accessorName, configuration);
if (!ACCESSOR_CACHE.containsKey(key) && !FIELD_CACHE.containsKey(key)) {
@SuppressWarnings("unchecked")
Class<Object> uncheckedType = (Class<Object>) type;
for (Entry<String, Accessor> entry : TypeInfoRegistry.typeInfoFor(uncheckedType, configuration).getAccessors().entrySet()) {
if (entry.getValue().getMember() instanceof Method)
accessorFor(type, (Method) entry.getValue().getMember(), configuration, entry.getKey());
else if (entry.getValue().getMember() instanceof Field)
fieldPropertyFor(type, (Field) entry.getValue().getMember(), configuration, entry.getKey());
}
}
if (ACCESSOR_CACHE.containsKey(key))
return ACCESSOR_CACHE.get(key);
return FIELD_CACHE.get(key);
}
/**
* Returns an Accessor for the given accessor method. The method must be externally validated to
* ensure that it accepts zero arguments and does not return void.class.
*/
static synchronized Accessor accessorFor(Class<?> type, Method method,
Configuration configuration, String name) {
PropertyInfoKey key = new PropertyInfoKey(type, name, configuration);
Accessor accessor = ACCESSOR_CACHE.get(key);
if (accessor == null) {
accessor = new MethodAccessor(type, method, name);
ACCESSOR_CACHE.put(key, accessor);
}
return accessor;
}
/**
* Returns a FieldPropertyInfo instance for the given field.
*/
static synchronized FieldPropertyInfo fieldPropertyFor(Class<?> type, Field field,
Configuration configuration, String name) {
PropertyInfoKey key = new PropertyInfoKey(type, name, configuration);
FieldPropertyInfo fieldPropertyInfo = FIELD_CACHE.get(key);
if (fieldPropertyInfo == null) {
fieldPropertyInfo = new FieldPropertyInfo(type, field, name);
FIELD_CACHE.put(key, fieldPropertyInfo);
}
return fieldPropertyInfo;
}
/**
* Returns an mutator for the {@code accessorName}, else {@code null} if none exists.
* Returns a Mutator instance for the given mutator method. The method must be externally
* validated to ensure that it accepts one argument and returns void.class.
*/
static synchronized Mutator mutatorFor(Class<?> type, String name, InheritingConfiguration configuration) {<FILL_FUNCTION_BODY>
|
PropertyInfoKey key = new PropertyInfoKey(type, name, configuration);
if (!MUTATOR_CACHE.containsKey(key) && !FIELD_CACHE.containsKey(key)) {
@SuppressWarnings("unchecked")
Class<Object> uncheckedType = (Class<Object>) type;
for (Entry<String, Mutator> entry : TypeInfoRegistry.typeInfoFor(uncheckedType, configuration).getMutators().entrySet()) {
if (entry.getValue().getMember() instanceof Method)
mutatorFor(type, (Method) entry.getValue().getMember(), configuration, entry.getKey());
else if (entry.getValue().getMember() instanceof Field)
fieldPropertyFor(type, (Field) entry.getValue().getMember(), configuration, entry.getKey());
}
}
if (MUTATOR_CACHE.containsKey(key))
return MUTATOR_CACHE.get(key);
return FIELD_CACHE.get(key);
| 1,070 | 265 | 1,335 | 32,203 |
questdb_questdb
|
questdb/core/src/main/java/io/questdb/griffin/engine/functions/conditional/NullIfLongFunctionFactory.java
|
NullIfLongFunction
|
toPlan
|
class NullIfLongFunction extends LongFunction implements BinaryFunction {
private final Function longFunc1;
private final Function longFunc2;
public NullIfLongFunction(Function longFunc1, Function longFunc2) {
this.longFunc1 = longFunc1;
this.longFunc2 = longFunc2;
}
@Override
public Function getLeft() {
return longFunc1;
}
@Override
public long getLong(Record rec) {
return longFunc1.getLong(rec) == longFunc2.getLong(rec) ? Numbers.LONG_NaN : longFunc1.getLong(rec);
}
@Override
public Function getRight() {
return longFunc2;
}
@Override
public void toPlan(PlanSink sink) {<FILL_FUNCTION_BODY>}
}
|
sink.val("nullif(").val(longFunc1).val(',').val(longFunc2).val(')');
| 218 | 33 | 251 | 61,818 |
Nepxion_Discovery
|
Discovery/discovery-plugin-admin-center/discovery-plugin-admin-center-starter/src/main/java/com/nepxion/discovery/plugin/admincenter/endpoint/VersionEndpoint.java
|
VersionEndpoint
|
doUpdate
|
class VersionEndpoint {
@Autowired
private VersionResource versionResource;
@RequestMapping(path = "/update-async", method = RequestMethod.POST)
@ResponseBody
public ResponseEntity<?> updateAsync(@RequestBody String version) {
return doUpdate(version, true);
}
@RequestMapping(path = "/update-sync", method = RequestMethod.POST)
@ResponseBody
public ResponseEntity<?> updateSync(@RequestBody String version) {
return doUpdate(version, false);
}
@RequestMapping(path = "/clear-async", method = RequestMethod.POST)
@ResponseBody
public ResponseEntity<?> clearAsync(@RequestBody(required = false) String version) {
return doClear(version, true);
}
@RequestMapping(path = "/clear-sync", method = RequestMethod.POST)
@ResponseBody
public ResponseEntity<?> clearSync(@RequestBody(required = false) String version) {
return doClear(version, false);
}
@RequestMapping(path = "/view", method = RequestMethod.GET)
@ResponseBody
public ResponseEntity<?> view() {
return doView();
}
private ResponseEntity<?> doUpdate(String version, boolean async) {<FILL_FUNCTION_BODY>}
private ResponseEntity<?> doClear(String version, boolean async) {
try {
versionResource.clear(version, async);
return ResponseUtil.getSuccessResponse(true);
} catch (Exception e) {
return ResponseUtil.getFailureResponse(e);
}
}
private ResponseEntity<?> doView() {
try {
List<String> versionList = versionResource.view();
return ResponseUtil.getSuccessResponse(versionList);
} catch (Exception e) {
return ResponseUtil.getFailureResponse(e);
}
}
}
|
try {
versionResource.update(version, async);
return ResponseUtil.getSuccessResponse(true);
} catch (Exception e) {
return ResponseUtil.getFailureResponse(e);
}
| 476 | 55 | 531 | 32,606 |
dianping_cat
|
cat/cat-core/src/main/java/com/dianping/cat/service/IpService2.java
|
IpService2
|
load
|
class IpService2 implements Initializable {
private int m_offset;
private int[] m_index = new int[65536];
private ByteBuffer m_dataBuffer;
private ByteBuffer m_indexBuffer;
private ReentrantLock m_lock = new ReentrantLock();
private long bytesToLong(byte a, byte b, byte c, byte d) {
return int2long((((a & 0xff) << 24) | ((b & 0xff) << 16) | ((c & 0xff) << 8) | (d & 0xff)));
}
private String[] find(String ip) {
String[] ips = ip.split("\\.");
int prefix_value = (Integer.valueOf(ips[0]) * 256 + Integer.valueOf(ips[1]));
long ip2long_value = ip2long(ip);
int start = m_index[prefix_value];
int max_comp_len = m_offset - 262144 - 4;
long tmpInt;
long index_offset = -1;
int index_length = -1;
byte b = 0;
for (start = start * 9 + 262144; start < max_comp_len; start += 9) {
tmpInt = int2long(m_indexBuffer.getInt(start));
if (tmpInt >= ip2long_value) {
index_offset = bytesToLong(b, m_indexBuffer.get(start + 6), m_indexBuffer.get(start + 5),
m_indexBuffer.get(start + 4));
index_length = (0xFF & m_indexBuffer.get(start + 7) << 8) + (0xFF & m_indexBuffer.get(start + 8));
break;
}
}
byte[] areaBytes;
m_lock.lock();
try {
m_dataBuffer.position(m_offset + (int) index_offset - 262144);
areaBytes = new byte[index_length];
m_dataBuffer.get(areaBytes, 0, index_length);
} finally {
m_lock.unlock();
}
return new String(areaBytes, Charset.forName("UTF-8")).split("\t", -1);
}
public IpInfo findIpInfoByString(String ip) {
String[] infos = find(ip);
if (infos.length >= 7) {
IpInfo ipInfo = new IpInfo();
ipInfo.setNation(infos[0]);
ipInfo.setProvince(infos[1]);
ipInfo.setCity(infos[2]);
ipInfo.setChannel(infos[4]);
ipInfo.setLatitude(infos[5]);
ipInfo.setLongitude(infos[6]);
return ipInfo;
}
return null;
}
@Override
public void initialize() throws InitializationException {
load("ip/ipdata.datx");
}
private long int2long(int i) {
long l = i & 0x7fffffffL;
if (i < 0) {
l |= 0x080000000L;
}
return l;
}
private long ip2long(String ip) {
return int2long(str2Ip(ip));
}
private void load(String filename) {<FILL_FUNCTION_BODY>}
private int str2Ip(String ip) {
String[] ss = ip.split("\\.");
int a = Integer.parseInt(ss[0]);
int b = Integer.parseInt(ss[1]);
int c = Integer.parseInt(ss[2]);
int d = Integer.parseInt(ss[3]);
return (a << 24) | (b << 16) | (c << 8) | d;
}
}
|
m_lock.lock();
try {
InputStream is = IpService.class.getClassLoader().getResourceAsStream(filename);
m_dataBuffer = ByteBuffer.wrap(Files.forIO().readFrom(is));
m_dataBuffer.position(0);
m_offset = m_dataBuffer.getInt(); // indexLength
byte[] indexBytes = new byte[m_offset];
m_dataBuffer.get(indexBytes, 0, m_offset - 4);
m_indexBuffer = ByteBuffer.wrap(indexBytes);
m_indexBuffer.order(ByteOrder.LITTLE_ENDIAN);
for (int i = 0; i < 256; i++) {
for (int j = 0; j < 256; j++) {
m_index[i * 256 + j] = m_indexBuffer.getInt();
}
}
m_indexBuffer.order(ByteOrder.BIG_ENDIAN);
} catch (IOException e) {
Cat.logError(e);
} finally {
m_lock.unlock();
}
| 1,012 | 284 | 1,296 | 69,483 |
alibaba_druid
|
druid/core/src/main/java/com/alibaba/druid/sql/dialect/odps/ast/OdpsStatementImpl.java
|
OdpsStatementImpl
|
toString
|
class OdpsStatementImpl extends SQLStatementImpl {
@Override
protected void accept0(SQLASTVisitor visitor) {
accept0((OdpsASTVisitor) visitor);
}
protected abstract void accept0(OdpsASTVisitor visitor);
public String toString() {<FILL_FUNCTION_BODY>}
}
|
return SQLUtils.toOdpsString(this);
| 86 | 17 | 103 | 50,724 |
fabric8io_kubernetes-client
|
kubernetes-client/crd-generator/api/src/main/java/io/fabric8/crd/generator/CRDGenerationInfo.java
|
CRDGenerationInfo
|
getCRDInfos
|
class CRDGenerationInfo {
static final CRDGenerationInfo EMPTY = new CRDGenerationInfo();
private final Map<String, Map<String, CRDInfo>> crdNameToVersionToCRDInfoMap = new HashMap<>();
public Map<String, CRDInfo> getCRDInfos(String crdName) {<FILL_FUNCTION_BODY>}
public Map<String, Map<String, CRDInfo>> getCRDDetailsPerNameAndVersion() {
return crdNameToVersionToCRDInfoMap;
}
void add(String crdName, String version, URI fileURI) {
crdNameToVersionToCRDInfoMap.computeIfAbsent(crdName, k -> new HashMap<>())
.put(version, new CRDInfo(crdName, version, new File(fileURI).getAbsolutePath(),
ClassDependenciesVisitor.getDependentClassesFromCRDName(crdName)));
}
public int numberOfGeneratedCRDs() {
return crdNameToVersionToCRDInfoMap.values().stream().map(Map::size).reduce(Integer::sum).orElse(0);
}
}
|
return crdNameToVersionToCRDInfoMap.get(crdName);
| 298 | 23 | 321 | 18,435 |
jeequan_jeepay
|
jeepay/jeepay-payment/src/main/java/com/jeequan/jeepay/pay/channel/xxpay/XxpayRefundService.java
|
XxpayRefundService
|
refund
|
class XxpayRefundService extends AbstractRefundService {
@Override
public String getIfCode() {
return CS.IF_CODE.XXPAY;
}
@Override
public String preCheck(RefundOrderRQ bizRQ, RefundOrder refundOrder, PayOrder payOrder) {
return null;
}
@Override
public ChannelRetMsg refund(RefundOrderRQ bizRQ, RefundOrder refundOrder, PayOrder payOrder, MchAppConfigContext mchAppConfigContext) throws Exception {<FILL_FUNCTION_BODY>}
@Override
public ChannelRetMsg query(RefundOrder refundOrder, MchAppConfigContext mchAppConfigContext) throws Exception {
XxpayNormalMchParams params = (XxpayNormalMchParams)configContextQueryService.queryNormalMchParams(mchAppConfigContext.getMchNo(), mchAppConfigContext.getAppId(), getIfCode());
// 构造支付请求参数
Map<String,Object> paramMap = new TreeMap();
paramMap.put("mchId", params.getMchId()); //商户ID
paramMap.put("mchRefundNo", refundOrder.getRefundOrderId()); //商户退款单号
// 生成签名
String sign = XxpayKit.getSign(paramMap, params.getKey());
paramMap.put("sign", sign);
// 退款查询地址
String queryRefundOrderUrl = XxpayKit.getQueryRefundOrderUrl(params.getPayUrl())+ "?" + JeepayKit.genUrlParams(paramMap);
String resStr = "";
try {
log.info("查询退款[{}]参数:{}", getIfCode(), queryRefundOrderUrl);
resStr = HttpUtil.createPost(queryRefundOrderUrl).timeout(60 * 1000).execute().body();
log.info("查询退款[{}]结果:{}", getIfCode(), resStr);
} catch (Exception e) {
log.error("http error", e);
}
ChannelRetMsg channelRetMsg = new ChannelRetMsg();
// 默认退款中状态
channelRetMsg.setChannelState(ChannelRetMsg.ChannelState.WAITING);
if(StringUtils.isEmpty(resStr)) {
return null;
}
JSONObject resObj = JSONObject.parseObject(resStr);
if(!"0".equals(resObj.getString("retCode"))){
return null;
}
// 验证响应数据签名
String checkSign = resObj.getString("sign");
resObj.remove("sign");
if(!checkSign.equals(XxpayKit.getSign(resObj, params.getKey()))) {
channelRetMsg.setChannelState(ChannelRetMsg.ChannelState.CONFIRM_FAIL);
return null;
}
// 退款状态:0-订单生成,1-退款中,2-退款成功,3-退款失败
String status = resObj.getString("status");
if("2".equals(status)) {
channelRetMsg.setChannelState(ChannelRetMsg.ChannelState.CONFIRM_SUCCESS);
}else if("3".equals(status)) {
channelRetMsg.setChannelState(ChannelRetMsg.ChannelState.CONFIRM_FAIL);
channelRetMsg.setChannelErrMsg(resObj.getString("retMsg"));
}
return channelRetMsg;
}
}
|
XxpayNormalMchParams params = (XxpayNormalMchParams)configContextQueryService.queryNormalMchParams(mchAppConfigContext.getMchNo(), mchAppConfigContext.getAppId(), getIfCode());
// 构造支付请求参数
Map<String,Object> paramMap = new TreeMap();
paramMap.put("mchId", params.getMchId()); //商户ID
paramMap.put("mchOrderNo", refundOrder.getPayOrderId()); //支付订单-商户订单号
paramMap.put("mchRefundNo", refundOrder.getRefundOrderId()); //商户退款单号
paramMap.put("amount", refundOrder.getRefundAmount()); //退款金额
paramMap.put("currency", "cny"); //币种
paramMap.put("clientIp", refundOrder.getClientIp()); //客户端IP
paramMap.put("device", "web"); //客户端设备
//如果notifyUrl 不为空表示异步退款,具体退款结果以退款通知为准
paramMap.put("notifyUrl", getNotifyUrl(refundOrder.getRefundOrderId())); // 异步退款通知
paramMap.put("remarkInfo", refundOrder.getRefundReason()); // 退款原因
// 生成签名
String sign = XxpayKit.getSign(paramMap, params.getKey());
paramMap.put("sign", sign);
// 退款地址
String refundUrl = XxpayKit.getRefundUrl(params.getPayUrl())+ "?" + JeepayKit.genUrlParams(paramMap);
String resStr = "";
try {
log.info("发起退款[{}]参数:{}", getIfCode(), refundUrl);
resStr = HttpUtil.createPost(refundUrl).timeout(60 * 1000).execute().body();
log.info("发起退款[{}]结果:{}", getIfCode(), resStr);
} catch (Exception e) {
log.error("http error", e);
}
ChannelRetMsg channelRetMsg = new ChannelRetMsg();
// 默认退款中状态
channelRetMsg.setChannelState(ChannelRetMsg.ChannelState.WAITING);
if(StringUtils.isEmpty(resStr)) {
channelRetMsg.setChannelState(ChannelRetMsg.ChannelState.CONFIRM_FAIL);
channelRetMsg.setChannelErrCode("");
channelRetMsg.setChannelErrMsg("请求"+getIfCode()+"接口异常");
return null;
}
JSONObject resObj = JSONObject.parseObject(resStr);
if(!"0".equals(resObj.getString("retCode"))){
String retMsg = resObj.getString("retMsg");
channelRetMsg.setChannelState(ChannelRetMsg.ChannelState.CONFIRM_FAIL);
channelRetMsg.setChannelErrCode("");
channelRetMsg.setChannelErrMsg(retMsg);
return null;
}
// 验证响应数据签名
String checkSign = resObj.getString("sign");
resObj.remove("sign");
if(!checkSign.equals(XxpayKit.getSign(resObj, params.getKey()))) {
channelRetMsg.setChannelState(ChannelRetMsg.ChannelState.CONFIRM_FAIL);
return null;
}
// 退款状态:0-订单生成,1-退款中,2-退款成功,3-退款失败
String status = resObj.getString("status");
if("2".equals(status)) {
channelRetMsg.setChannelState(ChannelRetMsg.ChannelState.CONFIRM_SUCCESS);
}else if("3".equals(status)) {
channelRetMsg.setChannelState(ChannelRetMsg.ChannelState.CONFIRM_FAIL);
channelRetMsg.setChannelErrMsg(resObj.getString("retMsg"));
}
return channelRetMsg;
| 888 | 1,014 | 1,902 | 25,085 |
apache_incubator-seata
|
incubator-seata/rm-datasource/src/main/java/org/apache/seata/rm/datasource/undo/sqlserver/SqlServerUndoUpdateExecutor.java
|
SqlServerUndoUpdateExecutor
|
getUndoRows
|
class SqlServerUndoUpdateExecutor extends BaseSqlServerUndoExecutor {
/**
* Instantiates a new SqlServer update undo executor.
*
* @param sqlUndoLog the sql undo log
*/
public SqlServerUndoUpdateExecutor(SQLUndoLog sqlUndoLog) {
super(sqlUndoLog);
}
@Override
protected String buildUndoSQL() {
TableRecords beforeImage = sqlUndoLog.getBeforeImage();
List<Row> beforeImageRows = beforeImage.getRows();
if (CollectionUtils.isEmpty(beforeImageRows)) {
// TODO
throw new ShouldNeverHappenException("Invalid UNDO LOG");
}
Row row = beforeImageRows.get(0);
List<Field> nonPkFields = row.nonPrimaryKeys();
// update sql undo log before image all field come from table meta. need add escape.
// see BaseTransactionalExecutor#buildTableRecords
String updateColumns = nonPkFields.stream().map(
field -> ColumnUtils.addEscape(field.getName(), JdbcConstants.SQLSERVER) + " = ?").collect(
Collectors.joining(", "));
List<String> pkNameList = getOrderedPkList(beforeImage, row, JdbcConstants.SQLSERVER).stream().map(Field::getName)
.collect(Collectors.toList());
String whereSql = SqlGenerateUtils.buildWhereConditionByPKs(pkNameList, JdbcConstants.SQLSERVER);
return "UPDATE " + sqlUndoLog.getTableName() + " SET " + updateColumns + " WHERE " + whereSql;
}
@Override
protected TableRecords getUndoRows() {<FILL_FUNCTION_BODY>}
}
|
return sqlUndoLog.getBeforeImage();
| 451 | 16 | 467 | 52,329 |
apache_incubator-seata
|
incubator-seata/common/src/main/java/org/apache/seata/common/util/BlobUtils.java
|
BlobUtils
|
string2blob
|
class BlobUtils {
private BlobUtils() {
}
/**
* String 2 blob blob.
*
* @param str the str
* @return the blob
*/
public static Blob string2blob(String str) {<FILL_FUNCTION_BODY>}
/**
* Blob 2 string string.
*
* @param blob the blob
* @return the string
*/
public static String blob2string(Blob blob) {
if (blob == null) {
return null;
}
try {
return new String(blob.getBytes(1, (int) blob.length()), Constants.DEFAULT_CHARSET);
} catch (Exception e) {
throw new ShouldNeverHappenException(e);
}
}
/**
* Byte array to blob
*
* @param bytes the byte array
* @return the blob
*/
public static Blob bytes2Blob(byte[] bytes) {
if (bytes == null) {
return null;
}
try {
return new SerialBlob(bytes);
} catch (Exception e) {
throw new ShouldNeverHappenException(e);
}
}
/**
* Blob to byte array.
*
* @param blob the blob
* @return the byte array
*/
public static byte[] blob2Bytes(Blob blob) {
if (blob == null) {
return null;
}
try {
return blob.getBytes(1, (int) blob.length());
} catch (Exception e) {
throw new ShouldNeverHappenException(e);
}
}
}
|
if (str == null) {
return null;
}
try {
return new SerialBlob(str.getBytes(Constants.DEFAULT_CHARSET));
} catch (Exception e) {
throw new ShouldNeverHappenException(e);
}
| 450 | 70 | 520 | 52,161 |
zhkl0228_unidbg
|
unidbg/unidbg-api/src/main/java/com/github/unidbg/arm/TraceFunctionCall.java
|
TraceFunctionCall
|
hook
|
class TraceFunctionCall implements CodeHook {
private static final Log log = LogFactory.getLog(TraceFunctionCall.class);
protected final Emulator<?> emulator;
private final FunctionCallListener listener;
TraceFunctionCall(Emulator<?> emulator, FunctionCallListener listener) {
this.emulator = emulator;
this.listener = listener;
}
final void pushFunction(long callerAddress, long functionAddress, long returnAddress, Number[] args) {
RunnableTask runningTask = emulator.getThreadDispatcher().getRunningTask();
FunctionCall call = new FunctionCall(callerAddress, functionAddress, returnAddress, args);
runningTask.pushFunction(emulator, call);
listener.onDebugPushFunction(emulator, call);
listener.onCall(emulator, callerAddress, functionAddress);
}
private boolean detectedIllegalState;
@Override
public void hook(Backend backend, long address, int size, Object user) {<FILL_FUNCTION_BODY>}
protected abstract Instruction disassemble(long address, int size);
protected abstract void onInstruction(Instruction instruction);
private UnHook unHook;
@Override
public void onAttach(UnHook unHook) {
this.unHook = unHook;
}
@Override
public void detach() {
if (unHook != null) {
unHook.unhook();
unHook = null;
}
}
}
|
if (detectedIllegalState) {
return;
}
RunnableTask runningTask = emulator.getThreadDispatcher().getRunningTask();
FunctionCall call = runningTask.popFunction(emulator, address);
if (call != null) {
listener.onDebugPopFunction(emulator, address, call);
if (call.returnAddress != address) {
log.warn("Illegal state address=" + UnidbgPointer.pointer(emulator, address) + ", call=" + call.toReadableString(emulator));
if (LogFactory.getLog(AbstractEmulator.class).isDebugEnabled() ||
LogFactory.getLog(BaseTask.class).isDebugEnabled()) {
emulator.attach().debug();
}
detectedIllegalState = true;
return;
} else {
listener.postCall(emulator, call.callerAddress, call.functionAddress, call.args);
}
}
try {
Instruction instruction = disassemble(address, size);
if (instruction != null) {
if (log.isDebugEnabled()) {
if (!instruction.getMnemonic().startsWith("bl")) {
log.warn(Inspector.inspectString(backend.mem_read(address, size), "Invalid " + instruction + ": thumb=" + ARM.isThumb(backend)));
}
}
onInstruction(instruction);
} else if (log.isDebugEnabled()) {
Instruction[] instructions = emulator.disassemble(address, size, 1);
if (instructions.length != 1) {
return;
}
instruction = instructions[0];
String mnemonic = instruction.getMnemonic();
if (emulator.is32Bit()) {
if (mnemonic.startsWith("bl") &&
!mnemonic.startsWith("ble") &&
!mnemonic.startsWith("blt") &&
!mnemonic.startsWith("bls") &&
!mnemonic.startsWith("blo")) {
log.warn(Inspector.inspectString(backend.mem_read(address, size), "Unsupported " + instruction + ": thumb=" + ARM.isThumb(backend)));
}
} else {
if (mnemonic.startsWith("bl")) {
log.warn(Inspector.inspectString(backend.mem_read(address, size), "Unsupported " + instruction + ": thumb=" + ARM.isThumb(backend)));
}
}
}
} catch (BackendException e) {
throw new IllegalStateException(e);
}
| 381 | 677 | 1,058 | 48,340 |
apache_rocketmq
|
rocketmq/remoting/src/main/java/org/apache/rocketmq/remoting/protocol/body/BrokerStatsData.java
|
BrokerStatsData
|
getStatsHour
|
class BrokerStatsData extends RemotingSerializable {
private BrokerStatsItem statsMinute;
private BrokerStatsItem statsHour;
private BrokerStatsItem statsDay;
public BrokerStatsItem getStatsMinute() {
return statsMinute;
}
public void setStatsMinute(BrokerStatsItem statsMinute) {
this.statsMinute = statsMinute;
}
public BrokerStatsItem getStatsHour() {<FILL_FUNCTION_BODY>}
public void setStatsHour(BrokerStatsItem statsHour) {
this.statsHour = statsHour;
}
public BrokerStatsItem getStatsDay() {
return statsDay;
}
public void setStatsDay(BrokerStatsItem statsDay) {
this.statsDay = statsDay;
}
}
|
return statsHour;
| 219 | 10 | 229 | 53,300 |
speedment_speedment
|
speedment/runtime-parent/runtime-core/src/main/java/com/speedment/runtime/core/internal/component/transaction/DataSourceHandlerImpl.java
|
DataSourceHandlerImpl
|
rollbacker
|
class DataSourceHandlerImpl<D, T> implements DataSourceHandler<D, T> {
private final Function<? super D, ? extends T> extractor;
private final BiFunction<? super T, Isolation, Isolation> isolationConfigurator;
private final Consumer<? super T> beginner;
private final Consumer<? super T> committer;
private final Consumer<? super T> rollbacker;
private final Consumer<? super T> closer;
public DataSourceHandlerImpl(
final Function<? super D, ? extends T> extractor,
final BiFunction<? super T, Isolation, Isolation> isolationConfigurator,
final Consumer<? super T> beginner,
final Consumer<? super T> committer,
final Consumer<? super T> rollbacker,
final Consumer<? super T> closer
) {
this.extractor = requireNonNull(extractor);
this.isolationConfigurator = requireNonNull(isolationConfigurator);
this.beginner = requireNonNull(beginner);
this.committer = requireNonNull(committer);
this.rollbacker = requireNonNull(rollbacker);
this.closer = requireNonNull(closer);
}
@Override
public Function<? super D, ? extends T> extractor() {
return extractor;
}
@Override
public BiFunction<? super T, Isolation, Isolation> isolationConfigurator() {
return isolationConfigurator;
}
@Override
public Consumer<? super T> beginner() {
return beginner;
}
@Override
public Consumer<? super T> committer() {
return committer;
}
@Override
public Consumer<? super T> rollbacker() {<FILL_FUNCTION_BODY>}
@Override
public Consumer<? super T> closer() {
return closer;
}
}
|
return rollbacker;
| 499 | 10 | 509 | 42,907 |
spring-cloud_spring-cloud-kubernetes
|
spring-cloud-kubernetes/spring-cloud-kubernetes-integration-tests/spring-cloud-kubernetes-fabric8-client-reload/src/main/java/org/springframework/cloud/kubernetes/fabric8/client/reload/LeftProperties.java
|
LeftProperties
|
getValue
|
class LeftProperties {
private String value;
public String getValue() {<FILL_FUNCTION_BODY>}
public void setValue(String value) {
this.value = value;
}
}
|
return value;
| 55 | 8 | 63 | 43,676 |
RipMeApp_ripme
|
ripme/src/main/java/com/rarchives/ripme/ripper/rippers/PornhubRipper.java
|
PornhubImageThread
|
fetchImage
|
class PornhubImageThread extends Thread {
private URL url;
private int index;
PornhubImageThread(URL url, int index, File workingDir) {
super();
this.url = url;
this.index = index;
}
@Override
public void run() {
fetchImage();
}
private void fetchImage() {<FILL_FUNCTION_BODY>}
}
|
try {
Document doc = Http.url(this.url)
.referrer(this.url)
.get();
// Find image
Elements images = doc.select("#photoImageSection img");
Element image = images.first();
String imgsrc = image.attr("src");
LOGGER.info("Found URL " + imgsrc + " via " + images.get(0));
// Provide prefix and let the AbstractRipper "guess" the filename
String prefix = "";
if (Utils.getConfigBoolean("download.save_order", true)) {
prefix = String.format("%03d_", index);
}
URL imgurl = new URL(url, imgsrc);
addURLToDownload(imgurl, prefix);
} catch (IOException e) {
LOGGER.error("[!] Exception while loading/parsing " + this.url, e);
}
| 111 | 231 | 342 | 39,686 |
javastacks_spring-boot-best-practice
|
spring-boot-best-practice/javastack-spring-boot-starter/src/main/java/cn/javastack/springboot/starter/config/TestServiceAutoConfiguration.java
|
TestServiceAutoConfiguration
|
testService
|
class TestServiceAutoConfiguration {
@Bean
public TestService testService() {<FILL_FUNCTION_BODY>}
}
|
return new TestService();
| 36 | 10 | 46 | 24,666 |
pf4j_pf4j
|
pf4j/pf4j/src/main/java/org/pf4j/util/ClassUtils.java
|
ClassUtils
|
getAnnotationMirror
|
class ClassUtils {
private ClassUtils() {}
public static List<String> getAllInterfacesNames(Class<?> aClass) {
return toString(getAllInterfaces(aClass));
}
public static List<Class<?>> getAllInterfaces(Class<?> aClass) {
List<Class<?>> list = new ArrayList<>();
while (aClass != null) {
Class<?>[] interfaces = aClass.getInterfaces();
for (Class<?> anInterface : interfaces) {
if (!list.contains(anInterface)) {
list.add(anInterface);
}
List<Class<?>> superInterfaces = getAllInterfaces(anInterface);
for (Class<?> superInterface : superInterfaces) {
if (!list.contains(superInterface)) {
list.add(superInterface);
}
}
}
aClass = aClass.getSuperclass();
}
return list;
}
/**
* Get a certain annotation of a {@link TypeElement}.
* See <a href="https://stackoverflow.com/a/10167558">stackoverflow.com</a> for more information.
*
* @param typeElement the type element, that contains the requested annotation
* @param annotationClass the class of the requested annotation
* @return the requested annotation or null, if no annotation of the provided class was found
* @throws NullPointerException if <code>typeElement</code> or <code>annotationClass</code> is null
*/
public static AnnotationMirror getAnnotationMirror(TypeElement typeElement, Class<?> annotationClass) {<FILL_FUNCTION_BODY>}
/**
* Get a certain parameter of an {@link AnnotationMirror}.
* See <a href="https://stackoverflow.com/a/10167558">stackoverflow.com</a> for more information.
*
* @param annotationMirror the annotation, that contains the requested parameter
* @param annotationParameter the name of the requested annotation parameter
* @return the requested parameter or null, if no parameter of the provided name was found
* @throws NullPointerException if <code>annotationMirror</code> is null
*/
public static AnnotationValue getAnnotationValue(AnnotationMirror annotationMirror, String annotationParameter) {
for (Map.Entry<? extends ExecutableElement, ? extends AnnotationValue> entry : annotationMirror.getElementValues().entrySet()) {
if (entry.getKey().getSimpleName().toString().equals(annotationParameter)) {
return entry.getValue();
}
}
return null;
}
/**
* Get a certain annotation parameter of a {@link TypeElement}.
* See <a href="https://stackoverflow.com/a/10167558">stackoverflow.com</a> for more information.
*
* @param typeElement the type element, that contains the requested annotation
* @param annotationClass the class of the requested annotation
* @param annotationParameter the name of the requested annotation parameter
* @return the requested parameter or null, if no annotation for the provided class was found or no annotation parameter was found
* @throws NullPointerException if <code>typeElement</code> or <code>annotationClass</code> is null
*/
public static AnnotationValue getAnnotationValue(TypeElement typeElement, Class<?> annotationClass, String annotationParameter) {
AnnotationMirror annotationMirror = getAnnotationMirror(typeElement, annotationClass);
return annotationMirror != null ? getAnnotationValue(annotationMirror, annotationParameter) : null;
}
/**
* Uses {@link Class#getSimpleName()} to convert from {@link Class} to {@link String}.
*/
private static List<String> toString(List<Class<?>> classes) {
List<String> list = new ArrayList<>();
for (Class<?> aClass : classes) {
list.add(aClass.getSimpleName());
}
return list;
}
}
|
String annotationClassName = annotationClass.getName();
for (AnnotationMirror m : typeElement.getAnnotationMirrors()) {
if (m.getAnnotationType().toString().equals(annotationClassName)) {
return m;
}
}
return null;
| 1,027 | 71 | 1,098 | 37,279 |
FasterXML_jackson-databind
|
jackson-databind/src/main/java/com/fasterxml/jackson/databind/deser/std/DateDeserializers.java
|
CalendarDeserializer
|
deserialize
|
class CalendarDeserializer extends DateBasedDeserializer<Calendar>
{
/**
* We may know actual expected type; if so, it will be
* used for instantiation.
*
* @since 2.9
*/
protected final Constructor<Calendar> _defaultCtor;
public CalendarDeserializer() {
super(Calendar.class);
_defaultCtor = null;
}
@SuppressWarnings("unchecked")
public CalendarDeserializer(Class<? extends Calendar> cc) {
super(cc);
_defaultCtor = (Constructor<Calendar>) ClassUtil.findConstructor(cc, false);
}
public CalendarDeserializer(CalendarDeserializer src, DateFormat df, String formatString) {
super(src, df, formatString);
_defaultCtor = src._defaultCtor;
}
@Override
protected CalendarDeserializer withDateFormat(DateFormat df, String formatString) {
return new CalendarDeserializer(this, df, formatString);
}
@Override // since 2.12
public Object getEmptyValue(DeserializationContext ctxt) {
GregorianCalendar cal = new GregorianCalendar();
cal.setTimeInMillis(0L);
return cal;
}
@Override
public Calendar deserialize(JsonParser p, DeserializationContext ctxt) throws IOException
{<FILL_FUNCTION_BODY>}
}
|
Date d = _parseDate(p, ctxt);
if (d == null) {
return null;
}
if (_defaultCtor == null) {
return ctxt.constructCalendar(d);
}
try {
Calendar c = _defaultCtor.newInstance();
c.setTimeInMillis(d.getTime());
TimeZone tz = ctxt.getTimeZone();
if (tz != null) {
c.setTimeZone(tz);
}
return c;
} catch (Exception e) {
return (Calendar) ctxt.handleInstantiationProblem(handledType(), d, e);
}
| 368 | 169 | 537 | 55,636 |
spring-projects_spring-batch
|
spring-batch/spring-batch-samples/src/main/java/org/springframework/batch/samples/file/patternmatching/Address.java
|
Address
|
equals
|
class Address {
public static final String LINE_ID_BILLING_ADDR = "BAD";
public static final String LINE_ID_SHIPPING_ADDR = "SAD";
private String addressee;
private String addrLine1;
private String addrLine2;
private String city;
private String zipCode;
private String state;
private String country;
public String getAddrLine1() {
return addrLine1;
}
public void setAddrLine1(String addrLine1) {
this.addrLine1 = addrLine1;
}
public String getAddrLine2() {
return addrLine2;
}
public void setAddrLine2(String addrLine2) {
this.addrLine2 = addrLine2;
}
public String getAddressee() {
return addressee;
}
public void setAddressee(String addressee) {
this.addressee = addressee;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
public String getZipCode() {
return zipCode;
}
public void setZipCode(String zipCode) {
this.zipCode = zipCode;
}
@Override
public String toString() {
return "Address [addressee=" + addressee + ", city=" + city + ", country=" + country + ", state=" + state
+ ", zipCode=" + zipCode + "]";
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((addressee == null) ? 0 : addressee.hashCode());
result = prime * result + ((country == null) ? 0 : country.hashCode());
result = prime * result + ((zipCode == null) ? 0 : zipCode.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {<FILL_FUNCTION_BODY>}
}
|
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
Address other = (Address) obj;
if (addressee == null) {
if (other.addressee != null) {
return false;
}
}
else if (!addressee.equals(other.addressee)) {
return false;
}
if (country == null) {
if (other.country != null) {
return false;
}
}
else if (!country.equals(other.country)) {
return false;
}
if (zipCode == null) {
if (other.zipCode != null) {
return false;
}
}
else if (!zipCode.equals(other.zipCode)) {
return false;
}
return true;
| 594 | 251 | 845 | 44,861 |
alibaba_Sentinel
|
Sentinel/sentinel-dashboard/src/main/java/com/alibaba/csp/sentinel/dashboard/repository/gateway/InMemApiDefinitionStore.java
|
InMemApiDefinitionStore
|
nextId
|
class InMemApiDefinitionStore extends InMemoryRuleRepositoryAdapter<ApiDefinitionEntity> {
private static AtomicLong ids = new AtomicLong(0);
@Override
protected long nextId() {<FILL_FUNCTION_BODY>}
}
|
return ids.incrementAndGet();
| 64 | 14 | 78 | 65,423 |
assertj_assertj
|
assertj/assertj-core/src/main/java/org/assertj/core/api/recursive/comparison/ComparisonDifference.java
|
ComparisonDifference
|
multiLineDescription
|
class ComparisonDifference implements Comparable<ComparisonDifference> {
// ELEMENT_WITH_INDEX_PATTERN should match [0] or [123] but not name[0] or [0].name, explanation:
// - ^ represents the start of the string in a regex
// - \[ represents [ in a regex, need another \ to escape it in a java string
// - d+ any number
// - \] represents ] in a regex
// - $ represents the end of the string in a regex
private static final String TOP_LEVEL_ELEMENT_PATTERN = "^\\[\\d+\\]$";
private static final String FIELD = "field/property '%s'";
private static final String TOP_LEVEL_OBJECTS = "Top level actual and expected objects";
private static final String TOP_LEVEL_ELEMENTS = "Top level actual and expected objects element at index %s";
public static final String DEFAULT_TEMPLATE = "%s differ:%n" +
"- actual value : %s%n" +
"- expected value: %s%s";
final List<String> decomposedPath;
final String concatenatedPath;
final Object actual;
final Object expected;
final Optional<String> additionalInformation;
final String template;
public ComparisonDifference(DualValue dualValue) {
this(dualValue.getDecomposedPath(), dualValue.actual, dualValue.expected, null, DEFAULT_TEMPLATE);
}
public ComparisonDifference(DualValue dualValue, String additionalInformation) {
this(dualValue.getDecomposedPath(), dualValue.actual, dualValue.expected, additionalInformation, DEFAULT_TEMPLATE);
}
public ComparisonDifference(DualValue dualValue, String additionalInformation, String template) {
this(dualValue.getDecomposedPath(), dualValue.actual, dualValue.expected, additionalInformation, template);
}
private ComparisonDifference(List<String> decomposedPath, Object actual, Object other, String additionalInformation,
String template) {
this.decomposedPath = unmodifiableList(requireNonNull(decomposedPath, "a path can't be null"));
this.concatenatedPath = toConcatenatedPath(decomposedPath);
this.actual = actual;
this.expected = other;
this.additionalInformation = Optional.ofNullable(additionalInformation);
this.template = template != null ? template : DEFAULT_TEMPLATE;
}
public static ComparisonDifference rootComparisonDifference(Object actual, Object other, String additionalInformation) {
return new ComparisonDifference(rootDualValue(actual, other), additionalInformation);
}
public Object getActual() {
return actual;
}
public Object getExpected() {
return expected;
}
public String getTemplate() {
return template;
}
public Optional<String> getAdditionalInformation() {
return additionalInformation;
}
public List<String> getDecomposedPath() {
return decomposedPath;
}
@Override
public String toString() {
return additionalInformation.isPresent()
? format("ComparisonDifference [path=%s, actual=%s, expected=%s, template=%s, additionalInformation=%s]",
concatenatedPath, actual, expected, template, additionalInformation.get())
: format("ComparisonDifference [path=%s, actual=%s, template=%s, expected=%s]",
concatenatedPath, actual, template, expected);
}
public String multiLineDescription() {<FILL_FUNCTION_BODY>}
public String multiLineDescription(Representation representation) {
UnambiguousRepresentation unambiguousRepresentation = new UnambiguousRepresentation(representation, actual, expected);
String additionalInfo = additionalInformation.map(ComparisonDifference::formatOnNewline).orElse("");
return format(getTemplate(),
fieldPathDescription(),
unambiguousRepresentation.getActual(),
unambiguousRepresentation.getExpected(),
additionalInfo);
}
// returns a user-friendly path description
protected String fieldPathDescription() {
if (concatenatedPath.isEmpty()) return TOP_LEVEL_OBJECTS;
if (concatenatedPath.matches(TOP_LEVEL_ELEMENT_PATTERN)) return format(TOP_LEVEL_ELEMENTS, extractIndex(concatenatedPath));
return format(FIELD, concatenatedPath);
}
private static String extractIndex(String path) {
// path looks like [12]
// index = 12]
String index = path.substring(1);
// index = 12
return index.replaceFirst("\\]", "");
}
private static String formatOnNewline(String info) {
return format("%n%s", info);
}
private static String toConcatenatedPath(List<String> decomposedPath) {
String concatenatedPath = join(".", decomposedPath);
// remove the . from array/list index, so person.children.[2].name -> person.children[2].name
return concatenatedPath.replaceAll("\\.\\[", "[");
}
@Override
public boolean equals(final Object other) {
if (!(other instanceof ComparisonDifference)) {
return false;
}
ComparisonDifference castOther = (ComparisonDifference) other;
return Objects.equals(concatenatedPath, castOther.concatenatedPath)
&& Objects.equals(actual, castOther.actual)
&& Objects.equals(expected, castOther.expected)
&& Objects.equals(template, castOther.template)
&& Objects.equals(additionalInformation, castOther.additionalInformation);
}
@Override
public int hashCode() {
return Objects.hash(concatenatedPath, actual, expected, template, additionalInformation);
}
@Override
public int compareTo(final ComparisonDifference other) {
// we don't use '.' to join path before comparing them as it would make a.b < aa
return concat(decomposedPath).compareTo(concat(other.decomposedPath));
}
private static String concat(List<String> decomposedPath) {
return join("", decomposedPath);
}
}
|
// use the default configured representation
return multiLineDescription(ConfigurationProvider.CONFIGURATION_PROVIDER.representation());
| 1,591 | 32 | 1,623 | 12,634 |
apache_maven
|
maven/maven-core/src/main/java/org/apache/maven/internal/aether/ResolverLifecycle.java
|
ResolverLifecycle
|
shutdown
|
class ResolverLifecycle {
private final Provider<RepositorySystem> repositorySystemProvider;
@Inject
ResolverLifecycle(Provider<RepositorySystem> repositorySystemProvider) {
this.repositorySystemProvider = requireNonNull(repositorySystemProvider);
}
@PreDestroy
public void shutdown() {<FILL_FUNCTION_BODY>}
}
|
repositorySystemProvider.get().shutdown();
| 95 | 14 | 109 | 11,157 |
jOOQ_jOOQ
|
jOOQ/jOOQ/src/main/java/org/jooq/impl/IsNotDocument.java
|
IsNotDocument
|
equals
|
class IsNotDocument
extends
AbstractCondition
implements
QOM.IsNotDocument
{
final Field<?> field;
IsNotDocument(
Field<?> field
) {
this.field = nullSafeNotNull(field, OTHER);
}
// -------------------------------------------------------------------------
// XXX: QueryPart API
// -------------------------------------------------------------------------
@Override
public final void accept(Context<?> ctx) {
switch (ctx.family()) {
default:
ctx.visit(field).sql(' ').visit(K_IS_NOT_DOCUMENT);
break;
}
}
// -------------------------------------------------------------------------
// XXX: Query Object Model
// -------------------------------------------------------------------------
@Override
public final Field<?> $arg1() {
return field;
}
@Override
public final QOM.IsNotDocument $arg1(Field<?> newValue) {
return $constructor().apply(newValue);
}
@Override
public final Function1<? super Field<?>, ? extends QOM.IsNotDocument> $constructor() {
return (a1) -> new IsNotDocument(a1);
}
// -------------------------------------------------------------------------
// XXX: The Object API
// -------------------------------------------------------------------------
@Override
public boolean equals(Object that) {<FILL_FUNCTION_BODY>}
}
|
if (that instanceof QOM.IsNotDocument o) {
return
StringUtils.equals($field(), o.$field())
;
}
else
return super.equals(that);
| 361 | 54 | 415 | 58,898 |
alibaba_jetcache
|
jetcache/jetcache-core/src/main/java/com/alicp/jetcache/CacheValueHolder.java
|
CacheValueHolder
|
setAccessTime
|
class CacheValueHolder<V> implements Serializable {
private static final long serialVersionUID = -7973743507831565203L;
private V value;
private long expireTime;
private long accessTime;
/**
* used by kyro
*/
public CacheValueHolder() {
}
public CacheValueHolder(V value, long expireAfterWrite) {
this.value = value;
this.accessTime = System.currentTimeMillis();
this.expireTime = accessTime + expireAfterWrite;
}
public V getValue() {
return value;
}
public void setValue(V value) {
this.value = value;
}
public long getExpireTime() {
return expireTime;
}
public void setExpireTime(long expireTime) {
this.expireTime = expireTime;
}
public long getAccessTime() {
return accessTime;
}
public void setAccessTime(long accessTime) {<FILL_FUNCTION_BODY>}
}
|
this.accessTime = accessTime;
| 289 | 13 | 302 | 6,446 |
apache_incubator-kie-optaplanner
|
incubator-kie-optaplanner/optaplanner-examples/src/main/java/org/optaplanner/examples/examination/domain/Exam.java
|
Exam
|
getTopic
|
class Exam extends AbstractPersistable implements Labeled {
protected Topic topic;
// Planning variables: changes during planning, between score calculations.
protected Room room;
public Topic getTopic() {<FILL_FUNCTION_BODY>}
public void setTopic(Topic topic) {
this.topic = topic;
}
@PlanningVariable(strengthWeightFactoryClass = RoomStrengthWeightFactory.class)
public Room getRoom() {
return room;
}
public void setRoom(Room room) {
this.room = room;
}
// ************************************************************************
// Complex methods
// ************************************************************************
public abstract Period getPeriod();
@JsonIgnore
public int getTopicDuration() {
return getTopic().getDuration();
}
@JsonIgnore
public int getTopicStudentSize() {
return getTopic().getStudentSize();
}
@JsonIgnore
public int getDayIndex() {
Period period = getPeriod();
if (period == null) {
return Integer.MIN_VALUE;
}
return period.getDayIndex();
}
@JsonIgnore
public int getPeriodIndex() {
Period period = getPeriod();
if (period == null) {
return Integer.MIN_VALUE;
}
return period.getPeriodIndex();
}
@JsonIgnore
public int getPeriodDuration() {
Period period = getPeriod();
if (period == null) {
return Integer.MIN_VALUE;
}
return period.getDuration();
}
@JsonIgnore
public boolean isTopicFrontLoadLarge() {
return topic.isFrontLoadLarge();
}
@JsonIgnore
public boolean isPeriodFrontLoadLast() {
Period period = getPeriod();
if (period == null) {
return false;
}
return period.isFrontLoadLast();
}
@Override
public String getLabel() {
return Long.toString(topic.getId());
}
@Override
public String toString() {
return topic.toString();
}
}
|
return topic;
| 556 | 8 | 564 | 9,807 |
lealone_Lealone
|
Lealone/lealone-sql/src/main/java/com/lealone/sql/StatementList.java
|
StatementList
|
update
|
class StatementList extends StatementBase {
private final StatementBase firstStatement;
private final String remaining;
public StatementList(ServerSession session, StatementBase firstStatement, String remaining) {
super(session);
this.firstStatement = firstStatement;
this.remaining = remaining;
}
public StatementBase getFirstStatement() {
return firstStatement;
}
public String getRemaining() {
return remaining;
}
@Override
public int getType() {
return firstStatement.getType();
}
@Override
public Future<Result> getMetaData() {
return firstStatement.getMetaData();
}
@Override
public ArrayList<Parameter> getParameters() {
return firstStatement.getParameters();
}
private void executeRemaining() {
StatementBase remainingStatement = (StatementBase) session.prepareStatement(remaining, -1);
if (remainingStatement.isQuery()) {
remainingStatement.query(0);
} else {
remainingStatement.update();
}
}
@Override
public PreparedSQLStatement prepare() {
firstStatement.prepare();
return this;
}
@Override
public boolean isQuery() {
return firstStatement.isQuery();
}
@Override
public Result query(int maxRows) {
Result result = firstStatement.query(maxRows);
executeRemaining();
return result;
}
@Override
public int update() {<FILL_FUNCTION_BODY>}
}
|
int updateCount = firstStatement.update();
executeRemaining();
return updateCount;
| 396 | 26 | 422 | 29,260 |
flowable_flowable-engine
|
flowable-engine/modules/flowable-engine/src/main/java/org/flowable/engine/impl/util/condition/ConditionUtil.java
|
ConditionUtil
|
hasTrueCondition
|
class ConditionUtil {
public static boolean hasTrueCondition(SequenceFlow sequenceFlow, DelegateExecution execution) {<FILL_FUNCTION_BODY>}
protected static String getActiveValue(String originalValue, String propertyName, ObjectNode elementProperties) {
String activeValue = originalValue;
if (elementProperties != null) {
JsonNode overrideValueNode = elementProperties.get(propertyName);
if (overrideValueNode != null) {
if (overrideValueNode.isNull()) {
activeValue = null;
} else {
activeValue = overrideValueNode.asText();
}
}
}
return activeValue;
}
}
|
String conditionExpression = null;
if (CommandContextUtil.getProcessEngineConfiguration().isEnableProcessDefinitionInfoCache()) {
ObjectNode elementProperties = BpmnOverrideContext.getBpmnOverrideElementProperties(sequenceFlow.getId(), execution.getProcessDefinitionId());
conditionExpression = getActiveValue(sequenceFlow.getConditionExpression(), DynamicBpmnConstants.SEQUENCE_FLOW_CONDITION, elementProperties);
} else {
conditionExpression = sequenceFlow.getConditionExpression();
}
if (StringUtils.isNotEmpty(conditionExpression)) {
Expression expression = CommandContextUtil.getProcessEngineConfiguration().getExpressionManager().createExpression(conditionExpression);
Condition condition = new UelExpressionCondition(expression);
return condition.evaluate(sequenceFlow.getId(), execution);
} else {
return true;
}
| 170 | 206 | 376 | 56,756 |
pmd_pmd
|
pmd/pmd-html/src/main/java/net/sourceforge/pmd/lang/html/ast/HtmlTreeBuilder.java
|
HtmlTreeBuilder
|
convertJsoupNode
|
class HtmlTreeBuilder {
public ASTHtmlDocument build(Document doc,
Parser.ParserTask task,
Map<Integer, String> suppressMap) {
ASTHtmlDocument root = new ASTHtmlDocument(doc, task, suppressMap);
addChildren(root, doc);
LineNumbers lineNumbers = new LineNumbers(root);
lineNumbers.determine();
return root;
}
private void addChildren(AbstractHtmlNode<?> parent, Node node) {
for (Node child : node.childNodes()) {
AbstractHtmlNode<?> converted = convertJsoupNode(child);
parent.addChild(converted, parent.getNumChildren());
addChildren(converted, child);
}
}
private AbstractHtmlNode<? extends Node> convertJsoupNode(Node node) {<FILL_FUNCTION_BODY>}
}
|
if (node instanceof Element) {
return new ASTHtmlElement((Element) node);
} else if (node instanceof CDataNode) {
return new ASTHtmlCDataNode((CDataNode) node);
} else if (node instanceof TextNode) {
return new ASTHtmlTextNode((TextNode) node);
} else if (node instanceof Comment) {
return new ASTHtmlComment((Comment) node);
} else if (node instanceof XmlDeclaration) {
return new ASTHtmlXmlDeclaration((XmlDeclaration) node);
} else if (node instanceof DocumentType) {
return new ASTHtmlDocumentType((DocumentType) node);
} else {
throw new RuntimeException("Unsupported node type: " + node.getClass());
}
| 228 | 188 | 416 | 38,596 |
iluwatar_java-design-patterns
|
java-design-patterns/data-locality/src/main/java/com/iluwatar/data/locality/game/component/manager/RenderComponentManager.java
|
RenderComponentManager
|
start
|
class RenderComponentManager {
private static final int MAX_ENTITIES = 10000;
private final int numEntities;
private final Component[] renderComponents = new RenderComponent[MAX_ENTITIES];
public RenderComponentManager(int numEntities) {
this.numEntities = numEntities;
}
/**
* Start render component.
*/
public void start() {<FILL_FUNCTION_BODY>}
/**
* render component.
*/
public void render() {
LOGGER.info("Update Render Game Component ");
// Process Render.
IntStream.range(0, numEntities)
.filter(i -> renderComponents.length > i && renderComponents[i] != null)
.forEach(i -> renderComponents[i].render());
}
}
|
LOGGER.info("Start Render Game Component ");
IntStream.range(0, numEntities).forEach(i -> renderComponents[i] = new RenderComponent());
| 222 | 46 | 268 | 372 |
648540858_wvp-GB28181-pro
|
wvp-GB28181-pro/src/main/java/com/genersoft/iot/vmp/gb28181/task/SipRunner.java
|
SipRunner
|
run
|
class SipRunner implements CommandLineRunner {
@Autowired
private IVideoManagerStorage storager;
@Autowired
private IRedisCatchStorage redisCatchStorage;
@Autowired
private SSRCFactory ssrcFactory;
@Autowired
private UserSetting userSetting;
@Autowired
private IDeviceService deviceService;
@Autowired
private IMediaServerService mediaServerService;
@Autowired
private IPlatformService platformService;
@Autowired
private ISIPCommanderForPlatform commanderForPlatform;
private final static Logger logger = LoggerFactory.getLogger(PlatformServiceImpl.class);
@Override
public void run(String... args) throws Exception {<FILL_FUNCTION_BODY>}
}
|
List<Device> deviceList = deviceService.getAllOnlineDevice();
for (Device device : deviceList) {
if (deviceService.expire(device)){
deviceService.offline(device.getDeviceId(), "注册已过期");
}else {
deviceService.online(device, null);
}
}
// 重置cseq计数
redisCatchStorage.resetAllCSEQ();
// 清理redis
// 清理数据库不存在但是redis中存在的数据
List<Device> devicesInDb = deviceService.getAll();
if (devicesInDb.size() == 0) {
redisCatchStorage.removeAllDevice();
}else {
List<Device> devicesInRedis = redisCatchStorage.getAllDevices();
if (devicesInRedis.size() > 0) {
Map<String, Device> deviceMapInDb = new HashMap<>();
devicesInDb.parallelStream().forEach(device -> {
deviceMapInDb.put(device.getDeviceId(), device);
});
devicesInRedis.parallelStream().forEach(device -> {
if (deviceMapInDb.get(device.getDeviceId()) == null) {
redisCatchStorage.removeDevice(device.getDeviceId());
}
});
}
}
// 查找国标推流
List<SendRtpItem> sendRtpItems = redisCatchStorage.queryAllSendRTPServer();
if (sendRtpItems.size() > 0) {
for (SendRtpItem sendRtpItem : sendRtpItems) {
MediaServer mediaServerItem = mediaServerService.getOne(sendRtpItem.getMediaServerId());
redisCatchStorage.deleteSendRTPServer(sendRtpItem.getPlatformId(),sendRtpItem.getChannelId(), sendRtpItem.getCallId(),sendRtpItem.getStream());
if (mediaServerItem != null) {
ssrcFactory.releaseSsrc(sendRtpItem.getMediaServerId(), sendRtpItem.getSsrc());
boolean stopResult = mediaServerService.stopSendRtp(mediaServerItem, sendRtpItem.getApp(), sendRtpItem.getStream(), sendRtpItem.getSsrc());
if (stopResult) {
ParentPlatform platform = platformService.queryPlatformByServerGBId(sendRtpItem.getPlatformId());
if (platform != null) {
try {
commanderForPlatform.streamByeCmd(platform, sendRtpItem.getCallId());
} catch (InvalidArgumentException | ParseException | SipException e) {
logger.error("[命令发送失败] 国标级联 发送BYE: {}", e.getMessage());
}
}
}
}
}
}
| 210 | 703 | 913 | 5,104 |
apache_incubator-kie-optaplanner
|
incubator-kie-optaplanner/optaplanner-examples/src/main/java/org/optaplanner/examples/taskassigning/domain/solver/TaskDifficultyComparator.java
|
TaskDifficultyComparator
|
compare
|
class TaskDifficultyComparator implements Comparator<Task> {
// FIXME This class is currently unused until the @PlanningListVariable(comparator = ???) API is stable.
// See https://issues.redhat.com/browse/PLANNER-2542.
static final Comparator<Task> INCREASING_DIFFICULTY_COMPARATOR = Comparator.comparing(Task::getPriority)
.thenComparingInt(task -> task.getTaskType().getRequiredSkillList().size())
.thenComparingInt(task -> task.getTaskType().getBaseDuration())
.thenComparingLong(Task::getId);
static final Comparator<Task> DECREASING_DIFFICULTY_COMPARATOR = INCREASING_DIFFICULTY_COMPARATOR.reversed();
@Override
public int compare(Task a, Task b) {<FILL_FUNCTION_BODY>}
}
|
return DECREASING_DIFFICULTY_COMPARATOR.compare(a, b);
| 246 | 27 | 273 | 9,903 |
houbb_sensitive-word
|
sensitive-word/src/main/java/com/github/houbb/sensitive/word/bs/SensitiveWordContext.java
|
SensitiveWordContext
|
enableNumCheck
|
class SensitiveWordContext implements IWordContext {
/**
* 忽略大小写
* @since 0.0.4
*/
private boolean ignoreCase;
/**
* 忽略半角全角
* @since 0.0.4
*/
private boolean ignoreWidth;
/**
* 是否忽略数字格式
* @since 0.0.5
*/
private boolean ignoreNumStyle;
/**
* 启动单词校验
* @since 0.4.0
*/
private boolean enableWordCheck;
/**
* 是否进行敏感数字检测
* @since 0.0.6
*/
private boolean enableNumCheck;
/**
* 是否忽略中文繁简体
* @since 0.0.6
*/
private boolean ignoreChineseStyle;
/**
* 是否忽略英文的写法
* @since 0.0.6
*/
private boolean ignoreEnglishStyle;
/**
* 忽略重复词
* @since 0.0.7
*/
private boolean ignoreRepeat;
/**
* 是否进行邮箱测试
* @since 0.0.9
*/
private boolean enableEmailCheck;
/**
* 是否进行 url 测试
* @since 0.0.12
*/
private boolean enableUrlCheck;
/**
* 敏感数字检测对应的长度限制
* @since 0.2.1
*/
private int sensitiveCheckNumLen;
/**
* 检测策略
* @since 0.3.0
*/
private IWordCheck wordCheck;
/**
* 替换策略
* @since 0.3.0
*/
private IWordReplace wordReplace;
/**
* 格式化
* @since 0.3.0
*/
private IWordFormat wordFormat;
/**
* 单词 map 信息
*
* @since 0.3.2
*/
private IWordData wordData;
/**
* 单词标签
*
* @since 0.10.0
*/
private IWordTag wordTag;
/**
* 忽略的字符
* @since 0.11.0
*/
private ISensitiveWordCharIgnore charIgnore;
/**
* 敏感词结果匹配
*
* @since 0.13.0
*/
private IWordResultCondition wordResultCondition;
public IWordData wordData() {
return wordData;
}
public SensitiveWordContext wordData(IWordData wordData) {
this.wordData = wordData;
return this;
}
@Override
public IWordReplace wordReplace() {
return wordReplace;
}
public SensitiveWordContext wordReplace(IWordReplace wordReplace) {
this.wordReplace = wordReplace;
return this;
}
@Override
public IWordCheck sensitiveCheck() {
return wordCheck;
}
public SensitiveWordContext sensitiveCheck(IWordCheck sensitiveCheck) {
this.wordCheck = sensitiveCheck;
return this;
}
/**
* 私有化构造器
* @since 0.0.4
*/
private SensitiveWordContext() {
}
/**
* 新建一个对象实例
* @return 对象实例
* @since 0.0.4
*/
public static SensitiveWordContext newInstance() {
return new SensitiveWordContext();
}
@Override
public boolean ignoreCase() {
return ignoreCase;
}
@Override
public SensitiveWordContext ignoreCase(boolean ignoreCase) {
this.ignoreCase = ignoreCase;
return this;
}
@Override
public boolean ignoreWidth() {
return ignoreWidth;
}
@Override
public SensitiveWordContext ignoreWidth(boolean ignoreWidth) {
this.ignoreWidth = ignoreWidth;
return this;
}
@Override
public boolean ignoreNumStyle() {
return ignoreNumStyle;
}
@Override
public SensitiveWordContext ignoreNumStyle(boolean ignoreNumStyle) {
this.ignoreNumStyle = ignoreNumStyle;
return this;
}
public boolean enableWordCheck() {
return enableWordCheck;
}
public SensitiveWordContext enableWordCheck(boolean enableWordCheck) {
this.enableWordCheck = enableWordCheck;
return this;
}
@Override
public boolean enableNumCheck() {
return enableNumCheck;
}
@Override
public SensitiveWordContext enableNumCheck(boolean enableNumCheck) {<FILL_FUNCTION_BODY>}
@Override
public boolean ignoreChineseStyle() {
return ignoreChineseStyle;
}
@Override
public SensitiveWordContext ignoreChineseStyle(boolean ignoreChineseStyle) {
this.ignoreChineseStyle = ignoreChineseStyle;
return this;
}
@Override
public boolean ignoreEnglishStyle() {
return ignoreEnglishStyle;
}
@Override
public SensitiveWordContext ignoreEnglishStyle(boolean ignoreEnglishStyle) {
this.ignoreEnglishStyle = ignoreEnglishStyle;
return this;
}
@Override
public boolean ignoreRepeat() {
return ignoreRepeat;
}
@Override
public SensitiveWordContext ignoreRepeat(boolean ignoreRepeat) {
this.ignoreRepeat = ignoreRepeat;
return this;
}
@Override
public boolean enableEmailCheck() {
return enableEmailCheck;
}
@Override
public SensitiveWordContext enableEmailCheck(boolean enableEmailCheck) {
this.enableEmailCheck = enableEmailCheck;
return this;
}
@Override
public boolean enableUrlCheck() {
return enableUrlCheck;
}
@Override
public SensitiveWordContext enableUrlCheck(boolean enableUrlCheck) {
this.enableUrlCheck = enableUrlCheck;
return this;
}
@Override
public int sensitiveCheckNumLen() {
return sensitiveCheckNumLen;
}
@Override
public SensitiveWordContext sensitiveCheckNumLen(int sensitiveCheckNumLen) {
this.sensitiveCheckNumLen = sensitiveCheckNumLen;
return this;
}
@Override
public IWordFormat wordFormat() {
return wordFormat;
}
public SensitiveWordContext wordFormat(IWordFormat wordFormat) {
this.wordFormat = wordFormat;
return this;
}
public IWordTag wordTag() {
return wordTag;
}
public SensitiveWordContext wordTag(IWordTag wordTag) {
this.wordTag = wordTag;
return this;
}
public ISensitiveWordCharIgnore charIgnore() {
return charIgnore;
}
public SensitiveWordContext charIgnore(ISensitiveWordCharIgnore charIgnore) {
this.charIgnore = charIgnore;
return this;
}
public IWordResultCondition wordResultCondition() {
return wordResultCondition;
}
public SensitiveWordContext wordResultCondition(IWordResultCondition wordResultCondition) {
this.wordResultCondition = wordResultCondition;
return this;
}
}
|
this.enableNumCheck = enableNumCheck;
return this;
| 1,901 | 20 | 1,921 | 22,585 |
qiurunze123_miaosha
|
miaosha/miaosha-v2/miaosha-web/src/main/java/com/geekq/miaosha/interceptor/AccessKey.java
|
AccessKey
|
withExpire
|
class AccessKey extends BasePrefix {
private AccessKey(int expireSeconds, String prefix) {
super(expireSeconds, prefix);
}
public static AccessKey withExpire(int expireSeconds) {<FILL_FUNCTION_BODY>}
}
|
return new AccessKey(expireSeconds, "interceptor");
| 72 | 20 | 92 | 60,929 |
jtablesaw_tablesaw
|
tablesaw/excel/src/main/java/tech/tablesaw/io/xlsx/XlsxReadOptions.java
|
Builder
|
missingValueIndicator
|
class Builder extends ReadOptions.Builder {
protected Integer sheetIndex;
protected Builder(Source source) {
super(source);
}
protected Builder(URL url) throws IOException {
super(url);
}
public Builder(File file) {
super(file);
}
public Builder(InputStream stream) {
super(stream);
}
public Builder(Reader reader) {
super(reader);
}
@Override
public XlsxReadOptions build() {
return new XlsxReadOptions(this);
}
// Override super-class setters to return an instance of this class
@Override
public Builder header(boolean header) {
super.header(header);
return this;
}
@Override
public Builder tableName(String tableName) {
super.tableName(tableName);
return this;
}
@Override
public Builder sample(boolean sample) {
super.sample(sample);
return this;
}
@Override
public Builder dateFormat(DateTimeFormatter dateFormat) {
super.dateFormat(dateFormat);
return this;
}
@Override
public Builder timeFormat(DateTimeFormatter timeFormat) {
super.timeFormat(timeFormat);
return this;
}
@Override
public Builder dateTimeFormat(DateTimeFormatter dateTimeFormat) {
super.dateTimeFormat(dateTimeFormat);
return this;
}
@Override
public Builder locale(Locale locale) {
super.locale(locale);
return this;
}
@Override
public Builder missingValueIndicator(String... missingValueIndicators) {<FILL_FUNCTION_BODY>}
@Override
public Builder minimizeColumnSizes() {
super.minimizeColumnSizes();
return this;
}
public Builder sheetIndex(int sheetIndex) {
this.sheetIndex = sheetIndex;
return this;
}
@Override
public Builder columnTypes(ColumnType[] columnTypes) {
super.columnTypes(columnTypes);
return this;
}
@Override
public Builder columnTypes(Function<String, ColumnType> columnTypeFunction) {
super.columnTypes(columnTypeFunction);
return this;
}
@Override
public Builder columnTypesPartial(Function<String, Optional<ColumnType>> columnTypeFunction) {
super.columnTypesPartial(columnTypeFunction);
return this;
}
@Override
public Builder columnTypesPartial(Map<String, ColumnType> columnTypeByName) {
super.columnTypesPartial(columnTypeByName);
return this;
}
}
|
super.missingValueIndicator(missingValueIndicators);
return this;
| 689 | 26 | 715 | 27,182 |
sannies_mp4parser
|
mp4parser/isoparser/src/main/java/org/mp4parser/boxes/iso14496/part12/FileTypeBox.java
|
FileTypeBox
|
_parseDetails
|
class FileTypeBox extends AbstractBox {
public static final String TYPE = "ftyp";
private String majorBrand;
private long minorVersion;
private List<String> compatibleBrands = Collections.emptyList();
public FileTypeBox() {
super(TYPE);
}
public FileTypeBox(String majorBrand, long minorVersion, List<String> compatibleBrands) {
super(TYPE);
this.majorBrand = majorBrand;
this.minorVersion = minorVersion;
this.compatibleBrands = compatibleBrands;
}
protected long getContentSize() {
return 8 + compatibleBrands.size() * 4;
}
@Override
public void _parseDetails(ByteBuffer content) {<FILL_FUNCTION_BODY>}
@Override
protected void getContent(ByteBuffer byteBuffer) {
byteBuffer.put(IsoFile.fourCCtoBytes(majorBrand));
IsoTypeWriter.writeUInt32(byteBuffer, minorVersion);
for (String compatibleBrand : compatibleBrands) {
byteBuffer.put(IsoFile.fourCCtoBytes(compatibleBrand));
}
}
/**
* Gets the brand identifier.
*
* @return the brand identifier
*/
public String getMajorBrand() {
return majorBrand;
}
/**
* Sets the major brand of the file used to determine an appropriate reader.
*
* @param majorBrand the new major brand
*/
public void setMajorBrand(String majorBrand) {
this.majorBrand = majorBrand;
}
/**
* Gets an informative integer for the minor version of the major brand.
*
* @return an informative integer
* @see FileTypeBox#getMajorBrand()
*/
public long getMinorVersion() {
return minorVersion;
}
/**
* Sets the "informative integer for the minor version of the major brand".
*
* @param minorVersion the version number of the major brand
*/
public void setMinorVersion(long minorVersion) {
this.minorVersion = minorVersion;
}
/**
* Gets an array of 4-cc brands.
*
* @return the compatible brands
*/
public List<String> getCompatibleBrands() {
return compatibleBrands;
}
public void setCompatibleBrands(List<String> compatibleBrands) {
this.compatibleBrands = compatibleBrands;
}
@DoNotParseDetail
public String toString() {
StringBuilder result = new StringBuilder();
result.append("FileTypeBox[");
result.append("majorBrand=").append(getMajorBrand());
result.append(";");
result.append("minorVersion=").append(getMinorVersion());
for (String compatibleBrand : compatibleBrands) {
result.append(";");
result.append("compatibleBrand=").append(compatibleBrand);
}
result.append("]");
return result.toString();
}
}
|
majorBrand = IsoTypeReader.read4cc(content);
minorVersion = IsoTypeReader.readUInt32(content);
int compatibleBrandsCount = content.remaining() / 4;
compatibleBrands = new LinkedList<String>();
for (int i = 0; i < compatibleBrandsCount; i++) {
compatibleBrands.add(IsoTypeReader.read4cc(content));
}
| 789 | 110 | 899 | 39,811 |
apache_incubator-kie-optaplanner
|
incubator-kie-optaplanner/core/optaplanner-constraint-streams-bavet/src/main/java/org/optaplanner/constraint/streams/bavet/bi/AbstractGroupBiNode.java
|
AbstractGroupBiNode
|
accumulate
|
class AbstractGroupBiNode<OldA, OldB, OutTuple_ extends Tuple, MutableOutTuple_ extends OutTuple_, GroupKey_, ResultContainer_, Result_>
extends AbstractGroupNode<BiTuple<OldA, OldB>, OutTuple_, MutableOutTuple_, GroupKey_, ResultContainer_, Result_> {
private final TriFunction<ResultContainer_, OldA, OldB, Runnable> accumulator;
protected AbstractGroupBiNode(int groupStoreIndex, int undoStoreIndex,
Function<BiTuple<OldA, OldB>, GroupKey_> groupKeyFunction,
BiConstraintCollector<OldA, OldB, ResultContainer_, Result_> collector,
TupleLifecycle<OutTuple_> nextNodesTupleLifecycle, EnvironmentMode environmentMode) {
super(groupStoreIndex, undoStoreIndex, groupKeyFunction,
collector == null ? null : collector.supplier(),
collector == null ? null : collector.finisher(),
nextNodesTupleLifecycle, environmentMode);
accumulator = collector == null ? null : collector.accumulator();
}
protected AbstractGroupBiNode(int groupStoreIndex, Function<BiTuple<OldA, OldB>, GroupKey_> groupKeyFunction,
TupleLifecycle<OutTuple_> nextNodesTupleLifecycle, EnvironmentMode environmentMode) {
super(groupStoreIndex, groupKeyFunction, nextNodesTupleLifecycle, environmentMode);
accumulator = null;
}
@Override
protected final Runnable accumulate(ResultContainer_ resultContainer, BiTuple<OldA, OldB> tuple) {<FILL_FUNCTION_BODY>}
}
|
return accumulator.apply(resultContainer, tuple.getFactA(), tuple.getFactB());
| 421 | 26 | 447 | 9,452 |
crate_crate
|
crate/libs/shared/src/main/java/io/crate/common/concurrent/CompletableFutures.java
|
CompletableFutures
|
allSuccessfulAsList
|
class CompletableFutures {
private CompletableFutures() {
}
/**
* Return a new {@link CompletableFuture} that is completed when all of the given futures
* complete. The future contains a List containing the results of all futures that completed successfully.
*
* Failed futures are skipped. Their result is not included in the result list.
*/
public static <T> CompletableFuture<List<T>> allSuccessfulAsList(Collection<? extends CompletableFuture<? extends T>> futures) {<FILL_FUNCTION_BODY>}
/**
* Return a new {@link CompletableFuture} that is completed when all of the given futures
* complete. The future contains a List containing the result of all futures.
*
* If any future failed, the result is a failed future.
*/
public static <T> CompletableFuture<List<T>> allAsList(Collection<? extends CompletableFuture<? extends T>> futures) {
return CompletableFuture.allOf(futures.toArray(new CompletableFuture[0]))
.thenApply(aVoid -> {
ArrayList<T> results = new ArrayList<>(futures.size());
for (CompletableFuture<? extends T> future : futures) {
results.add(future.join());
}
return results;
});
}
@SuppressForbidden(reason = "This is the wrapper for supplyAsync that should be used - it handles exceptions")
public static <T> CompletableFuture<T> supplyAsync(Supplier<T> supplier, Executor executor) {
try {
return CompletableFuture.supplyAsync(supplier, executor);
} catch (Exception e) {
return CompletableFuture.failedFuture(e);
}
}
}
|
return CompletableFuture.allOf(futures.toArray(new CompletableFuture[0]))
.handle((ignored, ignoredErr) -> {
ArrayList<T> results = new ArrayList<>(futures.size());
for (CompletableFuture<? extends T> future : futures) {
if (future.isCompletedExceptionally()) {
continue;
}
results.add(future.join());
}
return results;
});
| 447 | 118 | 565 | 16,457 |
apache_hertzbeat
|
hertzbeat/manager/src/main/java/org/apache/hertzbeat/manager/scheduler/SchedulerInit.java
|
SchedulerInit
|
run
|
class SchedulerInit implements CommandLineRunner {
@Autowired
private CollectorScheduling collectorScheduling;
@Autowired
private CollectJobScheduling collectJobScheduling;
private static final String MAIN_COLLECTOR_NODE_IP = "127.0.0.1";
@Autowired
private AppService appService;
@Autowired
private MonitorDao monitorDao;
@Autowired
private ParamDao paramDao;
@Autowired
private CollectorDao collectorDao;
@Autowired
private CollectorMonitorBindDao collectorMonitorBindDao;
@Override
public void run(String... args) throws Exception {<FILL_FUNCTION_BODY>}
}
|
// init pre collector status
List<Collector> collectors = collectorDao.findAll().stream()
.peek(item -> item.setStatus(CommonConstants.COLLECTOR_STATUS_OFFLINE))
.collect(Collectors.toList());
collectorDao.saveAll(collectors);
// insert default consistent node
CollectorInfo collectorInfo = CollectorInfo.builder()
.name(CommonConstants.MAIN_COLLECTOR_NODE)
.ip(MAIN_COLLECTOR_NODE_IP)
.build();
collectorScheduling.collectorGoOnline(CommonConstants.MAIN_COLLECTOR_NODE, collectorInfo);
// init jobs
List<Monitor> monitors = monitorDao.findMonitorsByStatusNotInAndAndJobIdNotNull(List.of((byte) 0));
List<CollectorMonitorBind> monitorBinds = collectorMonitorBindDao.findAll();
Map<Long, String> monitorIdCollectorMap = monitorBinds.stream().collect(
Collectors.toMap(CollectorMonitorBind::getMonitorId, CollectorMonitorBind::getCollector));
for (Monitor monitor : monitors) {
try {
// 构造采集任务Job实体
Job appDefine = appService.getAppDefine(monitor.getApp());
if (CommonConstants.PROMETHEUS.equals(monitor.getApp())) {
appDefine.setApp(CommonConstants.PROMETHEUS_APP_PREFIX + monitor.getName());
}
appDefine.setId(monitor.getJobId());
appDefine.setMonitorId(monitor.getId());
appDefine.setInterval(monitor.getIntervals());
appDefine.setCyclic(true);
appDefine.setTimestamp(System.currentTimeMillis());
List<Param> params = paramDao.findParamsByMonitorId(monitor.getId());
List<Configmap> configmaps = params.stream()
.map(param -> new Configmap(param.getField(), param.getValue(),
param.getType())).collect(Collectors.toList());
List<ParamDefine> paramDefaultValue = appDefine.getParams().stream()
.filter(item -> StringUtils.hasText(item.getDefaultValue()))
.collect(Collectors.toList());
paramDefaultValue.forEach(defaultVar -> {
if (configmaps.stream().noneMatch(item -> item.getKey().equals(defaultVar.getField()))) {
// todo type
Configmap configmap = new Configmap(defaultVar.getField(), defaultVar.getDefaultValue(), (byte) 1);
configmaps.add(configmap);
}
});
appDefine.setConfigmap(configmaps);
String collector = monitorIdCollectorMap.get(monitor.getId());
long jobId = collectJobScheduling.addAsyncCollectJob(appDefine, collector);
monitor.setJobId(jobId);
monitorDao.save(monitor);
} catch (Exception e) {
log.error("init monitor job: {} error,continue next monitor", monitor, e);
}
}
| 208 | 772 | 980 | 7,211 |
speedment_speedment
|
speedment/runtime-parent/runtime-core/src/main/java/com/speedment/runtime/core/internal/db/SqlQueryLoggerUtil.java
|
SqlQueryLoggerUtil
|
logOperation
|
class SqlQueryLoggerUtil {
private SqlQueryLoggerUtil() {}
public static void logOperation(Logger logger, final String sql, final List<?> values) {<FILL_FUNCTION_BODY>}
}
|
if (logger.getLevel().isEqualOrLowerThan(Level.DEBUG)) {
final String text = sql + " " + values.stream()
.map(o -> o == null
? "null"
: o.getClass().getSimpleName() + " " + o.toString())
.collect(Collectors.joining(", ", "[", "]"));
logger.debug(text);
}
| 55 | 105 | 160 | 42,616 |
alibaba_nacos
|
nacos/core/src/main/java/com/alibaba/nacos/core/control/http/HttpTpsPointRegistry.java
|
HttpTpsPointRegistry
|
onApplicationEvent
|
class HttpTpsPointRegistry implements ApplicationListener<ContextRefreshedEvent> {
private volatile AtomicBoolean isInit = new AtomicBoolean(false);
@Override
public void onApplicationEvent(ContextRefreshedEvent event) {<FILL_FUNCTION_BODY>}
}
|
if (!isInit.compareAndSet(false, true)) {
return;
}
RequestMappingHandlerMapping requestMapping = event.getApplicationContext()
.getBean("requestMappingHandlerMapping", RequestMappingHandlerMapping.class);
Map<RequestMappingInfo, HandlerMethod> handlerMethods = requestMapping.getHandlerMethods();
for (HandlerMethod handlerMethod : handlerMethods.values()) {
Method method = handlerMethod.getMethod();
if (method.isAnnotationPresent(TpsControl.class) && TpsControlConfig.isTpsControlEnabled()) {
TpsControl tpsControl = method.getAnnotation(TpsControl.class);
String pointName = tpsControl.pointName();
ControlManagerCenter.getInstance().getTpsControlManager().registerTpsPoint(pointName);
}
}
| 73 | 197 | 270 | 51,886 |
jOOQ_jOOQ
|
jOOQ/jOOQ/src/main/java/org/jooq/impl/UDTFieldImpl.java
|
UDTFieldImpl
|
getUDT
|
class UDTFieldImpl<R extends UDTRecord<R>, T> extends AbstractField<T> implements UDTField<R, T>, UNotYetImplemented, TypedReference<T> {
private final UDT<R> udt;
UDTFieldImpl(Name name, DataType<T> type, UDT<R> udt, Comment comment, Binding<?, T> binding) {
super(name, type, comment, binding);
this.udt = udt;
// [#1199] The public API of UDT returns immutable field lists
if (udt instanceof UDTImpl<?> u)
u.fields0().add(this);
}
@Override
public final UDT<R> getUDT() {<FILL_FUNCTION_BODY>}
@Override
public final void accept(Context<?> ctx) {
ctx.literal(getName());
}
}
|
return udt;
| 242 | 10 | 252 | 58,550 |
questdb_questdb
|
questdb/core/src/main/java/io/questdb/griffin/engine/functions/catalogue/PrefixedCurrentSchemasFunctionFactory.java
|
PrefixedCurrentSchemasFunctionFactory
|
getSignature
|
class PrefixedCurrentSchemasFunctionFactory extends CurrentSchemasFunctionFactory {
@Override
public String getSignature() {<FILL_FUNCTION_BODY>}
}
|
return "pg_catalog.current_schemas(T)";
| 43 | 19 | 62 | 61,520 |
alibaba_nacos
|
nacos/prometheus/src/main/java/com/alibaba/nacos/prometheus/exception/PrometheusApiExceptionHandler.java
|
PrometheusApiExceptionHandler
|
handleNacosException
|
class PrometheusApiExceptionHandler {
private static final Logger LOGGER = LoggerFactory.getLogger(PrometheusApiExceptionHandler.class);
@ExceptionHandler(NacosException.class)
public ResponseEntity<Result<String>> handleNacosException(NacosException e) {<FILL_FUNCTION_BODY>}
@ExceptionHandler(NacosRuntimeException.class)
public ResponseEntity<Result<String>> handleNacosRuntimeException(NacosRuntimeException e) {
LOGGER.error("got exception. {}", e.getMessage());
return ResponseEntity.status(e.getErrCode()).body(Result.failure(e.getMessage()));
}
}
|
LOGGER.error("got exception. {}", e.getErrMsg());
return ResponseEntity.internalServerError().body(Result.failure(e.getErrMsg()));
| 175 | 44 | 219 | 51,878 |
alibaba_nacos
|
nacos/config/src/main/java/com/alibaba/nacos/config/server/model/ConfigMetadata.java
|
ConfigExportItem
|
setMetadata
|
class ConfigExportItem {
private String group;
private String dataId;
private String desc;
private String type;
private String appName;
public String getGroup() {
return group;
}
public void setGroup(String group) {
this.group = group;
}
public String getDataId() {
return dataId;
}
public void setDataId(String dataId) {
this.dataId = dataId;
}
public String getDesc() {
return desc;
}
public void setDesc(String desc) {
this.desc = desc;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getAppName() {
return appName;
}
public void setAppName(String appName) {
this.appName = appName;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
ConfigExportItem that = (ConfigExportItem) o;
return Objects.equals(group, that.group) && Objects.equals(dataId, that.dataId) && Objects
.equals(desc, that.desc) && Objects.equals(type, that.type) && Objects
.equals(appName, that.appName);
}
@Override
public int hashCode() {
return Objects.hash(group, dataId, desc, type, appName);
}
}
public List<ConfigExportItem> getMetadata() {
return metadata;
}
public void setMetadata(List<ConfigExportItem> metadata) {<FILL_FUNCTION_BODY>
|
this.metadata = metadata;
| 509 | 11 | 520 | 51,043 |
alibaba_nacos
|
nacos/config/src/main/java/com/alibaba/nacos/config/server/service/ClientTrackService.java
|
ClientTrackService
|
listSubStatus
|
class ClientTrackService {
/**
* Put the specified value(ip/groupKey/clientMd5) into clientRecords Map.
*
* @param ip ip string value.
* @param groupKey groupKey string value.
* @param clientMd5 clientMd5 string value.
*/
public static void trackClientMd5(String ip, String groupKey, String clientMd5) {
ClientRecord record = getClientRecord(ip);
record.setLastTime(System.currentTimeMillis());
record.getGroupKey2md5Map().put(groupKey, clientMd5);
record.getGroupKey2pollingTsMap().put(groupKey, record.getLastTime());
}
/**
* Get subscribe client count.
*
* @return subscribe client count.
*/
public static int subscribeClientCount() {
return clientRecords.size();
}
/**
* Get all of subscriber count.
*
* @return all of subscriber count.
*/
public static long subscriberCount() {
long count = 0;
for (ClientRecord record : clientRecords.values()) {
count += record.getGroupKey2md5Map().size();
}
return count;
}
/**
* Groupkey -> SubscriberStatus.
*/
public static Map<String, SubscriberStatus> listSubStatus(String ip) {<FILL_FUNCTION_BODY>}
/**
* Specify subscriber's ip and look up whether data is latest.
* groupKey -> isUptodate.
*/
public static Map<String, Boolean> isClientUptodate(String ip) {
Map<String, Boolean> result = new HashMap<>(100);
for (Map.Entry<String, String> entry : getClientRecord(ip).getGroupKey2md5Map().entrySet()) {
String groupKey = entry.getKey();
String clientMd5 = entry.getValue();
Boolean isuptodate = ConfigCacheService.isUptodate(groupKey, clientMd5);
result.put(groupKey, isuptodate);
}
return result;
}
/**
* Get and return the record of specified client ip.
*
* @param clientIp clientIp string value.
* @return the record of specified client ip.
*/
private static ClientRecord getClientRecord(String clientIp) {
ClientRecord record = clientRecords.get(clientIp);
if (null != record) {
return record;
}
ClientRecord clientRecord = new ClientRecord(clientIp);
record = clientRecords.putIfAbsent(clientIp, clientRecord);
return null == record ? clientRecord : record;
}
public static void refreshClientRecord() {
clientRecords = new ConcurrentHashMap<>(50);
}
/**
* All of client records, adding or deleting.
*/
static volatile ConcurrentMap<String, ClientRecord> clientRecords = new ConcurrentHashMap<>();
}
|
Map<String, SubscriberStatus> status = new HashMap<>(100);
// record here is non-null
ClientRecord record = getClientRecord(ip);
for (Map.Entry<String, String> entry : record.getGroupKey2md5Map().entrySet()) {
String groupKey = entry.getKey();
String clientMd5 = entry.getValue();
long lastPollingTs = record.getGroupKey2pollingTsMap().get(groupKey);
boolean isUpdate = ConfigCacheService.isUptodate(groupKey, clientMd5);
status.put(groupKey, new SubscriberStatus(groupKey, isUpdate, clientMd5, lastPollingTs));
}
return status;
| 789 | 192 | 981 | 51,366 |
apache_shenyu
|
shenyu/shenyu-plugin/shenyu-plugin-fault-tolerance/shenyu-plugin-resilience4j/src/main/java/org/apache/shenyu/plugin/resilience4j/Resilience4JPlugin.java
|
Resilience4JPlugin
|
combined
|
class Resilience4JPlugin extends AbstractShenyuPlugin {
private final CombinedExecutor combinedExecutor;
private final RateLimiterExecutor ratelimiterExecutor;
public Resilience4JPlugin(final CombinedExecutor combinedExecutor,
final RateLimiterExecutor ratelimiterExecutor) {
this.combinedExecutor = combinedExecutor;
this.ratelimiterExecutor = ratelimiterExecutor;
}
@Override
protected Mono<Void> doExecute(final ServerWebExchange exchange, final ShenyuPluginChain chain, final SelectorData selector, final RuleData rule) {
final ShenyuContext shenyuContext = exchange.getAttribute(Constants.CONTEXT);
Objects.requireNonNull(shenyuContext);
Resilience4JHandle resilience4JHandle = Resilience4JHandler.CACHED_HANDLE.get().obtainHandle(CacheKeyUtils.INST.getKey(rule));
resilience4JHandle.checkData(resilience4JHandle);
if (resilience4JHandle.getCircuitEnable() == 1) {
return combined(exchange, chain, rule);
}
return rateLimiter(exchange, chain, rule);
}
private Mono<Void> rateLimiter(final ServerWebExchange exchange, final ShenyuPluginChain chain, final RuleData rule) {
return ratelimiterExecutor.run(
chain.execute(exchange), fallback(ratelimiterExecutor, exchange, null), Resilience4JBuilder.build(rule))
.onErrorResume(throwable -> ratelimiterExecutor.withoutFallback(exchange, throwable));
}
private Mono<Void> combined(final ServerWebExchange exchange, final ShenyuPluginChain chain, final RuleData rule) {<FILL_FUNCTION_BODY>}
private Function<Throwable, Mono<Void>> fallback(final Executor executor,
final ServerWebExchange exchange, final String uri) {
return throwable -> executor.fallback(exchange, UriUtils.createUri(uri), throwable).doFinally(monoV -> {
final Consumer<HttpStatus> consumer = exchange.getAttribute(Constants.METRICS_RESILIENCE4J);
Optional.ofNullable(consumer).ifPresent(c -> c.accept(exchange.getResponse().getStatusCode()));
});
}
@Override
public int getOrder() {
return PluginEnum.RESILIENCE4J.getCode();
}
@Override
public String named() {
return PluginEnum.RESILIENCE4J.getName();
}
public static class CircuitBreakerStatusCodeException extends HttpStatusCodeException {
public CircuitBreakerStatusCodeException(final HttpStatus statusCode) {
super(statusCode);
}
}
}
|
Resilience4JConf conf = Resilience4JBuilder.build(rule);
return combinedExecutor.run(
chain.execute(exchange).doOnSuccess(v -> {
HttpStatus status = exchange.getResponse().getStatusCode();
if (Objects.isNull(status) || !status.is2xxSuccessful()) {
exchange.getResponse().setStatusCode(null);
throw new CircuitBreakerStatusCodeException(Objects.isNull(status) ? HttpStatus.INTERNAL_SERVER_ERROR : status);
}
}), fallback(combinedExecutor, exchange, conf.getFallBackUri()), conf);
| 724 | 157 | 881 | 68,522 |
apache_rocketmq
|
rocketmq/tools/src/main/java/org/apache/rocketmq/tools/command/message/SendMessageCommand.java
|
SendMessageCommand
|
execute
|
class SendMessageCommand implements SubCommand {
private DefaultMQProducer producer;
@Override
public String commandName() {
return "sendMessage";
}
@Override
public String commandDesc() {
return "Send a message.";
}
@Override
public Options buildCommandlineOptions(Options options) {
Option opt = new Option("t", "topic", true, "Topic name");
opt.setRequired(true);
options.addOption(opt);
opt = new Option("p", "body", true, "UTF-8 string format of the message body");
opt.setRequired(true);
options.addOption(opt);
opt = new Option("k", "key", true, "Message keys");
opt.setRequired(false);
options.addOption(opt);
opt = new Option("c", "tags", true, "Message tags");
opt.setRequired(false);
options.addOption(opt);
opt = new Option("b", "broker", true, "Send message to target broker");
opt.setRequired(false);
options.addOption(opt);
opt = new Option("i", "qid", true, "Send message to target queue");
opt.setRequired(false);
options.addOption(opt);
opt = new Option("m", "msgTraceEnable", true, "Message Trace Enable, Default: false");
opt.setRequired(false);
options.addOption(opt);
return options;
}
private DefaultMQProducer createProducer(RPCHook rpcHook, boolean msgTraceEnable) {
if (this.producer != null) {
return producer;
} else {
producer = new DefaultMQProducer(null, rpcHook, msgTraceEnable, null);
producer.setProducerGroup(Long.toString(System.currentTimeMillis()));
return producer;
}
}
@Override
public void execute(CommandLine commandLine, Options options, RPCHook rpcHook) throws SubCommandException {<FILL_FUNCTION_BODY>}
}
|
Message msg = null;
String topic = commandLine.getOptionValue('t').trim();
String body = commandLine.getOptionValue('p').trim();
String tag = null;
String keys = null;
String brokerName = null;
int queueId = -1;
try {
if (commandLine.hasOption('k')) {
keys = commandLine.getOptionValue('k').trim();
}
if (commandLine.hasOption('c')) {
tag = commandLine.getOptionValue('c').trim();
}
if (commandLine.hasOption('b')) {
brokerName = commandLine.getOptionValue('b').trim();
}
if (commandLine.hasOption('i')) {
if (!commandLine.hasOption('b')) {
System.out.print("Broker name must be set if the queue is chosen!");
return;
} else {
queueId = Integer.parseInt(commandLine.getOptionValue('i').trim());
}
}
msg = new Message(topic, tag, keys, body.getBytes(StandardCharsets.UTF_8));
} catch (Exception e) {
throw new RuntimeException(this.getClass().getSimpleName() + " command failed", e);
}
boolean msgTraceEnable = false;
if (commandLine.hasOption('m')) {
msgTraceEnable = Boolean.parseBoolean(commandLine.getOptionValue('m').trim());
}
DefaultMQProducer producer = this.createProducer(rpcHook, msgTraceEnable);
SendResult result;
try {
producer.start();
if (brokerName != null && queueId > -1) {
MessageQueue messageQueue = new MessageQueue(topic, brokerName, queueId);
result = producer.send(msg, messageQueue);
} else {
result = producer.send(msg);
}
} catch (Exception e) {
throw new RuntimeException(this.getClass().getSimpleName() + " command failed", e);
} finally {
producer.shutdown();
}
System.out.printf("%-32s %-4s %-20s %s%n",
"#Broker Name",
"#QID",
"#Send Result",
"#MsgId"
);
if (result != null) {
System.out.printf("%-32s %-4s %-20s %s%n",
result.getMessageQueue().getBrokerName(),
result.getMessageQueue().getQueueId(),
result.getSendStatus(),
result.getMsgId()
);
} else {
System.out.printf("%-32s %-4s %-20s %s%n",
"Unknown",
"Unknown",
"Failed",
"None"
);
}
| 528 | 717 | 1,245 | 53,746 |
pig-mesh_pig
|
pig/pig-common/pig-common-oss/src/main/java/com/pig4cloud/pig/common/file/oss/http/OssEndpoint.java
|
OssEndpoint
|
deleteObject
|
class OssEndpoint {
private final OssTemplate template;
/**
* Bucket Endpoints
*/
@SneakyThrows
@PostMapping("/bucket/{bucketName}")
public Bucket createBucket(@PathVariable String bucketName) {
template.createBucket(bucketName);
return template.getBucket(bucketName).get();
}
@SneakyThrows
@GetMapping("/bucket")
public List<Bucket> getBuckets() {
return template.getAllBuckets();
}
@SneakyThrows
@GetMapping("/bucket/{bucketName}")
public Bucket getBucket(@PathVariable String bucketName) {
return template.getBucket(bucketName).orElseThrow(() -> new IllegalArgumentException("Bucket Name not found!"));
}
@SneakyThrows
@DeleteMapping("/bucket/{bucketName}")
@ResponseStatus(HttpStatus.ACCEPTED)
public void deleteBucket(@PathVariable String bucketName) {
template.removeBucket(bucketName);
}
/**
* Object Endpoints
*/
@SneakyThrows
@PostMapping("/object/{bucketName}")
public S3Object createObject(@RequestBody MultipartFile object, @PathVariable String bucketName) {
String name = object.getOriginalFilename();
@Cleanup
InputStream inputStream = object.getInputStream();
template.putObject(bucketName, name, inputStream, object.getSize(), object.getContentType());
return template.getObjectInfo(bucketName, name);
}
@SneakyThrows
@PostMapping("/object/{bucketName}/{objectName}")
public S3Object createObject(@RequestBody MultipartFile object, @PathVariable String bucketName,
@PathVariable String objectName) {
@Cleanup
InputStream inputStream = object.getInputStream();
template.putObject(bucketName, objectName, inputStream, object.getSize(), object.getContentType());
return template.getObjectInfo(bucketName, objectName);
}
@SneakyThrows
@GetMapping("/object/{bucketName}/{objectName}")
public List<S3ObjectSummary> filterObject(@PathVariable String bucketName, @PathVariable String objectName) {
return template.getAllObjectsByPrefix(bucketName, objectName, true);
}
@SneakyThrows
@GetMapping("/object/{bucketName}/{objectName}/{expires}")
public Map<String, Object> getObject(@PathVariable String bucketName, @PathVariable String objectName,
@PathVariable Integer expires) {
Map<String, Object> responseBody = new HashMap<>(8);
// Put Object info
responseBody.put("bucket", bucketName);
responseBody.put("object", objectName);
responseBody.put("url", template.getObjectURL(bucketName, objectName, expires));
responseBody.put("expires", expires);
return responseBody;
}
@SneakyThrows
@ResponseStatus(HttpStatus.ACCEPTED)
@DeleteMapping("/object/{bucketName}/{objectName}/")
public void deleteObject(@PathVariable String bucketName, @PathVariable String objectName) {<FILL_FUNCTION_BODY>}
}
|
template.removeObject(bucketName, objectName);
| 825 | 19 | 844 | 37,354 |
apache_incubator-kie-optaplanner
|
incubator-kie-optaplanner/optaplanner-persistence/optaplanner-persistence-jpa/src/main/java/org/optaplanner/persistence/jpa/api/score/buildin/hardmediumsoftbigdecimal/HardMediumSoftBigDecimalScoreConverter.java
|
HardMediumSoftBigDecimalScoreConverter
|
convertToEntityAttribute
|
class HardMediumSoftBigDecimalScoreConverter implements AttributeConverter<HardMediumSoftBigDecimalScore, String> {
@Override
public String convertToDatabaseColumn(HardMediumSoftBigDecimalScore score) {
if (score == null) {
return null;
}
return score.toString();
}
@Override
public HardMediumSoftBigDecimalScore convertToEntityAttribute(String scoreString) {<FILL_FUNCTION_BODY>}
}
|
if (scoreString == null) {
return null;
}
return HardMediumSoftBigDecimalScore.parseScore(scoreString);
| 121 | 40 | 161 | 9,263 |
apache_incubator-hugegraph
|
incubator-hugegraph/hugegraph-server/hugegraph-core/src/main/java/org/apache/hugegraph/traversal/algorithm/SubGraphTraverser.java
|
Traverser
|
reachLimit
|
class Traverser {
private final Id source;
private final Id label;
private final long degree;
private final long capacity;
private final long limit;
private final boolean rings;
private final boolean sourceInRing;
private final Set<Id> accessedVertices = newIdSet();
private final EdgeRecord edgeRecord;
private MultivaluedMap<Id, Node> sources = newMultivalueMap();
private int depth;
private long pathCount;
private long edgeCount;
public Traverser(Id sourceV, Id label, int depth, long degree,
long capacity, long limit, boolean rings,
boolean sourceInRing) {
this.source = sourceV;
this.sources.add(sourceV, new Node(sourceV));
this.accessedVertices.add(sourceV);
this.label = label;
this.depth = depth;
this.degree = degree;
this.capacity = capacity;
this.limit = limit;
this.rings = rings;
this.sourceInRing = sourceInRing;
this.pathCount = 0L;
this.edgeCount = 0L;
this.edgeRecord = new EdgeRecord(false);
}
/**
* Search forward from source
*/
public PathSet forward(Directions direction) {
PathSet paths = new PathSet();
MultivaluedMap<Id, Node> newVertices = newMultivalueMap();
Iterator<Edge> edges;
// Traversal vertices of previous level
for (Map.Entry<Id, List<Node>> entry : this.sources.entrySet()) {
Id vid = entry.getKey();
// Record edgeList to determine if multiple edges exist
List<Edge> edgeList = IteratorUtils.list(edgesOfVertex(
vid, direction, this.label, this.degree));
edges = edgeList.iterator();
if (!edges.hasNext()) {
// Reach the end, rays found
if (this.rings) {
continue;
}
for (Node n : entry.getValue()) {
// Store rays
paths.add(new Path(n.path()));
this.pathCount++;
if (this.reachLimit()) {
return paths;
}
}
}
int neighborCount = 0;
Set<Id> currentNeighbors = newIdSet();
while (edges.hasNext()) {
neighborCount++;
HugeEdge edge = (HugeEdge) edges.next();
this.edgeCount += 1L;
Id target = edge.id().otherVertexId();
this.edgeRecord.addEdge(vid, target, edge);
// Avoid deduplicate path
if (currentNeighbors.contains(target)) {
continue;
}
currentNeighbors.add(target);
this.accessedVertices.add(target);
for (Node node : entry.getValue()) {
// No ring, continue
if (!node.contains(target)) {
// Add node to next start-nodes
newVertices.add(target, new Node(target, node));
continue;
}
// Rays found if it's fake ring like:
// path is pattern: A->B<-A && A is only neighbor of B
boolean uniqueEdge = neighborCount == 1 &&
!edges.hasNext();
boolean bothBack = target.equals(node.parent().id()) &&
direction == Directions.BOTH;
if (!this.rings && bothBack && uniqueEdge) {
paths.add(new Path(node.path()));
this.pathCount++;
if (this.reachLimit()) {
return paths;
}
}
// Actual rings found
if (this.rings) {
boolean ringsFound = false;
// 1. sourceInRing is false, or
// 2. sourceInRing is true and target == source
if (!sourceInRing || target.equals(this.source)) {
if (!target.equals(node.parent().id())) {
ringsFound = true;
} else if (direction != Directions.BOTH) {
ringsFound = true;
} else if (hasMultiEdges(edgeList, target)) {
ringsFound = true;
}
}
if (ringsFound) {
List<Id> path = node.path();
path.add(target);
paths.add(new RingPath(null, path));
this.pathCount++;
if (this.reachLimit()) {
return paths;
}
}
}
}
}
}
// Re-init sources
this.sources = newVertices;
if (!this.rings && --this.depth <= 0) {
for (List<Node> list : newVertices.values()) {
for (Node n : list) {
paths.add(new Path(n.path()));
this.pathCount++;
if (this.reachLimit()) {
return paths;
}
}
}
}
return paths;
}
private boolean reachLimit() {<FILL_FUNCTION_BODY>}
private boolean finished() {
return this.sources.isEmpty();
}
}
|
checkCapacity(this.capacity, this.accessedVertices.size(),
this.rings ? "rings" : "rays");
return this.limit != NO_LIMIT && this.pathCount >= this.limit;
| 1,335 | 60 | 1,395 | 8,686 |
vert-x3_vertx-examples
|
vertx-examples/web-examples/src/main/java/io/vertx/example/web/openapi_router/RequestValidationExample.java
|
RequestValidationExample
|
start
|
class RequestValidationExample extends AbstractVerticle {
public static void main(String[] args) {
Launcher.executeCommand("run", ResponseValidationExample.class.getName());
}
private String getContractFilePath() {
Path resourceDir = Paths.get("src", "test", "resources");
Path packagePath = Paths.get(this.getClass().getPackage().getName().replace(".", "/"));
return resourceDir.resolve(packagePath).resolve("petstore.json").toString();
}
@Override
public void start(Promise<Void> startPromise) {<FILL_FUNCTION_BODY>}
}
|
OpenAPIContract.from(vertx, getContractFilePath()).compose(contract -> {
// Create the RouterBuilder
RouterBuilder routerBuilder = RouterBuilder.create(vertx, contract);
// Add handler for Operation showPetById
routerBuilder.getRoute("showPetById").addHandler(routingContext -> {
// Get the validated request
ValidatedRequest validatedRequest = routingContext.get(KEY_META_DATA_VALIDATED_REQUEST);
// Get the parameter value
int petId = validatedRequest.getPathParameters().get("petId").getInteger();
// Due to the fact that we don't validate the resonse here, you can send back a response,
// that doesn't fit to the contract
routingContext.response().setStatusCode(200).end();
});
// Create the Router
Router router = routerBuilder.createRouter();
return vertx.createHttpServer().requestHandler(router).listen(0, "localhost");
}).onSuccess(server -> System.out.println("Server started on port " + server.actualPort()))
.map((Void) null)
.onComplete(startPromise);
| 157 | 294 | 451 | 64,056 |
speedment_speedment
|
speedment/tool-parent/tool-core/src/main/java/com/speedment/tool/core/internal/util/Throttler.java
|
Throttler
|
call
|
class Throttler {
/**
* Returns a {@link Throttler} that never executes the same request more
* than once every {@code millis}.
*
* @param millis minimum frequency in milliseconds
* @return the created throttler
*/
public static Throttler limitToOnceEvery(long millis) {
return new Throttler(millis);
}
private final ConcurrentHashMap<String, AtomicLong> timers;
private final long millis;
private Throttler(long millis) {
this.millis = millis;
this.timers = new ConcurrentHashMap<>();
}
/**
* Attempts to invoke the specified {@code runnable} if no other action with
* the same specifier has been called recently. Otherwise, the method will
* return with no effect.
*
* @param action the action specifier
* @param runnable the callable action to invoke
*/
public void call(String action, Runnable runnable) {<FILL_FUNCTION_BODY>}
private static long now() {
return System.currentTimeMillis();
}
}
|
final long now = now();
final AtomicLong timer = timers.computeIfAbsent(action, a -> new AtomicLong(0));
if (now == timer.updateAndGet(
lastCall -> lastCall + millis < now
? now : lastCall
)) runnable.run();
| 309 | 81 | 390 | 42,791 |
AxonFramework_AxonFramework
|
AxonFramework/eventsourcing/src/main/java/org/axonframework/eventsourcing/eventstore/IteratorBackedDomainEventStream.java
|
IteratorBackedDomainEventStream
|
next
|
class IteratorBackedDomainEventStream implements DomainEventStream {
private final Iterator<? extends DomainEventMessage<?>> iterator;
private boolean hasPeeked;
private DomainEventMessage<?> peekEvent;
private Long sequenceNumber;
/**
* Initialize the stream which provides access to message from the given {@code iterator}
*
* @param iterator The iterator providing the messages to stream
*/
public IteratorBackedDomainEventStream(Iterator<? extends DomainEventMessage<?>> iterator) {
this.iterator = iterator;
}
@Override
public DomainEventMessage<?> peek() {
if (!hasPeeked) {
peekEvent = readNext();
hasPeeked = true;
}
return peekEvent;
}
@Override
public boolean hasNext() {
return hasPeeked || iterator.hasNext();
}
@Override
public DomainEventMessage<?> next() {<FILL_FUNCTION_BODY>}
private DomainEventMessage<?> readNext() {
DomainEventMessage<?> next = iterator.next();
this.sequenceNumber = next.getSequenceNumber();
return next;
}
@Override
public Long getLastSequenceNumber() {
return sequenceNumber;
}
}
|
if (!hasPeeked) {
return readNext();
}
DomainEventMessage<?> result = peekEvent;
peekEvent = null;
hasPeeked = false;
return result;
| 345 | 59 | 404 | 54,798 |
jitsi_jitsi
|
jitsi/modules/impl/gui/src/main/java/net/java/sip/communicator/impl/gui/main/contactlist/ContactProtocolButton.java
|
ContactProtocolButton
|
getProtocolContact
|
class ContactProtocolButton
extends SIPCommButton
{
private Contact protocolContact;
/**
* Creates an instance of ContactProtocolButton.
* @param bgImage The background image of the button.
*/
public ContactProtocolButton(Image bgImage) {
super(bgImage, bgImage);
}
/**
* Returns the specific protocol contact corresponding to this button.
* @return The specific protocol contact corresponding to this button.
*/
public Contact getProtocolContact() {<FILL_FUNCTION_BODY>}
/**
* Sets the specific protocol contact corresponding to this button.
* @param protocolContact The specific protocol contact.
*/
public void setProtocolContact(Contact protocolContact) {
this.protocolContact = protocolContact;
}
}
|
return protocolContact;
| 195 | 9 | 204 | 26,735 |
sohutv_cachecloud
|
cachecloud/cachecloud-web/src/main/java/com/sohu/cache/inspect/impl/AppClientConnInspector.java
|
AppClientConnInspector
|
inspect
|
class AppClientConnInspector extends BaseAlertService implements Inspector {
/**
* app统计相关
*/
private AppStatsCenter appStatsCenter;
/**
* 实例统计相关
*/
private InstanceStatsCenter instanceStatsCenter;
@Override
public boolean inspect(Map<InspectParamEnum, Object> paramMap) {<FILL_FUNCTION_BODY>}
/**
* 获取报警阀值(如果用户预设超过系统预设,以系统为准,反之以用户为准)
* @param appDesc
* @return
*/
private int getClientConnThreshold(AppDesc appDesc) {
int userClientConnThreshold = appDesc.getClientConnAlertValue();
int systemClientConnThreshold = ConstUtils.APP_CLIENT_CONN_THRESHOLD;
return userClientConnThreshold > systemClientConnThreshold ? systemClientConnThreshold : userClientConnThreshold;
}
/**
* 应用连接数报警
* @param appDetailVO
* @param appClientConnThreshold
* @param instanceCount
*/
private void alertAppClientConn(final AppDetailVO appDetailVO, final int appClientConnThreshold, final int instanceCount) {
AppDesc appDesc = appDetailVO.getAppDesc();
String content = String.format("应用(%s)-客户端连接数报警-预设阀值每个分片为%s-现已达到%s(分片个数:%s)-请及时关注",
appDesc.getAppId(), appClientConnThreshold, appDetailVO.getConn(), instanceCount);
String title = "CacheCloud系统-客户端连接数报警";
logger.warn("app title {}", title);
logger.warn("app content {}", content);
appAlertRecordService.saveAlertInfoByType(AlertTypeEnum.APP_CLIENT_CONNECTION, title, content, appDetailVO);
emailComponent.sendMail(title, content, appDetailVO.getEmailList(),
Arrays.asList(emailComponent.getAdminEmail().split(ConstUtils.COMMA)));
weChatComponent.sendWeChatToAll(title,content,appDetailVO.getWeChatList());
}
/**
* 单个分片连接数报警
* @param instanceStats
* @param appDetailVO
* @param appClientConnThreshold
*/
private void alertInstanceClientConn(final InstanceStats instanceStats, final AppDetailVO appDetailVO,
final int appClientConnThreshold) {
String instanceHostPort = instanceStats.getIp() + ":" + instanceStats.getPort();
String content = String.format("分片(%s,应用(%s))客户端连接数报警-预设%s-现已达到%s-请及时关注", instanceHostPort,
instanceStats.getAppId(), appClientConnThreshold, instanceStats.getCurrConnections());
String title = "CacheCloud系统-分片客户端连接数报警";
logger.warn("instance title {}", title);
logger.warn("instace content {}", content);
appAlertRecordService.saveAlertInfoByType(AlertTypeEnum.APP_SHARD_CLENT_CONNECTION, title, content, appDetailVO, instanceStats);
emailComponent.sendMail(title, content, appDetailVO.getEmailList(),
Arrays.asList(emailComponent.getAdminEmail().split(ConstUtils.COMMA)));
weChatComponent.sendWeChatToAll(title,content,appDetailVO.getWeChatList());
}
public void setAppStatsCenter(AppStatsCenter appStatsCenter) {
this.appStatsCenter = appStatsCenter;
}
public void setInstanceStatsCenter(InstanceStatsCenter instanceStatsCenter) {
this.instanceStatsCenter = instanceStatsCenter;
}
}
|
Long appId = MapUtils.getLong(paramMap, InspectParamEnum.SPLIT_KEY);
AppDetailVO appDetailVO = appStatsCenter.getAppDetail(appId);
if (appDetailVO == null) {
logger.warn("appId {} appDetailVO is empty", appId);
return true;
}
List<InstanceInfo> appInstanceInfoList = (List<InstanceInfo>) paramMap.get(InspectParamEnum.INSTANCE_LIST);
if (CollectionUtils.isEmpty(appInstanceInfoList)) {
logger.warn("appId {} instanceList is empty", appId);
return true;
}
// 报警阀值
int appClientConnThreshold = getClientConnThreshold(appDetailVO.getAppDesc());
int appClientConnNum = appDetailVO.getConn();
// 阀值乘以分片个数
int instanceCount = appInstanceInfoList.size();
if (appClientConnNum > appClientConnThreshold * instanceCount) {
alertAppClientConn(appDetailVO, appClientConnThreshold, instanceCount);
} else {
for (InstanceInfo instanceInfo : appInstanceInfoList) {
if (instanceInfo == null) {
continue;
}
if (instanceInfo.isOffline()) {
continue;
}
if (!TypeUtil.isRedisType(instanceInfo.getType())) {
continue;
}
// 忽略sentinel观察者
if (TypeUtil.isRedisSentinel(instanceInfo.getType())) {
continue;
}
long instanceId = instanceInfo.getId();
InstanceStats instanceStats = instanceStatsCenter.getInstanceStats(instanceId);
if (instanceStats == null) {
continue;
}
double instanceClientConnNum = instanceStats.getCurrConnections();
// 大于标准值
if (instanceClientConnNum > appClientConnThreshold) {
alertInstanceClientConn(instanceStats, appDetailVO, appClientConnThreshold);
}
}
}
return true;
| 1,046 | 574 | 1,620 | 3,585 |
dianping_cat
|
cat/cat-home/src/main/java/com/dianping/cat/report/alert/exception/ExceptionAlert.java
|
ExceptionAlert
|
queryTopReport
|
class ExceptionAlert implements Task {
protected static final long DURATION = TimeHelper.ONE_MINUTE;
protected static final int ALERT_PERIOD = 1;
@Inject
protected ExceptionRuleConfigManager m_exceptionConfigManager;
@Inject
protected AlertExceptionBuilder m_alertBuilder;
@Inject(type = ModelService.class, value = TopAnalyzer.ID)
protected ModelService<TopReport> m_topService;
@Inject
protected AlertManager m_sendManager;
protected TopMetric buildTopMetric(Date date) {
TopReport topReport = queryTopReport(date);
TopMetric topMetric = new TopMetric(ALERT_PERIOD, Integer.MAX_VALUE, m_exceptionConfigManager);
topMetric.setStart(date).setEnd(new Date(date.getTime() + TimeHelper.ONE_MINUTE - 1));
topMetric.visitTopReport(topReport);
return topMetric;
}
public String getName() {
return AlertType.Exception.getName();
}
private void handleExceptions(List<Item> itemList) {
Map<String, List<AlertException>> alertExceptions = m_alertBuilder.buildAlertExceptions(itemList);
//告警开关
if (alertExceptions.isEmpty()) {
return;
}
for (Entry<String, List<AlertException>> entry : alertExceptions.entrySet()) {
try {
String domain = entry.getKey();
List<AlertException> exceptions = entry.getValue();
for (AlertException exception : exceptions) {
String metricName = exception.getName();
AlertEntity entity = new AlertEntity();
entity.setDate(new Date()).setContent(exception.toString()).setLevel(exception.getType());
entity.setMetric(metricName).setType(getName()).setGroup(domain);
m_sendManager.addAlert(entity);
}
} catch (Exception e) {
Cat.logError(e);
}
}
}
protected TopReport queryTopReport(Date start) {<FILL_FUNCTION_BODY>}
@Override
public void run() {
boolean active = TimeHelper.sleepToNextMinute();
while (active) {
long current = System.currentTimeMillis();
Transaction t = Cat.newTransaction("AlertException", TimeHelper.getMinuteStr());
try {
TopMetric topMetric = buildTopMetric(new Date(current - TimeHelper.ONE_MINUTE - current%TimeHelper.ONE_MINUTE));
Collection<List<Item>> itemLists = topMetric.getError().getResult().values();
List<Item> itemList = new ArrayList<Item>();
if (!itemLists.isEmpty()) {
itemList = itemLists.iterator().next();
}
List<Item> items = new ArrayList<Item>();
for (Item item : itemList) {
if (!Constants.FRONT_END.equals(item.getDomain())) {
items.add(item);
}
}
handleExceptions(items);
t.setStatus(Transaction.SUCCESS);
} catch (Exception e) {
t.setStatus(e);
} finally {
t.complete();
}
long duration = System.currentTimeMillis() - current;
try {
if (duration < DURATION) {
Thread.sleep(DURATION - duration);
}
} catch (InterruptedException e) {
active = false;
}
}
}
@Override
public void shutdown() {
}
}
|
String domain = Constants.CAT;
String date = String.valueOf(start.getTime());
ModelRequest request = new ModelRequest(domain, start.getTime()).setProperty("date", date);
if (m_topService.isEligable(request)) {
ModelResponse<TopReport> response = m_topService.invoke(request);
TopReport report = response.getModel();
report.accept(new TopExceptionExclude(m_exceptionConfigManager));
return report;
} else {
throw new RuntimeException("Internal error: no eligable top service registered for " + request + "!");
}
| 945 | 162 | 1,107 | 69,555 |
java8_Java8InAction
|
Java8InAction/src/main/java/lambdasinaction/chap9/Game.java
|
Game
|
main
|
class Game {
public static void main(String...args){<FILL_FUNCTION_BODY>}
}
|
List<Resizable> resizableShapes =
Arrays.asList(new Square(),
new Triangle(), new Ellipse());
Utils.paint(resizableShapes);
| 30 | 50 | 80 | 58,253 |
zhkl0228_unidbg
|
unidbg/unidbg-ios/src/main/java/com/github/unidbg/ios/struct/kernel/AuditToken.java
|
AuditToken
|
getFieldOrder
|
class AuditToken extends UnidbgStructure {
public AuditToken(Pointer p) {
super(p);
}
public int[] val = new int[8];
@Override
protected List<String> getFieldOrder() {<FILL_FUNCTION_BODY>}
}
|
return Collections.singletonList("val");
| 78 | 15 | 93 | 48,556 |
apache_dubbo
|
dubbo/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/loadbalance/ConsistentHashLoadBalance.java
|
ConsistentHashSelector
|
hash
|
class ConsistentHashSelector<T> {
private final TreeMap<Long, Invoker<T>> virtualInvokers;
private final int replicaNumber;
private final int identityHashCode;
private final int[] argumentIndex;
ConsistentHashSelector(List<Invoker<T>> invokers, String methodName, int identityHashCode) {
this.virtualInvokers = new TreeMap<>();
this.identityHashCode = identityHashCode;
URL url = invokers.get(0).getUrl();
this.replicaNumber = url.getMethodParameter(methodName, HASH_NODES, 160);
String[] index = COMMA_SPLIT_PATTERN.split(url.getMethodParameter(methodName, HASH_ARGUMENTS, "0"));
argumentIndex = new int[index.length];
for (int i = 0; i < index.length; i++) {
argumentIndex[i] = Integer.parseInt(index[i]);
}
for (Invoker<T> invoker : invokers) {
String address = invoker.getUrl().getAddress();
for (int i = 0; i < replicaNumber / 4; i++) {
byte[] digest = Bytes.getMD5(address + i);
for (int h = 0; h < 4; h++) {
long m = hash(digest, h);
virtualInvokers.put(m, invoker);
}
}
}
}
public Invoker<T> select(Invocation invocation) {
String key = toKey(RpcUtils.getArguments(invocation));
byte[] digest = Bytes.getMD5(key);
return selectForKey(hash(digest, 0));
}
private String toKey(Object[] args) {
StringBuilder buf = new StringBuilder();
for (int i : argumentIndex) {
if (i >= 0 && args != null && i < args.length) {
buf.append(args[i]);
}
}
return buf.toString();
}
private Invoker<T> selectForKey(long hash) {
Map.Entry<Long, Invoker<T>> entry = virtualInvokers.ceilingEntry(hash);
if (entry == null) {
entry = virtualInvokers.firstEntry();
}
return entry.getValue();
}
private long hash(byte[] digest, int number) {<FILL_FUNCTION_BODY>}
}
|
return (((long) (digest[3 + number * 4] & 0xFF) << 24)
| ((long) (digest[2 + number * 4] & 0xFF) << 16)
| ((long) (digest[1 + number * 4] & 0xFF) << 8)
| (digest[number * 4] & 0xFF))
& 0xFFFFFFFFL;
| 627 | 112 | 739 | 67,644 |
apache_maven
|
maven/maven-compat/src/main/java/org/apache/maven/execution/DefaultRuntimeInformation.java
|
DefaultRuntimeInformation
|
initialize
|
class DefaultRuntimeInformation implements RuntimeInformation, Initializable {
@Inject
private org.apache.maven.rtinfo.RuntimeInformation rtInfo;
private ArtifactVersion applicationVersion;
public ArtifactVersion getApplicationVersion() {
return applicationVersion;
}
public void initialize() throws InitializationException {<FILL_FUNCTION_BODY>}
}
|
String mavenVersion = rtInfo.getMavenVersion();
if (mavenVersion == null || mavenVersion.isEmpty()) {
throw new InitializationException("Unable to read Maven version from maven-core");
}
applicationVersion = new DefaultArtifactVersion(mavenVersion);
| 93 | 75 | 168 | 11,007 |
jetlinks_jetlinks-community
|
jetlinks-community/jetlinks-components/script-component/src/main/java/org/jetlinks/community/script/jsr223/Jsr223ScriptFactory.java
|
Console
|
trace
|
class Console {
private final Logger logger;
public void trace(String text, Object... args) {<FILL_FUNCTION_BODY>}
public void warn(String text, Object... args) {
logger.warn(text, args);
}
public void log(String text, Object... args) {
logger.debug(text, args);
}
public void error(String text, Object... args) {
logger.error(text, args);
}
}
|
logger.trace(text, args);
| 126 | 13 | 139 | 25,575 |
ainilili_ratel
|
ratel/landlords-common/src/main/java/org/nico/ratel/landlords/handler/DefaultDecoder.java
|
DefaultDecoder
|
decode
|
class DefaultDecoder extends ByteToMessageDecoder {
@Override
protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) {<FILL_FUNCTION_BODY>}
}
|
int startIndex;
int endIndex;
if ((startIndex = in.indexOf(in.readerIndex(), in.writerIndex(), TransferProtocolUtils.PROTOCOL_HAED)) != -1 &&
(endIndex = in.indexOf(startIndex + 1, in.writerIndex(), TransferProtocolUtils.PROTOCOL_TAIL)) != -1) {
endIndex++;
byte[] bytes = new byte[endIndex - startIndex];
in.skipBytes(startIndex - in.readerIndex());
in.readBytes(bytes, 0, bytes.length);
out.add(bytes);
}
| 54 | 157 | 211 | 5,578 |
iluwatar_java-design-patterns
|
java-design-patterns/cqrs/src/main/java/com/iluwatar/cqrs/app/App.java
|
App
|
main
|
class App {
/**
* Program entry point.
*
* @param args command line args
*/
public static void main(String[] args) {<FILL_FUNCTION_BODY>}
}
|
var commands = new CommandServiceImpl();
// Create Authors and Books using CommandService
commands.authorCreated(AppConstants.E_EVANS, "Eric Evans", "evans@email.com");
commands.authorCreated(AppConstants.J_BLOCH, "Joshua Bloch", "jBloch@email.com");
commands.authorCreated(AppConstants.M_FOWLER, "Martin Fowler", "mFowler@email.com");
commands.bookAddedToAuthor("Domain-Driven Design", 60.08, AppConstants.E_EVANS);
commands.bookAddedToAuthor("Effective Java", 40.54, AppConstants.J_BLOCH);
commands.bookAddedToAuthor("Java Puzzlers", 39.99, AppConstants.J_BLOCH);
commands.bookAddedToAuthor("Java Concurrency in Practice", 29.40, AppConstants.J_BLOCH);
commands.bookAddedToAuthor("Patterns of Enterprise"
+ " Application Architecture", 54.01, AppConstants.M_FOWLER);
commands.bookAddedToAuthor("Domain Specific Languages", 48.89, AppConstants.M_FOWLER);
commands.authorNameUpdated(AppConstants.E_EVANS, "Eric J. Evans");
var queries = new QueryServiceImpl();
// Query the database using QueryService
var nullAuthor = queries.getAuthorByUsername("username");
var evans = queries.getAuthorByUsername(AppConstants.E_EVANS);
var blochBooksCount = queries.getAuthorBooksCount(AppConstants.J_BLOCH);
var authorsCount = queries.getAuthorsCount();
var dddBook = queries.getBook("Domain-Driven Design");
var blochBooks = queries.getAuthorBooks(AppConstants.J_BLOCH);
LOGGER.info("Author username : {}", nullAuthor);
LOGGER.info("Author evans : {}", evans);
LOGGER.info("jBloch number of books : {}", blochBooksCount);
LOGGER.info("Number of authors : {}", authorsCount);
LOGGER.info("DDD book : {}", dddBook);
LOGGER.info("jBloch books : {}", blochBooks);
HibernateUtil.getSessionFactory().close();
| 57 | 603 | 660 | 347 |
knowm_XChange
|
XChange/xchange-okcoin/src/main/java/org/knowm/xchange/okcoin/v3/dto/trade/OkexFuturesOpenOrder.java
|
OkexFuturesOpenOrder
|
getTimestamp
|
class OkexFuturesOpenOrder {
@JsonProperty("instrument_id")
/** Contract ID, e.g. “BTC-USD-180213” */
private String instrumentId;
@JsonProperty("client_oid")
/** String the order ID customised by yourself */
private String clientOid;
/** Quantity */
private BigDecimal size;
/** Order creation date */
private String timestamp;
@JsonProperty("filled_qty")
/** Filled quantity */
private BigDecimal filledQty;
/** Fees */
private String fee;
@JsonProperty("order_id")
/** order ID */
private String orderId;
/** Order Price */
private BigDecimal price;
@JsonProperty("price_avg")
/** Average price */
private BigDecimal priceAvg;
/** Type (1: open long 2: open short 3: close long 4: close short) */
private FuturesSwapType type;
/** Contract Value */
@JsonProperty("contract_val")
private BigDecimal contractVal;
/** Leverage , 1-100x */
private BigDecimal leverage;
@JsonProperty("order_type")
/** 0: Normal limit order 1: Post only 2: Fill Or Kill 3: Immediatel Or Cancel */
private OrderPlacementType orderType;
/** profit */
private BigDecimal pnl;
/**
* Order Status("-2":Failed,"-1":Cancelled,"0":Open ,"1":Partially Filled, "2":Fully
* Filled,"3":Submitting,"4":Cancelling,)
*/
private String state;
public Date getTimestamp() {<FILL_FUNCTION_BODY>}
}
|
return Date.from(Instant.parse(timestamp));
| 471 | 17 | 488 | 27,872 |
hs-web_hsweb-framework
|
hsweb-framework/hsweb-authorization/hsweb-authorization-basic/src/main/java/org/hswebframework/web/authorization/basic/handler/UserAllowPermissionHandler.java
|
UserAllowPermissionHandler
|
handEvent
|
class UserAllowPermissionHandler {
@Getter
@Setter
private Map<String, Map<String, String>> allows = new HashMap<>();
private final PathMatcher pathMatcher = new AntPathMatcher(".");
@EventListener
public void handEvent(AuthorizingHandleBeforeEvent event) {<FILL_FUNCTION_BODY>}
}
|
if (allows.isEmpty() || event.getHandleType() == HandleType.DATA) {
return;
}
AuthorizingContext context = event.getContext();
// class full name.method
String path = ClassUtils.getUserClass(context.getParamContext()
.getTarget())
.getName().concat(".")
.concat(context.getParamContext()
.getMethod().getName());
AtomicBoolean allow = new AtomicBoolean();
for (Map.Entry<String, Map<String, String>> entry : allows.entrySet()) {
String dimension = entry.getKey();
if ("user".equals(dimension)) {
String userId = context.getAuthentication().getUser().getId();
allow.set(Optional.ofNullable(entry.getValue().get(userId))
.filter(pattern -> "*".equals(pattern) || pathMatcher.match(pattern, path))
.isPresent());
} else { //其他维度
for (Map.Entry<String, String> confEntry : entry.getValue().entrySet()) {
context.getAuthentication()
.getDimension(dimension, confEntry.getKey())
.ifPresent(dim -> {
String pattern = confEntry.getValue();
allow.set("*".equals(pattern) || pathMatcher.match(confEntry.getValue(), path));
});
}
}
if (allow.get()) {
event.setAllow(true);
return;
}
}
| 92 | 372 | 464 | 22,727 |
google_error-prone
|
error-prone/core/src/main/java/com/google/errorprone/bugpatterns/javadoc/UrlInSee.java
|
UrlInSee
|
matchVariable
|
class UrlInSee extends BugChecker
implements ClassTreeMatcher, MethodTreeMatcher, VariableTreeMatcher {
@Override
public Description matchClass(ClassTree classTree, VisitorState state) {
DocTreePath path = getDocTreePath(state);
if (path != null) {
new UrlInSeeChecker(state).scan(path, null);
}
return NO_MATCH;
}
@Override
public Description matchMethod(MethodTree methodTree, VisitorState state) {
DocTreePath path = getDocTreePath(state);
if (path != null) {
new UrlInSeeChecker(state).scan(path, null);
}
return NO_MATCH;
}
@Override
public Description matchVariable(VariableTree variableTree, VisitorState state) {<FILL_FUNCTION_BODY>}
private final class UrlInSeeChecker extends DocTreePathScanner<Void, Void> {
private final VisitorState state;
private UrlInSeeChecker(VisitorState state) {
this.state = state;
}
@Override
public Void visitErroneous(ErroneousTree erroneousTree, Void unused) {
if (erroneousTree.getBody().startsWith("@see http")) {
state.reportMatch(
describeMatch(
diagnosticPosition(getCurrentPath(), state),
replace(
erroneousTree, erroneousTree.getBody().replaceFirst("@see", "See"), state)));
}
return super.visitErroneous(erroneousTree, unused);
}
}
}
|
DocTreePath path = getDocTreePath(state);
if (path != null) {
new UrlInSeeChecker(state).scan(path, null);
}
return NO_MATCH;
| 417 | 56 | 473 | 57,549 |
springdoc_springdoc-openapi
|
springdoc-openapi/springdoc-openapi-starter-webmvc-ui/src/main/java/org/springdoc/webmvc/ui/SwaggerWelcomeWebMvc.java
|
SwaggerWelcomeWebMvc
|
buildUrl
|
class SwaggerWelcomeWebMvc extends SwaggerWelcomeCommon {
/**
* The Spring web provider.
*/
private final SpringWebProvider springWebProvider;
/**
* The Mvc servlet path.
*/
// To keep compatibility with spring-boot 1 - WebMvcProperties changed package from spring 4 to spring 5
@Value(MVC_SERVLET_PATH)
private String mvcServletPath;
/**
* The Path prefix.
*/
private String pathPrefix;
/**
* Instantiates a new Swagger welcome web mvc.
* @param swaggerUiConfig the swagger ui config
* @param springDocConfigProperties the spring doc config properties
* @param swaggerUiConfigParameters the swagger ui config parameters
* @param springWebProvider the spring web provider
*/
public SwaggerWelcomeWebMvc(SwaggerUiConfigProperties swaggerUiConfig, SpringDocConfigProperties springDocConfigProperties, SwaggerUiConfigParameters swaggerUiConfigParameters, SpringWebProvider springWebProvider) {
super(swaggerUiConfig, springDocConfigProperties, swaggerUiConfigParameters);
this.springWebProvider = springWebProvider;
}
/**
* Redirect to ui string.
*
* @param request the request
* @return the string
*/
@Operation(hidden = true)
@GetMapping(SWAGGER_UI_PATH)
@Override
public ResponseEntity<Void> redirectToUi(HttpServletRequest request) {
return super.redirectToUi(request);
}
/**
* Calculate ui root path.
*
* @param sbUrls the sb urls
*/
@Override
protected void calculateUiRootPath(StringBuilder... sbUrls) {
StringBuilder sbUrl = new StringBuilder();
if (SpringDocUtils.isValidPath(mvcServletPath))
sbUrl.append(mvcServletPath);
calculateUiRootCommon(sbUrl, sbUrls);
}
/**
* Build url string.
*
* @param contextPath the context path
* @param docsUrl the docs url
* @return the string
*/
@Override
protected String buildUrl(String contextPath, final String docsUrl) {<FILL_FUNCTION_BODY>}
/**
* Build api doc url string.
*
* @return the string
*/
@Override
protected String buildApiDocUrl() {
return buildUrlWithContextPath(springDocConfigProperties.getApiDocs().getPath());
}
@Override
protected String buildUrlWithContextPath(String swaggerUiUrl) {
if (this.pathPrefix == null)
this.pathPrefix = springWebProvider.findPathPrefix(springDocConfigProperties);
return buildUrl(contextPath + pathPrefix, swaggerUiUrl);
}
/**
* Build swagger config url string.
*
* @return the string
*/
@Override
protected String buildSwaggerConfigUrl() {
return apiDocsUrl + DEFAULT_PATH_SEPARATOR + SWAGGER_CONFIG_FILE;
}
}
|
if (SpringDocUtils.isValidPath(mvcServletPath))
contextPath += mvcServletPath;
return super.buildUrl(contextPath, docsUrl);
| 772 | 47 | 819 | 43,918 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.