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
noear_solon
solon/solon-projects/solon-cloud/solon.cloud/src/main/java/org/noear/solon/cloud/utils/ExpirationUtils.java
ExpirationUtils
getExpiration
class ExpirationUtils { public static long getExpiration(int times){<FILL_FUNCTION_BODY>} }
int second = 0; switch (times){ case 0:second = 0;break;//0秒 case 1:second = second+5;break; //5秒 case 2:second = second+10;break; //10秒 case 3:second = second+30;break; //30秒 case 4:second = second+60;break; //1分钟 case 5:second = second+2*60;break;//2分种 case 6:second = second+5*60;break;//5分钟 case 7:second = second+10*60;break;//10分钟 case 8:second = second+30*60;break;//30分钟 case 9:second = second+60*60;break;//1小时 default:second = second+120*60;break;//2小时 } return second * 1000;
32
247
279
34,098
sofastack_sofa-jraft
sofa-jraft/jraft-core/src/main/java/com/alipay/sofa/jraft/util/SystemPropertyUtil.java
SystemPropertyUtil
get
class SystemPropertyUtil { private static final Logger LOG = LoggerFactory.getLogger(SystemPropertyUtil.class); /** * Returns {@code true} if and only if the system property * with the specified {@code key} exists. */ public static boolean contains(String key) { return get(key) != null; } /** * Returns the value of the Java system property with the * specified {@code key}, while falling back to {@code null} * if the property access fails. * * @return the property value or {@code null} */ public static String get(String key) { return get(key, null); } /** * Returns the value of the Java system property with the * specified {@code key}, while falling back to the specified * default value if the property access fails. * * @return the property value. * {@code def} if there's no such property or if an access to * the specified property is not allowed. */ public static String get(final String key, String def) {<FILL_FUNCTION_BODY>} /** * Returns the value of the Java system property with the * specified {@code key}, while falling back to the specified * default value if the property access fails. * * @return the property value. * {@code def} if there's no such property or if an access to * the specified property is not allowed. */ public static boolean getBoolean(String key, boolean def) { String value = get(key); if (value == null) { return def; } value = value.trim().toLowerCase(); if (value.isEmpty()) { return true; } if ("true".equals(value) || "yes".equals(value) || "1".equals(value)) { return true; } if ("false".equals(value) || "no".equals(value) || "0".equals(value)) { return false; } LOG.warn("Unable to parse the boolean system property '{}':{} - using the default value: {}.", key, value, def); return def; } /** * Returns the value of the Java system property with the * specified {@code key}, while falling back to the specified * default value if the property access fails. * * @return the property value. * {@code def} if there's no such property or if an access * to the specified property is not allowed. */ public static int getInt(String key, int def) { String value = get(key); if (value == null) { return def; } value = value.trim().toLowerCase(); try { return Integer.parseInt(value); } catch (Exception ignored) { // ignored } LOG.warn("Unable to parse the integer system property '{}':{} - using the default value: {}.", key, value, def); return def; } /** * Returns the value of the Java system property with the * specified {@code key}, while falling back to the specified * default value if the property access fails. * * @return the property value. * {@code def} if there's no such property or if an access to * the specified property is not allowed. */ public static long getLong(String key, long def) { String value = get(key); if (value == null) { return def; } value = value.trim().toLowerCase(); try { return Long.parseLong(value); } catch (Exception ignored) { // ignored } LOG.warn("Unable to parse the long system property '{}':{} - using the default value: {}.", key, value, def); return def; } /** * Sets the value of the Java system property with the * specified {@code key} */ public static Object setProperty(String key, String value) { return System.getProperties().setProperty(key, value); } private SystemPropertyUtil() { } }
if (key == null) { throw new NullPointerException("key"); } if (key.isEmpty()) { throw new IllegalArgumentException("key must not be empty."); } String value = null; try { if (System.getSecurityManager() == null) { value = System.getProperty(key); } else { value = AccessController.doPrivileged((PrivilegedAction<String>) () -> System.getProperty(key)); } } catch (Exception e) { if (LOG.isWarnEnabled()) { LOG.warn("Unable to retrieve a system property '{}'; default values will be used, {}.", key, e); } } if (value == null) { return def; } return value;
1,055
206
1,261
62,866
speedment_speedment
speedment/runtime-parent/runtime-core/src/main/java/com/speedment/runtime/core/internal/stream/builder/action/reference/SortedComparatorAction.java
SortedComparatorAction
getComparator
class SortedComparatorAction<T> extends Action<Stream<T>, Stream<T>> implements HasComparator<T> { public final Comparator<? super T> comparator; public SortedComparatorAction(Comparator<? super T> comparator) { super(s -> s.sorted(requireNonNull(comparator)), Stream.class, SORTED); this.comparator = comparator; } @Override public Comparator<? super T> getComparator() {<FILL_FUNCTION_BODY>} }
return comparator;
150
9
159
42,688
apache_linkis
linkis/linkis-public-enhancements/linkis-context-service/linkis-cs-server/src/main/java/org/apache/linkis/cs/execution/impl/ContextValueTypeConditionExecution.java
ContextValueTypeConditionExecution
needOptimization
class ContextValueTypeConditionExecution extends AbstractConditionExecution { public ContextValueTypeConditionExecution( ContextValueTypeCondition condition, ContextCacheService contextCacheService, ContextID contextID) { super(condition, contextCacheService, contextID); this.contextSearchMatcher = new ContextValueTypeContextSearchMatcher(condition); this.contextSearchRuler = new CommonListContextSearchRuler(contextSearchMatcher); this.contextCacheFetcher = new IterateContextCacheFetcher(contextCacheService, contextSearchRuler); } @Override protected boolean needOptimization() {<FILL_FUNCTION_BODY>} @Override protected ContextCacheFetcher getFastFetcher() { return null; } }
return false;
192
8
200
10,526
macrozheng_mall-swarm
mall-swarm/mall-demo/src/main/java/com/macro/mall/demo/config/FeignConfig.java
FeignConfig
requestInterceptor
class FeignConfig { @Bean Logger.Level feignLoggerLevel() { return Logger.Level.FULL; } @Bean RequestInterceptor requestInterceptor() {<FILL_FUNCTION_BODY>} }
return new FeignRequestInterceptor();
67
14
81
2,795
INRIA_spoon
spoon/src/main/java/spoon/support/reflect/code/CtFieldWriteImpl.java
CtFieldWriteImpl
clone
class CtFieldWriteImpl<T> extends CtFieldAccessImpl<T> implements CtFieldWrite<T> { private static final long serialVersionUID = 1L; @Override public void accept(CtVisitor visitor) { visitor.visitCtFieldWrite(this); } @Override public CtFieldWrite<T> clone() {<FILL_FUNCTION_BODY>} }
return (CtFieldWrite<T>) super.clone();
103
19
122
58,024
fabric8io_kubernetes-client
kubernetes-client/java-generator/core/src/main/java/io/fabric8/java/generator/nodes/JMap.java
JMap
getClassType
class JMap extends AbstractJSONSchema2Pojo { private final String type; private final AbstractJSONSchema2Pojo nested; public JMap(AbstractJSONSchema2Pojo nested, Config config, String description, final boolean isNullable, JsonNode defaultValue) { super(config, description, isNullable, defaultValue, null); this.type = new ClassOrInterfaceType() .setName(JAVA_UTIL_MAP) .setTypeArguments( new ClassOrInterfaceType().setName(JAVA_LANG_STRING), new ClassOrInterfaceType().setName(nested.getType())) .toString(); this.nested = nested; } @Override public String getType() { return this.type; } @Override protected String getClassType() {<FILL_FUNCTION_BODY>} @Override public GeneratorResult generateJava() { return nested.generateJava(); } }
return JAVA_UTIL_MAP;
248
15
263
18,634
apache_dubbo
dubbo/dubbo-common/src/main/java/org/apache/dubbo/common/threadpool/serial/SerializingExecutor.java
SerializingExecutor
schedule
class SerializingExecutor implements Executor, Runnable { private static final ErrorTypeAwareLogger LOGGER = LoggerFactory.getErrorTypeAwareLogger(SerializingExecutor.class); /** * Use false to stop and true to run */ private final AtomicBoolean atomicBoolean = new AtomicBoolean(); private final Executor executor; private final Queue<Runnable> runQueue = new ConcurrentLinkedQueue<>(); /** * Creates a SerializingExecutor, running tasks using {@code executor}. * * @param executor Executor in which tasks should be run. Must not be null. */ public SerializingExecutor(Executor executor) { this.executor = executor; } /** * Runs the given runnable strictly after all Runnables that were submitted * before it, and using the {@code executor} passed to the constructor. . */ @Override public void execute(Runnable r) { runQueue.add(r); schedule(r); } private void schedule(Runnable removable) {<FILL_FUNCTION_BODY>} @Override public void run() { Runnable r; try { while ((r = runQueue.poll()) != null) { InternalThreadLocalMap internalThreadLocalMap = InternalThreadLocalMap.getAndRemove(); try { r.run(); } catch (RuntimeException e) { LOGGER.error(COMMON_ERROR_RUN_THREAD_TASK, "", "", "Exception while executing runnable " + r, e); } finally { InternalThreadLocalMap.set(internalThreadLocalMap); } } } finally { atomicBoolean.set(false); } if (!runQueue.isEmpty()) { // we didn't enqueue anything but someone else did. schedule(null); } } }
if (atomicBoolean.compareAndSet(false, true)) { boolean success = false; try { if (!isShutdown(executor)) { executor.execute(this); success = true; } } finally { // It is possible that at this point that there are still tasks in // the queue, it would be nice to keep trying but the error may not // be recoverable. So we update our state and propagate so that if // our caller deems it recoverable we won't be stuck. if (!success) { if (removable != null) { // This case can only be reached if 'this' was not currently running, and we failed to // reschedule. The item should still be in the queue for removal. // ConcurrentLinkedQueue claims that null elements are not allowed, but seems to not // throw if the item to remove is null. If removable is present in the queue twice, // the wrong one may be removed. It doesn't seem possible for this case to exist today. // This is important to run in case of RejectedExecutionException, so that future calls // to execute don't succeed and accidentally run a previous runnable. runQueue.remove(removable); } atomicBoolean.set(false); } } }
487
333
820
67,156
questdb_questdb
questdb/core/src/main/java/io/questdb/griffin/engine/functions/math/AbsShortFunctionFactory.java
AbsShortFunctionFactory
newInstance
class AbsShortFunctionFactory implements FunctionFactory { @Override public String getSignature() { return "abs(E)"; } @Override public Function newInstance(int position, ObjList<Function> args, IntList argPositions, CairoConfiguration configuration, SqlExecutionContext sqlExecutionContext) {<FILL_FUNCTION_BODY>} private static class AbsFunction extends ShortFunction implements UnaryFunction { final Function function; public AbsFunction(Function function) { this.function = function; } @Override public Function getArg() { return function; } @Override public String getName() { return "abs"; } @Override public short getShort(Record rec) { short value = function.getShort(rec); return (short) Math.abs(value); } } }
return new AbsFunction(args.getQuick(0));
223
17
240
61,892
201206030_novel
novel/src/main/java/io/github/xxyopen/novel/dao/entity/AuthorCode.java
AuthorCode
getInviteCode
class AuthorCode implements Serializable { private static final long serialVersionUID = 1L; /** * 主键 */ @TableId(value = "id", type = IdType.AUTO) private Long id; /** * 邀请码 */ private String inviteCode; /** * 有效时间 */ private LocalDateTime validityTime; /** * 是否使用过;0-未使用 1-使用过 */ private Integer isUsed; /** * 创建时间 */ private LocalDateTime createTime; /** * 更新时间 */ private LocalDateTime updateTime; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getInviteCode() {<FILL_FUNCTION_BODY>} public void setInviteCode(String inviteCode) { this.inviteCode = inviteCode; } public LocalDateTime getValidityTime() { return validityTime; } public void setValidityTime(LocalDateTime validityTime) { this.validityTime = validityTime; } public Integer getIsUsed() { return isUsed; } public void setIsUsed(Integer isUsed) { this.isUsed = isUsed; } public LocalDateTime getCreateTime() { return createTime; } public void setCreateTime(LocalDateTime createTime) { this.createTime = createTime; } public LocalDateTime getUpdateTime() { return updateTime; } public void setUpdateTime(LocalDateTime updateTime) { this.updateTime = updateTime; } @Override public String toString() { return "AuthorCode{" + "id=" + id + ", inviteCode=" + inviteCode + ", validityTime=" + validityTime + ", isUsed=" + isUsed + ", createTime=" + createTime + ", updateTime=" + updateTime + "}"; } }
return inviteCode;
555
9
564
4,942
lukas-krecan_ShedLock
ShedLock/providers/datastore/shedlock-provider-datastore/src/main/java/net/javacrumbs/shedlock/provider/datastore/DatastoreStorageAccessor.java
DatastoreStorageAccessor
updateExisting
class DatastoreStorageAccessor extends AbstractStorageAccessor { private static final Logger log = LoggerFactory.getLogger(DatastoreStorageAccessor.class); private final Datastore datastore; private final String hostname; private final String entityName; private final DatastoreLockProvider.FieldNames fieldNames; public DatastoreStorageAccessor(DatastoreLockProvider.Configuration configuration) { requireNonNull(configuration); this.datastore = configuration.getDatastore(); this.hostname = Utils.getHostname(); this.entityName = configuration.getEntityName(); this.fieldNames = configuration.getFieldNames(); } @Override public boolean insertRecord(LockConfiguration config) { return insert(config.getName(), config.getLockAtMostUntil()); } @Override public boolean updateRecord(LockConfiguration config) { return updateExisting(config.getName(), config.getLockAtMostUntil()); } @Override public void unlock(LockConfiguration config) { updateOwn(config.getName(), config.getUnlockTime()); } @Override public boolean extend(LockConfiguration config) { return updateOwn(config.getName(), config.getLockAtMostUntil()); } private boolean insert(String name, Instant until) { return doInTxn(txn -> { KeyFactory keyFactory = this.datastore.newKeyFactory().setKind(this.entityName); Key key = keyFactory.newKey(name); Entity entity = Entity.newBuilder(key) .set(this.fieldNames.lockUntil(), fromInstant(until)) .set(this.fieldNames.lockedAt(), fromInstant(ClockProvider.now())) .set(this.fieldNames.lockedBy(), this.hostname) .build(); txn.add(entity); return Optional.of(true); }) .orElse(false); } private boolean updateExisting(String name, Instant until) {<FILL_FUNCTION_BODY>} private boolean updateOwn(String name, Instant until) { return doInTxn(txn -> get(name, txn) .filter(entity -> this.hostname.equals(nullableString(entity, this.fieldNames.lockedBy()))) .filter(entity -> { var now = ClockProvider.now(); var lockUntilTs = nullableTimestamp(entity, this.fieldNames.lockUntil()); return lockUntilTs != null && (lockUntilTs.isAfter(now) || lockUntilTs.equals(now)); }) .map(entity -> { txn.put(Entity.newBuilder(entity) .set(this.fieldNames.lockUntil(), fromInstant(until)) .build()); return true; })) .orElse(false); } public Optional<Lock> findLock(String name) { return get(name) .map(entity -> new Lock( entity.getKey().getName(), nullableTimestamp(entity, this.fieldNames.lockedAt()), nullableTimestamp(entity, this.fieldNames.lockUntil()), nullableString(entity, this.fieldNames.lockedBy()))); } private Optional<Entity> get(String name) { KeyFactory keyFactory = this.datastore.newKeyFactory().setKind(this.entityName); Key key = keyFactory.newKey(name); return ofNullable(this.datastore.get(key)); } private Optional<Entity> get(String name, Transaction txn) { KeyFactory keyFactory = this.datastore.newKeyFactory().setKind(this.entityName); Key key = keyFactory.newKey(name); return ofNullable(txn.get(key)); } private <T> Optional<T> doInTxn(Function<Transaction, Optional<T>> work) { var txn = this.datastore.newTransaction(); try { var result = work.apply(txn); txn.commit(); return result; } catch (DatastoreException ex) { log.debug("Unable to perform a transactional unit of work: {}", ex.getMessage()); return Optional.empty(); } finally { if (txn.isActive()) { txn.rollback(); } } } private static String nullableString(Entity entity, String property) { return entity.contains(property) ? entity.getString(property) : null; } private static Instant nullableTimestamp(Entity entity, String property) { return entity.contains(property) ? toInstant(entity.getTimestamp(property)) : null; } private static Timestamp fromInstant(Instant instant) { return Timestamp.of(java.sql.Timestamp.from(requireNonNull(instant))); } private static Instant toInstant(Timestamp timestamp) { return requireNonNull(timestamp).toSqlTimestamp().toInstant(); } public record Lock(String name, Instant lockedAt, Instant lockedUntil, String lockedBy) {} }
return doInTxn(txn -> get(name, txn) .filter(entity -> { var now = ClockProvider.now(); var lockUntilTs = nullableTimestamp(entity, this.fieldNames.lockUntil()); return lockUntilTs != null && lockUntilTs.isBefore(now); }) .map(entity -> { txn.put(Entity.newBuilder(entity) .set(this.fieldNames.lockUntil(), fromInstant(until)) .set(this.fieldNames.lockedAt(), fromInstant(ClockProvider.now())) .set(this.fieldNames.lockedBy(), this.hostname) .build()); return true; })) .orElse(false);
1,310
196
1,506
31,610
macrozheng_mall-swarm
mall-swarm/mall-mbg/src/main/java/com/macro/mall/model/UmsMemberTag.java
UmsMemberTag
getFinishOrderCount
class UmsMemberTag implements Serializable { private Long id; private String name; @ApiModelProperty(value = "自动打标签完成订单数量") private Integer finishOrderCount; @ApiModelProperty(value = "自动打标签完成订单金额") private BigDecimal finishOrderAmount; private static final long serialVersionUID = 1L; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Integer getFinishOrderCount() {<FILL_FUNCTION_BODY>} public void setFinishOrderCount(Integer finishOrderCount) { this.finishOrderCount = finishOrderCount; } public BigDecimal getFinishOrderAmount() { return finishOrderAmount; } public void setFinishOrderAmount(BigDecimal finishOrderAmount) { this.finishOrderAmount = finishOrderAmount; } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append(getClass().getSimpleName()); sb.append(" ["); sb.append("Hash = ").append(hashCode()); sb.append(", id=").append(id); sb.append(", name=").append(name); sb.append(", finishOrderCount=").append(finishOrderCount); sb.append(", finishOrderAmount=").append(finishOrderAmount); sb.append(", serialVersionUID=").append(serialVersionUID); sb.append("]"); return sb.toString(); } }
return finishOrderCount;
454
10
464
2,948
thymeleaf_thymeleaf
thymeleaf/lib/thymeleaf/src/main/java/org/thymeleaf/processor/element/AbstractElementModelProcessor.java
AbstractElementModelProcessor
process
class AbstractElementModelProcessor extends AbstractProcessor implements IElementModelProcessor { private final String dialectPrefix; private final MatchingElementName matchingElementName; private final MatchingAttributeName matchingAttributeName; public AbstractElementModelProcessor( final TemplateMode templateMode, final String dialectPrefix, final String elementName, final boolean prefixElementName, final String attributeName, final boolean prefixAttributeName, final int precedence) { super(templateMode, precedence); this.dialectPrefix = dialectPrefix; this.matchingElementName = (elementName == null? null : MatchingElementName.forElementName( templateMode, ElementNames.forName(templateMode, (prefixElementName? this.dialectPrefix : null), elementName))); this.matchingAttributeName = (attributeName == null? null : MatchingAttributeName.forAttributeName( templateMode, AttributeNames.forName(templateMode, (prefixAttributeName? this.dialectPrefix : null), attributeName))); } protected final String getDialectPrefix() { return this.dialectPrefix; } public final MatchingElementName getMatchingElementName() { return this.matchingElementName; } public final MatchingAttributeName getMatchingAttributeName() { return this.matchingAttributeName; } public final void process( final ITemplateContext context, final IModel model, final IElementModelStructureHandler structureHandler) {<FILL_FUNCTION_BODY>} protected abstract void doProcess( final ITemplateContext context, final IModel model, final IElementModelStructureHandler structureHandler); }
ITemplateEvent firstEvent = null; try { firstEvent = model.get(0); doProcess(context, model, structureHandler); } catch (final TemplateProcessingException e) { // We will try to add all information possible to the exception report (template name, line, col) if (firstEvent != null) { String modelTemplateName = firstEvent.getTemplateName(); int modelLine = firstEvent.getLine(); int modelCol = firstEvent.getCol(); if (modelTemplateName != null) { if (!e.hasTemplateName()) { e.setTemplateName(modelTemplateName); } } if (modelLine != -1 && modelCol != -1) { if (!e.hasLineAndCol()) { e.setLineAndCol(modelLine, modelCol); } } } throw e; } catch (final Exception e) { // We will try to add all information possible to the exception report (template name, line, col) String modelTemplateName = null; int modelLine = -1; int modelCol = -1; if (firstEvent != null) { modelTemplateName = firstEvent.getTemplateName(); modelLine = firstEvent.getLine(); modelCol = firstEvent.getCol(); } throw new TemplateProcessingException( "Error during execution of processor '" + this.getClass().getName() + "'", modelTemplateName, modelLine, modelCol, e); }
437
397
834
45,848
alibaba_fastjson2
fastjson2/core/src/main/java/com/alibaba/fastjson2/reader/ObjectArrayReader.java
ObjectArrayReader
readObject
class ObjectArrayReader extends ObjectReaderPrimitive { public static final ObjectArrayReader INSTANCE = new ObjectArrayReader(); public static final long TYPE_HASH_CODE = Fnv.hashCode64("[O"); public ObjectArrayReader() { super(Object[].class); } @Override public Object[] createInstance(Collection collection) { Object[] array = new Object[collection.size()]; int i = 0; for (Object item : collection) { array[i++] = item; } return array; } @Override public Object readObject(JSONReader jsonReader, Type fieldType, Object fieldName, long features) {<FILL_FUNCTION_BODY>} @Override public Object readJSONBObject(JSONReader jsonReader, Type fieldType, Object fieldName, long features) { if (jsonReader.getType() == BC_TYPED_ANY) { ObjectReader autoTypeObjectReader = jsonReader.checkAutoType(Object[].class, TYPE_HASH_CODE, features); if (autoTypeObjectReader != this) { return autoTypeObjectReader.readJSONBObject(jsonReader, fieldType, fieldName, features); } } int itemCnt = jsonReader.startArray(); if (itemCnt == -1) { return null; } Object[] array = new Object[itemCnt]; for (int i = 0; i < itemCnt; i++) { byte type = jsonReader.getType(); Object value; ObjectReader autoTypeValueReader; if (type >= BC_STR_ASCII_FIX_MIN && type <= BC_STR_UTF16BE) { value = jsonReader.readString(); } else if (type == BC_TYPED_ANY) { autoTypeValueReader = jsonReader.checkAutoType(Object.class, 0, features); if (autoTypeValueReader != null) { value = autoTypeValueReader.readJSONBObject(jsonReader, null, null, features); } else { value = jsonReader.readAny(); } } else if (type == BC_NULL) { jsonReader.next(); value = null; } else if (type == BC_TRUE) { jsonReader.next(); value = Boolean.TRUE; } else if (type == BC_FALSE) { jsonReader.next(); value = Boolean.FALSE; } else if (type == BC_INT64) { value = jsonReader.readInt64Value(); } else { value = jsonReader.readAny(); } array[i] = value; } return array; } }
if (jsonReader.nextIfNullOrEmptyString()) { return null; } if (jsonReader.nextIfArrayStart()) { Object[] values = new Object[16]; int size = 0; while (!jsonReader.nextIfArrayEnd()) { int minCapacity = size + 1; if (minCapacity - values.length > 0) { int oldCapacity = values.length; int newCapacity = oldCapacity + (oldCapacity >> 1); if (newCapacity - minCapacity < 0) { newCapacity = minCapacity; } values = Arrays.copyOf(values, newCapacity); } Object value; char ch = jsonReader.current(); switch (ch) { case '"': value = jsonReader.readString(); break; case '+': case '-': case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': case '.': value = jsonReader.readNumber(); break; case 'n': jsonReader.readNull(); value = null; break; case 't': case 'f': value = jsonReader.readBoolValue(); break; case '{': value = jsonReader.read(Object.class); break; case '[': value = jsonReader.readArray(); break; default: throw new JSONException(jsonReader.info()); } values[size++] = value; } jsonReader.nextIfComma(); return Arrays.copyOf(values, size); } if (jsonReader.current() == '{') { jsonReader.next(); long filedHash = jsonReader.readFieldNameHashCode(); if (filedHash == HASH_TYPE) { jsonReader.readString(); } } if (jsonReader.isString()) { String str = jsonReader.readString(); if (str == null || str.isEmpty()) { return null; } if (VALUE_NAME.equals(str)) { jsonReader.next(); Object result = this.readObject(jsonReader, fieldType, fieldName, features); jsonReader.nextIfObjectEnd(); return result; } } throw new JSONException(jsonReader.info("TODO"));
687
647
1,334
5,973
apache_incubator-kie-optaplanner
incubator-kie-optaplanner/optaplanner-test/src/main/java/org/optaplanner/test/api/solver/change/MockProblemChangeDirector.java
MockProblemChangeDirector
changeProblemProperty
class MockProblemChangeDirector implements ProblemChangeDirector { private Map<Object, Object> lookUpTable = new IdentityHashMap<>(); @Override public <Entity> void addEntity(Entity entity, Consumer<Entity> entityConsumer) { entityConsumer.accept(lookUpWorkingObjectOrFail(entity)); } @Override public <Entity> void removeEntity(Entity entity, Consumer<Entity> entityConsumer) { entityConsumer.accept(lookUpWorkingObjectOrFail(entity)); } @Override public <Entity> void changeVariable(Entity entity, String variableName, Consumer<Entity> entityConsumer) { entityConsumer.accept(lookUpWorkingObjectOrFail(entity)); } @Override public <ProblemFact> void addProblemFact(ProblemFact problemFact, Consumer<ProblemFact> problemFactConsumer) { problemFactConsumer.accept(lookUpWorkingObjectOrFail(problemFact)); } @Override public <ProblemFact> void removeProblemFact(ProblemFact problemFact, Consumer<ProblemFact> problemFactConsumer) { problemFactConsumer.accept(lookUpWorkingObjectOrFail(problemFact)); } @Override public <EntityOrProblemFact> void changeProblemProperty(EntityOrProblemFact problemFactOrEntity, Consumer<EntityOrProblemFact> problemFactOrEntityConsumer) {<FILL_FUNCTION_BODY>} /** * If the look-up result has been provided by a {@link #whenLookingUp(Object)} call, returns the defined object. * Otherwise, returns the original externalObject. * * @param externalObject entity or problem fact to look up */ @Override public <EntityOrProblemFact> EntityOrProblemFact lookUpWorkingObjectOrFail(EntityOrProblemFact externalObject) { EntityOrProblemFact entityOrProblemFact = (EntityOrProblemFact) lookUpTable.get(externalObject); return entityOrProblemFact == null ? externalObject : entityOrProblemFact; } /** * If the look-up result has been provided by a {@link #whenLookingUp(Object)} call, returns the defined object. * Otherwise, returns null. * * @param externalObject entity or problem fact to look up */ @Override public <EntityOrProblemFact> Optional<EntityOrProblemFact> lookUpWorkingObject(EntityOrProblemFact externalObject) { return Optional.ofNullable((EntityOrProblemFact) lookUpTable.get(externalObject)); } @Override public void updateShadowVariables() { // Do nothing. } /** * Defines what {@link #lookUpWorkingObjectOrFail(Object)} returns. */ public LookUpMockBuilder whenLookingUp(Object forObject) { return new LookUpMockBuilder(forObject); } public final class LookUpMockBuilder { private final Object forObject; public LookUpMockBuilder(Object forObject) { this.forObject = forObject; } public MockProblemChangeDirector thenReturn(Object returnObject) { lookUpTable.put(forObject, returnObject); return MockProblemChangeDirector.this; } } }
problemFactOrEntityConsumer.accept(lookUpWorkingObjectOrFail(problemFactOrEntity));
823
26
849
9,815
langchain4j_langchain4j
langchain4j/langchain4j-mongodb-atlas/src/main/java/dev/langchain4j/store/embedding/mongodb/IndexMapping.java
IndexMapping
defaultIndexMapping
class IndexMapping { private int dimension; private Set<String> metadataFieldNames; public static IndexMapping defaultIndexMapping() {<FILL_FUNCTION_BODY>} }
return IndexMapping.builder() .dimension(1536) .metadataFieldNames(new HashSet<>()) .build();
49
39
88
28,699
shopizer-ecommerce_shopizer
shopizer/sm-core/src/main/java/com/salesmanager/core/business/services/catalog/product/file/DigitalProductServiceImpl.java
DigitalProductServiceImpl
saveOrUpdate
class DigitalProductServiceImpl extends SalesManagerEntityServiceImpl<Long, DigitalProduct> implements DigitalProductService { private DigitalProductRepository digitalProductRepository; @Inject StaticContentFileManager productDownloadsFileManager; @Inject ProductService productService; @Inject public DigitalProductServiceImpl(DigitalProductRepository digitalProductRepository) { super(digitalProductRepository); this.digitalProductRepository = digitalProductRepository; } @Override public void addProductFile(Product product, DigitalProduct digitalProduct, InputContentFile inputFile) throws ServiceException { Assert.notNull(digitalProduct,"DigitalProduct cannot be null"); Assert.notNull(product,"Product cannot be null"); digitalProduct.setProduct(product); try { Assert.notNull(inputFile.getFile(),"InputContentFile.file cannot be null"); Assert.notNull(product.getMerchantStore(),"Product.merchantStore cannot be null"); this.saveOrUpdate(digitalProduct); String path = null; productDownloadsFileManager.addFile(product.getMerchantStore().getCode(), Optional.of(path), inputFile); product.setProductVirtual(true); productService.update(product); } catch (Exception e) { throw new ServiceException(e); } finally { try { if(inputFile.getFile()!=null) { inputFile.getFile().close(); } } catch(Exception ignore) {} } } @Override public DigitalProduct getByProduct(MerchantStore store, Product product) throws ServiceException { return digitalProductRepository.findByProduct(store.getId(), product.getId()); } @Override public void delete(DigitalProduct digitalProduct) throws ServiceException { Assert.notNull(digitalProduct,"DigitalProduct cannot be null"); Assert.notNull(digitalProduct.getProduct(),"DigitalProduct.product cannot be null"); //refresh file digitalProduct = this.getById(digitalProduct.getId()); super.delete(digitalProduct); String path = null; productDownloadsFileManager.removeFile(digitalProduct.getProduct().getMerchantStore().getCode(), FileContentType.PRODUCT, digitalProduct.getProductFileName(), Optional.of(path)); digitalProduct.getProduct().setProductVirtual(false); productService.update(digitalProduct.getProduct()); } @Override public void saveOrUpdate(DigitalProduct digitalProduct) throws ServiceException {<FILL_FUNCTION_BODY>} }
Assert.notNull(digitalProduct,"DigitalProduct cannot be null"); Assert.notNull(digitalProduct.getProduct(),"DigitalProduct.product cannot be null"); if(digitalProduct.getId()==null || digitalProduct.getId() ==0) { super.save(digitalProduct); } else { super.create(digitalProduct); } digitalProduct.getProduct().setProductVirtual(true); productService.update(digitalProduct.getProduct());
698
138
836
40,289
noear_solon
solon/solon-projects/solon-view/solon.view.enjoy/src/main/java/org/noear/solon/view/enjoy/XPluginImp.java
XPluginImp
start
class XPluginImp implements Plugin { @Override public void start(AppContext context) {<FILL_FUNCTION_BODY>} }
EnjoyRender render = EnjoyRender.global(); context.lifecycle(-99, () -> { context.beanForeach((k, v) -> { if (k.startsWith("view:")) { //java view widget if (Directive.class.isAssignableFrom(v.clz())) { render.putDirective(k.split(":")[1], (Class<? extends Directive>) v.clz()); } return; } if (k.startsWith("share:")) { //java share object render.putVariable(k.split(":")[1], v.raw()); return; } }); }); RenderManager.register(render); RenderManager.mapping(".shtm", render); context.wrapAndPut(EnjoyRender.class, render); if (ClassUtil.hasClass(() -> AuthUtil.class)) { render.putDirective(AuthConstants.TAG_authPermissions, AuthPermissionsTag.class); render.putDirective(AuthConstants.TAG_authRoles, AuthRolesTag.class); }
39
289
328
33,401
thymeleaf_thymeleaf
thymeleaf/lib/thymeleaf/src/main/java/org/thymeleaf/util/Validate.java
Validate
notEmpty
class Validate { public static void notNull(final Object object, final String message) { if (object == null) { throw new IllegalArgumentException(message); } } public static void notEmpty(final String object, final String message) { if (StringUtils.isEmptyOrWhitespace(object)) { throw new IllegalArgumentException(message); } } public static void notEmpty(final Collection<?> object, final String message) {<FILL_FUNCTION_BODY>} public static void notEmpty(final Object[] object, final String message) { if (object == null || object.length == 0) { throw new IllegalArgumentException(message); } } public static void containsNoNulls(final Iterable<?> collection, final String message) { for (final Object object : collection) { notNull(object, message); } } public static void containsNoEmpties(final Iterable<String> collection, final String message) { for (final String object : collection) { notEmpty(object, message); } } public static void containsNoNulls(final Object[] array, final String message) { for (final Object object : array) { notNull(object, message); } } public static void isTrue(final boolean condition, final String message) { if (!condition) { throw new IllegalArgumentException(message); } } private Validate() { super(); } }
if (object == null || object.size() == 0) { throw new IllegalArgumentException(message); }
397
31
428
46,040
javastacks_spring-boot-best-practice
spring-boot-best-practice/spring-boot-redis/src/main/java/cn/javastack/springboot/redis/RedisController.java
RedisController
setObject
class RedisController { private final StringRedisTemplate stringRedisTemplate; @Resource(name = "stringRedisTemplate") private ValueOperations<String, String> valueOperations; private final RedisOptService redisOptService; private final RedisLockService redisLockService; @RequestMapping("/redis/set") public String set(@RequestParam("name") String name, @RequestParam("value") String value) { valueOperations.set(name, value); return valueOperations.get(name); } @RequestMapping("/redis/setObject") public String setObject(@RequestParam("name") String name) {<FILL_FUNCTION_BODY>} @GetMapping("/redis/lock") public String lock(@RequestParam("key") String key) { for (int i = 0; i < 10; i++) { new Thread(() -> { redisLockService.lock(key); try { Thread.sleep(3000L); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println(DateFormatUtils.format(new Date(), "yyyy-MM-dd HH:mm:ss")); redisLockService.unlock(key); } ).start(); } return "OK"; } @GetMapping("/redis/sentinel/set") public String sentinelSet(@RequestParam("name") String name) { redisOptService.set("name", name, 60000); return redisOptService.getStringValue("name"); } }
User user = new User(); user.setId(RandomUtils.nextInt()); user.setName(name); user.setBirthday(new Date()); List<String> list = new ArrayList<>(); list.add("sing"); list.add("run"); user.setInteresting(list); Map<String, Object> map = new HashMap<>(); map.put("hasHouse", "yes"); map.put("hasCar", "no"); map.put("hasKid", "no"); user.setOthers(map); redisOptService.set(name, user, 30000); User userValue = (User) redisOptService.get(name); return userValue.toString();
416
194
610
24,734
checkstyle_checkstyle
checkstyle/src/main/java/com/puppycrawl/tools/checkstyle/checks/coding/DefaultComesLastCheck.java
DefaultComesLastCheck
getRequiredTokens
class DefaultComesLastCheck extends AbstractCheck { /** * A key is pointing to the warning message text in "messages.properties" * file. */ public static final String MSG_KEY = "default.comes.last"; /** * A key is pointing to the warning message text in "messages.properties" * file. */ public static final String MSG_KEY_SKIP_IF_LAST_AND_SHARED_WITH_CASE = "default.comes.last.in.casegroup"; /** Control whether to allow {@code default} along with {@code case} if they are not last. */ private boolean skipIfLastAndSharedWithCase; @Override public int[] getAcceptableTokens() { return getRequiredTokens(); } @Override public int[] getDefaultTokens() { return getRequiredTokens(); } @Override public int[] getRequiredTokens() {<FILL_FUNCTION_BODY>} /** * Setter to control whether to allow {@code default} along with * {@code case} if they are not last. * * @param newValue whether to ignore checking. * @since 7.7 */ public void setSkipIfLastAndSharedWithCase(boolean newValue) { skipIfLastAndSharedWithCase = newValue; } @Override public void visitToken(DetailAST ast) { final DetailAST defaultGroupAST = ast.getParent(); // Switch rules are not subject to fall through. final boolean isSwitchRule = defaultGroupAST.getType() == TokenTypes.SWITCH_RULE; if (skipIfLastAndSharedWithCase && !isSwitchRule) { if (isNextSiblingOf(ast, TokenTypes.LITERAL_CASE)) { log(ast, MSG_KEY_SKIP_IF_LAST_AND_SHARED_WITH_CASE); } else if (ast.getPreviousSibling() == null && isNextSiblingOf(defaultGroupAST, TokenTypes.CASE_GROUP)) { log(ast, MSG_KEY); } } else if (isNextSiblingOf(defaultGroupAST, TokenTypes.CASE_GROUP) || isNextSiblingOf(defaultGroupAST, TokenTypes.SWITCH_RULE)) { log(ast, MSG_KEY); } } /** * Return true only if passed tokenType in argument is found or returns false. * * @param ast root node. * @param tokenType tokentype to be processed. * @return true if desired token is found or else false. */ private static boolean isNextSiblingOf(DetailAST ast, int tokenType) { return ast.getNextSibling() != null && ast.getNextSibling().getType() == tokenType; } }
return new int[] { TokenTypes.LITERAL_DEFAULT, };
750
25
775
68,938
alibaba_spring-cloud-alibaba
spring-cloud-alibaba/spring-cloud-alibaba-examples/integrated-example/integrated-praise-provider/src/main/java/com/alibaba/cloud/integration/provider/PraiseProviderApplication.java
PraiseProviderApplication
main
class PraiseProviderApplication { public static void main(String[] args) {<FILL_FUNCTION_BODY>} }
SpringApplication.run(PraiseProviderApplication.class, args);
34
21
55
65,693
langchain4j_langchain4j
langchain4j/langchain4j-core/src/main/java/dev/langchain4j/rag/content/retriever/EmbeddingStoreContentRetriever.java
EmbeddingStoreContentRetrieverBuilder
maxResults
class EmbeddingStoreContentRetrieverBuilder { public EmbeddingStoreContentRetrieverBuilder maxResults(Integer maxResults) {<FILL_FUNCTION_BODY>} public EmbeddingStoreContentRetrieverBuilder minScore(Double minScore) { if (minScore != null) { dynamicMinScore = (query) -> ensureBetween(minScore, 0, 1, "minScore"); } return this; } public EmbeddingStoreContentRetrieverBuilder filter(Filter filter) { if (filter != null) { dynamicFilter = (query) -> filter; } return this; } }
if (maxResults != null) { dynamicMaxResults = (query) -> ensureGreaterThanZero(maxResults, "maxResults"); } return this;
167
47
214
28,619
knowm_XChange
XChange/xchange-vaultoro/src/main/java/org/knowm/xchange/vaultoro/dto/trade/VaultoroNewOrderData.java
VaultoroNewOrderData
getPrice
class VaultoroNewOrderData { @JsonProperty("action") private String action; @JsonProperty("Order_ID") private String OrderID; @JsonProperty("type") private String type; @JsonProperty("time") private String time; @JsonProperty("price") private BigDecimal price; @JsonProperty("btc") private BigDecimal btc; @JsonProperty("gld") private BigDecimal gld; @JsonIgnore private Map<String, Object> additionalProperties = new HashMap<String, Object>(); /** * @return The action */ @JsonProperty("action") public String getAction() { return action; } /** * @param action The action */ @JsonProperty("action") public void setAction(String action) { this.action = action; } /** * @return The OrderID */ @JsonProperty("Order_ID") public String getOrderID() { return OrderID; } /** * @param OrderID The Order_ID */ @JsonProperty("Order_ID") public void setOrderID(String OrderID) { this.OrderID = OrderID; } /** * @return The type */ @JsonProperty("type") public String getType() { return type; } /** * @param type The type */ @JsonProperty("type") public void setType(String type) { this.type = type; } /** * @return The time */ @JsonProperty("time") public String getTime() { return time; } /** * @param time The time */ @JsonProperty("time") public void setTime(String time) { this.time = time; } /** * @return The price */ @JsonProperty("price") public BigDecimal getPrice() {<FILL_FUNCTION_BODY>} /** * @param price The price */ @JsonProperty("price") public void setPrice(BigDecimal price) { this.price = price; } /** * @return The btc */ @JsonProperty("btc") public BigDecimal getBtc() { return btc; } /** * @param btc The btc */ @JsonProperty("btc") public void setBtc(BigDecimal btc) { this.btc = btc; } /** * @return The gld */ @JsonProperty("gld") public BigDecimal getGld() { return gld; } /** * @param gld The gld */ @JsonProperty("gld") public void setGld(BigDecimal gld) { this.gld = gld; } @JsonAnyGetter public Map<String, Object> getAdditionalProperties() { return this.additionalProperties; } @JsonAnySetter public void setAdditionalProperty(String name, Object value) { this.additionalProperties.put(name, value); } }
return price;
876
9
885
27,856
apache_pdfbox
pdfbox/pdfbox/src/main/java/org/apache/pdfbox/pdmodel/interactive/form/PDCheckBox.java
PDCheckBox
getOnValue
class PDCheckBox extends PDButton { /** * @see PDField#PDField(PDAcroForm) * * @param acroForm The acroform. */ public PDCheckBox(PDAcroForm acroForm) { super(acroForm); } /** * Constructor. * * @param acroForm The form that this field is part of. * @param field the PDF object to represent as a field. * @param parent the parent node of the node */ PDCheckBox(PDAcroForm acroForm, COSDictionary field, PDNonTerminalField parent) { super(acroForm, field, parent); } /** * This will tell if this radio button is currently checked or not. * This is equivalent to calling {@link #getValue()}. * * @return true If this field is checked. */ public boolean isChecked() { return getValue().compareTo(getOnValue()) == 0; } /** * Checks the check box. * * @throws IOException if the appearance couldn't be generated. */ public void check() throws IOException { setValue(getOnValue()); } /** * Unchecks the check box. * * @throws IOException if the appearance couldn't be generated. */ public void unCheck() throws IOException { setValue(COSName.Off.getName()); } /** * Get the value which sets the check box to the On state. * * <p>The On value should be 'Yes' but other values are possible * so we need to look for that. On the other hand the Off value shall * always be 'Off'. If not set or not part of the normal appearance keys * 'Off' is the default</p> * * @return the value setting the check box to the On state. * If an empty string is returned there is no appearance definition. */ public String getOnValue() {<FILL_FUNCTION_BODY>} }
PDAnnotationWidget widget = this.getWidgets().get(0); PDAppearanceDictionary apDictionary = widget.getAppearance(); if (apDictionary != null) { PDAppearanceEntry normalAppearance = apDictionary.getNormalAppearance(); if (normalAppearance != null) { Set<COSName> entries = normalAppearance.getSubDictionary().keySet(); for (COSName entry : entries) { if (COSName.Off.compareTo(entry) != 0) { return entry.getName(); } } } } return "";
554
173
727
12,331
alibaba_fastjson2
fastjson2/benchmark/src/main/java/com/alibaba/fastjson2/benchmark/primitves/Date20TreeWrite.java
Date20TreeWrite
fastjson2
class Date20TreeWrite { static String str; static List array; static ObjectMapper mapper = new ObjectMapper(); public Date20TreeWrite() { try { InputStream is = Date20TreeWrite.class.getClassLoader().getResourceAsStream("data/date20.json"); str = IOUtils.toString(is, "UTF-8"); Date20Field object = JSON.parseObject(str, Date20Field.class); array = JSONArray.of( object.v0000, object.v0001, object.v0002, object.v0003, object.v0004, object.v0005, object.v0006, object.v0007, object.v0008, object.v0009, object.v0010, object.v0011, object.v0012, object.v0013, object.v0014, object.v0015, object.v0016, object.v0017, object.v0018, object.v0019 ); mapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")); } catch (Exception ex) { ex.printStackTrace(); } } @Benchmark public void fastjson1(Blackhole bh) { bh.consume( com.alibaba.fastjson.JSON.toJSONString(array) ); } @Benchmark public void fastjson2(Blackhole bh) {<FILL_FUNCTION_BODY>} @Benchmark public void fastjson2_jsonb(Blackhole bh) { bh.consume( JSONB.toBytes(array) ); } @Benchmark public void jackson(Blackhole bh) throws Exception { bh.consume( mapper.writeValueAsString(array) ); } public void wastjson(Blackhole bh) throws Exception { bh.consume( io.github.wycst.wast.json.JSON.toJsonString(array) ); } public static void main(String[] args) throws RunnerException { Options options = new OptionsBuilder() .include(Date20TreeWrite.class.getName()) .mode(Mode.Throughput) .timeUnit(TimeUnit.MILLISECONDS) .warmupIterations(3) .forks(1) .build(); new Runner(options).run(); } }
bh.consume( JSON.toJSONString(array) );
687
24
711
5,741
WuKongOpenSource_Wukong_HRM
Wukong_HRM/hrm/hrm-web/src/main/java/com/kakarote/hrm/service/impl/HrmAttendanceDateShiftServiceImpl.java
HrmAttendanceDateShiftServiceImpl
addOrUpdate
class HrmAttendanceDateShiftServiceImpl extends BaseServiceImpl<HrmAttendanceDateShiftMapper, HrmAttendanceDateShift> implements IHrmAttendanceDateShiftService { /** * 查询字段配置 * * @param id 主键ID * @return data * @author guomenghao * @since 2023-08-19 */ @Override public HrmAttendanceDateShift queryById(Serializable id) { return getById(id); } /** * 保存或新增信息 * * @param entity entity * @author guomenghao * @since 2023-08-19 */ @Override @Transactional(rollbackFor = Exception.class) public void addOrUpdate(HrmAttendanceDateShift entity) {<FILL_FUNCTION_BODY>} /** * 查询所有数据 * * @param search 搜索条件 * @return list * @author guomenghao * @since 2023-08-19 */ @Override public BasePage<HrmAttendanceDateShift> queryPageList(PageEntity search) { return lambdaQuery().page(search.parse()); } /** * 根据ID列表删除数据 * * @param ids ids * @author guomenghao * @since 2023-08-19 */ @Override public void deleteByIds(List<Serializable> ids) { if (ids == null || ids.isEmpty()) { return; } removeByIds(ids); } /** * 查询出已经初始化过历史班次的员工 * * @param localDateTime * @return */ @Override public Set<Long> queryEmployeeIds(LocalDateTime localDateTime) { return baseMapper.queryEmployeeIds(localDateTime); } }
saveOrUpdate(entity);
527
11
538
64,573
alibaba_jetcache
jetcache/jetcache-core/src/main/java/com/alicp/jetcache/support/JetCacheExecutor.java
JetCacheExecutor
run
class JetCacheExecutor { protected volatile static ScheduledExecutorService defaultExecutor; protected volatile static ScheduledExecutorService heavyIOExecutor; private static final ReentrantLock reentrantLock = new ReentrantLock(); private static AtomicInteger threadCount = new AtomicInteger(0); static { Runtime.getRuntime().addShutdownHook(new Thread() { @Override public void run() {<FILL_FUNCTION_BODY>} }); } public static ScheduledExecutorService defaultExecutor() { if (defaultExecutor != null) { return defaultExecutor; } reentrantLock.lock(); try{ if (defaultExecutor == null) { ThreadFactory tf = r -> { Thread t = new Thread(r, "JetCacheDefaultExecutor"); t.setDaemon(true); return t; }; defaultExecutor = new ScheduledThreadPoolExecutor( 1, tf, new ThreadPoolExecutor.DiscardPolicy()); } }finally { reentrantLock.unlock(); } return defaultExecutor; } public static ScheduledExecutorService heavyIOExecutor() { if (heavyIOExecutor != null) { return heavyIOExecutor; } reentrantLock.lock(); try { if (heavyIOExecutor == null) { ThreadFactory tf = r -> { Thread t = new Thread(r, "JetCacheHeavyIOExecutor" + threadCount.getAndIncrement()); t.setDaemon(true); return t; }; heavyIOExecutor = new ScheduledThreadPoolExecutor( 10, tf, new ThreadPoolExecutor.DiscardPolicy()); } }finally { reentrantLock.unlock(); } return heavyIOExecutor; } public static void setDefaultExecutor(ScheduledExecutorService executor) { JetCacheExecutor.defaultExecutor = executor; } public static void setHeavyIOExecutor(ScheduledExecutorService heavyIOExecutor) { JetCacheExecutor.heavyIOExecutor = heavyIOExecutor; } }
if (defaultExecutor != null) { defaultExecutor.shutdownNow(); } if (heavyIOExecutor != null) { heavyIOExecutor.shutdownNow(); }
543
52
595
6,500
apache_linkis
linkis/linkis-public-enhancements/linkis-bml/linkis-bml-server/src/main/java/org/apache/linkis/bml/common/LocalResourceHelper.java
LocalResourceHelper
upload
class LocalResourceHelper implements ResourceHelper { private static final Logger LOGGER = LoggerFactory.getLogger(LocalResourceHelper.class); private static final String LOCAL_SCHEMA = "file://"; @Override public long upload( String path, String user, InputStream inputStream, StringBuilder stringBuilder, boolean overwrite) throws UploadResourceException {<FILL_FUNCTION_BODY>} @Override public void update(String path) {} @Override public void getResource(String path, int start, int end) {} @Override public String generatePath(String user, String fileName, Map<String, Object> properties) { String resourceHeader = (String) properties.get("resourceHeader"); SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd"); String dateStr = format.format(new Date()); if (StringUtils.isNotEmpty(resourceHeader)) { return getSchema() + BmlServerConfiguration.BML_LOCAL_PREFIX().getValue() + "/" + user + "/" + dateStr + "/" + resourceHeader + "/" + fileName; } else { return getSchema() + BmlServerConfiguration.BML_LOCAL_PREFIX().getValue() + "/" + user + "/" + dateStr + "/" + fileName; } } @Override public String getSchema() { return LOCAL_SCHEMA; } @Override public boolean checkIfExists(String path, String user) throws IOException { Fs fileSystem = FSFactory.getFsByProxyUser(new FsPath(path), user); fileSystem.init(new HashMap<String, String>()); try { return fileSystem.exists(new FsPath(path)); } finally { fileSystem.close(); } } @Override public boolean checkBmlResourceStoragePrefixPathIfChanged(String path) { String prefixPath = getSchema() + BmlServerConfiguration.BML_LOCAL_PREFIX().getValue(); return !path.startsWith(prefixPath); } }
OutputStream outputStream = null; InputStream is0 = null; InputStream is1 = null; long size = 0; Fs fileSystem = null; try { FsPath fsPath = new FsPath(path); fileSystem = FSFactory.getFsByProxyUser(fsPath, user); fileSystem.init(new HashMap<String, String>()); if (!fileSystem.exists(fsPath)) { FileSystemUtils.createNewFile(fsPath, user, true); } byte[] buffer = new byte[1024]; long beforeSize = -1; is0 = fileSystem.read(fsPath); int ch0 = 0; while ((ch0 = is0.read(buffer)) != -1) { beforeSize += ch0; } outputStream = fileSystem.write(fsPath, overwrite); int ch = 0; MessageDigest md5Digest = DigestUtils.getMd5Digest(); while ((ch = inputStream.read(buffer)) != -1) { md5Digest.update(buffer, 0, ch); outputStream.write(buffer, 0, ch); size += ch; } if (stringBuilder != null) { stringBuilder.append(Hex.encodeHexString(md5Digest.digest())); } // Get all the bytes of the file by the file name. In this way, the wrong updated is // avoided. long afterSize = -1; is1 = fileSystem.read(fsPath); int ch1 = 0; while ((ch1 = is1.read(buffer)) != -1) { afterSize += ch1; } size = Math.max(size, afterSize - beforeSize); } catch (final IOException e) { LOGGER.error("{} write to {} failed, reason is, IOException:", user, path, e); UploadResourceException uploadResourceException = new UploadResourceException(); uploadResourceException.initCause(e); throw uploadResourceException; } catch (final Throwable t) { LOGGER.error("{} write to {} failed, reason is", user, path, t); UploadResourceException uploadResourceException = new UploadResourceException(); uploadResourceException.initCause(t); throw uploadResourceException; } finally { IOUtils.closeQuietly(outputStream); if (fileSystem != null) { try { fileSystem.close(); } catch (IOException e) { LOGGER.error("close filesystem failed", e); } } IOUtils.closeQuietly(inputStream); IOUtils.closeQuietly(is0); IOUtils.closeQuietly(is1); } return size;
564
709
1,273
10,727
graphhopper_graphhopper
graphhopper/core/src/main/java/com/graphhopper/routing/util/parsers/OSMWayIDParser.java
OSMWayIDParser
handleWayTags
class OSMWayIDParser implements TagParser { private final IntEncodedValue osmWayIdEnc; public OSMWayIDParser(IntEncodedValue osmWayIdEnc) { this.osmWayIdEnc = osmWayIdEnc; } @Override public void handleWayTags(int edgeId, EdgeIntAccess edgeIntAccess, ReaderWay way, IntsRef relationFlags) {<FILL_FUNCTION_BODY>} }
if (way.getId() > osmWayIdEnc.getMaxStorableInt()) throw new IllegalArgumentException("Cannot store OSM way ID: " + way.getId() + " as it is too large (> " + osmWayIdEnc.getMaxStorableInt() + "). You can disable " + osmWayIdEnc.getName() + " if you do not " + "need to store the OSM way IDs"); int wayId = Math.toIntExact(way.getId()); osmWayIdEnc.setInt(false, edgeId, edgeIntAccess, wayId);
118
150
268
21,198
apache_hertzbeat
hertzbeat/common/src/main/java/org/apache/hertzbeat/common/service/TencentSmsClient.java
TencentSmsClient
initSmsClient
class TencentSmsClient { private static final String RESPONSE_OK = "Ok"; private static final String REGION = "ap-guangzhou"; private SmsClient smsClient; private String appId; private String signName; private String templateId; public TencentSmsClient(CommonProperties properties) { if (properties == null || properties.getSms() == null || properties.getSms().getTencent() == null) { log.error("init error, please config TencentSmsClient props in application.yml"); throw new IllegalArgumentException("please config TencentSmsClient props"); } initSmsClient(properties.getSms().getTencent()); } private void initSmsClient(CommonProperties.TencentSmsProperties tencent) {<FILL_FUNCTION_BODY>} /** * send text message * @param appId appId * @param signName sign name * @param templateId template id * @param templateValues template values * @param phones phones num */ public void sendMessage(String appId, String signName, String templateId, String[] templateValues, String[] phones) { SendSmsRequest req = new SendSmsRequest(); req.setSmsSdkAppId(appId); req.setSignName(signName); req.setTemplateId(templateId); req.setTemplateParamSet(templateValues); req.setPhoneNumberSet(phones); try { SendSmsResponse smsResponse = this.smsClient.SendSms(req); SendStatus sendStatus = smsResponse.getSendStatusSet()[0]; if (!RESPONSE_OK.equals(sendStatus.getCode())) { throw new SendMessageException(sendStatus.getCode() + ":" + sendStatus.getMessage()); } } catch (Exception e) { log.warn(e.getMessage()); throw new SendMessageException(e.getMessage()); } } /** * send text message * @param templateValues template values * @param phones phones num */ public void sendMessage(String[] templateValues, String[] phones) { sendMessage(this.appId, this.signName, this.templateId, templateValues, phones); } }
this.appId = tencent.getAppId(); this.signName = tencent.getSignName(); this.templateId = tencent.getTemplateId(); Credential cred = new Credential(tencent.getSecretId(), tencent.getSecretKey()); smsClient = new SmsClient(cred, REGION);
594
93
687
7,138
zhkl0228_unidbg
unidbg/unidbg-ios/src/main/java/com/github/unidbg/ios/ipa/NSUserDefaultsResolver.java
NSUserDefaultsResolver
resolve
class NSUserDefaultsResolver implements IOResolver<DarwinFileIO> { private final String bundleIdentifier; private final Map<String, Object> map; public NSUserDefaultsResolver(String bundleIdentifier, Map<String, Object> map) { this.bundleIdentifier = bundleIdentifier; this.map = map; } @Override public FileResult<DarwinFileIO> resolve(Emulator<DarwinFileIO> emulator, String pathname, int oflags) {<FILL_FUNCTION_BODY>} }
if (pathname.endsWith(("/Library/Preferences/" + bundleIdentifier + ".plist"))) { NSDictionary root = (NSDictionary) NSDictionary.fromJavaObject(map); ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); try { PropertyListParser.saveAsBinary(root, outputStream); } catch (IOException e) { throw new IllegalStateException("save plist failed", e); } return FileResult.<DarwinFileIO>success(new ByteArrayFileIO(oflags, pathname, outputStream.toByteArray())); } return null;
141
152
293
48,506
thymeleaf_thymeleaf
thymeleaf/examples/springboot3/thymeleaf-examples-springboot3-biglist-mvc/src/main/java/org/thymeleaf/examples/springboot3/biglist/mvc/web/controller/ThymeleafController.java
ThymeleafController
smallList
class ThymeleafController { private PlaylistEntryRepository playlistEntryRepository; public ThymeleafController() { super(); } @Autowired public void setPlaylistEntryRepository(final PlaylistEntryRepository playlistEntryRepository) { this.playlistEntryRepository = playlistEntryRepository; } @RequestMapping({"/", "/thymeleaf"}) public String index() { return "thymeleaf/index"; } @RequestMapping("/smalllist.thymeleaf") public String smallList(final Model model) {<FILL_FUNCTION_BODY>} @RequestMapping("/biglist.thymeleaf") public String bigList(final Model model) { final Iterator<PlaylistEntry> playlistEntries = this.playlistEntryRepository.findLargeCollectionPlaylistEntries(); model.addAttribute("dataSource", playlistEntries); return "thymeleaf/biglist"; } }
model.addAttribute("entries", this.playlistEntryRepository.findAllPlaylistEntries()); return "thymeleaf/smalllist";
261
39
300
45,423
vsch_flexmark-java
flexmark-java/flexmark/src/main/java/com/vladsch/flexmark/html/renderer/AttributablePart.java
AttributablePart
hashCode
class AttributablePart { final public static AttributablePart NODE = new AttributablePart("NODE"); final public static AttributablePart NODE_POSITION = new AttributablePart("NODE_POSITION"); final public static AttributablePart LINK = new AttributablePart("LINK"); final public static AttributablePart ID = new AttributablePart("ID"); final private String myName; public AttributablePart(@NotNull String name) { this.myName = name; } public @NotNull String getName() { return myName; } @Override public boolean equals(Object o) { return this == o; } @Override public int hashCode() {<FILL_FUNCTION_BODY>} }
return super.hashCode();
201
11
212
46,777
apache_ignite
ignite/modules/core/src/main/java/org/apache/ignite/internal/processors/query/stat/ObjectStatisticsImpl.java
ObjectStatisticsImpl
clone
class ObjectStatisticsImpl implements Cloneable, ObjectStatistics { /** Total number of rows in object. */ private final long rowsCnt; /** Map columnKey to its statistic. */ @GridToStringInclude private final Map<String, ColumnStatistics> colNameToStat; /** * Constructor. * * @param rowsCnt Total rows count. * @param colNameToStat Column names to statistics map. */ public ObjectStatisticsImpl( long rowsCnt, Map<String, ColumnStatistics> colNameToStat ) { assert rowsCnt >= 0 : "rowsCnt >= 0"; assert colNameToStat != null : "colNameToStat != null"; this.rowsCnt = rowsCnt; this.colNameToStat = colNameToStat; } /** * @return Object rows count. */ public long rowCount() { return rowsCnt; } /** * Get column statistics. * * @param colName Column name. * @return Column statistics or {@code null} if there are no statistics for specified column. */ public ColumnStatistics columnStatistics(String colName) { return colNameToStat.get(colName); } /** * @return Column statistics map. */ public Map<String, ColumnStatistics> columnsStatistics() { return colNameToStat; } /** {@inheritDoc} */ @Override public ObjectStatisticsImpl clone() {<FILL_FUNCTION_BODY>} /** {@inheritDoc} */ @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; ObjectStatisticsImpl that = (ObjectStatisticsImpl)o; return rowsCnt == that.rowsCnt && Objects.equals(colNameToStat, that.colNameToStat); } /** {@inheritDoc} */ @Override public int hashCode() { return Objects.hash(rowsCnt, colNameToStat); } /** {@inheritDoc} */ @Override public String toString() { return S.toString(ObjectStatisticsImpl.class, this); } /** * Remove specified columns from clone of current ObjectStatistics object. * * @param cols Columns to remove. * @return Cloned object without specified columns statistics. */ public <T extends ObjectStatisticsImpl> T subtract(Set<String> cols) { T res = (T)clone(); for (String col : cols) res.columnsStatistics().remove(col); return res; } }
return new ObjectStatisticsImpl(rowsCnt, new HashMap<>(colNameToStat));
708
26
734
7,748
iluwatar_java-design-patterns
java-design-patterns/event-sourcing/src/main/java/com/iluwatar/event/sourcing/event/MoneyTransferEvent.java
MoneyTransferEvent
process
class MoneyTransferEvent extends DomainEvent { private final BigDecimal money; private final int accountNoFrom; private final int accountNoTo; /** * Instantiates a new Money transfer event. * * @param sequenceId the sequence id * @param createdTime the created time * @param money the money * @param accountNoFrom the account no from * @param accountNoTo the account no to */ @JsonCreator public MoneyTransferEvent(@JsonProperty("sequenceId") long sequenceId, @JsonProperty("createdTime") long createdTime, @JsonProperty("money") BigDecimal money, @JsonProperty("accountNoFrom") int accountNoFrom, @JsonProperty("accountNoTo") int accountNoTo) { super(sequenceId, createdTime, "MoneyTransferEvent"); this.money = money; this.accountNoFrom = accountNoFrom; this.accountNoTo = accountNoTo; } @Override public void process() {<FILL_FUNCTION_BODY>} }
var accountFrom = Optional.ofNullable(AccountAggregate.getAccount(accountNoFrom)) .orElseThrow(() -> new RuntimeException("Account not found " + accountNoFrom)); var accountTo = Optional.ofNullable(AccountAggregate.getAccount(accountNoTo)) .orElseThrow(() -> new RuntimeException("Account not found " + accountNoTo)); accountFrom.handleTransferFromEvent(this); accountTo.handleTransferToEvent(this);
274
119
393
440
apolloconfig_apollo
apollo/apollo-portal/src/main/java/com/ctrip/framework/apollo/portal/service/AdditionalUserInfoEnrichServiceImpl.java
AdditionalUserInfoEnrichServiceImpl
adapt
class AdditionalUserInfoEnrichServiceImpl implements AdditionalUserInfoEnrichService { private final UserService userService; private final List<AdditionalUserInfoEnricher> enricherList; public AdditionalUserInfoEnrichServiceImpl( UserService userService, List<AdditionalUserInfoEnricher> enricherList) { this.userService = userService; this.enricherList = enricherList; } @Override public <T> void enrichAdditionalUserInfo(List<? extends T> list, Function<? super T, ? extends UserInfoEnrichedAdapter> mapper) { if (CollectionUtils.isEmpty(list)) { return; } if (CollectionUtils.isEmpty(this.enricherList)) { return; } List<UserInfoEnrichedAdapter> adapterList = this.adapt(list, mapper); if (CollectionUtils.isEmpty(adapterList)) { return; } Set<String> userIdSet = this.extractOperatorId(adapterList); if (CollectionUtils.isEmpty(userIdSet)) { return; } List<UserInfo> userInfoList = this.userService.findByUserIds(new ArrayList<>(userIdSet)); if (CollectionUtils.isEmpty(userInfoList)) { return; } Map<String, UserInfo> userInfoMap = userInfoList.stream() .collect(Collectors.toMap(UserInfo::getUserId, Function.identity())); for (UserInfoEnrichedAdapter adapter : adapterList) { for (AdditionalUserInfoEnricher enricher : this.enricherList) { enricher.enrichAdditionalUserInfo(adapter, userInfoMap); } } } private <T> List<UserInfoEnrichedAdapter> adapt(List<? extends T> dtoList, Function<? super T, ? extends UserInfoEnrichedAdapter> mapper) {<FILL_FUNCTION_BODY>} private <T> Set<String> extractOperatorId(List<UserInfoEnrichedAdapter> adapterList) { Set<String> operatorIdSet = new HashSet<>(); for (UserInfoEnrichedAdapter adapter : adapterList) { if (StringUtils.hasText(adapter.getFirstUserId())) { operatorIdSet.add(adapter.getFirstUserId()); } if (StringUtils.hasText(adapter.getSecondUserId())) { operatorIdSet.add(adapter.getSecondUserId()); } if (StringUtils.hasText(adapter.getThirdUserId())) { operatorIdSet.add(adapter.getThirdUserId()); } } return operatorIdSet; } }
List<UserInfoEnrichedAdapter> adapterList = new ArrayList<>(dtoList.size()); for (T dto : dtoList) { if (dto == null) { continue; } UserInfoEnrichedAdapter enrichedAdapter = mapper.apply(dto); adapterList.add(enrichedAdapter); } return adapterList;
693
99
792
54,325
apache_dubbo
dubbo/dubbo-spring-boot/dubbo-spring-boot-starters/observability/autoconfigure/src/main/java/org/apache/dubbo/spring/boot/observability/autoconfigure/DubboMicrometerTracingAutoConfiguration.java
DubboMicrometerTracingAutoConfiguration
propagatingSenderTracingObservationHandler
class DubboMicrometerTracingAutoConfiguration { /** * {@code @Order} value of * {@link #propagatingReceiverTracingObservationHandler(io.micrometer.tracing.Tracer, io.micrometer.tracing.propagation.Propagator)}. */ public static final int RECEIVER_TRACING_OBSERVATION_HANDLER_ORDER = 1000; /** * {@code @Order} value of * {@link #propagatingSenderTracingObservationHandler(io.micrometer.tracing.Tracer, io.micrometer.tracing.propagation.Propagator)}. */ public static final int SENDER_TRACING_OBSERVATION_HANDLER_ORDER = 2000; @Bean @ConditionalOnMissingBean @ConditionalOnBean(io.micrometer.tracing.Tracer.class) public io.micrometer.tracing.handler.DefaultTracingObservationHandler defaultTracingObservationHandler( io.micrometer.tracing.Tracer tracer) { return new io.micrometer.tracing.handler.DefaultTracingObservationHandler(tracer); } @Bean @ConditionalOnMissingBean @ConditionalOnBean({io.micrometer.tracing.Tracer.class, io.micrometer.tracing.propagation.Propagator.class}) @Order(SENDER_TRACING_OBSERVATION_HANDLER_ORDER) public io.micrometer.tracing.handler.PropagatingSenderTracingObservationHandler<?> propagatingSenderTracingObservationHandler( io.micrometer.tracing.Tracer tracer, io.micrometer.tracing.propagation.Propagator propagator) {<FILL_FUNCTION_BODY>} @Bean @ConditionalOnMissingBean @ConditionalOnBean({io.micrometer.tracing.Tracer.class, io.micrometer.tracing.propagation.Propagator.class}) @Order(RECEIVER_TRACING_OBSERVATION_HANDLER_ORDER) public io.micrometer.tracing.handler.PropagatingReceiverTracingObservationHandler<?> propagatingReceiverTracingObservationHandler( io.micrometer.tracing.Tracer tracer, io.micrometer.tracing.propagation.Propagator propagator) { return new io.micrometer.tracing.handler.PropagatingReceiverTracingObservationHandler<>(tracer, propagator); } }
return new io.micrometer.tracing.handler.PropagatingSenderTracingObservationHandler<>(tracer, propagator);
672
36
708
67,135
alibaba_Sentinel
Sentinel/sentinel-cluster/sentinel-cluster-server-default/src/main/java/com/alibaba/csp/sentinel/cluster/flow/ClusterFlowChecker.java
ClusterFlowChecker
acquireClusterToken
class ClusterFlowChecker { private static double calcGlobalThreshold(FlowRule rule) { double count = rule.getCount(); switch (rule.getClusterConfig().getThresholdType()) { case ClusterRuleConstant.FLOW_THRESHOLD_GLOBAL: return count; case ClusterRuleConstant.FLOW_THRESHOLD_AVG_LOCAL: default: int connectedCount = ClusterFlowRuleManager.getConnectedCount(rule.getClusterConfig().getFlowId()); return count * connectedCount; } } static boolean allowProceed(long flowId) { String namespace = ClusterFlowRuleManager.getNamespace(flowId); return GlobalRequestLimiter.tryPass(namespace); } static TokenResult acquireClusterToken(/*@Valid*/ FlowRule rule, int acquireCount, boolean prioritized) {<FILL_FUNCTION_BODY>} private static TokenResult blockedResult() { return new TokenResult(TokenResultStatus.BLOCKED) .setRemaining(0) .setWaitInMs(0); } private ClusterFlowChecker() {} }
Long id = rule.getClusterConfig().getFlowId(); if (!allowProceed(id)) { return new TokenResult(TokenResultStatus.TOO_MANY_REQUEST); } ClusterMetric metric = ClusterMetricStatistics.getMetric(id); if (metric == null) { return new TokenResult(TokenResultStatus.FAIL); } double latestQps = metric.getAvg(ClusterFlowEvent.PASS); double globalThreshold = calcGlobalThreshold(rule) * ClusterServerConfigManager.getExceedCount(); double nextRemaining = globalThreshold - latestQps - acquireCount; if (nextRemaining >= 0) { // TODO: checking logic and metric operation should be separated. metric.add(ClusterFlowEvent.PASS, acquireCount); metric.add(ClusterFlowEvent.PASS_REQUEST, 1); if (prioritized) { // Add prioritized pass. metric.add(ClusterFlowEvent.OCCUPIED_PASS, acquireCount); } // Remaining count is cut down to a smaller integer. return new TokenResult(TokenResultStatus.OK) .setRemaining((int) nextRemaining) .setWaitInMs(0); } else { if (prioritized) { // Try to occupy incoming buckets. double occupyAvg = metric.getAvg(ClusterFlowEvent.WAITING); if (occupyAvg <= ClusterServerConfigManager.getMaxOccupyRatio() * globalThreshold) { int waitInMs = metric.tryOccupyNext(ClusterFlowEvent.PASS, acquireCount, globalThreshold); // waitInMs > 0 indicates pre-occupy incoming buckets successfully. if (waitInMs > 0) { ClusterServerStatLogUtil.log("flow|waiting|" + id); return new TokenResult(TokenResultStatus.SHOULD_WAIT) .setRemaining(0) .setWaitInMs(waitInMs); } // Or else occupy failed, should be blocked. } } // Blocked. metric.add(ClusterFlowEvent.BLOCK, acquireCount); metric.add(ClusterFlowEvent.BLOCK_REQUEST, 1); ClusterServerStatLogUtil.log("flow|block|" + id, acquireCount); ClusterServerStatLogUtil.log("flow|block_request|" + id, 1); if (prioritized) { // Add prioritized block. metric.add(ClusterFlowEvent.OCCUPIED_BLOCK, acquireCount); ClusterServerStatLogUtil.log("flow|occupied_block|" + id, 1); } return blockedResult(); }
294
697
991
65,129
igniterealtime_Openfire
Openfire/xmppserver/src/main/java/org/jivesoftware/openfire/update/Update.java
Update
getComponentName
class Update { /** * Name of the component that is outdated. The name could be of the server * (i.e. "Openfire") or of installed plugins. */ private String componentName; /** * Latest version of the component that was found. */ private String latestVersion; /** * URL from where the latest version of the component can be downloaded. */ private String url; /** * Changelog URL of the latest version of the component. */ private String changelog; /** * Flag that indicates if the plugin was downloaded. This flag only makes sense for * plugins since we currently do not support download new openfire releases. */ private boolean downloaded; public Update(String componentName, String latestVersion, String changelog, String url) { this.componentName = componentName; this.latestVersion = latestVersion; this.changelog = changelog; this.url = url; } /** * Returns the name of the component that is outdated. When the server is the * outdated component then a "Openfire" will be returned. Otherwise, the name of * the outdated plugin is returned. * * @return the name of the component that is outdated. */ public String getComponentName() {<FILL_FUNCTION_BODY>} /** * Returns the latest version of the component that was found. * * @return the latest version of the component that was found. */ public String getLatestVersion() { return latestVersion; } /** * Returns the URL to the change log of the latest version of the component. * * @return the URL to the change log of the latest version of the component. */ public String getChangelog() { return changelog; } /** * Returns the URL from where the latest version of the component can be downloaded. * * @return the URL from where the latest version of the component can be downloaded. */ public String getURL() { return url; } /** * Returns true if the plugin was downloaded. Once a plugin has been downloaded * it may take a couple of seconds to be installed. This flag only makes sense for * plugins since we currently do not support download new openfire releases. * * @return true if the plugin was downloaded. */ public boolean isDownloaded() { return downloaded; } /** * Sets if the plugin was downloaded. Once a plugin has been downloaded * it may take a couple of seconds to be installed. This flag only makes sense for * plugins since we currently do not support download new openfire releases. * * @param downloaded true if the plugin was downloaded. */ public void setDownloaded(boolean downloaded) { this.downloaded = downloaded; } /** * Returns the hashCode for this update object. * @return hashCode */ public int getHashCode(){ return hashCode(); } }
return componentName;
771
9
780
23,455
junit-team_junit4
junit4/src/main/java/junit/framework/ComparisonFailure.java
ComparisonFailure
getMessage
class ComparisonFailure extends AssertionFailedError { private static final int MAX_CONTEXT_LENGTH = 20; private static final long serialVersionUID = 1L; private String fExpected; private String fActual; /** * Constructs a comparison failure. * * @param message the identifying message or null * @param expected the expected string value * @param actual the actual string value */ public ComparisonFailure(String message, String expected, String actual) { super(message); fExpected = expected; fActual = actual; } /** * Returns "..." in place of common prefix and "..." in * place of common suffix between expected and actual. * * @see Throwable#getMessage() */ @Override public String getMessage() {<FILL_FUNCTION_BODY>} /** * Gets the actual string value * * @return the actual string value */ public String getActual() { return fActual; } /** * Gets the expected string value * * @return the expected string value */ public String getExpected() { return fExpected; } }
return new ComparisonCompactor(MAX_CONTEXT_LENGTH, fExpected, fActual).compact(super.getMessage());
308
32
340
59,049
alibaba_druid
druid/core/src/main/java/com/alibaba/druid/sql/ast/statement/SQLCharacterDataType.java
SQLCharacterDataType
getLength
class SQLCharacterDataType extends SQLDataTypeImpl { private String charSetName; private String collate; private String charType; private boolean hasBinary; public List<SQLCommentHint> hints; public static final String CHAR_TYPE_BYTE = "BYTE"; public static final String CHAR_TYPE_CHAR = "CHAR"; public SQLCharacterDataType(String name) { super(name); } public SQLCharacterDataType(String name, int precision) { super(name, precision); } public String getCharSetName() { return charSetName; } public void setCharSetName(String charSetName) { this.charSetName = charSetName; } public boolean isHasBinary() { return hasBinary; } public void setHasBinary(boolean hasBinary) { this.hasBinary = hasBinary; } public String getCollate() { return collate; } public void setCollate(String collate) { this.collate = collate; } public String getCharType() { return charType; } public void setCharType(String charType) { this.charType = charType; } public List<SQLCommentHint> getHints() { return hints; } public void setHints(List<SQLCommentHint> hints) { this.hints = hints; } public int getLength() {<FILL_FUNCTION_BODY>} @Override protected void accept0(SQLASTVisitor visitor) { if (visitor.visit(this)) { for (int i = 0; i < arguments.size(); i++) { SQLExpr arg = arguments.get(i); if (arg != null) { arg.accept(visitor); } } } visitor.endVisit(this); } public SQLCharacterDataType clone() { SQLCharacterDataType x = new SQLCharacterDataType(getName()); super.cloneTo(x); x.charSetName = charSetName; x.collate = collate; x.charType = charType; x.hasBinary = hasBinary; return x; } @Override public String toString() { return SQLUtils.toSQLString(this); } public int jdbcType() { long nameNash = nameHashCode64(); if (nameNash == FnvHash.Constants.NCHAR) { return Types.NCHAR; } if (nameNash == FnvHash.Constants.CHAR || nameNash == FnvHash.Constants.JSON) { return Types.CHAR; } if (nameNash == FnvHash.Constants.VARCHAR || nameNash == FnvHash.Constants.VARCHAR2 || nameNash == FnvHash.Constants.STRING) { return Types.VARCHAR; } if (nameNash == FnvHash.Constants.NVARCHAR || nameNash == FnvHash.Constants.NVARCHAR2) { return Types.NVARCHAR; } return Types.OTHER; } }
if (this.arguments.size() == 1) { SQLExpr arg = this.arguments.get(0); if (arg instanceof SQLIntegerExpr) { return ((SQLIntegerExpr) arg).getNumber().intValue(); } } return -1;
843
71
914
50,677
soot-oss_soot
soot/src/main/java/soot/toDex/instructions/Insn20t.java
Insn20t
getMaxJumpOffset
class Insn20t extends InsnWithOffset { public Insn20t(Opcode opc) { super(opc); } @Override protected BuilderInstruction getRealInsn0(LabelAssigner assigner) { return new BuilderInstruction20t(opc, assigner.getOrCreateLabel(target)); } @Override public int getMaxJumpOffset() {<FILL_FUNCTION_BODY>} }
return Short.MAX_VALUE;
122
12
134
42,063
jtablesaw_tablesaw
tablesaw/html/src/main/java/tech/tablesaw/io/html/HtmlReader.java
HtmlReader
read
class HtmlReader implements DataReader<HtmlReadOptions> { private static final HtmlReader INSTANCE = new HtmlReader(); static { register(Table.defaultReaderRegistry); } public static void register(ReaderRegistry registry) { registry.registerExtension("html", INSTANCE); registry.registerMimeType("text/html", INSTANCE); registry.registerOptions(HtmlReadOptions.class, INSTANCE); } @Override public Table read(HtmlReadOptions options) {<FILL_FUNCTION_BODY>} @Override public Table read(Source source) { return read(HtmlReadOptions.builder(source).build()); } }
Document doc; InputStream inputStream = options.source().inputStream(); try { if (inputStream != null) { // Reader must support mark, so can't use InputStreamReader // Parse the InputStream directly doc = Jsoup.parse(inputStream, null, ""); } else { doc = Parser.htmlParser().parseInput(options.source().createReader(null), ""); } } catch (IOException e) { throw new RuntimeIOException(e); } Elements tables = doc.select("table"); int tableIndex = 0; if (tables.size() != 1) { if (options.tableIndex() != null) { if (options.tableIndex() >= 0 && options.tableIndex() < tables.size()) { tableIndex = options.tableIndex(); } else { throw new IndexOutOfBoundsException( "Table index outside bounds. The URL has " + tables.size() + " tables"); } } else { throw new IllegalStateException( tables.size() + " tables found. When more than one html table is present on the page you must specify the index of the table to read from."); } } Element htmlTable = tables.get(tableIndex); List<String[]> rows = new ArrayList<>(); for (Element row : htmlTable.select("tr")) { Elements headerCells = row.getElementsByTag("th"); Elements cells = row.getElementsByTag("td"); String[] nextLine = Stream.concat(headerCells.stream(), cells.stream()) .map(Element::text) .toArray(String[]::new); rows.add(nextLine); } Table table = Table.create(options.tableName()); if (rows.isEmpty()) { return table; } List<String> columnNames = new ArrayList<>(); if (options.header()) { String[] headerRow = rows.remove(0); for (int i = 0; i < headerRow.length; i++) { columnNames.add(headerRow[i]); } } else { for (int i = 0; i < rows.get(0).length; i++) { columnNames.add("C" + i); } } return TableBuildingUtils.build(columnNames, rows, options);
177
603
780
27,185
confluentinc_ksql
ksql/ksqldb-functional-tests/src/main/java/io/confluent/ksql/test/model/TestFileContext.java
TestFileContext
getLineNumber
class TestFileContext { private static final Path RESOURCE_ROOT = getRoot() .resolve("src") .resolve("test") .resolve("resources"); private final Path originalFileName; private final Path testPath; private final ImmutableList<String> lines; public TestFileContext(final Path testPath, final List<String> lines) { this.originalFileName = requireNonNull(testPath, "testPath"); this.testPath = RESOURCE_ROOT.resolve(originalFileName); this.lines = ImmutableList.copyOf(lines); } public Path getOriginalFileName() { return originalFileName; } public TestLocation getFileLocation() { return new PathLocation(testPath); } public TestLocation getTestLocation(final String testName) { return new LocationWithinFile(testPath, getLineNumber(testName)); } private int getLineNumber(final String testName) {<FILL_FUNCTION_BODY>} private static Path getRoot() { final Path currentDir = Paths.get("").toAbsolutePath(); if (currentDir.endsWith("ksqldb-functional-tests")) { return currentDir; } return currentDir.resolve("ksqldb-functional-tests"); } }
final Pattern pattern = Pattern .compile(".*\"name\"\\s*:\\s*\"" + Pattern.quote(testName) + "\".*"); int lineNumber = 0; for (final String line : lines) { lineNumber++; if (pattern.matcher(line).matches()) { return lineNumber; } } throw new TestFrameworkException("Can't find test in test file" + System.lineSeparator() + "test: " + testName + System.lineSeparator() + "file: " + testPath );
338
156
494
15,464
karatelabs_karate
karate/karate-core/src/main/java/com/intuit/karate/template/KarateEachTagProcessor.java
KarateEachTagProcessor
doProcess
class KarateEachTagProcessor extends AbstractAttributeTagProcessor { private static final Logger logger = LoggerFactory.getLogger(KarateEachTagProcessor.class); public static final int PRECEDENCE = 200; public static final String ATTR_NAME = "each"; public KarateEachTagProcessor(final TemplateMode templateMode, final String dialectPrefix) { super(templateMode, dialectPrefix, null, false, ATTR_NAME, true, PRECEDENCE, true); } @Override protected void doProcess( final ITemplateContext context, final IProcessableElementTag tag, final AttributeName attributeName, String av, final IElementTagStructureHandler structureHandler) {<FILL_FUNCTION_BODY>} }
int pos = av.indexOf(':'); String iterVarName; if (pos == -1) { iterVarName = "_"; } else { iterVarName = av.substring(0, pos).trim(); av = av.substring(pos + 1); } Object value = KarateEngineContext.get().evalLocal(av, true).getValue(); structureHandler.iterateElement(iterVarName, null, value);
194
115
309
59,646
lealone_Lealone
Lealone/lealone-common/src/main/java/com/lealone/sql/PreparedSQLStatement.java
YieldableCommand
getPriority
class YieldableCommand { private final int packetId; private final PreparedSQLStatement.Yieldable<?> yieldable; private final int sessionId; public YieldableCommand(int packetId, PreparedSQLStatement.Yieldable<?> yieldable, int sessionId) { this.packetId = packetId; this.yieldable = yieldable; this.sessionId = sessionId; } public int getPacketId() { return packetId; } public int getSessionId() { return sessionId; } public Session getSession() { return yieldable.getSession(); } public int getPriority() {<FILL_FUNCTION_BODY>} public void run() { yieldable.run(); } public void stop() { yieldable.stop(); } }
return yieldable.getPriority();
231
12
243
29,092
apache_incubator-seata
incubator-seata/common/src/main/java/org/apache/seata/common/exception/FrameworkException.java
FrameworkException
getErrcode
class FrameworkException extends RuntimeException { private static final Logger LOGGER = LoggerFactory.getLogger(FrameworkException.class); private static final long serialVersionUID = 5531074229174745826L; private final FrameworkErrorCode errcode; /** * Instantiates a new Framework exception. */ public FrameworkException() { this(FrameworkErrorCode.UnknownAppError); } /** * Instantiates a new Framework exception. * * @param err the err */ public FrameworkException(FrameworkErrorCode err) { this(err.getErrMessage(), err); } /** * Instantiates a new Framework exception. * * @param msg the msg */ public FrameworkException(String msg) { this(msg, FrameworkErrorCode.UnknownAppError); } /** * Instantiates a new Framework exception. * * @param msg the msg * @param errCode the err code */ public FrameworkException(String msg, FrameworkErrorCode errCode) { this(null, msg, errCode); } /** * Instantiates a new Framework exception. * * @param cause the cause * @param msg the msg * @param errCode the err code */ public FrameworkException(Throwable cause, String msg, FrameworkErrorCode errCode) { super(msg, cause); this.errcode = errCode; } /** * Instantiates a new Framework exception. * * @param th the th */ public FrameworkException(Throwable th) { this(th, th.getMessage()); } /** * Instantiates a new Framework exception. * * @param th the th * @param msg the msg */ public FrameworkException(Throwable th, String msg) { this(th, msg, FrameworkErrorCode.UnknownAppError); } /** * Gets errcode. * * @return the errcode */ public FrameworkErrorCode getErrcode() {<FILL_FUNCTION_BODY>} /** * Nested exception framework exception. * * @param e the e * @return the framework exception */ public static FrameworkException nestedException(Throwable e) { return nestedException("", e); } /** * Nested exception framework exception. * * @param msg the msg * @param e the e * @return the framework exception */ public static FrameworkException nestedException(String msg, Throwable e) { LOGGER.error(msg, e.getMessage(), e); if (e instanceof FrameworkException) { return (FrameworkException)e; } return new FrameworkException(e, msg); } /** * Nested sql exception sql exception. * * @param e the e * @return the sql exception */ public static SQLException nestedSQLException(Throwable e) { return nestedSQLException("", e); } /** * Nested sql exception sql exception. * * @param msg the msg * @param e the e * @return the sql exception */ public static SQLException nestedSQLException(String msg, Throwable e) { LOGGER.error(msg, e.getMessage(), e); if (e instanceof SQLException) { return (SQLException)e; } return new SQLException(e); } }
return errcode;
937
9
946
52,020
dromara_dynamic-tp
dynamic-tp/core/src/main/java/org/dromara/dynamictp/core/support/task/runnable/MdcRunnable.java
MdcRunnable
run
class MdcRunnable implements Runnable { private final Runnable runnable; private final Thread parentThread; /** * Saves the MDC value of the current thread */ private final Map<String, String> parentMdc; public MdcRunnable(Runnable runnable) { this.runnable = runnable; this.parentMdc = MDC.getCopyOfContextMap(); this.parentThread = Thread.currentThread(); } public static MdcRunnable get(Runnable runnable) { return new MdcRunnable(runnable); } @Override public void run() {<FILL_FUNCTION_BODY>} }
if (MapUtils.isEmpty(parentMdc) || Objects.equals(Thread.currentThread(), parentThread)) { runnable.run(); return; } // Assign the MDC value of the parent thread to the child thread for (Map.Entry<String, String> entry : parentMdc.entrySet()) { MDC.put(entry.getKey(), entry.getValue()); } try { // Execute the decorated thread run method runnable.run(); } finally { // Remove MDC value at the end of execution for (Map.Entry<String, String> entry : parentMdc.entrySet()) { if (!TRACE_ID.equals(entry.getKey())) { MDC.remove(entry.getKey()); } } }
192
205
397
17,617
checkstyle_checkstyle
checkstyle/src/main/java/com/puppycrawl/tools/checkstyle/checks/coding/EmptyStatementCheck.java
EmptyStatementCheck
getAcceptableTokens
class EmptyStatementCheck extends AbstractCheck { /** * A key is pointing to the warning message text in "messages.properties" * file. */ public static final String MSG_KEY = "empty.statement"; @Override public int[] getDefaultTokens() { return getRequiredTokens(); } @Override public int[] getAcceptableTokens() {<FILL_FUNCTION_BODY>} @Override public int[] getRequiredTokens() { return new int[] {TokenTypes.EMPTY_STAT}; } @Override public void visitToken(DetailAST ast) { log(ast, MSG_KEY); } }
return getRequiredTokens();
181
11
192
68,939
soot-oss_soot
soot/src/main/java/soot/javaToJimple/jj/Version.java
Version
patch_level
class Version extends polyglot.main.Version { public String name() { return "jj"; } // TODO: define a version number, the default (below) is 0.1.0 public int major() { return 0; } public int minor() { return 1; } public int patch_level() {<FILL_FUNCTION_BODY>} }
return 0;
109
9
118
42,367
noear_solon
solon/solon-projects/solon-boot/solon.boot.websocket/src/main/java/org/noear/solon/boot/websocket/WsServer.java
WsServer
getSession
class WsServer extends WebSocketServer { static final Logger log = LoggerFactory.getLogger(WsServer.class); static final WebSocketServerProps wsProps = WebSocketServerProps.getInstance(); private final WebSocketRouter webSocketRouter = WebSocketRouter.getInstance(); public WsServer(int port) { super(new InetSocketAddress(port)); } public WsServer(InetAddress address, int port) { super(new InetSocketAddress(address, port)); } @Override public void onStart() { LogUtil.global().info("Server:Websocket onStart..."); } private WebSocketImpl getSession(WebSocket conn) { return getSession(conn, null); } private WebSocketImpl getSession(WebSocket conn, ClientHandshake shake) {<FILL_FUNCTION_BODY>} @Override public void onOpen(WebSocket conn, ClientHandshake shake) { WebSocketImpl webSocket = getSession(conn, shake); webSocketRouter.getListener().onOpen(webSocket); //设置闲置超时 if (wsProps.getIdleTimeout() > 0) { webSocket.setIdleTimeout(wsProps.getIdleTimeout()); } } @Override public void onClose(WebSocket conn, int i, String s, boolean b) { WebSocketImpl webSocket = getSession(conn); if (webSocket.isClosed()) { return; } else { webSocket.close(); } webSocketRouter.getListener().onClose(webSocket); } @Override public void onWebsocketPing(WebSocket conn, Framedata f) { super.onWebsocketPing(conn, f); WebSocketImpl webSocket = getSession(conn); if (webSocket != null) { webSocket.onReceive(); } } @Override public void onWebsocketPong(WebSocket conn, Framedata f) { super.onWebsocketPong(conn, f); WebSocketImpl webSocket = getSession(conn); if (webSocket != null) { webSocket.onReceive(); } } @Override public void onMessage(WebSocket conn, String data) { try { WebSocketImpl webSocket = getSession(conn); webSocket.onReceive(); webSocketRouter.getListener().onMessage(webSocket, data); } catch (Throwable e) { log.warn(e.getMessage(), e); } } @Override public void onMessage(WebSocket conn, ByteBuffer data) { try { WebSocketImpl webSocket = getSession(conn); webSocket.onReceive(); webSocketRouter.getListener().onMessage(webSocket, data); } catch (Throwable e) { log.warn(e.getMessage(), e); } } @Override public void onError(WebSocket conn, Exception ex) { try { WebSocketImpl webSocket = getSession(conn); webSocketRouter.getListener().onError(webSocket, ex); } catch (Throwable e) { log.warn(e.getMessage(), e); } } }
WebSocketImpl session = conn.getAttachment(); if (session == null) { //直接从附件拿,不一定可靠 session = new WebSocketImpl(conn); conn.setAttachment(session); if (shake != null) { Iterator<String> httpFields = shake.iterateHttpFields(); while (httpFields.hasNext()) { String name = httpFields.next(); session.param(name, shake.getFieldValue(name)); } } } return session;
851
141
992
33,463
flowable_flowable-engine
flowable-engine/modules/flowable-identitylink-service/src/main/java/org/flowable/identitylink/service/impl/persistence/entity/data/impl/cachematcher/IdentityLinksByProcessInstanceUserGroupAndTypeMatcher.java
IdentityLinksByProcessInstanceUserGroupAndTypeMatcher
isRetained
class IdentityLinksByProcessInstanceUserGroupAndTypeMatcher extends CachedEntityMatcherAdapter<IdentityLinkEntity> { @Override public boolean isRetained(IdentityLinkEntity entity, Object parameter) {<FILL_FUNCTION_BODY>} }
@SuppressWarnings("unchecked") Map<String, String> parameterMap = (Map<String, String>) parameter; if (!Objects.equals(entity.getProcessInstanceId(), parameterMap.get("processInstanceId"))) { return false; } if (!Objects.equals(entity.getUserId(), parameterMap.get("userId"))) { return false; } if (!Objects.equals(entity.getGroupId(), parameterMap.get("groupId"))) { return false; } return Objects.equals(entity.getType(), parameterMap.get("type"));
65
153
218
56,230
apache_incubator-seata
incubator-seata/serializer/seata-serializer-protobuf/src/main/java/org/apache/seata/serializer/protobuf/convertor/RegisterRMResponseConvertor.java
RegisterRMResponseConvertor
convert2Proto
class RegisterRMResponseConvertor implements PbConvertor<RegisterRMResponse, RegisterRMResponseProto> { @Override public RegisterRMResponseProto convert2Proto(RegisterRMResponse registerRMResponse) {<FILL_FUNCTION_BODY>} @Override public RegisterRMResponse convert2Model(RegisterRMResponseProto registerRMResponseProto) { RegisterRMResponse registerRMRequest = new RegisterRMResponse(); AbstractIdentifyResponseProto abstractIdentifyRequestProto = registerRMResponseProto .getAbstractIdentifyResponse(); registerRMRequest.setExtraData(abstractIdentifyRequestProto.getExtraData()); registerRMRequest.setVersion(abstractIdentifyRequestProto.getVersion()); registerRMRequest.setIdentified(abstractIdentifyRequestProto.getIdentified()); registerRMRequest.setMsg(abstractIdentifyRequestProto.getAbstractResultMessage().getMsg()); registerRMRequest.setResultCode( ResultCode.valueOf(abstractIdentifyRequestProto.getAbstractResultMessage().getResultCode().name())); return registerRMRequest; } }
final short typeCode = registerRMResponse.getTypeCode(); final AbstractMessageProto abstractMessage = AbstractMessageProto.newBuilder().setMessageType( MessageTypeProto.forNumber(typeCode)).build(); final String msg = registerRMResponse.getMsg(); //for code if (registerRMResponse.getResultCode() == null) { if (registerRMResponse.isIdentified()) { registerRMResponse.setResultCode(ResultCode.Success); } else { registerRMResponse.setResultCode(ResultCode.Failed); } } final AbstractResultMessageProto abstractResultMessageProto = AbstractResultMessageProto.newBuilder().setMsg( msg == null ? "" : msg).setResultCode(ResultCodeProto.valueOf(registerRMResponse.getResultCode().name())) .setAbstractMessage(abstractMessage).build(); final String extraData = registerRMResponse.getExtraData(); AbstractIdentifyResponseProto abstractIdentifyResponseProto = AbstractIdentifyResponseProto.newBuilder() .setAbstractResultMessage(abstractResultMessageProto).setExtraData(extraData == null ? "" : extraData) .setVersion(registerRMResponse.getVersion()).setIdentified(registerRMResponse.isIdentified()).build(); RegisterRMResponseProto result = RegisterRMResponseProto.newBuilder().setAbstractIdentifyResponse( abstractIdentifyResponseProto).build(); return result;
278
356
634
52,281
flowable_flowable-engine
flowable-engine/modules/flowable-task-service/src/main/java/org/flowable/task/service/impl/TaskQueryProperty.java
TaskQueryProperty
findByName
class TaskQueryProperty implements QueryProperty { private static final long serialVersionUID = 1L; private static final Map<String, TaskQueryProperty> properties = new HashMap<>(); public static final TaskQueryProperty TASK_ID = new TaskQueryProperty("RES.ID_"); public static final TaskQueryProperty NAME = new TaskQueryProperty("RES.NAME_"); public static final TaskQueryProperty DESCRIPTION = new TaskQueryProperty("RES.DESCRIPTION_"); public static final TaskQueryProperty PRIORITY = new TaskQueryProperty("RES.PRIORITY_"); public static final TaskQueryProperty ASSIGNEE = new TaskQueryProperty("RES.ASSIGNEE_"); public static final TaskQueryProperty OWNER = new TaskQueryProperty("RES.OWNER_"); public static final TaskQueryProperty CREATE_TIME = new TaskQueryProperty("RES.CREATE_TIME_"); public static final TaskQueryProperty PROCESS_INSTANCE_ID = new TaskQueryProperty("RES.PROC_INST_ID_"); public static final TaskQueryProperty EXECUTION_ID = new TaskQueryProperty("RES.EXECUTION_ID_"); public static final TaskQueryProperty PROCESS_DEFINITION_ID = new TaskQueryProperty("RES.PROC_DEF_ID_"); public static final TaskQueryProperty DUE_DATE = new TaskQueryProperty("RES.DUE_DATE_"); public static final TaskQueryProperty TENANT_ID = new TaskQueryProperty("RES.TENANT_ID_"); public static final TaskQueryProperty TASK_DEFINITION_KEY = new TaskQueryProperty("RES.TASK_DEF_KEY_"); public static final TaskQueryProperty CATEGORY = new TaskQueryProperty("RES.CATEGORY_"); private String name; public TaskQueryProperty(String name) { this.name = name; properties.put(name, this); } @Override public String getName() { return name; } public static TaskQueryProperty findByName(String propertyName) {<FILL_FUNCTION_BODY>} }
return properties.get(propertyName);
510
13
523
56,401
pagehelper_Mybatis-PageHelper
Mybatis-PageHelper/src/main/java/com/github/pagehelper/dialect/auto/DataSourceNegotiationAutoDialect.java
DataSourceNegotiationAutoDialect
extractDialectKey
class DataSourceNegotiationAutoDialect implements AutoDialect<String> { private static final List<DataSourceAutoDialect> AUTO_DIALECTS = new ArrayList<DataSourceAutoDialect>(); private Map<String, DataSourceAutoDialect> urlMap = new ConcurrentHashMap<String, DataSourceAutoDialect>(); static { //创建时,初始化所有实现,当依赖的连接池不存在时,这里不会添加成功,所以理论上这里包含的内容不会多,执行时不会迭代多次 try { AUTO_DIALECTS.add(new HikariAutoDialect()); } catch (Exception ignore) { } try { AUTO_DIALECTS.add(new DruidAutoDialect()); } catch (Exception ignore) { } try { AUTO_DIALECTS.add(new TomcatAutoDialect()); } catch (Exception ignore) { } try { AUTO_DIALECTS.add(new C3P0AutoDialect()); } catch (Exception ignore) { } try { AUTO_DIALECTS.add(new DbcpAutoDialect()); } catch (Exception ignore) { } } /** * 允许手工添加额外的实现,实际上没有必要 * * @param autoDialect */ public static void registerAutoDialect(DataSourceAutoDialect autoDialect) { AUTO_DIALECTS.add(autoDialect); } @Override public String extractDialectKey(MappedStatement ms, DataSource dataSource, Properties properties) {<FILL_FUNCTION_BODY>} @Override public AbstractHelperDialect extractDialect(String dialectKey, MappedStatement ms, DataSource dataSource, Properties properties) { if (dialectKey != null && urlMap.containsKey(dialectKey)) { return urlMap.get(dialectKey).extractDialect(dialectKey, ms, dataSource, properties); } //都不匹配的时候使用默认方式 return DefaultAutoDialect.DEFAULT.extractDialect(dialectKey, ms, dataSource, properties); } }
for (DataSourceAutoDialect autoDialect : AUTO_DIALECTS) { String dialectKey = autoDialect.extractDialectKey(ms, dataSource, properties); if (dialectKey != null) { if (!urlMap.containsKey(dialectKey)) { urlMap.put(dialectKey, autoDialect); } return dialectKey; } } //都不匹配的时候使用默认方式 return DefaultAutoDialect.DEFAULT.extractDialectKey(ms, dataSource, properties);
583
149
732
3,428
orientechnologies_orientdb
orientdb/core/src/main/java/com/orientechnologies/orient/core/index/OIndexUnique.java
OIndexUnique
interpretTxKeyChanges
class OIndexUnique extends OIndexOneValue { private final IndexEngineValidator<Object, ORID> uniqueValidator = new UniqueIndexEngineValidator(this); public OIndexUnique(OIndexMetadata im, final OStorage storage) { super(im, storage); } @Override public boolean isNativeTxSupported() { return true; } @Override public void doPut(OAbstractPaginatedStorage storage, Object key, ORID rid) throws OInvalidIndexEngineIdException { storage.validatedPutIndexValue(indexId, key, rid, uniqueValidator); } @Override public boolean canBeUsedInEqualityOperators() { return true; } @Override public boolean supportsOrderedIterations() { while (true) { try { return storage.hasIndexRangeQuerySupport(indexId); } catch (OInvalidIndexEngineIdException ignore) { doReloadIndexEngine(); } } } @Override public Iterable<OTransactionIndexChangesPerKey.OTransactionIndexEntry> interpretTxKeyChanges( OTransactionIndexChangesPerKey changes) {<FILL_FUNCTION_BODY>} }
return changes.interpret(OTransactionIndexChangesPerKey.Interpretation.Unique);
310
25
335
35,643
apache_incubator-seata
incubator-seata/saga/seata-saga-engine/src/main/java/org/apache/seata/saga/engine/exception/EngineExecutionException.java
EngineExecutionException
getStateMachineInstanceId
class EngineExecutionException extends FrameworkException { private String stateName; private String stateMachineName; private String stateMachineInstanceId; private String stateInstanceId; public EngineExecutionException() { } public EngineExecutionException(FrameworkErrorCode err) { super(err); } public EngineExecutionException(String msg) { super(msg); } public EngineExecutionException(String msg, FrameworkErrorCode errCode) { super(msg, errCode); } public EngineExecutionException(Throwable cause, String msg, FrameworkErrorCode errCode) { super(cause, msg, errCode); } public EngineExecutionException(Throwable th) { super(th); } public EngineExecutionException(Throwable th, String msg) { super(th, msg); } public String getStateName() { return stateName; } public void setStateName(String stateName) { this.stateName = stateName; } public String getStateMachineName() { return stateMachineName; } public void setStateMachineName(String stateMachineName) { this.stateMachineName = stateMachineName; } public String getStateMachineInstanceId() {<FILL_FUNCTION_BODY>} public void setStateMachineInstanceId(String stateMachineInstanceId) { this.stateMachineInstanceId = stateMachineInstanceId; } public String getStateInstanceId() { return stateInstanceId; } public void setStateInstanceId(String stateInstanceId) { this.stateInstanceId = stateInstanceId; } }
return stateMachineInstanceId;
427
11
438
52,352
WuKongOpenSource_Wukong_HRM
Wukong_HRM/hrm/hrm-web/src/main/java/com/kakarote/hrm/entity/BO/QueryEmployeePageListBO.java
QueryEmployeePageListBO
toString
class QueryEmployeePageListBO extends PageEntity { @ApiModelProperty(value = "员工姓名") private String employeeName; @ApiModelProperty(value = "手机") private String mobile; @ApiModelProperty(value = "性别 1 男 2 女") private Integer sex; @ApiModelProperty(value = "入职时间") private List<LocalDate> entryTime; @ApiModelProperty(value = "工号") private String jobNumber; @ApiModelProperty(value = "部门ID") private Long deptId; @ApiModelProperty(value = "岗位") private String post; @ApiModelProperty(value = "转正日期") private List<LocalDate> becomeTime; @ApiModelProperty(value = "工作地点") private String workAddress; @ApiModelProperty(value = "聘用形式 1 正式 2 非正式") private Integer employmentForms; @ApiModelProperty(value = "员工状态 1正式 2试用 3实习 4兼职 5劳务 6顾问 7返聘 8外包 9待离职 10已离职 11 在职 12 全职") private Integer status; @ApiModelProperty("人事概况 1 入职 2 离职 3 转正 4 调岗 5 待入职 6 待离职") private Integer employeeSurvey; @ApiModelProperty("代办提醒 2 待离职 3 合同到期 4 待转正 5 待入职 6 生日") private Integer toDoRemind; @ApiModelProperty("员工id(导出使用)") private List<Long> employeeIds; @ApiModelProperty(value = "排序字段") private String sortField; @ApiModelProperty(value = "排序字段 1 倒序 2 正序") private Integer order; @Override public String toString() {<FILL_FUNCTION_BODY>} }
return "QueryEmployeePageListBO{" + "employeeName='" + employeeName + '\'' + ", mobile='" + mobile + '\'' + ", sex=" + sex + ", entryTime=" + entryTime + ", jobNumber='" + jobNumber + '\'' + ", deptId=" + deptId + ", post='" + post + '\'' + ", becomeTime=" + becomeTime + ", workAddress='" + workAddress + '\'' + ", employmentForms=" + employmentForms + ", status=" + status + ", employeeSurvey=" + employeeSurvey + ", toDoRemind=" + toDoRemind + ", employeeIds=" + employeeIds + ", sortField='" + sortField + '\'' + ", order=" + order + '}';
533
214
747
64,409
find-sec-bugs_find-sec-bugs
find-sec-bugs/findsecbugs-samples-deps/src/main/java/org/springframework/web/servlet/support/ServletUriComponentsBuilder.java
ServletUriComponentsBuilder
fromContextPath
class ServletUriComponentsBuilder extends UriComponentsBuilder { public static ServletUriComponentsBuilder fromContextPath(HttpServletRequest request) {<FILL_FUNCTION_BODY>} }
return null;
50
8
58
19,617
fabric8io_kubernetes-client
kubernetes-client/extensions/knative/client/src/main/java/io/fabric8/knative/client/DefaultKnativeClient.java
DefaultKnativeClient
parallels
class DefaultKnativeClient extends ExtensionRootClientAdapter<DefaultKnativeClient> implements NamespacedKnativeClient, SupportTestingClient { public DefaultKnativeClient() { super(); } public DefaultKnativeClient(Config config) { super(config); } public DefaultKnativeClient(Client client) { super(client); } @Override protected DefaultKnativeClient newInstance(Client client) { return new DefaultKnativeClient(client); } @Override public FunctionCallable<NamespacedKnativeClient> withRequestConfig(RequestConfig requestConfig) { return new WithRequestCallable<>(this, requestConfig); } @Override public MixedOperation<Service, ServiceList, Resource<Service>> services() { return resources(Service.class, ServiceList.class); } @Override public MixedOperation<Route, RouteList, Resource<Route>> routes() { return resources(Route.class, RouteList.class); } @Override public MixedOperation<Revision, RevisionList, Resource<Revision>> revisions() { return resources(Revision.class, RevisionList.class); } @Override public MixedOperation<Configuration, ConfigurationList, Resource<Configuration>> configurations() { return resources(Configuration.class, ConfigurationList.class); } @Override public MixedOperation<DomainMapping, DomainMappingList, Resource<DomainMapping>> domainMappings() { return resources(DomainMapping.class, DomainMappingList.class); } @Override public MixedOperation<Broker, BrokerList, Resource<Broker>> brokers() { return resources(Broker.class, BrokerList.class); } @Override public MixedOperation<Trigger, TriggerList, Resource<Trigger>> triggers() { return resources(Trigger.class, TriggerList.class); } @Override public MixedOperation<Channel, ChannelList, Resource<Channel>> channels() { return resources(Channel.class, ChannelList.class); } @Override public MixedOperation<Subscription, SubscriptionList, Resource<Subscription>> subscriptions() { return resources(Subscription.class, SubscriptionList.class); } @Override public MixedOperation<EventType, EventTypeList, Resource<EventType>> eventTypes() { return resources(EventType.class, EventTypeList.class); } @Override public MixedOperation<Sequence, SequenceList, Resource<Sequence>> sequences() { return resources(Sequence.class, SequenceList.class); } @Override public MixedOperation<Parallel, ParallelList, Resource<Parallel>> parallels() {<FILL_FUNCTION_BODY>} @Override public MixedOperation<InMemoryChannel, InMemoryChannelList, Resource<InMemoryChannel>> inMemoryChannels() { return resources(InMemoryChannel.class, InMemoryChannelList.class); } @Override public MixedOperation<PingSource, PingSourceList, Resource<PingSource>> pingSources() { return resources(PingSource.class, PingSourceList.class); } @Override public MixedOperation<SinkBinding, SinkBindingList, Resource<SinkBinding>> sinkBindings() { return resources(SinkBinding.class, SinkBindingList.class); } @Override public MixedOperation<ContainerSource, ContainerSourceList, Resource<ContainerSource>> containerSources() { return resources(ContainerSource.class, ContainerSourceList.class); } @Override public MixedOperation<ApiServerSource, ApiServerSourceList, Resource<ApiServerSource>> apiServerSources() { return resources(ApiServerSource.class, ApiServerSourceList.class); } @Override public MixedOperation<AwsSqsSource, AwsSqsSourceList, Resource<AwsSqsSource>> awsSqsSources() { return resources(AwsSqsSource.class, AwsSqsSourceList.class); } @Override public MixedOperation<CouchDbSource, CouchDbSourceList, Resource<CouchDbSource>> couchDbSources() { return resources(CouchDbSource.class, CouchDbSourceList.class); } @Override public MixedOperation<GitHubSource, GitHubSourceList, Resource<GitHubSource>> gitHubSources() { return resources(GitHubSource.class, GitHubSourceList.class); } @Override public MixedOperation<GitHubBinding, GitHubBindingList, Resource<GitHubBinding>> gitHubBindings() { return resources(GitHubBinding.class, GitHubBindingList.class); } @Override public MixedOperation<GitLabSource, GitLabSourceList, Resource<GitLabSource>> gitLabSources() { return resources(GitLabSource.class, GitLabSourceList.class); } @Override public MixedOperation<GitLabBinding, GitLabBindingList, Resource<GitLabBinding>> gitLabBindings() { return resources(GitLabBinding.class, GitLabBindingList.class); } @Override public MixedOperation<PrometheusSource, PrometheusSourceList, Resource<PrometheusSource>> prometheusSources() { return resources(PrometheusSource.class, PrometheusSourceList.class); } @Override public MixedOperation<KafkaChannel, KafkaChannelList, Resource<KafkaChannel>> kafkaChannels() { return resources(KafkaChannel.class, KafkaChannelList.class); } @Override public MixedOperation<KafkaSource, KafkaSourceList, Resource<KafkaSource>> kafkasSources() { return resources(KafkaSource.class, KafkaSourceList.class); } @Override public MixedOperation<KafkaBinding, KafkaBindingList, Resource<KafkaBinding>> kafkaBindings() { return resources(KafkaBinding.class, KafkaBindingList.class); } @Override public boolean isSupported() { return hasApiGroup("knative.dev", false); } }
return resources(Parallel.class, ParallelList.class);
1,601
19
1,620
18,521
oshi_oshi
oshi/oshi-core/src/main/java/oshi/hardware/platform/unix/solaris/SolarisHWDiskStore.java
SolarisHWDiskStore
updateAttributes2
class SolarisHWDiskStore extends AbstractHWDiskStore { private long reads = 0L; private long readBytes = 0L; private long writes = 0L; private long writeBytes = 0L; private long currentQueueLength = 0L; private long transferTime = 0L; private long timeStamp = 0L; private List<HWPartition> partitionList; private SolarisHWDiskStore(String name, String model, String serial, long size) { super(name, model, serial, size); } @Override public long getReads() { return reads; } @Override public long getReadBytes() { return readBytes; } @Override public long getWrites() { return writes; } @Override public long getWriteBytes() { return writeBytes; } @Override public long getCurrentQueueLength() { return currentQueueLength; } @Override public long getTransferTime() { return transferTime; } @Override public long getTimeStamp() { return timeStamp; } @Override public List<HWPartition> getPartitions() { return this.partitionList; } @Override public boolean updateAttributes() { this.timeStamp = System.currentTimeMillis(); if (HAS_KSTAT2) { // Use Kstat2 implementation return updateAttributes2(); } try (KstatChain kc = KstatUtil.openChain()) { Kstat ksp = kc.lookup(null, 0, getName()); if (ksp != null && kc.read(ksp)) { KstatIO data = new KstatIO(ksp.ks_data); this.reads = data.reads; this.writes = data.writes; this.readBytes = data.nread; this.writeBytes = data.nwritten; this.currentQueueLength = (long) data.wcnt + data.rcnt; // rtime and snaptime are nanoseconds, convert to millis this.transferTime = data.rtime / 1_000_000L; this.timeStamp = ksp.ks_snaptime / 1_000_000L; return true; } } return false; } private boolean updateAttributes2() {<FILL_FUNCTION_BODY>} /** * Gets the disks on this machine * * @return a list of {@link HWDiskStore} objects representing the disks */ public static List<HWDiskStore> getDisks() { // Create map to correlate disk name with block device mount point for // later use in partition info Map<String, String> deviceMap = Iostat.queryPartitionToMountMap(); // Create map to correlate disk name with block device mount point for // later use in partition info. Run lshal, if available, to get block device // major (we'll use partition # for minor) Map<String, Integer> majorMap = Lshal.queryDiskToMajorMap(); // Create map of model, vendor, product, serial, size // We'll use Model if available, otherwise Vendor+Product Map<String, Quintet<String, String, String, String, Long>> deviceStringMap = Iostat .queryDeviceStrings(deviceMap.keySet()); List<HWDiskStore> storeList = new ArrayList<>(); for (Entry<String, Quintet<String, String, String, String, Long>> entry : deviceStringMap.entrySet()) { String storeName = entry.getKey(); Quintet<String, String, String, String, Long> val = entry.getValue(); storeList.add(createStore(storeName, val.getA(), val.getB(), val.getC(), val.getD(), val.getE(), deviceMap.getOrDefault(storeName, ""), majorMap.getOrDefault(storeName, 0))); } return storeList; } private static SolarisHWDiskStore createStore(String diskName, String model, String vendor, String product, String serial, long size, String mount, int major) { SolarisHWDiskStore store = new SolarisHWDiskStore(diskName, model.isEmpty() ? (vendor + " " + product).trim() : model, serial, size); store.partitionList = Collections.unmodifiableList(Prtvtoc.queryPartitions(mount, major).stream() .sorted(Comparator.comparing(HWPartition::getName)).collect(Collectors.toList())); store.updateAttributes(); return store; } }
String fullName = getName(); String alpha = fullName; String numeric = ""; for (int c = 0; c < fullName.length(); c++) { if (fullName.charAt(c) >= '0' && fullName.charAt(c) <= '9') { alpha = fullName.substring(0, c); numeric = fullName.substring(c); break; } } // Try device style notation Object[] results = KstatUtil.queryKstat2("kstat:/disk/" + alpha + "/" + getName() + "/0", "reads", "writes", "nread", "nwritten", "wcnt", "rcnt", "rtime", "snaptime"); // If failure try io notation if (results[results.length - 1] == null) { results = KstatUtil.queryKstat2("kstat:/disk/" + alpha + "/" + numeric + "/io", "reads", "writes", "nread", "nwritten", "wcnt", "rcnt", "rtime", "snaptime"); } if (results[results.length - 1] == null) { return false; } this.reads = results[0] == null ? 0L : (long) results[0]; this.writes = results[1] == null ? 0L : (long) results[1]; this.readBytes = results[2] == null ? 0L : (long) results[2]; this.writeBytes = results[3] == null ? 0L : (long) results[3]; this.currentQueueLength = results[4] == null ? 0L : (long) results[4]; this.currentQueueLength += results[5] == null ? 0L : (long) results[5]; // rtime and snaptime are nanoseconds, convert to millis this.transferTime = results[6] == null ? 0L : (long) results[6] / 1_000_000L; this.timeStamp = (long) results[7] / 1_000_000L; return true;
1,215
552
1,767
36,597
alibaba_easyexcel
easyexcel/easyexcel-core/src/main/java/com/alibaba/excel/converters/doubleconverter/DoubleStringConverter.java
DoubleStringConverter
convertToExcelData
class DoubleStringConverter implements Converter<Double> { @Override public Class<?> supportJavaTypeKey() { return Double.class; } @Override public CellDataTypeEnum supportExcelTypeKey() { return CellDataTypeEnum.STRING; } @Override public Double convertToJavaData(ReadCellData<?> cellData, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) throws ParseException { return NumberUtils.parseDouble(cellData.getStringValue(), contentProperty); } @Override public WriteCellData<?> convertToExcelData(Double value, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) {<FILL_FUNCTION_BODY>} }
return NumberUtils.formatToCellDataString(value, contentProperty);
185
20
205
50,816
lilishop_lilishop
lilishop/framework/src/main/java/cn/lili/modules/distribution/serviceimpl/DistributionCashServiceImpl.java
DistributionCashServiceImpl
audit
class DistributionCashServiceImpl extends ServiceImpl<DistributionCashMapper, DistributionCash> implements DistributionCashService { /** * 分销员 */ @Autowired private DistributionService distributionService; /** * 会员余额 */ @Autowired private MemberWalletService memberWalletService; @Autowired private RocketMQTemplate rocketMQTemplate; @Autowired private RocketmqCustomProperties rocketmqCustomProperties; @Override @Transactional(rollbackFor = Exception.class) public Boolean cash(Double applyMoney) { //检查分销功能开关 distributionService.checkDistributionSetting(); //获取分销员 Distribution distribution = distributionService.getDistribution(); //如果未找到分销员或者分销员状态不是已通过则无法申请提现 if (distribution != null && distribution.getDistributionStatus().equals(DistributionStatusEnum.PASS.name())) { //校验分销佣金是否大于提现金额 if (distribution.getCanRebate() < applyMoney) { throw new ServiceException(ResultCode.WALLET_WITHDRAWAL_INSUFFICIENT); } //将提现金额存入冻结金额,扣减可提现金额 distribution.setCanRebate(CurrencyUtil.sub(distribution.getCanRebate(), applyMoney)); distribution.setCommissionFrozen(CurrencyUtil.add(distribution.getCommissionFrozen(), applyMoney)); distributionService.updateById(distribution); //提现申请记录 DistributionCash distributionCash = new DistributionCash("D" + SnowFlake.getId(), distribution.getId(), applyMoney, distribution.getMemberName()); boolean result = this.save(distributionCash); if (result) { //发送提现消息 MemberWithdrawalMessage memberWithdrawalMessage = new MemberWithdrawalMessage(); memberWithdrawalMessage.setMemberId(distribution.getMemberId()); memberWithdrawalMessage.setPrice(applyMoney); memberWithdrawalMessage.setStatus(WithdrawStatusEnum.APPLY.name()); String destination = rocketmqCustomProperties.getMemberTopic() + ":" + MemberTagsEnum.MEMBER_WITHDRAWAL.name(); rocketMQTemplate.asyncSend(destination, memberWithdrawalMessage, RocketmqSendCallbackBuilder.commonCallback()); return true; } return false; } throw new ServiceException(ResultCode.DISTRIBUTION_NOT_EXIST); } @Override public IPage<DistributionCash> getDistributionCash(PageVO page) { Distribution distribution = distributionService.getDistribution(); QueryWrapper<DistributionCash> queryWrapper = new QueryWrapper<>(); queryWrapper.eq("distribution_id", distribution.getId()); return this.page(PageUtil.initPage(page), queryWrapper); } @Override public IPage<DistributionCash> getDistributionCash(DistributionCashSearchParams distributionCashSearchParams) { return this.page(PageUtil.initPage(distributionCashSearchParams), distributionCashSearchParams.queryWrapper()); } @Override @Transactional(rollbackFor = Exception.class) public DistributionCash audit(String id, String result) {<FILL_FUNCTION_BODY>} }
//检查分销功能开关 distributionService.checkDistributionSetting(); //获取分销佣金信息 DistributionCash distributorCash = this.getById(id); //只有分销员和分销佣金记录存在的情况才可以审核 if (distributorCash != null) { //获取分销员 Distribution distribution = distributionService.getById(distributorCash.getDistributionId()); if (distribution != null && distribution.getDistributionStatus().equals(DistributionStatusEnum.PASS.name())) { MemberWithdrawalMessage memberWithdrawalMessage = new MemberWithdrawalMessage(); //审核通过 if (result.equals(WithdrawStatusEnum.VIA_AUDITING.name())) { memberWithdrawalMessage.setStatus(WithdrawStatusEnum.VIA_AUDITING.name()); //分销记录操作 distributorCash.setDistributionCashStatus(WithdrawStatusEnum.VIA_AUDITING.name()); distributorCash.setPayTime(new Date()); //提现到余额 memberWalletService.increase(new MemberWalletUpdateDTO(distributorCash.getPrice(), distribution.getMemberId(), "分销[" + distributorCash.getSn() + "]佣金提现到余额[" + distributorCash.getPrice() + "]", DepositServiceTypeEnum.WALLET_COMMISSION.name())); } else { memberWithdrawalMessage.setStatus(WithdrawStatusEnum.FAIL_AUDITING.name()); //分销员可提现金额退回 distribution.setCanRebate(CurrencyUtil.add(distribution.getCanRebate(), distributorCash.getPrice())); distributorCash.setDistributionCashStatus(WithdrawStatusEnum.FAIL_AUDITING.name()); } distribution.setCommissionFrozen(CurrencyUtil.sub(distribution.getCommissionFrozen(), distributorCash.getPrice())); //分销员金额相关处理 distributionService.updateById(distribution); //修改分销提现申请 boolean bool = this.updateById(distributorCash); //if (bool) { // //组织会员提现审核消息 // memberWithdrawalMessage.setMemberId(distribution.getMemberId()); // memberWithdrawalMessage.setPrice(distributorCash.getPrice()); // String destination = rocketmqCustomProperties.getMemberTopic() + ":" + MemberTagsEnum.MEMBER_WITHDRAWAL.name(); // rocketMQTemplate.asyncSend(destination, memberWithdrawalMessage, RocketmqSendCallbackBuilder.commonCallback()); //} return distributorCash; } throw new ServiceException(ResultCode.DISTRIBUTION_NOT_EXIST); } throw new ServiceException(ResultCode.DISTRIBUTION_CASH_NOT_EXIST);
870
749
1,619
29,967
macrozheng_mall-swarm
mall-swarm/mall-admin/src/main/java/com/macro/mall/controller/SmsFlashPromotionSessionController.java
SmsFlashPromotionSessionController
selectList
class SmsFlashPromotionSessionController { @Autowired private SmsFlashPromotionSessionService flashPromotionSessionService; @ApiOperation("添加场次") @RequestMapping(value = "/create", method = RequestMethod.POST) @ResponseBody public CommonResult create(@RequestBody SmsFlashPromotionSession promotionSession) { int count = flashPromotionSessionService.create(promotionSession); if (count > 0) { return CommonResult.success(count); } return CommonResult.failed(); } @ApiOperation("修改场次") @RequestMapping(value = "/update/{id}", method = RequestMethod.POST) @ResponseBody public CommonResult update(@PathVariable Long id, @RequestBody SmsFlashPromotionSession promotionSession) { int count = flashPromotionSessionService.update(id, promotionSession); if (count > 0) { return CommonResult.success(count); } return CommonResult.failed(); } @ApiOperation("修改启用状态") @RequestMapping(value = "/update/status/{id}", method = RequestMethod.POST) @ResponseBody public CommonResult updateStatus(@PathVariable Long id, Integer status) { int count = flashPromotionSessionService.updateStatus(id, status); if (count > 0) { return CommonResult.success(count); } return CommonResult.failed(); } @ApiOperation("删除场次") @RequestMapping(value = "/delete/{id}", method = RequestMethod.POST) @ResponseBody public CommonResult delete(@PathVariable Long id) { int count = flashPromotionSessionService.delete(id); if (count > 0) { return CommonResult.success(count); } return CommonResult.failed(); } @ApiOperation("获取场次详情") @RequestMapping(value = "/{id}", method = RequestMethod.GET) @ResponseBody public CommonResult<SmsFlashPromotionSession> getItem(@PathVariable Long id) { SmsFlashPromotionSession promotionSession = flashPromotionSessionService.getItem(id); return CommonResult.success(promotionSession); } @ApiOperation("获取全部场次") @RequestMapping(value = "/list", method = RequestMethod.GET) @ResponseBody public CommonResult<List<SmsFlashPromotionSession>> list() { List<SmsFlashPromotionSession> promotionSessionList = flashPromotionSessionService.list(); return CommonResult.success(promotionSessionList); } @ApiOperation("获取全部可选场次及其数量") @RequestMapping(value = "/selectList", method = RequestMethod.GET) @ResponseBody public CommonResult<List<SmsFlashPromotionSessionDetail>> selectList(Long flashPromotionId) {<FILL_FUNCTION_BODY>} }
List<SmsFlashPromotionSessionDetail> promotionSessionList = flashPromotionSessionService.selectList(flashPromotionId); return CommonResult.success(promotionSessionList);
735
47
782
2,730
apache_incubator-seata
incubator-seata/core/src/main/java/org/apache/seata/core/exception/AbstractExceptionHandler.java
AbstractCallback
exceptionHandleTemplate
class AbstractCallback<T extends AbstractTransactionRequest, S extends AbstractTransactionResponse> implements Callback<T, S> { @Override public void onSuccess(T request, S response) { response.setResultCode(ResultCode.Success); } @Override public void onTransactionException(T request, S response, TransactionException tex) { response.setTransactionExceptionCode(tex.getCode()); response.setResultCode(ResultCode.Failed); response.setMsg("TransactionException[" + tex.getMessage() + "]"); } @Override public void onException(T request, S response, Exception rex) { response.setResultCode(ResultCode.Failed); response.setMsg("RuntimeException[" + rex.getMessage() + "]"); } } /** * Exception handle template. * * @param <T> the type parameter * @param <S> the type parameter * @param callback the callback * @param request the request * @param response the response */ public <T extends AbstractTransactionRequest, S extends AbstractTransactionResponse> void exceptionHandleTemplate(Callback<T, S> callback, T request, S response) {<FILL_FUNCTION_BODY>
try { callback.execute(request, response); callback.onSuccess(request, response); } catch (TransactionException tex) { if (Objects.equals(TransactionExceptionCode.LockKeyConflict, tex.getCode())) { LOGGER.error("this request cannot acquire global lock, you can let Seata retry by setting config [{}] = false or manually retry by yourself. request: {}", ConfigurationKeys.CLIENT_LOCK_RETRY_POLICY_BRANCH_ROLLBACK_ON_CONFLICT, request); } else if (Objects.equals(TransactionExceptionCode.LockKeyConflictFailFast, tex.getCode())) { LOGGER.error("this request cannot acquire global lock, decide fail-fast because LockStatus is {}. request: {}", LockStatus.Rollbacking, request); } else { LOGGER.error("Catch TransactionException while do RPC, request: {}", request, tex); } callback.onTransactionException(request, response, tex); } catch (RuntimeException rex) { LOGGER.error("Catch RuntimeException while do RPC, request: {}", request, rex); callback.onException(request, response, rex); }
316
308
624
52,475
flowable_flowable-engine
flowable-engine/modules/flowable-engine/src/main/java/org/flowable/engine/impl/util/EventInstanceBpmnUtil.java
EventInstanceBpmnUtil
handleEventInstanceOutParameters
class EventInstanceBpmnUtil { /** * Processes the 'out parameters' of an {@link EventInstance} and stores the corresponding variables on the {@link VariableScope}. * * Typically used when mapping incoming event payload into a runtime instance (the {@link VariableScope}). */ public static void handleEventInstanceOutParameters(VariableScope variableScope, BaseElement baseElement, EventInstance eventInstance) {<FILL_FUNCTION_BODY>} /** * Reads the 'in parameters' and converts them to {@link EventPayloadInstance} instances. * * Typically used when needing to create {@link EventInstance}'s and populate the payload. */ public static Collection<EventPayloadInstance> createEventPayloadInstances(VariableScope variableScope, ExpressionManager expressionManager, BaseElement baseElement, EventModel eventDefinition) { List<EventPayloadInstance> eventPayloadInstances = new ArrayList<>(); if (baseElement instanceof SendEventServiceTask) { SendEventServiceTask eventServiceTask = (SendEventServiceTask) baseElement; if (!eventServiceTask.getEventInParameters().isEmpty()) { for (IOParameter parameter : eventServiceTask.getEventInParameters()) { String sourceValue = null; if (StringUtils.isNotEmpty(parameter.getSourceExpression())) { sourceValue = parameter.getSourceExpression(); } else { sourceValue = parameter.getSource(); } addEventPayloadInstance(eventPayloadInstances, sourceValue, parameter.getTarget(), variableScope, expressionManager, eventDefinition); } } } else { List<ExtensionElement> inParameters = baseElement.getExtensionElements() .getOrDefault(BpmnXMLConstants.ELEMENT_EVENT_IN_PARAMETER, Collections.emptyList()); if (!inParameters.isEmpty()) { for (ExtensionElement inParameter : inParameters) { String sourceExpression = inParameter.getAttributeValue(null, BpmnXMLConstants.ATTRIBUTE_IOPARAMETER_SOURCE_EXPRESSION); String source = inParameter.getAttributeValue(null, BpmnXMLConstants.ATTRIBUTE_IOPARAMETER_SOURCE); String target = inParameter.getAttributeValue(null, BpmnXMLConstants.ATTRIBUTE_IOPARAMETER_TARGET); String sourceValue = null; if (StringUtils.isNotEmpty(sourceExpression)) { sourceValue = sourceExpression; } else { sourceValue = source; } addEventPayloadInstance(eventPayloadInstances, sourceValue, target, variableScope, expressionManager, eventDefinition); } } } return eventPayloadInstances; } protected static void setEventParameterVariable(String source, String target, boolean isTransient, Map<String, EventPayloadInstance> payloadInstances, VariableScope variableScope) { EventPayloadInstance payloadInstance = payloadInstances.get(source); if (StringUtils.isNotEmpty(target)) { Object value = payloadInstance != null ? payloadInstance.getValue() : null; if (Boolean.TRUE.equals(isTransient)) { variableScope.setTransientVariable(target, value); } else { variableScope.setVariable(target, value); } } } protected static void addEventPayloadInstance(List<EventPayloadInstance> eventPayloadInstances, String source, String target, VariableScope variableScope, ExpressionManager expressionManager, EventModel eventDefinition) { EventPayload eventPayloadDefinition = eventDefinition.getPayload(target); if (eventPayloadDefinition != null) { Expression sourceExpression = expressionManager.createExpression(source); Object value = sourceExpression.getValue(variableScope); eventPayloadInstances.add(new EventPayloadInstanceImpl(eventPayloadDefinition, value)); } } }
Map<String, EventPayloadInstance> payloadInstances = eventInstance.getPayloadInstances() .stream() .collect(Collectors.toMap(EventPayloadInstance::getDefinitionName, Function.identity())); if (baseElement instanceof SendEventServiceTask) { SendEventServiceTask eventServiceTask = (SendEventServiceTask) baseElement; if (!eventServiceTask.getEventOutParameters().isEmpty()) { for (IOParameter parameter : eventServiceTask.getEventOutParameters()) { setEventParameterVariable(parameter.getSource(), parameter.getTarget(), parameter.isTransient(), payloadInstances, variableScope); } } } else { List<ExtensionElement> outParameters = baseElement.getExtensionElements() .getOrDefault(BpmnXMLConstants.ELEMENT_EVENT_OUT_PARAMETER, Collections.emptyList()); if (!outParameters.isEmpty()) { for (ExtensionElement outParameter : outParameters) { String payloadSourceName = outParameter.getAttributeValue(null, BpmnXMLConstants.ATTRIBUTE_IOPARAMETER_SOURCE); String variableName = outParameter.getAttributeValue(null, BpmnXMLConstants.ATTRIBUTE_IOPARAMETER_TARGET); boolean isTransient = Boolean.parseBoolean(outParameter.getAttributeValue(null, "transient")); setEventParameterVariable(payloadSourceName, variableName, isTransient, payloadInstances, variableScope); } } }
983
372
1,355
56,260
SonicCloudOrg_sonic-agent
sonic-agent/src/main/java/org/cloud/sonic/agent/transport/TransportController.java
TransportController
catchAll
class TransportController { public final static String DELEGATE_PREFIX = "/uia"; @Autowired private RoutingDelegate routingDelegate; @RequestMapping(value = "/**", method = {RequestMethod.GET, RequestMethod.POST, RequestMethod.PUT, RequestMethod.DELETE}, produces = MediaType.ALL_VALUE) public ResponseEntity catchAll(HttpServletRequest request, HttpServletResponse response) {<FILL_FUNCTION_BODY>} }
System.out.println(request.getRequestURI()); return routingDelegate.redirect(request, response, "http://localhost:" + request.getRequestURI().replace(DELEGATE_PREFIX + "/", ""), request.getRequestURI());
118
62
180
41,473
alibaba_Sentinel
Sentinel/sentinel-core/src/main/java/com/alibaba/csp/sentinel/slots/block/flow/FlowRule.java
FlowRule
setMaxQueueingTimeMs
class FlowRule extends AbstractRule { public FlowRule() { super(); setLimitApp(RuleConstant.LIMIT_APP_DEFAULT); } public FlowRule(String resourceName) { super(); setResource(resourceName); setLimitApp(RuleConstant.LIMIT_APP_DEFAULT); } /** * The threshold type of flow control (0: thread count, 1: QPS). */ private int grade = RuleConstant.FLOW_GRADE_QPS; /** * Flow control threshold count. */ private double count; /** * Flow control strategy based on invocation chain. * * {@link RuleConstant#STRATEGY_DIRECT} for direct flow control (by origin); * {@link RuleConstant#STRATEGY_RELATE} for relevant flow control (with relevant resource); * {@link RuleConstant#STRATEGY_CHAIN} for chain flow control (by entrance resource). */ private int strategy = RuleConstant.STRATEGY_DIRECT; /** * Reference resource in flow control with relevant resource or context. */ private String refResource; /** * Rate limiter control behavior. * 0. default(reject directly), 1. warm up, 2. rate limiter, 3. warm up + rate limiter */ private int controlBehavior = RuleConstant.CONTROL_BEHAVIOR_DEFAULT; private int warmUpPeriodSec = 10; /** * Max queueing time in rate limiter behavior. */ private int maxQueueingTimeMs = 500; private boolean clusterMode; /** * Flow rule config for cluster mode. */ private ClusterFlowConfig clusterConfig; /** * The traffic shaping (throttling) controller. */ private TrafficShapingController controller; public int getControlBehavior() { return controlBehavior; } public FlowRule setControlBehavior(int controlBehavior) { this.controlBehavior = controlBehavior; return this; } public int getMaxQueueingTimeMs() { return maxQueueingTimeMs; } public FlowRule setMaxQueueingTimeMs(int maxQueueingTimeMs) {<FILL_FUNCTION_BODY>} FlowRule setRater(TrafficShapingController rater) { this.controller = rater; return this; } TrafficShapingController getRater() { return controller; } public int getWarmUpPeriodSec() { return warmUpPeriodSec; } public FlowRule setWarmUpPeriodSec(int warmUpPeriodSec) { this.warmUpPeriodSec = warmUpPeriodSec; return this; } public int getGrade() { return grade; } public FlowRule setGrade(int grade) { this.grade = grade; return this; } public double getCount() { return count; } public FlowRule setCount(double count) { this.count = count; return this; } public int getStrategy() { return strategy; } public FlowRule setStrategy(int strategy) { this.strategy = strategy; return this; } public String getRefResource() { return refResource; } public FlowRule setRefResource(String refResource) { this.refResource = refResource; return this; } public boolean isClusterMode() { return clusterMode; } public FlowRule setClusterMode(boolean clusterMode) { this.clusterMode = clusterMode; return this; } public ClusterFlowConfig getClusterConfig() { return clusterConfig; } public FlowRule setClusterConfig(ClusterFlowConfig clusterConfig) { this.clusterConfig = clusterConfig; return this; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } if (!super.equals(o)) { return false; } FlowRule rule = (FlowRule)o; if (grade != rule.grade) { return false; } if (Double.compare(rule.count, count) != 0) { return false; } if (strategy != rule.strategy) { return false; } if (controlBehavior != rule.controlBehavior) { return false; } if (warmUpPeriodSec != rule.warmUpPeriodSec) { return false; } if (maxQueueingTimeMs != rule.maxQueueingTimeMs) { return false; } if (clusterMode != rule.clusterMode) { return false; } if (refResource != null ? !refResource.equals(rule.refResource) : rule.refResource != null) { return false; } return clusterConfig != null ? clusterConfig.equals(rule.clusterConfig) : rule.clusterConfig == null; } @Override public int hashCode() { int result = super.hashCode(); long temp; result = 31 * result + grade; temp = Double.doubleToLongBits(count); result = 31 * result + (int)(temp ^ (temp >>> 32)); result = 31 * result + strategy; result = 31 * result + (refResource != null ? refResource.hashCode() : 0); result = 31 * result + controlBehavior; result = 31 * result + warmUpPeriodSec; result = 31 * result + maxQueueingTimeMs; result = 31 * result + (clusterMode ? 1 : 0); result = 31 * result + (clusterConfig != null ? clusterConfig.hashCode() : 0); return result; } @Override public String toString() { return "FlowRule{" + "resource=" + getResource() + ", limitApp=" + getLimitApp() + ", grade=" + grade + ", count=" + count + ", strategy=" + strategy + ", refResource=" + refResource + ", controlBehavior=" + controlBehavior + ", warmUpPeriodSec=" + warmUpPeriodSec + ", maxQueueingTimeMs=" + maxQueueingTimeMs + ", clusterMode=" + clusterMode + ", clusterConfig=" + clusterConfig + ", controller=" + controller + '}'; } }
this.maxQueueingTimeMs = maxQueueingTimeMs; return this;
1,683
24
1,707
65,297
igniterealtime_Openfire
Openfire/xmppserver/src/main/java/org/jivesoftware/openfire/net/DNSUtil.java
HostAddress
isDirectTLS
class HostAddress implements Serializable { private final String host; private final int port; private final boolean directTLS; public HostAddress(String host, int port, boolean directTLS) { // Host entries in DNS should end with a ".". if (host.endsWith(".")) { this.host = host.substring(0, host.length()-1); } else { this.host = host; } this.port = port; this.directTLS = directTLS; } /** * Returns the hostname. * * @return the hostname. */ public String getHost() { return host; } /** * Returns the port. * * @return the port. */ public int getPort() { return port; } public boolean isDirectTLS() {<FILL_FUNCTION_BODY>} @Override public String toString() { return host + ":" + port; } }
return directTLS;
275
10
285
23,298
baomidou_mybatis-plus-samples
mybatis-plus-samples/mybatis-plus-sample-optimistic-locker/src/main/java/com/baomidou/mybatisplus/samples/optlocker/OptlockerApplication.java
OptlockerApplication
main
class OptlockerApplication { public static void main(String[] args) {<FILL_FUNCTION_BODY>} }
SpringApplication.run(OptlockerApplication.class, args);
34
19
53
13,354
redis_lettuce
lettuce/src/main/java/io/lettuce/core/cluster/AbstractClusterNodeConnectionFactory.java
AbstractClusterNodeConnectionFactory
getSocketAddressSupplier
class AbstractClusterNodeConnectionFactory<K, V> implements ClusterNodeConnectionFactory<K, V> { private static final InternalLogger logger = InternalLoggerFactory .getInstance(PooledClusterConnectionProvider.DefaultClusterNodeConnectionFactory.class); private final ClientResources clientResources; private volatile Partitions partitions; /** * Create a new {@link AbstractClusterNodeConnectionFactory} given {@link ClientResources}. * * @param clientResources must not be {@code null}. */ public AbstractClusterNodeConnectionFactory(ClientResources clientResources) { this.clientResources = clientResources; } public void setPartitions(Partitions partitions) { this.partitions = partitions; } public Partitions getPartitions() { return partitions; } /** * Get a {@link Mono} of {@link SocketAddress} for a * {@link io.lettuce.core.cluster.ClusterNodeConnectionFactory.ConnectionKey}. * <p> * This {@link Supplier} resolves the requested endpoint on each {@link Supplier#get()}. * * @param connectionKey must not be {@code null}. * @return */ Mono<SocketAddress> getSocketAddressSupplier(ConnectionKey connectionKey) {<FILL_FUNCTION_BODY>} /** * Get the {@link SocketAddress} for a {@code nodeId} from {@link Partitions}. * * @param nodeId * @return the {@link SocketAddress}. * @throws IllegalArgumentException if {@code nodeId} cannot be looked up. */ private SocketAddress getSocketAddress(String nodeId) { for (RedisClusterNode partition : partitions) { if (partition.getNodeId().equals(nodeId)) { return resolve(partition.getUri()); } } throw new IllegalArgumentException(String.format("Cannot resolve a RedisClusterNode for nodeId %s", nodeId)); } private SocketAddress resolve(RedisURI redisURI) { return clientResources.socketAddressResolver().resolve(redisURI); } }
return Mono.fromCallable(() -> { if (connectionKey.nodeId != null) { SocketAddress socketAddress = getSocketAddress(connectionKey.nodeId); logger.debug("Resolved SocketAddress {} using for Cluster node {}", socketAddress, connectionKey.nodeId); return socketAddress; } SocketAddress socketAddress = resolve(RedisURI.create(connectionKey.host, connectionKey.port)); logger.debug("Resolved SocketAddress {} using for Cluster node at {}:{}", socketAddress, connectionKey.host, connectionKey.port); return socketAddress; });
526
161
687
39,247
knowm_XChange
XChange/xchange-stream-kucoin/src/main/java/info/bitrich/xchangestream/kucoin/KucoinStreamingMarketDataService.java
KucoinStreamingMarketDataService
getTicker
class KucoinStreamingMarketDataService implements StreamingMarketDataService { private static final Logger logger = LoggerFactory.getLogger(KucoinStreamingMarketDataService.class); private final ObjectMapper mapper = StreamingObjectMapperHelper.getObjectMapper(); private final Map<CurrencyPair, Observable<OrderBook>> orderbookSubscriptions = new ConcurrentHashMap<>(); private final Map<CurrencyPair, Observable<KucoinOrderBookEventData>> orderBookRawUpdatesSubscriptions = new ConcurrentHashMap<>(); private final KucoinStreamingService service; private final KucoinMarketDataService marketDataService; private final Runnable onApiCall; public KucoinStreamingMarketDataService( KucoinStreamingService service, KucoinMarketDataService marketDataService, Runnable onApiCall) { this.service = service; this.marketDataService = marketDataService; this.onApiCall = onApiCall; } @Override public Observable<Ticker> getTicker(CurrencyPair currencyPair, Object... args) {<FILL_FUNCTION_BODY>} @Override public Observable<OrderBook> getOrderBook(CurrencyPair currencyPair, Object... args) { return orderbookSubscriptions.computeIfAbsent(currencyPair, this::initOrderBookIfAbsent); } private Observable<OrderBook> initOrderBookIfAbsent(CurrencyPair currencyPair) { orderBookRawUpdatesSubscriptions.computeIfAbsent( currencyPair, s -> triggerObservableBody(rawOrderBookUpdates(s))); return createOrderBookObservable(currencyPair); } private Observable<KucoinOrderBookEventData> rawOrderBookUpdates(CurrencyPair currencyPair) { String channelName = "/market/level2:" + KucoinAdapters.adaptCurrencyPair(currencyPair); return service .subscribeChannel(channelName) .doOnError( ex -> logger.warn("encountered error while subscribing to channel " + channelName, ex)) .map(it -> mapper.treeToValue(it, KucoinOrderBookEvent.class)) .map(e -> e.data); } private Observable<OrderBook> createOrderBookObservable(CurrencyPair currencyPair) { // 1. Open a stream // 2. Buffer the events you receive from the stream. OrderbookSubscription subscription = new OrderbookSubscription(orderBookRawUpdatesSubscriptions.get(currencyPair)); return subscription .stream // 3. Get a depth snapshot // (we do this if we don't already have one or we've invalidated a previous one) .doOnNext(transaction -> subscription.initSnapshotIfInvalid(currencyPair)) .doOnError(ex -> logger.warn("encountered error while processing order book event", ex)) // If we failed, don't return anything. Just keep trying until it works .filter(transaction -> subscription.snapshotLastUpdateId.get() > 0L) // 4. Drop any event where u is <= lastUpdateId in the snapshot .filter(depth -> depth.sequenceEnd > subscription.snapshotLastUpdateId.get()) // 5. The first processed should have U <= lastUpdateId+1 AND u >= lastUpdateId+1, and // subsequent events would // normally have u == lastUpdateId + 1 which is stricter version of the above - let's be // more relaxed // each update has absolute numbers so even if there's an overlap it does no harm .filter( depth -> { long lastUpdateId = subscription.lastUpdateId.get(); boolean result = lastUpdateId == 0L || (depth.sequenceStart <= lastUpdateId + 1 && depth.sequenceEnd >= lastUpdateId + 1); if (result) { subscription.lastUpdateId.set(depth.sequenceEnd); } else { // If not, we re-sync logger.info( "Orderbook snapshot for {} out of date (last={}, U={}, u={}). This is normal. Re-syncing.", currencyPair, lastUpdateId, depth.sequenceStart, depth.sequenceEnd); subscription.invalidateSnapshot(); } return result; }) // 7. The data in each event is the absolute quantity for a price level // 8. If the quantity is 0, remove the price level // 9. Receiving an event that removes a price level that is not in your local order book can // happen and is normal. .map( depth -> { depth.update(currencyPair, subscription.orderBook); return subscription.orderBook; }) .share(); } private <T> Observable<T> triggerObservableBody(Observable<T> observable) { Consumer<T> NOOP = whatever -> {}; observable.subscribe(NOOP); return observable; } @Override public Observable<Trade> getTrades(CurrencyPair currencyPair, Object... args) { throw new NotYetImplementedForExchangeException(); } private final class OrderbookSubscription { final Observable<KucoinOrderBookEventData> stream; final AtomicLong lastUpdateId = new AtomicLong(); final AtomicLong snapshotLastUpdateId = new AtomicLong(); OrderBook orderBook; private OrderbookSubscription(Observable<KucoinOrderBookEventData> stream) { this.stream = stream; } void invalidateSnapshot() { snapshotLastUpdateId.set(0); } void initSnapshotIfInvalid(CurrencyPair currencyPair) { if (snapshotLastUpdateId.get() != 0) return; try { logger.info("Fetching initial orderbook snapshot for {} ", currencyPair); onApiCall.run(); OrderBookResponse book = marketDataService.getKucoinOrderBookFull(currencyPair); lastUpdateId.set(Long.parseLong(book.getSequence())); snapshotLastUpdateId.set(lastUpdateId.get()); orderBook = KucoinAdapters.adaptOrderBook(currencyPair, book); } catch (Exception e) { logger.error("Failed to fetch initial order book for " + currencyPair, e); snapshotLastUpdateId.set(0); lastUpdateId.set(0); orderBook = null; } } } }
String channelName = "/market/ticker:" + KucoinAdapters.adaptCurrencyPair(currencyPair); return service .subscribeChannel(channelName) .doOnError( ex -> logger.warn("encountered error while subscribing to channel " + channelName, ex)) .map(node -> mapper.treeToValue(node, KucoinTickerEvent.class)) .map(KucoinTickerEvent::getTicker);
1,645
117
1,762
27,652
pac4j_pac4j
pac4j/pac4j-core/src/main/java/org/pac4j/core/credentials/password/SpringSecurityPasswordEncoder.java
SpringSecurityPasswordEncoder
getDelegate
class SpringSecurityPasswordEncoder implements PasswordEncoder { private final org.springframework.security.crypto.password.PasswordEncoder delegate; /** * <p>Constructor for SpringSecurityPasswordEncoder.</p> * * @param delegate a {@link org.springframework.security.crypto.password.PasswordEncoder} object */ public SpringSecurityPasswordEncoder(final org.springframework.security.crypto.password.PasswordEncoder delegate) { CommonHelper.assertNotNull("delegate", delegate); this.delegate = delegate; } /** {@inheritDoc} */ @Override public String encode(final String password) { return delegate.encode(password); } /** {@inheritDoc} */ @Override public boolean matches(final String plainPassword, final String encodedPassword) { return delegate.matches(plainPassword, encodedPassword); } /** * <p>Getter for the field <code>delegate</code>.</p> * * @return a {@link org.springframework.security.crypto.password.PasswordEncoder} object */ public org.springframework.security.crypto.password.PasswordEncoder getDelegate() {<FILL_FUNCTION_BODY>} }
return delegate;
319
8
327
36,821
dropwizard_dropwizard
dropwizard/docs/source/examples/core/src/main/java/io/dropwizard/documentation/db/DatabaseHealthCheck.java
DatabaseHealthCheck
check
class DatabaseHealthCheck extends HealthCheck { private final Database database; public DatabaseHealthCheck(Database database) { this.database = database; } @Override protected Result check() throws Exception {<FILL_FUNCTION_BODY>} }
if (database.isConnected()) { return Result.healthy(); } else { return Result.unhealthy("Cannot connect to " + database.getUrl()); }
67
49
116
69,973
apache_linkis
linkis/linkis-public-enhancements/linkis-context-service/linkis-cs-server/src/main/java/org/apache/linkis/cs/condition/construction/NotConditionParser.java
NotConditionParser
getName
class NotConditionParser implements ConditionParser { @Override public Condition parse(Map<Object, Object> conditionMap) { Map<Object, Object> origin = (Map<Object, Object>) conditionMap.get("origin"); return new NotCondition(parserMap.get(origin.get("type")).parse(origin)); } @Override public String getName() {<FILL_FUNCTION_BODY>} }
return "Not";
107
9
116
10,390
apache_dubbo
dubbo/dubbo-common/src/main/java/org/apache/dubbo/rpc/model/ConsumerModel.java
ConsumerModel
initMethodModels
class ConsumerModel extends ServiceModel { private final Set<String> apps = new TreeSet<>(); private final Map<String, AsyncMethodInfo> methodConfigs; private Map<Method, ConsumerMethodModel> methodModels = new HashMap<>(); /** * This constructor creates an instance of ConsumerModel and passed objects should not be null. * If service name, service instance, proxy object,methods should not be null. If these are null * then this constructor will throw {@link IllegalArgumentException} * * @param serviceKey Name of the service. * @param proxyObject Proxy object. */ public ConsumerModel( String serviceKey, Object proxyObject, ServiceDescriptor serviceDescriptor, Map<String, AsyncMethodInfo> methodConfigs, ClassLoader interfaceClassLoader) { super(proxyObject, serviceKey, serviceDescriptor, null, interfaceClassLoader); Assert.notEmptyString(serviceKey, "Service name can't be null or blank"); this.methodConfigs = methodConfigs == null ? new HashMap<>() : methodConfigs; } public ConsumerModel( String serviceKey, Object proxyObject, ServiceDescriptor serviceDescriptor, ServiceMetadata metadata, Map<String, AsyncMethodInfo> methodConfigs, ClassLoader interfaceClassLoader) { super(proxyObject, serviceKey, serviceDescriptor, null, metadata, interfaceClassLoader); Assert.notEmptyString(serviceKey, "Service name can't be null or blank"); this.methodConfigs = methodConfigs == null ? new HashMap<>() : methodConfigs; } public ConsumerModel( String serviceKey, Object proxyObject, ServiceDescriptor serviceDescriptor, ModuleModel moduleModel, ServiceMetadata metadata, Map<String, AsyncMethodInfo> methodConfigs, ClassLoader interfaceClassLoader) { super(proxyObject, serviceKey, serviceDescriptor, moduleModel, metadata, interfaceClassLoader); Assert.notEmptyString(serviceKey, "Service name can't be null or blank"); this.methodConfigs = methodConfigs == null ? new HashMap<>() : methodConfigs; } public AsyncMethodInfo getMethodConfig(String methodName) { return methodConfigs.get(methodName); } public Set<String> getApps() { return apps; } public AsyncMethodInfo getAsyncInfo(String methodName) { return methodConfigs.get(methodName); } public void initMethodModels() {<FILL_FUNCTION_BODY>} /** * Return method model for the given method on consumer side * * @param method method object * @return method model */ public ConsumerMethodModel getMethodModel(Method method) { return methodModels.get(method); } /** * Return method model for the given method on consumer side * * @param method method object * @return method model */ public ConsumerMethodModel getMethodModel(String method) { Optional<Map.Entry<Method, ConsumerMethodModel>> consumerMethodModelEntry = methodModels.entrySet().stream() .filter(entry -> entry.getKey().getName().equals(method)) .findFirst(); return consumerMethodModelEntry.map(Map.Entry::getValue).orElse(null); } /** * @param method methodName * @param argsType method arguments type * @return */ public ConsumerMethodModel getMethodModel(String method, String[] argsType) { Optional<ConsumerMethodModel> consumerMethodModel = methodModels.entrySet().stream() .filter(entry -> entry.getKey().getName().equals(method)) .map(Map.Entry::getValue) .filter(methodModel -> Arrays.equals(argsType, methodModel.getParameterTypes())) .findFirst(); return consumerMethodModel.orElse(null); } /** * Return all method models for the current service * * @return method model list */ public List<ConsumerMethodModel> getAllMethodModels() { return new ArrayList<>(methodModels.values()); } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } if (!super.equals(o)) { return false; } ConsumerModel that = (ConsumerModel) o; return Objects.equals(apps, that.apps) && Objects.equals(methodConfigs, that.methodConfigs) && Objects.equals(methodModels, that.methodModels); } @Override public int hashCode() { return Objects.hash(super.hashCode(), apps, methodConfigs, methodModels); } }
Class<?>[] interfaceList; if (getProxyObject() == null) { Class<?> serviceInterfaceClass = getServiceInterfaceClass(); if (serviceInterfaceClass != null) { interfaceList = new Class[] {serviceInterfaceClass}; } else { interfaceList = new Class[0]; } } else { interfaceList = getProxyObject().getClass().getInterfaces(); } for (Class<?> interfaceClass : interfaceList) { for (Method method : interfaceClass.getMethods()) { methodModels.put(method, new ConsumerMethodModel(method)); } }
1,230
159
1,389
67,143
obsidiandynamics_kafdrop
kafdrop/src/main/java/kafdrop/controller/ClusterController.java
ClusterController
clusterInfo
class ClusterController { private final KafkaConfiguration kafkaConfiguration; private final KafkaMonitor kafkaMonitor; private final BuildProperties buildProperties; private final boolean topicCreateEnabled; public ClusterController(KafkaConfiguration kafkaConfiguration, KafkaMonitor kafkaMonitor, ObjectProvider<BuildInfo> buildInfoProvider, @Value("${topic.createEnabled:true}") Boolean topicCreateEnabled) { this.kafkaConfiguration = kafkaConfiguration; this.kafkaMonitor = kafkaMonitor; this.buildProperties = buildInfoProvider.stream() .map(BuildInfo::getBuildProperties) .findAny() .orElseGet(ClusterController::blankBuildProperties); this.topicCreateEnabled = topicCreateEnabled; } private static BuildProperties blankBuildProperties() { final var properties = new Properties(); properties.setProperty("version", "3.x"); properties.setProperty("time", String.valueOf(System.currentTimeMillis())); return new BuildProperties(properties); } @RequestMapping("/") public String clusterInfo(Model model, @RequestParam(value = "filter", required = false) String filter) {<FILL_FUNCTION_BODY>} @Operation(summary = "getCluster", description = "Get high level broker, topic, and partition data for the Kafka " + "cluster") @ApiResponses(value = { @ApiResponse(responseCode = "200", description = "Success") }) @GetMapping(path = "/", produces = MediaType.APPLICATION_JSON_VALUE) public @ResponseBody ClusterInfoVO getCluster() { final var vo = new ClusterInfoVO(); vo.brokers = kafkaMonitor.getBrokers(); vo.topics = kafkaMonitor.getTopics(); vo.summary = kafkaMonitor.getClusterSummary(vo.topics); return vo; } @ExceptionHandler(BrokerNotFoundException.class) public String brokerNotFound(Model model) { model.addAttribute("brokers", Collections.emptyList()); model.addAttribute("topics", Collections.emptyList()); return "cluster-overview"; } @ResponseStatus(HttpStatus.OK) @RequestMapping("/health_check") public void healthCheck() { // only http code shall be checked } /** * Simple DTO to encapsulate the cluster state. */ public static final class ClusterInfoVO { ClusterSummaryVO summary; List<BrokerVO> brokers; List<TopicVO> topics; public ClusterSummaryVO getSummary() { return summary; } public List<BrokerVO> getBrokers() { return brokers; } public List<TopicVO> getTopics() { return topics; } } }
model.addAttribute("bootstrapServers", kafkaConfiguration.getBrokerConnect()); model.addAttribute("buildProperties", buildProperties); final var brokers = kafkaMonitor.getBrokers(); final var topics = kafkaMonitor.getTopics(); final var clusterSummary = kafkaMonitor.getClusterSummary(topics); final var missingBrokerIds = clusterSummary.getExpectedBrokerIds().stream() .filter(brokerId -> brokers.stream().noneMatch(b -> b.getId() == brokerId)) .collect(Collectors.toList()); model.addAttribute("brokers", brokers); model.addAttribute("missingBrokerIds", missingBrokerIds); model.addAttribute("topics", topics); model.addAttribute("clusterSummary", clusterSummary); model.addAttribute("topicCreateEnabled", topicCreateEnabled); if (filter != null) { model.addAttribute("filter", filter); } return "cluster-overview";
740
255
995
34,298
vsch_flexmark-java
flexmark-java/flexmark-ext-escaped-character/src/main/java/com/vladsch/flexmark/ext/escaped/character/EscapedCharacter.java
EscapedCharacter
getAstExtra
class EscapedCharacter extends Node implements DoNotDecorate { protected BasedSequence openingMarker = BasedSequence.NULL; protected BasedSequence text = BasedSequence.NULL; @NotNull @Override public BasedSequence[] getSegments() { //return EMPTY_SEGMENTS; return new BasedSequence[] { openingMarker, text }; } @Override public void getAstExtra(@NotNull StringBuilder out) {<FILL_FUNCTION_BODY>} public EscapedCharacter() { } public EscapedCharacter(BasedSequence chars) { super(chars); } public EscapedCharacter(BasedSequence openingMarker, BasedSequence text) { super(openingMarker.baseSubSequence(openingMarker.getStartOffset(), text.getEndOffset())); this.openingMarker = openingMarker; this.text = text; } public BasedSequence getOpeningMarker() { return openingMarker; } public void setOpeningMarker(BasedSequence openingMarker) { this.openingMarker = openingMarker; } public BasedSequence getText() { return text; } public void setText(BasedSequence text) { this.text = text; } }
delimitedSegmentSpanChars(out, openingMarker, text, BasedSequence.NULL, "text");
316
28
344
46,275
vert-x3_vertx-examples
vertx-examples/web-examples/src/main/java/io/vertx/example/web/auth/Server.java
Server
start
class Server extends AbstractVerticle { public static void main(String[] args) { Launcher.executeCommand("run", Server.class.getName()); } @Override public void start() throws Exception {<FILL_FUNCTION_BODY>} }
Router router = Router.router(vertx); // We need sessions and request bodies router.route().handler(BodyHandler.create()); router.route().handler(SessionHandler.create(LocalSessionStore.create(vertx))); // Simple auth service which uses a properties file for user/role info PropertyFileAuthentication authn = PropertyFileAuthentication.create(vertx, "vertx-users.properties"); // Any requests to URI starting '/private/' require login router.route("/private/*").handler(RedirectAuthHandler.create(authn, "/loginpage.html")); // Serve the static private pages from directory 'private' router.route("/private/*").handler(StaticHandler.create("io/vertx/example/web/auth/private").setCachingEnabled(false)); // Handles the actual login router.route("/loginhandler").handler(FormLoginHandler.create(authn)); // Implement logout router.route("/logout").handler(context -> { context.clearUser(); // Redirect back to the index page context.response().putHeader("location", "/").setStatusCode(302).end(); }); // Serve the non private static pages router.route().handler(StaticHandler.create("io/vertx/example/web/auth/webroot")); vertx.createHttpServer().requestHandler(router).listen(8080);
68
351
419
64,039
apache_pdfbox
pdfbox/pdfbox/src/main/java/org/apache/pdfbox/pdmodel/interactive/annotation/PDAnnotationSquare.java
PDAnnotationSquare
constructAppearances
class PDAnnotationSquare extends PDAnnotationSquareCircle { /** * The type of annotation. */ public static final String SUB_TYPE = "Square"; private PDAppearanceHandler customAppearanceHandler; public PDAnnotationSquare() { super(SUB_TYPE); } /** * Creates a square annotation from a COSDictionary, expected to be a correct object definition. * * @param field the PDF object to represent as a field. */ public PDAnnotationSquare(COSDictionary field) { super(field); } /** * Set a custom appearance handler for generating the annotations appearance streams. * * @param appearanceHandler custom appearance handler */ public void setCustomAppearanceHandler(PDAppearanceHandler appearanceHandler) { customAppearanceHandler = appearanceHandler; } @Override public void constructAppearances() { this.constructAppearances(null); } @Override public void constructAppearances(PDDocument document) {<FILL_FUNCTION_BODY>} }
if (customAppearanceHandler == null) { PDSquareAppearanceHandler appearanceHandler = new PDSquareAppearanceHandler(this, document); appearanceHandler.generateAppearanceStreams(); } else { customAppearanceHandler.generateAppearanceStreams(); }
303
82
385
12,267
FasterXML_jackson-databind
jackson-databind/src/main/java/com/fasterxml/jackson/databind/util/RootNameLookup.java
RootNameLookup
findRootName
class RootNameLookup implements java.io.Serializable { private static final long serialVersionUID = 1L; /** * For efficient operation, let's try to minimize number of times we * need to introspect root element name to use. */ protected transient LRUMap<ClassKey,PropertyName> _rootNames; public RootNameLookup() { _rootNames = new LRUMap<ClassKey,PropertyName>(20, 200); } public PropertyName findRootName(JavaType rootType, MapperConfig<?> config) {<FILL_FUNCTION_BODY>} public PropertyName findRootName(Class<?> rootType, MapperConfig<?> config) { ClassKey key = new ClassKey(rootType); PropertyName name = _rootNames.get(key); if (name != null) { return name; } BeanDescription beanDesc = config.introspectClassAnnotations(rootType); AnnotationIntrospector intr = config.getAnnotationIntrospector(); AnnotatedClass ac = beanDesc.getClassInfo(); name = intr.findRootName(ac); // No answer so far? Let's just default to using simple class name if (name == null || !name.hasSimpleName()) { // Should we strip out enclosing class tho? For now, nope: name = PropertyName.construct(rootType.getSimpleName()); } _rootNames.put(key, name); return name; } /* /********************************************************** /* Serializable overrides /********************************************************** */ /** * Need to override to reproduce cache object via constructor, instead * of serialize/deserialize (since we do NOT want to retain cached data) */ protected Object readResolve() { return new RootNameLookup(); } }
return findRootName(rootType.getRawClass(), config);
484
19
503
55,918
crate_crate
crate/server/src/main/java/io/crate/expression/reference/file/SourceUriExpression.java
SourceUriExpression
getReferenceForRelation
class SourceUriExpression extends LineCollectorExpression<String> { public static final String COLUMN_NAME = "_uri"; private static final ColumnIdent COLUMN_IDENT = new ColumnIdent(COLUMN_NAME); private LineContext context; @Override public void startCollect(LineContext context) { this.context = context; } @Override public String value() { return context.currentUri(); } public static Reference getReferenceForRelation(RelationName relationName) {<FILL_FUNCTION_BODY>} }
return new SimpleReference( new ReferenceIdent(relationName, COLUMN_IDENT), RowGranularity.DOC, DataTypes.STRING, 0, null );
145
46
191
16,123
spring-io_start.spring.io
start.spring.io/start-site/src/main/java/io/spring/start/site/extension/dependency/graalvm/GraalVmMavenBuildCustomizer.java
GraalVmMavenBuildCustomizer
customize
class GraalVmMavenBuildCustomizer implements BuildCustomizer<MavenBuild> { @Override public void customize(MavenBuild build) {<FILL_FUNCTION_BODY>} }
build.plugins().add("org.graalvm.buildtools", "native-maven-plugin");
51
28
79
44,213
INRIA_spoon
spoon/src/main/java/spoon/reflect/cu/position/NoSourcePosition.java
NullCompilationUnit
getSourceEnd
class NullCompilationUnit extends CompilationUnitImpl { private NullCompilationUnit() { } } private static final CompilationUnit instanceNullCompilationUnit = new NullCompilationUnit(); @Override public CompilationUnit getCompilationUnit() { return instanceNullCompilationUnit; } @Override public boolean isValidPosition() { return false; } @Override public int getLine() { throw new UnsupportedOperationException("PartialSourcePosition only contains a CompilationUnit"); } @Override public int getEndLine() { throw new UnsupportedOperationException("PartialSourcePosition only contains a CompilationUnit"); } @Override public int getColumn() { throw new UnsupportedOperationException("PartialSourcePosition only contains a CompilationUnit"); } @Override public int getEndColumn() { throw new UnsupportedOperationException("PartialSourcePosition only contains a CompilationUnit"); } @Override public int getSourceEnd() {<FILL_FUNCTION_BODY>
throw new UnsupportedOperationException("PartialSourcePosition only contains a CompilationUnit");
249
24
273
57,839
liquibase_liquibase
liquibase/liquibase-standard/src/main/java/liquibase/datatype/core/TimestampType.java
TimestampType
toDatabaseDataType
class TimestampType extends DateTimeType { /** * Returns a DBMS-specific String representation of this TimestampType for use in SQL statements. * @param database the database for which the String must be generated * @return a String with the DBMS-specific type specification */ @Override public DatabaseDataType toDatabaseDataType(Database database) {<FILL_FUNCTION_BODY>} @Override public LoadDataChange.LOAD_DATA_TYPE getLoadTypeName() { return LoadDataChange.LOAD_DATA_TYPE.DATE; } }
String originalDefinition = StringUtil.trimToEmpty(getRawDefinition()); // If a fractional precision is given, check is the DBMS supports the length if (getParameters().length > 0) { Integer desiredLength = null; try { desiredLength = Integer.parseInt(String.valueOf(getParameters()[0])); } catch (NumberFormatException e) { // That is ok, we won't touch the parameter in this case. } if (desiredLength != null) { int maxFractionalDigits = database.getMaxFractionalDigitsForTimestamp(); if (maxFractionalDigits < desiredLength) { throw new DatabaseIncapableOfOperation( String.format( "Using a TIMESTAMP data type with a fractional precision of %d", desiredLength ), String.format( "A timestamp datatype with %d fractional digits was requested, but %s " + "only supports %d digits.", desiredLength, database.getDatabaseProductName(), maxFractionalDigits ), database ); } } } if (database instanceof MySQLDatabase) { if (originalDefinition.contains(" ") || originalDefinition.contains("(")) { return new DatabaseDataType(getRawDefinition()); } return super.toDatabaseDataType(database); } if (database instanceof MSSQLDatabase) { if (Boolean.TRUE.equals(!GlobalConfiguration.CONVERT_DATA_TYPES.getCurrentValue()) && originalDefinition.toLowerCase(Locale.US).startsWith("timestamp")) { return new DatabaseDataType(database.escapeDataTypeName("timestamp")); } Object[] parameters = getParameters(); if (parameters.length >= 1) { final int paramValue = Integer.parseInt(parameters[0].toString()); // If the scale for datetime2 is the database default anyway, omit it. // If the scale is 8, omit it since it's not a valid value for datetime2 if (paramValue > 7 || paramValue == (database.getDefaultScaleForNativeDataType("datetime2"))) { parameters = new Object[0]; } } return new DatabaseDataType(database.escapeDataTypeName("datetime2"), parameters); } if (database instanceof SybaseDatabase) { return new DatabaseDataType(database.escapeDataTypeName("datetime")); } if (database instanceof AbstractDb2Database) { Object[] parameters = getParameters(); if ((parameters != null) && (parameters.length > 1)) { parameters = new Object[] {parameters[1]}; } return new DatabaseDataType(database.escapeDataTypeName("timestamp"), parameters); } /* * From here on, we assume that we have a SQL standard compliant database that supports the * TIMESTAMP[(p)] [WITH TIME ZONE|WITHOUT TIME ZONE] syntax. p is the number of fractional digits, * i.e. if "2017-06-02 23:59:45.123456" is supported by the DBMS, p would be 6. */ DatabaseDataType type; if (getParameters().length > 0 && !(database instanceof SybaseASADatabase)) { int fractionalDigits = 0; String fractionalDigitsInput = getParameters()[0].toString(); try { fractionalDigits = Integer.parseInt(fractionalDigitsInput); } catch (NumberFormatException e) { throw new RuntimeException( new ParseException(String.format("A timestamp with '%s' fractional digits was requested, but '%s' does not " + "seem to be an integer.", fractionalDigitsInput, fractionalDigitsInput)) ); } int maxFractionalDigits = database.getMaxFractionalDigitsForTimestamp(); if (maxFractionalDigits < fractionalDigits) { Scope.getCurrentScope().getLog(getClass()).warning(String.format( "A timestamp datatype with %d fractional digits was requested, but the DBMS %s only supports " + "%d digits. Because of this, the number of digits was reduced to %d.", fractionalDigits, database.getDatabaseProductName(), maxFractionalDigits, maxFractionalDigits) ); fractionalDigits = maxFractionalDigits; } type = new DatabaseDataType("TIMESTAMP", fractionalDigits); } else { type = new DatabaseDataType("TIMESTAMP"); } if (originalDefinition.startsWith("java.sql.Types.TIMESTAMP_WITH_TIMEZONE") && (database instanceof PostgresDatabase || database instanceof OracleDatabase || database instanceof H2Database || database instanceof HsqlDatabase || database instanceof SybaseASADatabase)) { if (database instanceof PostgresDatabase || database instanceof H2Database || database instanceof SybaseASADatabase) { type.addAdditionalInformation("WITH TIME ZONE"); } else { type.addAdditionalInformation("WITH TIMEZONE"); } return type; } if (getAdditionalInformation() != null && (database instanceof PostgresDatabase || database instanceof OracleDatabase) || database instanceof H2Database || database instanceof HsqlDatabase || database instanceof SybaseASADatabase){ String additionalInformation = this.getAdditionalInformation(); if (additionalInformation != null) { String additionInformation = additionalInformation.toUpperCase(Locale.US); if ((database instanceof PostgresDatabase || database instanceof H2Database || database instanceof SybaseASADatabase) && additionInformation.toUpperCase(Locale.US).contains("TIMEZONE")) { additionalInformation = additionInformation.toUpperCase(Locale.US).replace("TIMEZONE", "TIME ZONE"); } // CORE-3229 Oracle 11g doesn't support WITHOUT clause in TIMESTAMP data type if ((database instanceof OracleDatabase) && additionInformation.startsWith("WITHOUT")) { // https://docs.oracle.com/cd/B19306_01/server.102/b14225/ch4datetime.htm#sthref389 additionalInformation = null; } if ((database instanceof H2Database) && additionInformation.startsWith("WITHOUT")) { // http://www.h2database.com/html/datatypes.html additionalInformation = null; } if ((database instanceof SybaseASADatabase) && additionInformation.startsWith("WITHOUT")) { // https://help.sap.com/docs/SAP_SQL_Anywhere/93079d4ba8e44920ae63ffb4def91f5b/81fe3e6b6ce2101487d8acce02f6aba5.html additionalInformation = null; } } type.addAdditionalInformation(additionalInformation); return type; } return super.toDatabaseDataType(database);
144
1,795
1,939
30,880
apache_shenyu
shenyu/shenyu-sync-data-center/shenyu-sync-data-websocket/src/main/java/org/apache/shenyu/plugin/sync/data/websocket/handler/RuleDataHandler.java
RuleDataHandler
doRefresh
class RuleDataHandler extends AbstractDataHandler<RuleData> { private final PluginDataSubscriber pluginDataSubscriber; public RuleDataHandler(final PluginDataSubscriber pluginDataSubscriber) { this.pluginDataSubscriber = pluginDataSubscriber; } @Override public List<RuleData> convert(final String json) { return GsonUtils.getInstance().fromList(json, RuleData.class); } @Override protected void doRefresh(final List<RuleData> dataList) {<FILL_FUNCTION_BODY>} @Override protected void doUpdate(final List<RuleData> dataList) { dataList.forEach(pluginDataSubscriber::onRuleSubscribe); } @Override protected void doDelete(final List<RuleData> dataList) { dataList.forEach(pluginDataSubscriber::unRuleSubscribe); } }
pluginDataSubscriber.refreshRuleDataSelf(dataList); dataList.forEach(pluginDataSubscriber::onRuleSubscribe);
237
38
275
68,409
lukas-krecan_ShedLock
ShedLock/shedlock-core/src/main/java/net/javacrumbs/shedlock/core/DefaultLockingTaskExecutor.java
DefaultLockingTaskExecutor
executeWithLock
class DefaultLockingTaskExecutor implements LockingTaskExecutor { private static final Logger logger = LoggerFactory.getLogger(DefaultLockingTaskExecutor.class); private final LockProvider lockProvider; public DefaultLockingTaskExecutor(LockProvider lockProvider) { this.lockProvider = requireNonNull(lockProvider); } @Override public void executeWithLock(Runnable task, LockConfiguration lockConfig) { try { executeWithLock((Task) task::run, lockConfig); } catch (RuntimeException | Error e) { throw e; } catch (Throwable throwable) { // Should not happen throw new IllegalStateException(throwable); } } @Override public void executeWithLock(Task task, LockConfiguration lockConfig) throws Throwable { executeWithLock( () -> { task.call(); return null; }, lockConfig); } @Override public <T> TaskResult<T> executeWithLock(TaskWithResult<T> task, LockConfiguration lockConfig) throws Throwable {<FILL_FUNCTION_BODY>} }
String lockName = lockConfig.getName(); if (alreadyLockedBy(lockName)) { logger.debug("Already locked '{}'", lockName); return TaskResult.result(task.call()); } Optional<SimpleLock> lock = lockProvider.lock(lockConfig); if (lock.isPresent()) { try { LockAssert.startLock(lockName); LockExtender.startLock(lock.get()); logger.debug( "Locked '{}', lock will be held at most until {}", lockName, lockConfig.getLockAtMostUntil()); return TaskResult.result(task.call()); } finally { LockAssert.endLock(); SimpleLock activeLock = LockExtender.endLock(); if (activeLock != null) { activeLock.unlock(); } else { // This should never happen, but I do not know any better way to handle the null // case. logger.warn("No active lock, please report this as a bug."); lock.get().unlock(); } if (logger.isDebugEnabled()) { Instant lockAtLeastUntil = lockConfig.getLockAtLeastUntil(); Instant now = ClockProvider.now(); if (lockAtLeastUntil.isAfter(now)) { logger.debug("Task finished, lock '{}' will be released at {}", lockName, lockAtLeastUntil); } else { logger.debug("Task finished, lock '{}' released", lockName); } } } } else { logger.debug("Not executing '{}'. It's locked.", lockName); return TaskResult.notExecuted(); }
285
420
705
31,669
igniterealtime_Openfire
Openfire/xmppserver/src/main/java/org/jivesoftware/openfire/LocalSessionManager.java
LocalSessionManager
stop
class LocalSessionManager { private static final Logger Log = LoggerFactory.getLogger(LocalSessionManager.class); /** * Map that holds sessions that has been created but haven't been authenticated yet. The Map * will hold client sessions. */ private Map<String, LocalClientSession> preAuthenticatedSessions = new ConcurrentHashMap<>(); /** * The sessions contained in this List are component sessions. For each connected component * this Map will keep the component's session. */ private List<LocalComponentSession> componentsSessions = new CopyOnWriteArrayList<>(); /** * Map of connection multiplexer sessions grouped by connection managers. Each connection * manager may have many connections to the server (i.e. connection pool). All connections * originated from the same connection manager are grouped as a single entry in the map. * Once all connections have been closed users that were logged using the connection manager * will become unavailable. */ private Map<String, LocalConnectionMultiplexerSession> connnectionManagerSessions = new ConcurrentHashMap<>(); /** * The sessions contained in this Map are server sessions originated by a remote server. These * sessions can only receive packets from the remote server but are not capable of sending * packets to the remote server. Sessions will be added to this collection only after they were * authenticated. * Key: streamID, Value: the IncomingServerSession associated to the streamID. */ private final Map<StreamID, LocalIncomingServerSession> incomingServerSessions = new ConcurrentHashMap<>(); public Map<String, LocalClientSession> getPreAuthenticatedSessions() { return preAuthenticatedSessions; } public List<LocalComponentSession> getComponentsSessions() { return componentsSessions; } public Map<String, LocalConnectionMultiplexerSession> getConnnectionManagerSessions() { return connnectionManagerSessions; } public LocalIncomingServerSession getIncomingServerSession(StreamID streamID) { return incomingServerSessions.get(streamID); } public Collection<LocalIncomingServerSession> getIncomingServerSessions() { return incomingServerSessions.values(); } public void addIncomingServerSessions(StreamID streamID, LocalIncomingServerSession session) { incomingServerSessions.put(streamID, session); } public LocalIncomingServerSession removeIncomingServerSessions(StreamID streamID) { return incomingServerSessions.remove(streamID); } public void start() { // Run through the server sessions every 3 minutes after a 3 minutes server startup delay (default values) Duration period = Duration.ofMinutes(3); TaskEngine.getInstance().scheduleAtFixedRate(new ServerCleanupTask(), period, period); } public void stop() {<FILL_FUNCTION_BODY>} /** * Task that closes idle server sessions. */ private class ServerCleanupTask extends TimerTask { /** * Close incoming server sessions that have been idle for a long time. */ @Override public void run() { // Do nothing if this feature is disabled int idleTime = SessionManager.getInstance().getServerSessionIdleTime(); if (idleTime == -1) { return; } final long deadline = System.currentTimeMillis() - idleTime; for (LocalIncomingServerSession session : incomingServerSessions.values()) { try { if (session.getLastActiveDate().getTime() < deadline) { Log.debug( "ServerCleanupTask is closing an incoming server session that has been idle for a long time. Last active: {}. Session to be closed: {}", session.getLastActiveDate(), session ); session.close(); } } catch (Throwable e) { Log.error(LocaleUtils.getLocalizedString("admin.error"), e); } } } } }
try { // Send the close stream header to all connected connections Set<LocalSession> sessions = new HashSet<>(); sessions.addAll(preAuthenticatedSessions.values()); sessions.addAll(componentsSessions); for (LocalIncomingServerSession incomingSession : incomingServerSessions.values()) { sessions.add(incomingSession); } for (LocalConnectionMultiplexerSession multiplexer : connnectionManagerSessions.values()) { sessions.add(multiplexer); } for (LocalSession session : sessions) { try { // Notify connected client that the server is being shut down. final Connection connection = session.getConnection(); if (connection != null) { // The session may have been detached. connection.systemShutdown(); } } catch (Throwable t) { Log.debug("Error while sending system shutdown to session {}", session, t); } } } catch (Exception e) { Log.debug("Error while sending system shutdown to sessions", e); }
1,007
270
1,277
23,021
google_error-prone
error-prone/docgen_processor/src/main/java/com/google/errorprone/DocGenProcessor.java
DocGenProcessor
process
class DocGenProcessor extends AbstractProcessor { @Override public SourceVersion getSupportedSourceVersion() { return SourceVersion.latest(); } private final Map<String, BugPatternInstance> bugPatterns = new HashMap<>(); /** {@inheritDoc} */ @Override public synchronized void init(ProcessingEnvironment processingEnv) { super.init(processingEnv); } /** {@inheritDoc} */ @Override public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {<FILL_FUNCTION_BODY>} }
for (Element element : roundEnv.getElementsAnnotatedWith(BugPattern.class)) { BugPatternInstance bugPattern = BugPatternInstance.fromElement(element); bugPatterns.put(bugPattern.name, bugPattern); } if (roundEnv.processingOver()) { try { FileObject manifest = processingEnv .getFiler() .createResource(StandardLocation.SOURCE_OUTPUT, "", "bugPatterns.txt"); try (OutputStream os = manifest.openOutputStream(); PrintWriter pw = new PrintWriter(new BufferedWriter(new OutputStreamWriter(os, UTF_8)))) { Gson gson = new Gson(); bugPatterns.entrySet().stream() .sorted(Map.Entry.comparingByKey()) .forEachOrdered( e -> { gson.toJson(e.getValue(), pw); pw.println(); }); } } catch (IOException e) { throw new UncheckedIOException(e); } } return false;
149
274
423
57,736
weibocom_motan
motan/motan-registry-consul/src/main/java/com/weibo/api/motan/registry/consul/ConsulRegistryFactory.java
ConsulRegistryFactory
createRegistry
class ConsulRegistryFactory extends AbstractRegistryFactory { @Override protected Registry createRegistry(URL url) {<FILL_FUNCTION_BODY>} }
String host = ConsulConstants.DEFAULT_HOST; int port = ConsulConstants.DEFAULT_PORT; if (StringUtils.isNotBlank(url.getHost())) { host = url.getHost(); } if (url.getPort() > 0) { port = url.getPort(); } //可以使用不同的client实现 MotanConsulClient client = new ConsulEcwidClient(host, port); return new ConsulRegistry(url, client);
43
126
169
47,078
moquette-io_moquette
moquette/broker/src/main/java/io/moquette/broker/MemoryRetainedRepository.java
MemoryRetainedRepository
payloadToByteArray
class MemoryRetainedRepository implements IRetainedRepository { private final ConcurrentMap<Topic, RetainedMessage> storage = new ConcurrentHashMap<>(); private final ConcurrentMap<Topic, RetainedMessage> storageExpire = new ConcurrentHashMap<>(); @Override public void cleanRetained(Topic topic) { storage.remove(topic); storageExpire.remove(topic); } @Override public void retain(Topic topic, MqttPublishMessage msg) { byte[] rawPayload = payloadToByteArray(msg); final RetainedMessage toStore = new RetainedMessage(topic, msg.fixedHeader().qosLevel(), rawPayload, extractPropertiesArray(msg)); storage.put(topic, toStore); } @Override public void retain(Topic topic, MqttPublishMessage msg, Instant expiryTime) { byte[] rawPayload = payloadToByteArray(msg); final RetainedMessage toStore = new RetainedMessage(topic, msg.fixedHeader().qosLevel(), rawPayload, extractPropertiesArray(msg), expiryTime); storageExpire.put(topic, toStore); } private static MqttProperties.MqttProperty[] extractPropertiesArray(MqttPublishMessage msg) { MqttProperties properties = msg.variableHeader().properties(); return properties.listAll().toArray(new MqttProperties.MqttProperty[0]); } private static byte[] payloadToByteArray(MqttPublishMessage msg) {<FILL_FUNCTION_BODY>} @Override public boolean isEmpty() { return storage.isEmpty() && storageExpire.isEmpty(); } @Override public Collection<RetainedMessage> retainedOnTopic(String topic) { final Topic searchTopic = new Topic(topic); final List<RetainedMessage> matchingMessages = new ArrayList<>(); matchingMessages.addAll(findMatching(searchTopic, storage)); matchingMessages.addAll(findMatching(searchTopic, storageExpire)); return matchingMessages; } @Override public Collection<RetainedMessage> listExpirable() { return storageExpire.values(); } private List<RetainedMessage> findMatching(Topic searchTopic, ConcurrentMap<Topic, RetainedMessage> map) { final List<RetainedMessage> matchingMessages = new ArrayList<>(); for (Map.Entry<Topic, RetainedMessage> entry : map.entrySet()) { final Topic scanTopic = entry.getKey(); if (scanTopic.match(searchTopic)) { matchingMessages.add(entry.getValue()); } } return matchingMessages; } }
final ByteBuf payload = msg.content(); byte[] rawPayload = new byte[payload.readableBytes()]; payload.getBytes(0, rawPayload); return rawPayload;
685
53
738
32,323
spring-projects_spring-batch
spring-batch/spring-batch-core/src/main/java/org/springframework/batch/core/step/item/SimpleRetryExceptionHandler.java
SimpleRetryExceptionHandler
handleException
class SimpleRetryExceptionHandler implements RetryListener, ExceptionHandler { /** * Attribute key, whose existence signals an exhausted retry. */ private static final String EXHAUSTED = SimpleRetryExceptionHandler.class.getName() + ".RETRY_EXHAUSTED"; private static final Log logger = LogFactory.getLog(SimpleRetryExceptionHandler.class); final private RetryPolicy retryPolicy; final private ExceptionHandler exceptionHandler; final private BinaryExceptionClassifier fatalExceptionClassifier; /** * Create an exception handler from its mandatory properties. * @param retryPolicy the retry policy that will be under effect when an exception is * encountered * @param exceptionHandler the delegate to use if an exception actually needs to be * handled * @param fatalExceptionClasses exceptions */ public SimpleRetryExceptionHandler(RetryPolicy retryPolicy, ExceptionHandler exceptionHandler, Collection<Class<? extends Throwable>> fatalExceptionClasses) { this.retryPolicy = retryPolicy; this.exceptionHandler = exceptionHandler; this.fatalExceptionClassifier = new BinaryExceptionClassifier(fatalExceptionClasses); } /** * Check if the exception is going to be retried, and veto the handling if it is. If * retry is exhausted or the exception is on the fatal list, then handle using the * delegate. * * @see ExceptionHandler#handleException(org.springframework.batch.repeat.RepeatContext, * java.lang.Throwable) */ @Override public void handleException(RepeatContext context, Throwable throwable) throws Throwable {<FILL_FUNCTION_BODY>} /** * If retry is exhausted set up some state in the context that can be used to signal * that the exception should be handled. * * @see org.springframework.retry.RetryListener#close(org.springframework.retry.RetryContext, * org.springframework.retry.RetryCallback, java.lang.Throwable) */ @Override public <T, E extends Throwable> void close(RetryContext context, RetryCallback<T, E> callback, Throwable throwable) { if (!retryPolicy.canRetry(context)) { if (logger.isDebugEnabled()) { logger.debug("Marking retry as exhausted: " + context); } getRepeatContext().setAttribute(EXHAUSTED, "true"); } } /** * Get the parent context (the retry is in an inner "chunk" loop and we want the * exception to be handled at the outer "step" level). * @return the {@link RepeatContext} that should hold the exhausted flag. */ private RepeatContext getRepeatContext() { RepeatContext context = RepeatSynchronizationManager.getContext(); if (context.getParent() != null) { return context.getParent(); } return context; } }
// Only bother to check the delegate exception handler if we know that // retry is exhausted if (fatalExceptionClassifier.classify(throwable) || context.hasAttribute(EXHAUSTED)) { logger.debug("Handled fatal exception"); exceptionHandler.handleException(context, throwable); } else { logger.debug("Handled non-fatal exception", throwable); }
741
107
848
44,504
gz-yami_mall4cloud
mall4cloud/mall4cloud-product/src/main/java/com/mall4j/cloud/product/dto/BrandDTO.java
BrandDTO
setCategoryIds
class BrandDTO{ private static final long serialVersionUID = 1L; @Schema(description = "brand_id" ) private Long brandId; @NotNull(message = "品牌名称不能为空") @Schema(description = "品牌名称" ) private String name; @Schema(description = "品牌描述" ) private String desc; @NotNull(message = "logo图片不能为空") @Schema(description = "品牌logo图片" ) private String imgUrl; @NotNull(message = "首字母不能为空") @Schema(description = "检索首字母" ) private String firstLetter; @NotNull(message = "序号不能为空") @Schema(description = "排序" ) private Integer seq; @Schema(description = "状态 1:enable, 0:disable, -1:deleted" ) private Integer status; @NotNull(message = "分类不能为空") @Schema(description = "分类" ) private List<Long> categoryIds; public Long getBrandId() { return brandId; } public void setBrandId(Long brandId) { this.brandId = brandId; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getDesc() { return desc; } public void setDesc(String desc) { this.desc = desc; } public String getImgUrl() { return imgUrl; } public void setImgUrl(String imgUrl) { this.imgUrl = imgUrl; } public String getFirstLetter() { return firstLetter; } public void setFirstLetter(String firstLetter) { this.firstLetter = firstLetter; } public Integer getSeq() { return seq; } public void setSeq(Integer seq) { this.seq = seq; } public Integer getStatus() { return status; } public void setStatus(Integer status) { this.status = status; } public List<Long> getCategoryIds() { return categoryIds; } public void setCategoryIds(List<Long> categoryIds) {<FILL_FUNCTION_BODY>} @Override public String toString() { return "BrandDTO{" + "brandId=" + brandId + ", name='" + name + '\'' + ", desc='" + desc + '\'' + ", imgUrl='" + imgUrl + '\'' + ", firstLetter='" + firstLetter + '\'' + ", seq=" + seq + ", status=" + status + ", categoryIds=" + categoryIds + '}'; } }
this.categoryIds = categoryIds;
731
13
744
21,731
lealone_Lealone
Lealone/lealone-sql/src/main/java/com/lealone/sql/expression/Wildcard.java
Wildcard
getCost
class Wildcard extends Expression { private final String schema; private final String table; public Wildcard(String schema, String table) { this.schema = schema; this.table = table; } @Override public boolean isWildcard() { return true; } @Override public Value getValue(ServerSession session) { throw DbException.getInternalError(); } @Override public int getType() { throw DbException.getInternalError(); } @Override public void mapColumns(ColumnResolver resolver, int level) { throw DbException.get(ErrorCode.SYNTAX_ERROR_1, table); } @Override public Expression optimize(ServerSession session) { throw DbException.get(ErrorCode.SYNTAX_ERROR_1, table); } @Override public int getScale() { throw DbException.getInternalError(); } @Override public long getPrecision() { throw DbException.getInternalError(); } @Override public int getDisplaySize() { throw DbException.getInternalError(); } @Override public String getSchemaName() { return schema; } @Override public String getTableName() { return table; } @Override public String getSQL() { if (table == null) { return "*"; } return StringUtils.quoteIdentifier(table) + ".*"; } @Override public void updateAggregate(ServerSession session) { DbException.throwInternalError(); } @Override public int getCost() {<FILL_FUNCTION_BODY>} @Override public <R> R accept(ExpressionVisitor<R> visitor) { return visitor.visitWildcard(this); } }
throw DbException.getInternalError();
500
14
514
29,355
logfellow_logstash-logback-encoder
logstash-logback-encoder/src/main/java/net/logstash/logback/argument/DeferredStructuredArgument.java
DeferredStructuredArgument
getSuppliedValue
class DeferredStructuredArgument implements StructuredArgument { /** * Supplier for the deferred {@link StructuredArgument} */ private final Supplier<? extends StructuredArgument> structureArgumentSupplier; /** * Cached value of the structured argument returned by {@link #structureArgumentSupplier}. * {@code null} until {@link #getSuppliedValue()} is first called. */ private volatile StructuredArgument suppliedValue; public DeferredStructuredArgument(Supplier<? extends StructuredArgument> structureArgumentSupplier) { this.structureArgumentSupplier = Objects.requireNonNull(structureArgumentSupplier, "structureArgumentSupplier must not be null"); } @Override public void writeTo(JsonGenerator generator) throws IOException { getSuppliedValue().writeTo(generator); } /** * Get the deferred structure argument from the supplier or return it from the cache * if already initialized. * * @return the deferred structured argument */ private StructuredArgument getSuppliedValue() {<FILL_FUNCTION_BODY>} }
if (suppliedValue == null) { synchronized (this) { if (suppliedValue == null) { StructuredArgument structuredArgument = structureArgumentSupplier.get(); if (structuredArgument == null) { structuredArgument = new EmptyLogstashMarker(); } suppliedValue = structuredArgument; } } } return suppliedValue;
276
98
374
31,444
questdb_questdb
questdb/core/src/main/java/io/questdb/griffin/engine/functions/cast/CastIntToDateFunctionFactory.java
CastIntToDateFunctionFactory
newInstance
class CastIntToDateFunctionFactory implements FunctionFactory { @Override public String getSignature() { return "cast(Im)"; } @Override public Function newInstance(int position, ObjList<Function> args, IntList argPositions, CairoConfiguration configuration, SqlExecutionContext sqlExecutionContext) {<FILL_FUNCTION_BODY>} public static class CastIntToDateFunction extends AbstractCastToDateFunction { public CastIntToDateFunction(Function arg) { super(arg); } @Override public long getDate(Record rec) { final int value = arg.getInt(rec); return value != Numbers.INT_NaN ? value : Numbers.LONG_NaN; } } }
return new CastIntToDateFunction(args.getQuick(0));
193
20
213
60,977
knowm_XChange
XChange/xchange-stream-btcmarkets/src/main/java/info/bitrich/xchangestream/btcmarkets/dto/BTCMarketsWebSocketTradeMessage.java
BTCMarketsWebSocketTradeMessage
getMarketId
class BTCMarketsWebSocketTradeMessage { private final String marketId; private final String timestamp; private final String messageType; private final String tradeId; private final String side; private final BigDecimal price; private final BigDecimal volume; public BTCMarketsWebSocketTradeMessage( @JsonProperty("marketId") String marketId, @JsonProperty("timestamp") String timestamp, @JsonProperty("tradeId") String tradeId, @JsonProperty("side") String side, @JsonProperty("price") BigDecimal price, @JsonProperty("volume") BigDecimal volume, @JsonProperty("messageType") String messageType) { this.marketId = marketId; this.timestamp = timestamp; this.messageType = messageType; this.tradeId = tradeId; this.side = side; this.price = price; this.volume = volume; } public String getMarketId() {<FILL_FUNCTION_BODY>} public String getTimestamp() { return timestamp; } public String getMessageType() { return messageType; } public String getTradeId() { return tradeId; } public String getSide() { return side; } public BigDecimal getPrice() { return price; } public BigDecimal getVolume() { return volume; } }
return marketId;
377
9
386
28,265
speedment_speedment
speedment/runtime-parent/runtime-field/src/main/java/com/speedment/runtime/field/internal/predicate/enums/EnumIsNotNullPredicate.java
EnumIsNotNullPredicate
negate
class EnumIsNotNullPredicate<ENTITY, D, E extends Enum<E>> implements FieldIsNotNullPredicate<ENTITY, E> { private final EnumField<ENTITY, D, E> field; public EnumIsNotNullPredicate(EnumField<ENTITY, D, E> field) { this.field = requireNonNull(field); } @Override public boolean test(ENTITY value) { return field.apply(value) != null; } @Override public FieldIsNullPredicate<ENTITY, E> negate() {<FILL_FUNCTION_BODY>} @Override public ToNullable<ENTITY, E, ?> expression() { return field; } @Override public EnumField<ENTITY, D, E> getField() { return field; } }
return new EnumIsNullPredicate<>(field);
222
17
239
42,789
dianping_cat
cat/cat-client/src/main/java/com/dianping/cat/message/internal/DefaultMetric.java
DefaultMetric
sum
class DefaultMetric implements Metric { private MetricContext m_ctx; private String m_name; private long m_timestamp; private Kind m_kind; private int m_count; private double m_sum; private long m_duration; public DefaultMetric(MetricContext ctx, String name) { m_ctx = ctx; m_name = name; m_timestamp = System.currentTimeMillis(); } @Override public void count(int quantity) { m_kind = Kind.COUNT; m_count += quantity; m_ctx.add(this); } @Override public void duration(int quantity, long durationInMillis) { m_kind = Kind.DURATION; m_count += quantity; m_duration += durationInMillis; m_ctx.add(this); } @Override public int getCount() { return m_count; } @Override public long getDuration() { return m_duration; } @Override public String getName() { return m_name; } @Override public long getTimestamp() { return m_timestamp; } @Override public double getSum() { return m_sum; } @Override public Kind getKind() { return m_kind; } public void setTimestamp(long timestamp) { m_timestamp = timestamp; } @Override public void sum(int count, double sum) {<FILL_FUNCTION_BODY>} @Override public String toString() { return String.format("Metric(type=%s, count=%s, total=%s, duration=%s)", m_kind, m_count, m_sum, m_duration); } @Override public void add(Metric metric) { m_count += metric.getCount(); m_sum += metric.getSum(); m_duration += metric.getDuration(); } }
m_kind = Kind.SUM; m_count += count; m_sum += sum; m_ctx.add(this);
497
40
537
69,297