proj_name
stringclasses
26 values
relative_path
stringlengths
42
165
class_name
stringlengths
3
46
func_name
stringlengths
2
44
masked_class
stringlengths
80
7.9k
func_body
stringlengths
76
5.98k
len_input
int64
30
1.88k
len_output
int64
25
1.43k
total
int64
73
2.03k
initial_context
stringclasses
74 values
eirslett_frontend-maven-plugin
frontend-maven-plugin/frontend-maven-plugin/src/main/java/com/github/eirslett/maven/plugins/frontend/mojo/GruntMojo.java
GruntMojo
shouldExecute
class GruntMojo extends AbstractFrontendMojo { /** * Grunt arguments. Default is empty (runs just the "grunt" command). */ @Parameter(property = "frontend.grunt.arguments") private String arguments; /** * Files that should be checked for changes, in addition to the srcdir files. * Defaults to Gruntfile.js in the {@link #workingDirectory}. */ @Parameter(property = "triggerfiles") private List<File> triggerfiles; /** * The directory containing front end files that will be processed by grunt. * If this is set then files in the directory will be checked for * modifications before running grunt. */ @Parameter(property = "srcdir") private File srcdir; /** * The directory where front end files will be output by grunt. If this is * set then they will be refreshed so they correctly show as modified in * Eclipse. */ @Parameter(property = "outputdir") private File outputdir; /** * Skips execution of this mojo. */ @Parameter(property = "skip.grunt", defaultValue = "${skip.grunt}") private boolean skip; @Component private BuildContext buildContext; @Override protected boolean skipExecution() { return this.skip; } @Override public synchronized void execute(FrontendPluginFactory factory) throws TaskRunnerException { if (shouldExecute()) { factory.getGruntRunner().execute(arguments, environmentVariables); if (outputdir != null) { getLog().info("Refreshing files after grunt: " + outputdir); buildContext.refresh(outputdir); } } else { getLog().info("Skipping grunt as no modified files in " + srcdir); } } private boolean shouldExecute() {<FILL_FUNCTION_BODY>} }
if (triggerfiles == null || triggerfiles.isEmpty()) { triggerfiles = Arrays.asList(new File(workingDirectory, "Gruntfile.js")); } return MojoUtils.shouldExecute(buildContext, triggerfiles, srcdir);
508
67
575
public abstract class AbstractFrontendMojo extends AbstractMojo { @Component protected MojoExecution execution; /** * Whether you should skip while running in the test phase (default is false) */ @Parameter(property="skipTests",required=false,defaultValue="false") protected Boolean skipTests; /** * Set this to true to ignore a failure during testing. Its use is NOT RECOMMENDED, but quite convenient on occasion. * @since 1.4 */ @Parameter(property="maven.test.failure.ignore",defaultValue="false") protected boolean testFailureIgnore; /** * The base directory for running all Node commands. (Usually the directory that contains package.json) */ @Parameter(defaultValue="${basedir}",property="workingDirectory",required=false) protected File workingDirectory; /** * The base directory for installing node and npm. */ @Parameter(property="installDirectory",required=false) protected File installDirectory; /** * Additional environment variables to pass to the build. */ @Parameter protected Map<String,String> environmentVariables; @Parameter(defaultValue="${project}",readonly=true) private MavenProject project; @Parameter(defaultValue="${repositorySystemSession}",readonly=true) private RepositorySystemSession repositorySystemSession; /** * Determines if this execution should be skipped. */ private boolean skipTestPhase(); /** * Determines if the current execution is during a testing phase (e.g., "test" or "integration-test"). */ private boolean isTestingPhase(); protected abstract void execute( FrontendPluginFactory factory) throws FrontendException ; /** * Implemented by children to determine if this execution should be skipped. */ protected abstract boolean skipExecution(); @Override public void execute() throws MojoFailureException; }
YunaiV_ruoyi-vue-pro
ruoyi-vue-pro/yudao-framework/yudao-spring-boot-starter-excel/src/main/java/cn/iocoder/yudao/framework/excel/core/convert/MoneyConvert.java
MoneyConvert
convertToExcelData
class MoneyConvert implements Converter<Integer> { @Override public Class<?> supportJavaTypeKey() { throw new UnsupportedOperationException("暂不支持,也不需要"); } @Override public CellDataTypeEnum supportExcelTypeKey() { throw new UnsupportedOperationException("暂不支持,也不需要"); } @Override public WriteCellData<String> convertToExcelData(Integer value, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) {<FILL_FUNCTION_BODY>} }
BigDecimal result = BigDecimal.valueOf(value) .divide(new BigDecimal(100), 2, RoundingMode.HALF_UP); return new WriteCellData<>(result.toString());
139
60
199
javamelody_javamelody
javamelody/javamelody-core/src/main/java/net/bull/javamelody/internal/model/SamplingProfiler.java
SampledMethod
limitDataSize
class SampledMethod implements Comparable<SampledMethod>, Serializable { private static final long serialVersionUID = 1L; private long count; private final String className; private final String methodName; private transient int hash; SampledMethod(String className, String methodName) { super(); assert className != null; assert methodName != null; this.className = className; this.methodName = methodName; this.hash = className.hashCode() * 31 + methodName.hashCode(); } // hash is transient private Object readResolve() { this.hash = className.hashCode() * 31 + methodName.hashCode(); return this; } void incrementCount() { count++; } public long getCount() { return count; } void setCount(long count) { this.count = count; } public String getClassName() { return this.className; } public String getMethodName() { return this.methodName; } @Override public int compareTo(SampledMethod method) { return Long.compare(method.count, count); } @Override public int hashCode() { return hash; } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null || getClass() != obj.getClass()) { return false; } final SampledMethod other = (SampledMethod) obj; return methodName.equals(other.methodName) && className.equals(other.className); } @Override public String toString() { return className + '.' + methodName; } } /** * Constructor. * Excluded packages by default "java,sun,com.sun,javax,org.apache,org.hibernate,oracle,org.postgresql,org.eclipse" */ public SamplingProfiler() { super(); this.excludedPackages = DEFAULT_EXCLUDED_PACKAGES; this.includedPackages = null; } /** * Constructor. * @param excludedPackages List of excluded packages (can be null) * @param includedPackages List of included packages (can be null) */ public SamplingProfiler(List<String> excludedPackages, List<String> includedPackages) { super(); assert excludedPackages != null || includedPackages != null; // In general, there are either excluded packages or included packages. // (If both, excluded result has priority over included result: it excludes some included.) this.excludedPackages = verifyPackageNames(excludedPackages); this.includedPackages = verifyPackageNames(includedPackages); } /** * Constructor. * @param excludedPackages List of excluded packages separated by comma (can be null) * @param includedPackages List of included packages separated by comma (can be null) */ public SamplingProfiler(String excludedPackages, String includedPackages) { this(splitPackageNames(excludedPackages), splitPackageNames(includedPackages)); // In general, there are either excluded packages or included packages. // (If both, excluded result has priority over included result: it excludes some included.) } private static List<String> splitPackageNames(String packageNames) { if (packageNames == null) { return null; } return Arrays.asList(packageNames.split(",")); } private String[] verifyPackageNames(List<String> packageNames) { if (packageNames == null) { return null; } final String[] packages = packageNames.toArray(new String[0]); for (int i = 0; i < packages.length; i++) { packages[i] = packages[i].trim(); // NOPMD if (packages[i].isEmpty()) { throw new IllegalArgumentException( "A package can not be empty, item " + i + " in " + packageNames); } if (!packages[i].endsWith(".")) { packages[i] = packages[i] + '.'; // NOPMD } } return packages; } public synchronized void update() { final Map<Thread, StackTraceElement[]> stackTraces = Thread.getAllStackTraces(); try { final Thread currentThread = Thread.currentThread(); for (final Map.Entry<Thread, StackTraceElement[]> entry : stackTraces.entrySet()) { final Thread thread = entry.getKey(); final StackTraceElement[] stackTrace = entry.getValue(); if (stackTrace.length > 0 && thread.getState() == Thread.State.RUNNABLE && thread != currentThread) { for (final StackTraceElement element : stackTrace) { if (!isPackageExcluded(element)) { addSample(element); break; } } } } } finally { limitDataSize(); } } private void addSample(StackTraceElement element) { final SampledMethod key = new SampledMethod(element.getClassName(), element.getMethodName()); // or final String key = element.getClassName() + '.' + element.getMethodName(); SampledMethod method = this.data.get(key); if (method == null) { method = key; // or method = new SampledMethod(element.getClassName(), element.getMethodName()); this.data.put(key, method); } // on pourrait incrémenter la valeur selon l'augmentation de cpuTime pour ce thread, // mais l'intervalle entre deux samples est probablement trop grand // pour que le cpu du thread entre les deux intervalles ait un rapport avec cette méthode method.incrementCount(); } private void limitDataSize() {<FILL_FUNCTION_BODY>
long minCount = 1; int size = data.size(); while (size > MAX_DATA_SIZE) { final Iterator<SampledMethod> iterator = data.keySet().iterator(); while (iterator.hasNext() && size > MAX_DATA_SIZE) { final SampledMethod method = iterator.next(); if (method.getCount() <= minCount) { iterator.remove(); size--; } } minCount++; }
1,724
147
1,871
logfellow_logstash-logback-encoder
logstash-logback-encoder/src/main/java/net/logstash/logback/appender/AsyncDisruptorAppender.java
EventClearingEventHandler
stop
class EventClearingEventHandler<Event> implements SequenceReportingEventHandler<LogEvent<Event>>, LifecycleAware { private final EventHandler<LogEvent<Event>> delegate; private Sequence sequenceCallback; EventClearingEventHandler(EventHandler<LogEvent<Event>> delegate) { super(); this.delegate = delegate; } @Override public void onEvent(LogEvent<Event> event, long sequence, boolean endOfBatch) throws Exception { try { delegate.onEvent(event, sequence, endOfBatch); } finally { /* * Clear the event so that it can be garbage collected. */ event.recycle(); /* * Notify the BatchEventProcessor that the sequence has progressed. * Without this callback the sequence would not be progressed * until the batch has completely finished. */ sequenceCallback.set(sequence); } } @Override public void onStart() { if (delegate instanceof LifecycleAware) { ((LifecycleAware) delegate).onStart(); } } @Override public void onShutdown() { if (delegate instanceof LifecycleAware) { ((LifecycleAware) delegate).onShutdown(); } } @Override public void setSequenceCallback(final Sequence sequenceCallback) { this.sequenceCallback = sequenceCallback; } } @Override public void start() { if (addDefaultStatusListener && getStatusManager() != null && getStatusManager().getCopyOfStatusListenerList().isEmpty()) { LevelFilteringStatusListener statusListener = new LevelFilteringStatusListener(); statusListener.setLevelValue(Status.WARN); statusListener.setDelegate(new OnConsoleStatusListener()); statusListener.setContext(getContext()); statusListener.start(); getStatusManager().add(statusListener); } this.disruptor = new Disruptor<>( this.eventFactory, this.ringBufferSize, this.threadFactory, this.producerType, this.waitStrategy); /* * Define the exceptionHandler first, so that it applies * to all future eventHandlers. */ this.disruptor.setDefaultExceptionHandler(this.exceptionHandler); this.disruptor.handleEventsWith(new EventClearingEventHandler<>(createEventHandler())); this.disruptor.start(); super.start(); fireAppenderStarted(); } @Override public void stop() {<FILL_FUNCTION_BODY>
/* * Check super.isStarted() instead of isStarted() because subclasses * might override isStarted() to perform other comparisons that we don't * want to check here. Those should be checked by subclasses * prior to calling super.stop() */ if (!super.isStarted()) { return; } /* * Don't allow any more events to be appended. */ super.stop(); /* * Shutdown Disruptor * * Calling Disruptor#shutdown() will wait until all enqueued events are fully processed, * but this waiting happens in a busy-spin. To avoid wasting CPU we wait for at most the configured * grace period before asking the Disruptor for an immediate shutdown. */ long deadline = getShutdownGracePeriod().getMilliseconds() < 0 ? Long.MAX_VALUE : System.currentTimeMillis() + getShutdownGracePeriod().getMilliseconds(); while (!isRingBufferEmpty() && (System.currentTimeMillis() < deadline)) { LockSupport.parkNanos(SLEEP_TIME_DURING_SHUTDOWN); } this.disruptor.halt(); if (!isRingBufferEmpty()) { addWarn("Some queued events have not been logged due to requested shutdown"); } fireAppenderStopped();
669
358
1,027
graphhopper_graphhopper
graphhopper/core/src/main/java/com/graphhopper/routing/util/parsers/StateParser.java
StateParser
handleWayTags
class StateParser implements TagParser { private final EnumEncodedValue<State> stateEnc; public StateParser(EnumEncodedValue<State> stateEnc) { this.stateEnc = stateEnc; } @Override public void handleWayTags(int edgeId, EdgeIntAccess edgeIntAccess, ReaderWay way, IntsRef relationFlags) {<FILL_FUNCTION_BODY>} }
State country = way.getTag("country_state", State.MISSING); stateEnc.setEnum(false, edgeId, edgeIntAccess, country);
103
42
145
eirslett_frontend-maven-plugin
frontend-maven-plugin/frontend-plugin-core/src/main/java/com/github/eirslett/maven/plugins/frontend/lib/ProxyConfig.java
Proxy
getUri
class Proxy { public final String id; public final String protocol; public final String host; public final int port; public final String username; public final String password; public final String nonProxyHosts; public Proxy(String id, String protocol, String host, int port, String username, String password, String nonProxyHosts) { this.host = host; this.id = id; this.protocol = protocol; this.port = port; this.username = username; this.password = password; this.nonProxyHosts = nonProxyHosts; } public boolean useAuthentication(){ return username != null && !username.isEmpty(); } public URI getUri() {<FILL_FUNCTION_BODY>} public boolean isSecure(){ return "https".equals(protocol); } public boolean isNonProxyHost(String host) { if (host != null && nonProxyHosts != null && nonProxyHosts.length() > 0) { for (StringTokenizer tokenizer = new StringTokenizer(nonProxyHosts, "|"); tokenizer.hasMoreTokens(); ) { String pattern = tokenizer.nextToken(); pattern = pattern.replace(".", "\\.").replace("*", ".*"); if (host.matches(pattern)) { return true; } } } return false; } /** * As per https://docs.npmjs.com/misc/config#noproxy , npm expects a comma (`,`) separated list but * maven settings.xml usually specifies the no proxy hosts as a bar (`|`) separated list (see * http://maven.apache.org/guides/mini/guide-proxies.html) . * * We could do the conversion here but npm seems to accept the bar separated list regardless * of what the documentation says so we do no conversion for now. * @return */ public String getNonProxyHosts() { return nonProxyHosts; } @Override public String toString() { return id + "{" + "protocol='" + protocol + '\'' + ", host='" + host + '\'' + ", port=" + port + ", nonProxyHosts='" + nonProxyHosts + '\'' + (useAuthentication()? ", with username/passport authentication" : "") + '}'; } }
String authentication = useAuthentication() ? username + ":" + password : null; try { // Proxies should be schemed with http, even if the protocol is https return new URI("http", authentication, host, port, null, null, null); } catch (URISyntaxException e) { throw new ProxyConfigException("Invalid proxy settings", e); }
627
94
721
elunez_eladmin
eladmin/eladmin-common/src/main/java/me/zhengjie/utils/SpringContextHolder.java
SpringContextHolder
setApplicationContext
class SpringContextHolder implements ApplicationContextAware, DisposableBean { private static ApplicationContext applicationContext = null; private static final List<CallBack> CALL_BACKS = new ArrayList<>(); private static boolean addCallback = true; /** * 针对 某些初始化方法,在SpringContextHolder 未初始化时 提交回调方法。 * 在SpringContextHolder 初始化后,进行回调使用 * * @param callBack 回调函数 */ public synchronized static void addCallBacks(CallBack callBack) { if (addCallback) { SpringContextHolder.CALL_BACKS.add(callBack); } else { log.warn("CallBack:{} 已无法添加!立即执行", callBack.getCallBackName()); callBack.executor(); } } /** * 从静态变量applicationContext中取得Bean, 自动转型为所赋值对象的类型. */ @SuppressWarnings("unchecked") public static <T> T getBean(String name) { assertContextInjected(); return (T) applicationContext.getBean(name); } /** * 从静态变量applicationContext中取得Bean, 自动转型为所赋值对象的类型. */ public static <T> T getBean(Class<T> requiredType) { assertContextInjected(); return applicationContext.getBean(requiredType); } /** * 获取SpringBoot 配置信息 * * @param property 属性key * @param defaultValue 默认值 * @param requiredType 返回类型 * @return / */ public static <T> T getProperties(String property, T defaultValue, Class<T> requiredType) { T result = defaultValue; try { result = getBean(Environment.class).getProperty(property, requiredType); } catch (Exception ignored) {} return result; } /** * 获取SpringBoot 配置信息 * * @param property 属性key * @return / */ public static String getProperties(String property) { return getProperties(property, null, String.class); } /** * 获取SpringBoot 配置信息 * * @param property 属性key * @param requiredType 返回类型 * @return / */ public static <T> T getProperties(String property, Class<T> requiredType) { return getProperties(property, null, requiredType); } /** * 检查ApplicationContext不为空. */ private static void assertContextInjected() { if (applicationContext == null) { throw new IllegalStateException("applicaitonContext属性未注入, 请在applicationContext" + ".xml中定义SpringContextHolder或在SpringBoot启动类中注册SpringContextHolder."); } } /** * 清除SpringContextHolder中的ApplicationContext为Null. */ private static void clearHolder() { log.debug("清除SpringContextHolder中的ApplicationContext:" + applicationContext); applicationContext = null; } @Override public void destroy() { SpringContextHolder.clearHolder(); } @Override public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {<FILL_FUNCTION_BODY>} /** * 获取 @Service 的所有 bean 名称 * @return / */ public static List<String> getAllServiceBeanName() { return new ArrayList<>(Arrays.asList(applicationContext .getBeanNamesForAnnotation(Service.class))); } }
if (SpringContextHolder.applicationContext != null) { log.warn("SpringContextHolder中的ApplicationContext被覆盖, 原有ApplicationContext为:" + SpringContextHolder.applicationContext); } SpringContextHolder.applicationContext = applicationContext; if (addCallback) { for (CallBack callBack : SpringContextHolder.CALL_BACKS) { callBack.executor(); } CALL_BACKS.clear(); } SpringContextHolder.addCallback = false;
957
127
1,084
jeecgboot_jeecg-boot
jeecg-boot/jeecg-module-system/jeecg-system-biz/src/main/java/org/jeecg/modules/system/service/impl/SysPositionServiceImpl.java
SysPositionServiceImpl
getPositionName
class SysPositionServiceImpl extends ServiceImpl<SysPositionMapper, SysPosition> implements ISysPositionService { @Override public SysPosition getByCode(String code) { LambdaQueryWrapper<SysPosition> queryWrapper = new LambdaQueryWrapper<>(); queryWrapper.eq(SysPosition::getCode, code); return super.getOne(queryWrapper); } @Override public List<SysPosition> getPositionList(String userId) { return this.baseMapper.getPositionList(userId); } @Override public String getPositionName(List<String> postList) {<FILL_FUNCTION_BODY>} }
List<SysPosition> positionNameList = this.baseMapper.getPositionName(postList); if (null != positionNameList && positionNameList.size()>0) { return positionNameList.stream().map(SysPosition::getName).collect(Collectors.joining(SymbolConstant.COMMA)); } return "";
172
86
258
docker-java_docker-java
docker-java/docker-java-core/src/main/java/com/github/dockerjava/core/command/RenameContainerCmdImpl.java
RenameContainerCmdImpl
withContainerId
class RenameContainerCmdImpl extends AbstrDockerCmd<RenameContainerCmd, Void> implements RenameContainerCmd { private String containerId; private String name; public RenameContainerCmdImpl(RenameContainerCmd.Exec exec, String containerId) { super(exec); withContainerId(containerId); } @Override public String getContainerId() { return containerId; } @Override public String getName() { return name; } @Override public RenameContainerCmd withContainerId(@Nonnull String containerId) {<FILL_FUNCTION_BODY>} @Override public RenameContainerCmd withName(@Nonnull String name) { this.name = Objects.requireNonNull(name, "name was not specified"); return this; } /** * @throws NotFoundException No such container */ @Override public Void exec() throws NotFoundException { return super.exec(); } }
this.containerId = Objects.requireNonNull(containerId, "containerId was not specified"); return this;
259
32
291
subhra74_snowflake
snowflake/muon-app/src/main/java/muon/app/ui/components/session/HopEntry.java
HopEntry
toString
class HopEntry { public HopEntry(String id, String host, int port, String user, String password, String keypath) { super(); this.id = id; this.host = host; this.port = port; this.user = user; this.password = password; this.keypath = keypath; } public HopEntry() { // TODO Auto-generated constructor stub } private String id, host, user, password, keypath; private int port; public String getId() { return id; } public void setId(String id) { this.id = id; } public String getHost() { return host; } public void setHost(String host) { this.host = host; } public String getUser() { return user; } public void setUser(String user) { this.user = user; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getKeypath() { return keypath; } public void setKeypath(String keypath) { this.keypath = keypath; } public int getPort() { return port; } public void setPort(int port) { this.port = port; } @Override public String toString() {<FILL_FUNCTION_BODY>} }
return host != null ? (user != null ? user + "@" + host : host) : "";
450
31
481
orientechnologies_orientdb
orientdb/client/src/main/java/com/orientechnologies/orient/client/remote/message/OBeginTransactionRequest.java
OBeginTransactionRequest
write
class OBeginTransactionRequest implements OBinaryRequest<OBeginTransactionResponse> { private int txId; private boolean usingLog; private boolean hasContent; private List<ORecordOperationRequest> operations; private List<IndexChange> indexChanges; public OBeginTransactionRequest( int txId, boolean hasContent, boolean usingLog, Iterable<ORecordOperation> operations, Map<String, OTransactionIndexChanges> indexChanges) { super(); this.txId = txId; this.hasContent = hasContent; this.usingLog = usingLog; this.indexChanges = new ArrayList<>(); this.operations = new ArrayList<>(); if (hasContent) { for (ORecordOperation txEntry : operations) { if (txEntry.type == ORecordOperation.LOADED) continue; ORecordOperationRequest request = new ORecordOperationRequest(); request.setType(txEntry.type); request.setVersion(txEntry.getRecord().getVersion()); request.setId(txEntry.getRecord().getIdentity()); request.setRecordType(ORecordInternal.getRecordType(txEntry.getRecord())); switch (txEntry.type) { case ORecordOperation.CREATED: case ORecordOperation.UPDATED: request.setRecord( ORecordSerializerNetworkV37Client.INSTANCE.toStream(txEntry.getRecord())); request.setContentChanged(ORecordInternal.isContentChanged(txEntry.getRecord())); break; } this.operations.add(request); } for (Map.Entry<String, OTransactionIndexChanges> change : indexChanges.entrySet()) { this.indexChanges.add(new IndexChange(change.getKey(), change.getValue())); } } } public OBeginTransactionRequest() {} @Override public void write(OChannelDataOutput network, OStorageRemoteSession session) throws IOException {<FILL_FUNCTION_BODY>} @Override public void read(OChannelDataInput channel, int protocolVersion, ORecordSerializer serializer) throws IOException { txId = channel.readInt(); hasContent = channel.readBoolean(); usingLog = channel.readBoolean(); operations = new ArrayList<>(); if (hasContent) { byte hasEntry; do { hasEntry = channel.readByte(); if (hasEntry == 1) { ORecordOperationRequest entry = OMessageHelper.readTransactionEntry(channel, serializer); operations.add(entry); } } while (hasEntry == 1); // RECEIVE MANUAL INDEX CHANGES this.indexChanges = OMessageHelper.readTransactionIndexChanges( channel, (ORecordSerializerNetworkV37) serializer); } else { this.indexChanges = new ArrayList<>(); } } @Override public byte getCommand() { return OChannelBinaryProtocol.REQUEST_TX_BEGIN; } @Override public OBeginTransactionResponse createResponse() { return new OBeginTransactionResponse(); } @Override public OBinaryResponse execute(OBinaryRequestExecutor executor) { return executor.executeBeginTransaction(this); } @Override public String getDescription() { return "Begin Transaction"; } public List<ORecordOperationRequest> getOperations() { return operations; } public List<IndexChange> getIndexChanges() { return indexChanges; } public int getTxId() { return txId; } public boolean isUsingLog() { return usingLog; } public boolean isHasContent() { return hasContent; } }
// from 3.0 the the serializer is bound to the protocol ORecordSerializerNetworkV37Client serializer = ORecordSerializerNetworkV37Client.INSTANCE; network.writeInt(txId); network.writeBoolean(hasContent); network.writeBoolean(usingLog); if (hasContent) { for (ORecordOperationRequest txEntry : operations) { network.writeByte((byte) 1); OMessageHelper.writeTransactionEntry(network, txEntry, serializer); } // END OF RECORD ENTRIES network.writeByte((byte) 0); // SEND MANUAL INDEX CHANGES OMessageHelper.writeTransactionIndexChanges(network, serializer, indexChanges); }
962
193
1,155
qiujiayu_AutoLoadCache
AutoLoadCache/autoload-cache-serializer/autoload-cache-serializer-protobuf/src/main/java/com/jarvis/cache/serializer/protobuf/ProtoBufSerializer.java
ProtoBufSerializer
deepCloneMethodArgs
class ProtoBufSerializer implements ISerializer<CacheWrapper<Object>> { private ConcurrentHashMap<Class, Lambda> lambdaMap = new ConcurrentHashMap<>(); private static final ObjectMapper MAPPER = new ObjectMapper(); public ProtoBufSerializer() { MAPPER.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); MAPPER.registerModule(new SimpleModule().addSerializer(new NullValueSerializer(null))); MAPPER.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL, JsonTypeInfo.As.PROPERTY); } @Override public byte[] serialize(CacheWrapper<Object> obj) throws Exception { WriteByteBuf byteBuf = new WriteByteBuf(); byteBuf.writeInt(obj.getExpire()); byteBuf.writeLong(obj.getLastLoadTime()); Object cacheObj = obj.getCacheObject(); if (cacheObj != null) { if (cacheObj instanceof Message) { byteBuf.writeBytes(((Message) cacheObj).toByteArray()); } else { MAPPER.writeValue(byteBuf, cacheObj); } } return byteBuf.toByteArray(); } @Override public CacheWrapper<Object> deserialize(final byte[] bytes, Type returnType) throws Exception { if (bytes == null || bytes.length == 0) { return null; } CacheWrapper<Object> cacheWrapper = new CacheWrapper<>(); ReadByteBuf byteBuf = new ReadByteBuf(bytes); cacheWrapper.setExpire(byteBuf.readInt()); cacheWrapper.setLastLoadTime(byteBuf.readLong()); byte[] body = byteBuf.readableBytes(); if (body == null || body.length == 0) { return cacheWrapper; } Class<?> clazz = TypeFactory.rawClass(returnType); if (Message.class.isAssignableFrom(clazz)) { Lambda lambda = getLambda(clazz); Object obj = lambda.invoke_for_Object(new ByteArrayInputStream(body)); cacheWrapper.setCacheObject(obj); } else { Type[] agsType = new Type[]{returnType}; JavaType javaType = MAPPER.getTypeFactory().constructType(ParameterizedTypeImpl.make(CacheWrapper.class, agsType, null)); cacheWrapper.setCacheObject(MAPPER.readValue(body, clazz)); } return cacheWrapper; } @SuppressWarnings("unchecked") @Override public Object deepClone(Object obj, Type type) throws Exception { if (null == obj) { return null; } Class<?> clazz = obj.getClass(); if (BeanUtil.isPrimitive(obj) || clazz.isEnum() || obj instanceof Class || clazz.isAnnotation() || clazz.isSynthetic()) {// 常见不会被修改的数据类型 return obj; } if (obj instanceof Date) { return ((Date) obj).clone(); } else if (obj instanceof Calendar) { Calendar cal = Calendar.getInstance(); cal.setTimeInMillis(((Calendar) obj).getTime().getTime()); return cal; } if (obj instanceof CacheWrapper) { CacheWrapper<Object> wrapper = (CacheWrapper<Object>) obj; CacheWrapper<Object> res = new CacheWrapper<>(); res.setExpire(wrapper.getExpire()); res.setLastLoadTime(wrapper.getLastLoadTime()); res.setCacheObject(deepClone(wrapper.getCacheObject(), null)); return res; } if (obj instanceof Message) { return ((Message) obj).toBuilder().build(); } return MAPPER.readValue(MAPPER.writeValueAsBytes(obj), clazz); } @Override public Object[] deepCloneMethodArgs(Method method, Object[] args) throws Exception {<FILL_FUNCTION_BODY>} @SuppressWarnings("unchecked") private Lambda getLambda(Class clazz) throws NoSuchMethodException { Lambda lambda = lambdaMap.get(clazz); if (lambda == null) { Method method = clazz.getDeclaredMethod("parseFrom", InputStream.class); try { lambda = LambdaFactory.create(method); lambdaMap.put(clazz, lambda); } catch (Throwable throwable) { throwable.printStackTrace(); } } return lambda; } private class NullValueSerializer extends StdSerializer<NullValue> { private static final long serialVersionUID = 1999052150548658808L; private final String classIdentifier; /** * @param classIdentifier can be {@literal null} and will be defaulted * to {@code @class}. */ NullValueSerializer(String classIdentifier) { super(NullValue.class); this.classIdentifier = StringUtil.hasText(classIdentifier) ? classIdentifier : "@class"; } /* * (non-Javadoc) * @see * com.fasterxml.jackson.databind.ser.std.StdSerializer#serialize(java. * lang.Object, com.fasterxml.jackson.core.JsonGenerator, * com.fasterxml.jackson.databind.SerializerProvider) */ @Override public void serialize(NullValue value, JsonGenerator jgen, SerializerProvider provider) throws IOException { jgen.writeStartObject(); jgen.writeStringField(classIdentifier, NullValue.class.getName()); jgen.writeEndObject(); } } }
if (null == args || args.length == 0) { return args; } Type[] genericParameterTypes = method.getGenericParameterTypes(); if (args.length != genericParameterTypes.length) { throw new Exception("the length of " + method.getDeclaringClass().getName() + "." + method.getName() + " must " + genericParameterTypes.length); } Object[] res = new Object[args.length]; int len = genericParameterTypes.length; for (int i = 0; i < len; i++) { res[i] = deepClone(args[i], null); } return res;
1,466
165
1,631
joelittlejohn_jsonschema2pojo
jsonschema2pojo/jsonschema2pojo-core/src/main/java/org/jsonschema2pojo/rules/CommentRule.java
CommentRule
apply
class CommentRule implements Rule<JDocCommentable, JDocComment> { protected CommentRule() { } /** * Applies this schema rule to take the required code generation steps. * <p> * When a $comment node is found and applied with this rule, the value of * the $comment is added as a method and field level JavaDoc comment. * * @param nodeName * the name of the object to which this description applies * @param node * the "$comment" schema node * @param parent * the parent node * @param generatableType * comment-able code generation construct, usually a java class, * which should have this description applied * @return the JavaDoc comment created to contain the description */ @Override public JDocComment apply(String nodeName, JsonNode node, JsonNode parent, JDocCommentable generatableType, Schema schema) {<FILL_FUNCTION_BODY>} }
JDocComment javadoc = generatableType.javadoc(); String descriptionText = node.asText(); if(StringUtils.isNotBlank(descriptionText)) { String[] lines = node.asText().split("/\r?\n/"); for(String line : lines) { javadoc.append(line); } } return javadoc;
248
101
349
pmd_pmd
pmd/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/symbols/table/coreimpl/MostlySingularMultimap.java
Builder
appendValue
class Builder<K, V> { private final MapMaker<K> mapMaker; private @Nullable Map<K, Object> map; private boolean consumed; /** True unless some entry has a list of values. */ private boolean isSingular = true; private Builder(MapMaker<K> mapMaker) { this.mapMaker = mapMaker; } private Map<K, Object> getMapInternal() { if (map == null) { map = mapMaker.copy(Collections.emptyMap()); Validate.isTrue(map.isEmpty(), "Map should be empty"); } return map; } public void replaceValue(K key, V v) { checkKeyValue(key, v); getMapInternal().put(key, v); } public void addUnlessKeyExists(K key, V v) { checkKeyValue(key, v); getMapInternal().putIfAbsent(key, v); } public void appendValue(K key, V v) { appendValue(key, v, false); } public void appendValue(K key, V v, boolean noDuplicate) {<FILL_FUNCTION_BODY>} private void checkKeyValue(K key, V v) { ensureOpen(); AssertionUtil.requireParamNotNull("value", v); AssertionUtil.requireParamNotNull("key", key); } public Builder<K, V> groupBy(Iterable<? extends V> values, Function<? super V, ? extends K> keyExtractor) { ensureOpen(); return groupBy(values, keyExtractor, Function.identity()); } public <I> Builder<K, V> groupBy(Iterable<? extends I> values, Function<? super I, ? extends K> keyExtractor, Function<? super I, ? extends V> valueExtractor) { ensureOpen(); for (I i : values) { appendValue(keyExtractor.apply(i), valueExtractor.apply(i)); } return this; } // no duplicates public Builder<K, V> absorb(Builder<K, V> other) { ensureOpen(); other.ensureOpen(); if (this.map == null) { this.map = other.map; this.isSingular = other.isSingular; } else { // isSingular may be changed in the loop by appendSingle this.isSingular &= other.isSingular; for (Entry<K, Object> otherEntry : other.getMapInternal().entrySet()) { K key = otherEntry.getKey(); Object otherV = otherEntry.getValue(); map.compute(key, (k, myV) -> { if (myV == null) { return otherV; } else if (otherV instanceof VList) { Object newV = myV; for (V v : (VList<V>) otherV) { newV = appendSingle(newV, v, true); } return newV; } else { return appendSingle(myV, (V) otherV, true); } }); } } other.consume(); return this; } private Object appendSingle(@Nullable Object vs, V v, boolean noDuplicate) { if (vs == null) { return v; } else if (vs instanceof VList) { if (noDuplicate && ((VList) vs).contains(v)) { return vs; } ((VList) vs).add(v); return vs; } else { if (noDuplicate && vs.equals(v)) { return vs; } List<V> vs2 = new VList<>(2); isSingular = false; vs2.add((V) vs); vs2.add(v); return vs2; } } public MostlySingularMultimap<K, V> build() { consume(); return isEmpty() ? empty() : new MostlySingularMultimap<>(getMapInternal()); } public @Nullable Map<K, V> buildAsSingular() { consume(); if (!isSingular) { return null; // NOPMD: returning null as in the spec (Nullable) } return (Map<K, V>) map; } private void consume() { ensureOpen(); consumed = true; } private void ensureOpen() { Validate.isTrue(!consumed, "Builder was already consumed"); } public boolean isSingular() { return isSingular; } public Map<K, List<V>> getMutableMap() { Map<K, List<V>> mutable = mapMaker.copy(Collections.emptyMap()); for (Entry<K, Object> entry : getMapInternal().entrySet()) { mutable.put(entry.getKey(), interpretValue(entry.getValue())); } return mutable; } public boolean isEmpty() { return map == null || map.isEmpty(); } }
checkKeyValue(key, v); getMapInternal().compute(key, (k, oldV) -> { return appendSingle(oldV, v, noDuplicate); });
1,325
51
1,376
houbb_sensitive-word
sensitive-word/src/main/java/com/github/houbb/sensitive/word/support/result/WordResultHandlerWordTags.java
WordResultHandlerWordTags
doHandle
class WordResultHandlerWordTags extends AbstractWordResultHandler<WordTagsDto> { @Override protected WordTagsDto doHandle(IWordResult wordResult, IWordContext wordContext, String originalText) {<FILL_FUNCTION_BODY>} }
// 截取 String word = InnerWordCharUtils.getString(originalText.toCharArray(), wordResult); // 标签 WordTagsDto dto = new WordTagsDto(); dto.setWord(word); // 获取 tags Set<String> wordTags = wordContext.wordTag().getTag(word); dto.setTags(wordTags); return dto;
66
107
173
orientechnologies_orientdb
orientdb/client/src/main/java/com/orientechnologies/orient/client/remote/message/OReadRecordResponse.java
OReadRecordResponse
read
class OReadRecordResponse implements OBinaryResponse { private byte recordType; private int version; private byte[] record; private Set<ORecord> recordsToSend; private ORawBuffer result; public OReadRecordResponse() {} public OReadRecordResponse( byte recordType, int version, byte[] record, Set<ORecord> recordsToSend) { this.recordType = recordType; this.version = version; this.record = record; this.recordsToSend = recordsToSend; } public void write(OChannelDataOutput network, int protocolVersion, ORecordSerializer serializer) throws IOException { if (record != null) { network.writeByte((byte) 1); if (protocolVersion <= OChannelBinaryProtocol.PROTOCOL_VERSION_27) { network.writeBytes(record); network.writeVersion(version); network.writeByte(recordType); } else { network.writeByte(recordType); network.writeVersion(version); network.writeBytes(record); } for (ORecord d : recordsToSend) { if (d.getIdentity().isValid()) { network.writeByte((byte) 2); // CLIENT CACHE // RECORD. IT ISN'T PART OF THE RESULT SET OMessageHelper.writeRecord(network, d, serializer); } } } // End of the response network.writeByte((byte) 0); } @Override public void read(OChannelDataInput network, OStorageRemoteSession session) throws IOException {<FILL_FUNCTION_BODY>} public byte[] getRecord() { return record; } public ORawBuffer getResult() { return result; } }
ORecordSerializerNetworkV37Client serializer = ORecordSerializerNetworkV37Client.INSTANCE; if (network.readByte() == 0) return; final ORawBuffer buffer; final byte type = network.readByte(); final int recVersion = network.readVersion(); final byte[] bytes = network.readBytes(); buffer = new ORawBuffer(bytes, recVersion, type); // TODO: This should not be here, move it in a callback or similar final ODatabaseDocument database = ODatabaseRecordThreadLocal.instance().getIfDefined(); ORecord record; while (network.readByte() == 2) { record = (ORecord) OMessageHelper.readIdentifiable(network, serializer); if (database != null) // PUT IN THE CLIENT LOCAL CACHE database.getLocalCache().updateRecord(record); } result = buffer;
461
229
690
Pay-Group_best-pay-sdk
best-pay-sdk/src/main/java/com/lly835/bestpay/config/WxPayConfig.java
WxPayConfig
initSSLContext
class WxPayConfig extends PayConfig { /** * 公众号appId */ private String appId; /** * 公众号appSecret */ private String appSecret; /** * 小程序appId */ private String miniAppId; /** * app应用appid */ private String appAppId; /** * 商户号 */ private String mchId; /** * 商户密钥 */ private String mchKey; /** * 商户证书路径 */ private String keyPath; /** * 证书内容 */ private SSLContext sslContext; /** * 初始化证书 * @return */ public SSLContext initSSLContext() {<FILL_FUNCTION_BODY>} }
FileInputStream inputStream = null; try { inputStream = new FileInputStream(new File(this.keyPath)); } catch (IOException e) { throw new RuntimeException("读取微信商户证书文件出错", e); } try { KeyStore keystore = KeyStore.getInstance("PKCS12"); char[] partnerId2charArray = mchId.toCharArray(); keystore.load(inputStream, partnerId2charArray); this.sslContext = SSLContexts.custom().loadKeyMaterial(keystore, partnerId2charArray).build(); return this.sslContext; } catch (Exception e) { throw new RuntimeException("证书文件有问题,请核实!", e); } finally { IOUtils.closeQuietly(inputStream); }
234
208
442
class PayConfig { /** * 支付完成后的异步通知地址. */ private String notifyUrl; /** * 支付完成后的同步返回地址. */ private String returnUrl; /** * 默认非沙箱测试 */ private boolean sandbox=false; public boolean isSandbox(); public void setSandbox( boolean sandbox); public String getNotifyUrl(); public void setNotifyUrl( String notifyUrl); public String getReturnUrl(); public void setReturnUrl( String returnUrl); public void check(); }
graphhopper_graphhopper
graphhopper/core/src/main/java/com/graphhopper/routing/AbstractRoutingAlgorithm.java
AbstractRoutingAlgorithm
accept
class AbstractRoutingAlgorithm implements RoutingAlgorithm { protected final Graph graph; protected final Weighting weighting; protected final TraversalMode traversalMode; protected final NodeAccess nodeAccess; protected final EdgeExplorer edgeExplorer; protected int maxVisitedNodes = Integer.MAX_VALUE; protected long timeoutMillis = Long.MAX_VALUE; private long finishTimeMillis = Long.MAX_VALUE; private boolean alreadyRun; /** * @param graph specifies the graph where this algorithm will run on * @param weighting set the used weight calculation (e.g. fastest, shortest). * @param traversalMode how the graph is traversed e.g. if via nodes or edges. */ public AbstractRoutingAlgorithm(Graph graph, Weighting weighting, TraversalMode traversalMode) { if (weighting.hasTurnCosts() && !traversalMode.isEdgeBased()) throw new IllegalStateException("Weightings supporting turn costs cannot be used with node-based traversal mode"); this.weighting = weighting; this.traversalMode = traversalMode; this.graph = graph; this.nodeAccess = graph.getNodeAccess(); edgeExplorer = graph.createEdgeExplorer(); } @Override public void setMaxVisitedNodes(int numberOfNodes) { this.maxVisitedNodes = numberOfNodes; } @Override public void setTimeoutMillis(long timeoutMillis) { this.timeoutMillis = timeoutMillis; } protected boolean accept(EdgeIteratorState iter, int prevOrNextEdgeId) {<FILL_FUNCTION_BODY>} protected void checkAlreadyRun() { if (alreadyRun) throw new IllegalStateException("Create a new instance per call"); alreadyRun = true; } protected void setupFinishTime() { try { this.finishTimeMillis = Math.addExact(System.currentTimeMillis(), timeoutMillis); } catch (ArithmeticException e) { this.finishTimeMillis = Long.MAX_VALUE; } } @Override public List<Path> calcPaths(int from, int to) { return Collections.singletonList(calcPath(from, to)); } protected Path createEmptyPath() { return new Path(graph); } @Override public String getName() { return getClass().getSimpleName(); } @Override public String toString() { return getName() + "|" + weighting; } protected boolean isMaxVisitedNodesExceeded() { return maxVisitedNodes < getVisitedNodes(); } protected boolean isTimeoutExceeded() { return finishTimeMillis < Long.MAX_VALUE && System.currentTimeMillis() > finishTimeMillis; } }
// for edge-based traversal we leave it for TurnWeighting to decide whether or not a u-turn is acceptable, // but for node-based traversal we exclude such a turn for performance reasons already here return traversalMode.isEdgeBased() || iter.getEdge() != prevOrNextEdgeId;
741
79
820
PlayEdu_PlayEdu
PlayEdu/playedu-course/src/main/java/xyz/playedu/course/domain/CourseCategory.java
CourseCategory
equals
class CourseCategory implements Serializable { /** */ @JsonProperty("course_id") private Integer courseId; /** */ @JsonProperty("category_id") private Integer categoryId; @TableField(exist = false) private static final long serialVersionUID = 1L; @Override public boolean equals(Object that) {<FILL_FUNCTION_BODY>} @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((getCourseId() == null) ? 0 : getCourseId().hashCode()); result = prime * result + ((getCategoryId() == null) ? 0 : getCategoryId().hashCode()); return result; } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append(getClass().getSimpleName()); sb.append(" ["); sb.append("Hash = ").append(hashCode()); sb.append(", courseId=").append(courseId); sb.append(", categoryId=").append(categoryId); sb.append(", serialVersionUID=").append(serialVersionUID); sb.append("]"); return sb.toString(); } }
if (this == that) { return true; } if (that == null) { return false; } if (getClass() != that.getClass()) { return false; } CourseCategory other = (CourseCategory) that; return (this.getCourseId() == null ? other.getCourseId() == null : this.getCourseId().equals(other.getCourseId())) && (this.getCategoryId() == null ? other.getCategoryId() == null : this.getCategoryId().equals(other.getCategoryId()));
324
157
481
orientechnologies_orientdb
orientdb/graphdb/src/main/java/com/tinkerpop/blueprints/impls/orient/OrientTransactionalGraph.java
OrientTransactionalGraph
autoStartTransaction
class OrientTransactionalGraph extends OrientBaseGraph implements TransactionalGraph { /** * Constructs a new object using an existent database instance. * * @param iDatabase Underlying database object to attach */ protected OrientTransactionalGraph(final ODatabaseDocumentInternal iDatabase) { this(iDatabase, true, null, null); } protected OrientTransactionalGraph( final ODatabaseDocumentInternal iDatabase, final String iUserName, final String iUserPasswd, final Settings iConfiguration) { super(iDatabase, iUserName, iUserPasswd, iConfiguration); setCurrentGraphInThreadLocal(); super.setAutoStartTx(isAutoStartTx()); if (isAutoStartTx()) ensureTransaction(); } protected OrientTransactionalGraph( final ODatabaseDocumentInternal iDatabase, final boolean iAutoStartTx, final String iUserName, final String iUserPasswd) { super(iDatabase, iUserName, iUserPasswd, null); setCurrentGraphInThreadLocal(); super.setAutoStartTx(iAutoStartTx); if (iAutoStartTx) ensureTransaction(); } protected OrientTransactionalGraph(final OPartitionedDatabasePool pool) { super(pool); setCurrentGraphInThreadLocal(); ensureTransaction(); } protected OrientTransactionalGraph( final OPartitionedDatabasePool pool, final Settings configuration) { super(pool, configuration); setCurrentGraphInThreadLocal(); if (configuration.isAutoStartTx()) ensureTransaction(); } protected OrientTransactionalGraph(final String url) { this(url, true); } protected OrientTransactionalGraph(final String url, final boolean iAutoStartTx) { super(url, ADMIN, ADMIN); setCurrentGraphInThreadLocal(); setAutoStartTx(iAutoStartTx); if (iAutoStartTx) ensureTransaction(); } protected OrientTransactionalGraph( final String url, final String username, final String password) { this(url, username, password, true); } protected OrientTransactionalGraph( final String url, final String username, final String password, final boolean iAutoStartTx) { super(url, username, password); setCurrentGraphInThreadLocal(); this.setAutoStartTx(iAutoStartTx); if (iAutoStartTx) ensureTransaction(); } protected OrientTransactionalGraph(final Configuration configuration) { super(configuration); final Boolean autoStartTx = configuration.getBoolean("blueprints.orientdb.autoStartTx", null); if (autoStartTx != null) setAutoStartTx(autoStartTx); } public boolean isUseLog() { makeActive(); return settings.isUseLog(); } public OrientTransactionalGraph setUseLog(final boolean useLog) { makeActive(); settings.setUseLog(useLog); return this; } @Override public void setAutoStartTx(boolean autoStartTx) { makeActive(); final boolean showWarning; if (!autoStartTx && isAutoStartTx() && getDatabase() != null && getDatabase().getTransaction().isActive()) { if (getDatabase().getTransaction().getEntryCount() == 0) { getDatabase().getTransaction().rollback(); showWarning = false; } else showWarning = true; } else showWarning = false; super.setAutoStartTx(autoStartTx); if (showWarning) OLogManager.instance() .warn( this, "Auto Transaction for graphs setting has been turned off, but a transaction was" + " already started. Commit it manually or consider disabling auto transactions" + " while creating the graph."); } /** * Closes a transaction. * * @param conclusion Can be SUCCESS for commit and FAILURE to rollback. */ @SuppressWarnings("deprecation") @Override public void stopTransaction(final Conclusion conclusion) { makeActive(); if (getDatabase().isClosed() || getDatabase().getTransaction() instanceof OTransactionNoTx || getDatabase().getTransaction().getStatus() != TXSTATUS.BEGUN) return; if (Conclusion.SUCCESS == conclusion) commit(); else rollback(); } /** Commits the current active transaction. */ public void commit() { makeActive(); if (getDatabase() == null) return; getDatabase().commit(); if (isAutoStartTx()) ensureTransaction(); } /** Rollbacks the current active transaction. All the pending changes are rollbacked. */ public void rollback() { makeActive(); if (getDatabase() == null) return; getDatabase().rollback(); if (isAutoStartTx()) ensureTransaction(); } @Override public void begin() { makeActive(); // XXX: Under some circumstances, auto started transactions are committed outside of the graph // using the // underlying database and later restarted using the graph. So we have to check the status of // the // database transaction to support this behaviour. if (isAutoStartTx() && getDatabase().getTransaction().isActive()) throw new OTransactionException( "A mixture of auto started and manually started transactions is not allowed. " + "Disable auto transactions for the graph before starting a manual transaction."); getDatabase().begin(); getDatabase().getTransaction().setUsingLog(settings.isUseLog()); } @Override protected void autoStartTransaction() {<FILL_FUNCTION_BODY>} private void ensureTransaction() { final boolean txBegun = getDatabase().getTransaction().isActive(); if (!txBegun) { getDatabase().begin(); getDatabase().getTransaction().setUsingLog(settings.isUseLog()); } } }
final boolean txBegun = getDatabase().getTransaction().isActive(); if (!isAutoStartTx()) { if (isRequireTransaction() && !txBegun) throw new OTransactionException("Transaction required to change the Graph"); return; } if (!txBegun) { getDatabase().begin(); getDatabase().getTransaction().setUsingLog(settings.isUseLog()); }
1,516
109
1,625
/** * A Blueprints implementation of the graph database OrientDB (http://orientdb.com) * @author Luca Garulli (l.garulli--(at)--orientdb.com) (http://orientdb.com) */ public abstract class OrientBaseGraph extends OrientConfigurableGraph implements OrientExtendedGraph, OStorageRecoverListener { public static final String CONNECTION_OUT="out"; public static final String CONNECTION_IN="in"; public static final String CLASS_PREFIX="class:"; public static final String CLUSTER_PREFIX="cluster:"; public static final String ADMIN="admin"; private static volatile ThreadLocal<OrientBaseGraph> activeGraph=new ThreadLocal<OrientBaseGraph>(); private static volatile ThreadLocal<Deque<OrientBaseGraph>> initializationStack=new InitializationStackThreadLocal(); private Map<String,Object> properties; static { Orient.instance().registerListener(new OOrientListenerAbstract(){ @Override public void onStartup(); @Override public void onShutdown(); } ); } private final OPartitionedDatabasePool pool; protected ODatabaseDocumentInternal database; private String url; private String username; private String password; /** * Constructs a new object using an existent database instance. * @param iDatabase Underlying database object to attach */ public OrientBaseGraph( final ODatabaseDocumentInternal iDatabase, final String iUserName, final String iUserPassword, final Settings iConfiguration); public OrientBaseGraph( final OPartitionedDatabasePool pool); public OrientBaseGraph( final OPartitionedDatabasePool pool, final Settings iConfiguration); public OrientBaseGraph( final String url); public OrientBaseGraph( final String url, final String username, final String password); /** * Builds a OrientGraph instance passing a configuration. Supported configuration settings are: <table> <tr> <td><b>Name</b></td> <td><b>Description</b></td> <td><b>Default value</b></td> </tr> <tr> <td>blueprints.orientdb.url</td> <td>Database URL</td> <td>-</td> </tr> <tr> <td>blueprints.orientdb.username</td> <td>User name</td> <td>admin</td> </tr> <tr> <td>blueprints.orientdb.password</td> <td>User password</td> <td>admin</td> </tr> <tr> <td>blueprints.orientdb.saveOriginalIds</td> <td>Saves the original element IDs by using the property origId. This could be useful on import of graph to preserve original ids</td> <td>false</td> </tr> <tr> <td>blueprints.orientdb.keepInMemoryReferences</td> <td>Avoid to keep records in memory but only RIDs</td> <td>false</td> </tr> <tr> <td>blueprints.orientdb.useCustomClassesForEdges</td> <td>Use Edge's label as OrientDB class. If doesn't exist create it under the hood</td> <td>true</td> </tr> <tr> <td>blueprints.orientdb.useCustomClassesForVertex</td> <td>Use Vertex's label as OrientDB class. If doesn't exist create it under the hood</td> <td>true</td> </tr> <tr> <td>blueprints.orientdb.useVertexFieldsForEdgeLabels</td> <td>Store the edge relationships in vertex by using the Edge's class. This allow to use multiple fields and make faster traversal by edge's label (class)</td> <td>true</td> </tr> <tr> <td>blueprints.orientdb.lightweightEdges</td> <td>Uses lightweight edges. This avoid to create a physical document per edge. Documents are created only when they have properties</td> <td>true</td> </tr> <tr> <td>blueprints.orientdb.autoScaleEdgeType</td> <td>Set auto scale of edge type. True means one edge is managed as LINK, 2 or more are managed with a LINKBAG</td> <td>false</td> </tr> <tr> <td>blueprints.orientdb.edgeContainerEmbedded2TreeThreshold</td> <td>Changes the minimum number of edges for edge containers to transform the underlying structure from embedded to tree. Use -1 to disable transformation</td> <td>-1</td> </tr> <tr> <td>blueprints.orientdb.edgeContainerTree2EmbeddedThreshold</td> <td>Changes the minimum number of edges for edge containers to transform the underlying structure from tree to embedded. Use -1 to disable transformation</td> <td>-1</td> </tr> </table> * @param configuration of graph */ public OrientBaseGraph( final Configuration configuration); abstract OrientEdge addEdgeInternal( OrientVertex currentVertex, String label, OrientVertex inVertex, String iClassName, String iClusterName, Object... fields); abstract void removeEdgesInternal( final OrientVertex vertex, final ODocument iVertex, final OIdentifiable iVertexToRemove, final boolean iAlsoInverse, final boolean useVertexFieldsForEdgeLabels, final boolean autoScaleEdgeType); abstract void removeEdgeInternal( OrientEdge currentVertex); public static OrientBaseGraph getActiveGraph(); /** * Internal use only. */ public static void clearInitStack(); @Override public void onStorageRecover(); /** * (Internal) */ public static void encodeClassNames( final String... iLabels); /** * (Internal) Returns the case sensitive edge class names. */ public static void getEdgeClassNames( final OrientBaseGraph graph, final String... iLabels); /** * (Internal) */ public static String encodeClassName( String iClassName); /** * (Internal) */ public static String decodeClassName( String iClassName); public void makeActive(); /** * (Blueprints Extension) Configure the Graph instance. * @param iSetting Settings object containing all the settings */ public OrientBaseGraph configure( final Settings iSetting); /** * (Blueprints Extension) Drops the database */ public void drop(); @SuppressWarnings({"unchecked","rawtypes"}) public <T extends Element>Index<T> createIndex( final String indexName, final Class<T> indexClass, final Parameter... indexParameters); /** * Returns an index by name and class * @param indexName Index name * @param indexClass Class as one or subclass of Vertex.class and Edge.class * @return Index instance */ @SuppressWarnings("unchecked") @Override public <T extends Element>Index<T> getIndex( final String indexName, final Class<T> indexClass); /** * Returns all the indices. * @return Iterable of Index instances */ public Iterable<Index<? extends Element>> getIndices(); /** * Drops an index by name. * @param indexName Index name */ public void dropIndex( final String indexName); /** * Creates a new unconnected vertex with no fields in the Graph. * @param id Optional, can contains the Vertex's class name by prefixing with "class:" * @return The new OrientVertex created */ @Override public OrientVertex addVertex( final Object id); public ORecordConflictStrategy getConflictStrategy(); public OrientBaseGraph setConflictStrategy( final String iStrategyName); public OrientBaseGraph setConflictStrategy( final ORecordConflictStrategy iResolver); /** * (Blueprints Extension) Creates a new unconnected vertex in the Graph setting the initial field values. * @param id Optional, can contains the Vertex's class name by prefixing with "class:" * @param prop Fields must be a odd pairs of key/value or a single object as Map containingentries as key/value pairs * @return The new OrientVertex created */ public OrientVertex addVertex( Object id, final Object... prop); /** * (Blueprints Extension) Creates a new unconnected vertex with no fields of specific class in a cluster in the Graph. * @param iClassName Vertex class name * @param iClusterName Vertex cluster name * @return New vertex created */ public OrientVertex addVertex( final String iClassName, final String iClusterName); /** * (Blueprints Extension) Creates a temporary vertex setting the initial field values. The vertex is not saved and the transaction is not started. * @param iClassName Vertex's class name * @param prop Fields must be a odd pairs of key/value or a single object as Map containingentries as key/value pairs * @return added vertex */ public OrientVertex addTemporaryVertex( final String iClassName, final Object... prop); /** * Creates an edge between a source Vertex and a destination Vertex setting label as Edge's label. * @param id Optional, can contains the Edge's class name by prefixing with "class:" * @param outVertex Source vertex * @param inVertex Destination vertex * @param label Edge's label */ @Override public OrientEdge addEdge( final Object id, Vertex outVertex, Vertex inVertex, final String label); /** * Returns a vertex by an ID. * @param id Can by a String, ODocument or an OIdentifiable object. */ public OrientVertex getVertex( final Object id); /** * Removes a vertex from the Graph. All the edges connected to the Vertex are automatically removed. * @param vertex Vertex to remove */ public void removeVertex( final Vertex vertex); /** * Get all the Vertices in Graph. * @return Vertices as Iterable */ public Iterable<Vertex> getVertices(); /** * Get all the Vertices in Graph specifying if consider or not sub-classes of V. * @param iPolymorphic If true then get all the vertices of any sub-class * @return Vertices as Iterable */ public Iterable<Vertex> getVertices( final boolean iPolymorphic); /** * Get all the Vertices in Graph of a specific vertex class and all sub-classes. * @param iClassName Vertex class name to filter * @return Vertices as Iterable */ public Iterable<Vertex> getVerticesOfClass( final String iClassName); /** * Get all the Vertices in Graph of a specific vertex class and all sub-classes only if iPolymorphic is true. * @param iClassName Vertex class name to filter * @param iPolymorphic If true consider also Vertex iClassName sub-classes * @return Vertices as Iterable */ public Iterable<Vertex> getVerticesOfClass( final String iClassName, final boolean iPolymorphic); /** * Get all the Vertices in Graph filtering by field name and value. Example:<code> Iterable<Vertex> resultset = getVertices("name", "Jay"); </code> * @param iKey Field name * @param iValue Field value * @return Vertices as Iterable */ public Iterable<Vertex> getVertices( final String iKey, Object iValue); /** * Lookup for a vertex by id using an index.<br> This API relies on Unique index (SBTREE/HASH) but is deprecated.<br> Example:<code> Vertex v = getVertexByKey("V.name", "name", "Jay"); </code> * @param iKey Name of the indexed property * @param iValue Field value * @return Vertex instance if found, otherwise null * @see #getVertices(String,Object) */ @Deprecated public Vertex getVertexByKey( final String iKey, Object iValue); /** * Get all the Vertices in Graph filtering by field name and value. Example:<code> Iterable<Vertex> resultset = getVertices("Person",new String[] {"name","surname"},new Object[] { "Sherlock" ,"Holmes"}); </code> * @param iKey Fields name * @param iValue Fields value * @return Vertices as Iterable */ public Iterable<Vertex> getVertices( final String label, final String[] iKey, Object[] iValue); /** * Returns all the edges in Graph. * @return Edges as Iterable */ public Iterable<Edge> getEdges(); /** * Get all the Edges in Graph specifying if consider or not sub-classes of E. * @param iPolymorphic If true then get all the edge of any sub-class * @return Edges as Iterable */ public Iterable<Edge> getEdges( final boolean iPolymorphic); /** * Get all the Edges in Graph of a specific edge class and all sub-classes. * @param iClassName Edge class name to filter * @return Edges as Iterable */ public Iterable<Edge> getEdgesOfClass( final String iClassName); /** * Get all the Edges in Graph of a specific edges class and all sub-classes only if iPolymorphic is true. * @param iClassName Edge class name to filter * @param iPolymorphic If true consider also iClassName Edge sub-classes * @return Edges as Iterable */ public Iterable<Edge> getEdgesOfClass( final String iClassName, final boolean iPolymorphic); /** * Get all the Edges in Graph filtering by field name and value. Example:<code> Iterable<Edges> resultset = getEdges("name", "Jay"); </code> * @param iKey Field name * @param value Field value * @return Edges as Iterable */ public Iterable<Edge> getEdges( final String iKey, Object value); /** * Returns a edge by an ID. * @param id Can by a String, ODocument or an OIdentifiable object. */ public OrientEdge getEdge( final Object id); /** * Removes an edge from the Graph. * @param edge Edge to remove */ public void removeEdge( final Edge edge); /** * Reuses the underlying database avoiding to create and open it every time. * @param iDatabase Underlying database object */ public OrientBaseGraph reuse( final ODatabaseDocumentInternal iDatabase); /** * Checks if the Graph has been closed. * @return True if it is closed, otherwise false */ public boolean isClosed(); /** * Closes the Graph. After closing the Graph cannot be used. */ public void shutdown(); /** * Closes the Graph. After closing the Graph cannot be used. */ public void shutdown( boolean closeDb); /** * Closes the Graph. After closing the Graph cannot be used. */ public void shutdown( boolean closeDb, boolean commitTx); /** * Returns the Graph URL. */ public String toString(); /** * Returns the underlying Database instance as ODatabaseDocumentTx instance. */ public ODatabaseDocument getRawGraph(); /** * begins current transaction (if the graph is transactional) */ public void begin(); /** * Commits the current active transaction. */ public void commit(); /** * Rollbacks the current active transaction. All the pending changes are rollbacked. */ public void rollback(); /** * Returns the V persistent class as OrientVertexType instance. */ public OrientVertexType getVertexBaseType(); /** * Returns the persistent class for type iTypeName as OrientVertexType instance. * @param iTypeName Vertex class name */ public OrientVertexType getVertexType( final String iTypeName); /** * Creates a new Vertex persistent class. * @param iClassName Vertex class name * @return OrientVertexType instance representing the persistent class */ public OrientVertexType createVertexType( final String iClassName); /** * Creates a new Vertex persistent class. * @param iClassName Vertex class name * @param clusters The number of clusters to create for the new class. By default theMINIMUMCLUSTERS database setting is used. In v2.2 and later, the number of clusters are proportioned to the amount of cores found on the machine * @return OrientVertexType instance representing the persistent class */ public OrientVertexType createVertexType( final String iClassName, final int clusters); /** * Creates a new Vertex persistent class specifying the super class. * @param iClassName Vertex class name * @param iSuperClassName Vertex class name to extend * @return OrientVertexType instance representing the persistent class */ public OrientVertexType createVertexType( final String iClassName, final String iSuperClassName); /** * Creates a new Vertex persistent class specifying the super class. * @param iClassName Vertex class name * @param iSuperClassName Vertex class name to extend * @param clusters The number of clusters to create for the new class. By default theMINIMUMCLUSTERS database setting is used. In v2.2 and later, the number of clusters are proportioned to the amount of cores found on the machine * @return OrientVertexType instance representing the persistent class */ public OrientVertexType createVertexType( final String iClassName, final String iSuperClassName, final int clusters); /** * Creates a new Vertex persistent class specifying the super class. * @param iClassName Vertex class name * @param iSuperClass OClass Vertex to extend * @return OrientVertexType instance representing the persistent class */ public OrientVertexType createVertexType( final String iClassName, final OClass iSuperClass); /** * Creates a new Vertex persistent class specifying the super class. * @param iClassName Vertex class name * @param iSuperClass OClass Vertex to extend * @return OrientVertexType instance representing the persistent class */ public OrientVertexType createVertexType( final String iClassName, final OClass iSuperClass, final int clusters); /** * Drop a vertex class. * @param iTypeName Vertex class name */ public void dropVertexType( final String iTypeName); /** * Returns the E persistent class as OrientEdgeType instance. */ public OrientEdgeType getEdgeBaseType(); /** * Returns the persistent class for type iTypeName as OrientEdgeType instance. * @param iTypeName Edge class name */ public OrientEdgeType getEdgeType( final String iTypeName); /** * Creates a new Edge persistent class. * @param iClassName Edge class name * @return OrientEdgeType instance representing the persistent class */ public OrientEdgeType createEdgeType( final String iClassName); /** * Creates a new Edge persistent class. * @param iClassName Edge class name * @param clusters The number of clusters to create for the new class. By default theMINIMUMCLUSTERS database setting is used. In v2.2 and later, the number of clusters are proportioned to the amount of cores found on the machine * @return OrientEdgeType instance representing the persistent class */ public OrientEdgeType createEdgeType( final String iClassName, final int clusters); /** * Creates a new Edge persistent class specifying the super class. * @param iClassName Edge class name * @param iSuperClassName Edge class name to extend * @return OrientEdgeType instance representing the persistent class */ public OrientEdgeType createEdgeType( final String iClassName, final String iSuperClassName); /** * Creates a new Edge persistent class specifying the super class. * @param iClassName Edge class name * @param iSuperClassName Edge class name to extend * @param clusters The number of clusters to create for the new class. By default theMINIMUMCLUSTERS database setting is used. In v2.2 and later, the number of clusters are proportioned to the amount of cores found on the machine * @return OrientEdgeType instance representing the persistent class */ public OrientEdgeType createEdgeType( final String iClassName, final String iSuperClassName, final int clusters); /** * Creates a new Edge persistent class specifying the super class. * @param iClassName Edge class name * @param iSuperClass OClass Edge to extend * @param clusters The number of clusters to create for the new class. By default theMINIMUMCLUSTERS database setting is used. In v2.2 and later, the number of clusters are proportioned to the amount of cores found on the machine * @return OrientEdgeType instance representing the persistent class */ public OrientEdgeType createEdgeType( final String iClassName, final OClass iSuperClass, final int clusters); /** * Creates a new Edge persistent class specifying the super class. * @param iClassName Edge class name * @param iSuperClass OClass Edge to extend * @return OrientEdgeType instance representing the persistent class */ public OrientEdgeType createEdgeType( final String iClassName, final OClass iSuperClass); /** * Drops an edge class. * @param iTypeName Edge class name */ public void dropEdgeType( final String iTypeName); /** * Detaches a Graph Element to be used offline. All the changes will be committed on further @attach call. * @param iElement Graph element to detach * @return The detached element * @see #attach(OrientElement) */ public OrientElement detach( final OrientElement iElement); /** * Attaches a previously detached Graph Element to the current Graph. All the pending changes will be committed. * @param iElement Graph element to attach * @return The attached element * @see #detach(OrientElement) */ public OrientElement attach( final OrientElement iElement); /** * Returns a graph element, vertex or edge, starting from an ID. * @param id Can by a String, ODocument or an OIdentifiable object. * @return OrientElement subclass such as OrientVertex or OrientEdge */ public OrientElement getElement( final Object id); /** * Drops the index against a field name. * @param key Field name * @param elementClass Element class as instances of Vertex and Edge */ public <T extends Element>void dropKeyIndex( final String key, final Class<T> elementClass); /** * Creates an automatic indexing structure for indexing provided key for element class. * @param key the key to create the index for * @param elementClass the element class that the index is for * @param indexParameters a collection of parameters for the underlying index implementation:<ul> <li>"type" is the index type between the supported types (UNIQUE, NOTUNIQUE, FULLTEXT). The default type is NOT_UNIQUE <li>"class" is the class to index when it's a custom type derived by Vertex (V) or Edge (E) <li>"keytype" to use a key type different by OType.STRING, </ul> * @param < T > the element class specification */ @SuppressWarnings({"rawtypes"}) @Override public <T extends Element>void createKeyIndex( final String key, final Class<T> elementClass, final Parameter... indexParameters); /** * Returns the indexed properties. * @param elementClass the element class that the index is for * @return Set of String containing the indexed properties */ @Override public <T extends Element>Set<String> getIndexedKeys( final Class<T> elementClass); /** * Returns the indexed properties. * @param elementClass the element class that the index is for * @param includeClassNames If true includes also the class name as prefix of fields * @return Set of String containing the indexed properties */ public <T extends Element>Set<String> getIndexedKeys( final Class<T> elementClass, final boolean includeClassNames); /** * Returns a GraphQuery object to execute queries against the Graph. * @return new GraphQuery instance */ @Override public GraphQuery query(); /** * Returns a OTraverse object to start traversing the graph. */ public OTraverse traverse(); /** * Executes commands against the graph. Commands are executed outside transaction. * @param iCommand Command request between SQL, GREMLIN and SCRIPT commands */ public OCommandRequest command( final OCommandRequest iCommand); public OResultSet sqlCommand( String iCommand); public OResultSet sqlQuery( String iCommand); public OResultSet sqlCommand( String iCommand, Object... args); public OResultSet sqlQuery( String iCommand, Object... args); /** * Counts the vertices in graph. * @return Long as number of total vertices */ public long countVertices(); /** * Counts the vertices in graph of a particular class. * @return Long as number of total vertices */ public long countVertices( final String iClassName); /** * Counts the edges in graph. Edge counting works only if useLightweightEdges is false. * @return Long as number of total edges */ public long countEdges(); /** * Counts the edges in graph of a particular class. Edge counting works only if useLightweightEdges is false. * @return Long as number of total edges */ public long countEdges( final String iClassName); public <RET>RET executeOutsideTx( final OCallable<RET,OrientBaseGraph> iCallable, final String... iOperationStrings) throws RuntimeException; protected void autoStartTransaction(); protected void saveIndexConfiguration(); protected <T>String getClassName( final Class<T> elementClass); protected Object convertKey( final OIndex idx, Object iValue); protected Object[] convertKeys( final OIndex idx, Object[] iValue); void throwRecordNotFoundException( final ORID identity, final String message); protected void setCurrentGraphInThreadLocal(); private void putInInitializationStack(); private void pollGraphFromStack( boolean updateDb); @SuppressWarnings("unchecked") private void readDatabaseConfiguration(); private void openOrCreate(); private List<Index<? extends Element>> loadManualIndexes(); private boolean hasIndexClass( OIndex idx); protected ODatabaseDocumentInternal getDatabase(); private static class InitializationStackThreadLocal extends ThreadLocal<Deque<OrientBaseGraph>> { @Override protected Deque<OrientBaseGraph> initialValue(); } /** * (Internal only) */ protected static void removeEdges( final OrientBaseGraph graph, final ODocument iVertex, final String iFieldName, final OIdentifiable iVertexToRemove, final boolean iAlsoInverse, final boolean useVertexFieldsForEdgeLabels, final boolean autoScaleEdgeType, final boolean forceReload); /** * (Internal only) */ private static void removeInverseEdge( final OrientBaseGraph graph, final ODocument iVertex, final String iFieldName, final OIdentifiable iVertexToRemove, final OIdentifiable currentRecord, final boolean useVertexFieldsForEdgeLabels, final boolean autoScaleEdgeType, boolean forceReload); protected static ODocument getDocument( final OIdentifiable id, final boolean forceReload); /** * (Internal only) */ protected static void deleteEdgeIfAny( final OIdentifiable iRecord, boolean forceReload); protected OrientVertex getVertexInstance( final OIdentifiable id); protected OrientVertex getVertexInstance( final String className, final Object... fields); protected OrientEdge getEdgeInstance( final OIdentifiable id); protected OrientEdge getEdgeInstance( final String className, final Object... fields); protected OrientEdge getEdgeInstance( final OIdentifiable from, final OIdentifiable to, final String label); public OrientConfigurableGraph setUseLightweightEdges( final boolean useDynamicEdges); @Override protected Object setProperty( String iName, Object iValue); @Override protected Object getProperty( String iName); @Override public Map<String,Object> getProperties(); }
javamelody_javamelody
javamelody/javamelody-core/src/main/java/net/bull/javamelody/internal/model/CounterRequestRumData.java
CounterRequestRumData
removeHits
class CounterRequestRumData implements Serializable, Cloneable { private static final long serialVersionUID = 745110095604593659L; // au-delà de 5 minutes, on considère une valeur RUM comme aberrante et à ignorer private static final long ABERRANT_VALUE = 5 * 60 * 1000; private long hits; private long networkTimeSum; private long domProcessingSum; private long pageRenderingSum; public long getHits() { return hits; } public int getNetworkTimeMean() { if (hits > 0) { return (int) (networkTimeSum / hits); } return -1; } public int getDomProcessingMean() { if (hits > 0) { return (int) (domProcessingSum / hits); } return -1; } public int getPageRenderingMean() { if (hits > 0) { return (int) (pageRenderingSum / hits); } return -1; } void addHit(long networkTime, long domProcessing, long pageRendering) { if (networkTime < 0 || networkTime > ABERRANT_VALUE || domProcessing < 0 || domProcessing > ABERRANT_VALUE || pageRendering < 0 || pageRendering > ABERRANT_VALUE) { // aberrant value, we ignore it return; } networkTimeSum += networkTime; domProcessingSum += domProcessing; pageRenderingSum += pageRendering; hits++; } void addHits(CounterRequestRumData rumData) { if (rumData.hits != 0) { hits += rumData.hits; networkTimeSum += rumData.networkTimeSum; domProcessingSum += rumData.domProcessingSum; pageRenderingSum += rumData.pageRenderingSum; } } void removeHits(CounterRequestRumData rumData) {<FILL_FUNCTION_BODY>} /** {@inheritDoc} */ @Override public CounterRequestRumData clone() { // NOPMD try { return (CounterRequestRumData) super.clone(); } catch (final CloneNotSupportedException e) { // ne peut arriver puisque CounterRequest implémente Cloneable throw new IllegalStateException(e); } } /** {@inheritDoc} */ @Override public String toString() { return getClass().getSimpleName() + "[hits=" + hits + ']'; } }
if (rumData.hits != 0) { hits -= rumData.hits; networkTimeSum -= rumData.networkTimeSum; domProcessingSum -= rumData.domProcessingSum; pageRenderingSum -= rumData.pageRenderingSum; }
758
89
847
orientechnologies_orientdb
orientdb/core/src/main/java/com/orientechnologies/orient/core/index/OIndexFullText.java
OIndexFullText
splitIntoWords
class OIndexFullText extends OIndexMultiValues { private static final String CONFIG_STOP_WORDS = "stopWords"; private static final String CONFIG_SEPARATOR_CHARS = "separatorChars"; private static final String CONFIG_IGNORE_CHARS = "ignoreChars"; private static final String CONFIG_INDEX_RADIX = "indexRadix"; private static final String CONFIG_MIN_WORD_LEN = "minWordLength"; private static final boolean DEF_INDEX_RADIX = true; private static final String DEF_SEPARATOR_CHARS = " \r\n\t:;,.|+*/\\=!?[]()"; private static final String DEF_IGNORE_CHARS = "'\""; private static final String DEF_STOP_WORDS = "the in a at as and or for his her " + "him this that what which while " + "up with be was were is"; private boolean indexRadix; private String separatorChars; private String ignoreChars; private int minWordLength; private Set<String> stopWords; public OIndexFullText(OIndexMetadata im, final OStorage storage) { super(im, storage); acquireExclusiveLock(); try { config(); configWithMetadata(im.getMetadata()); } finally { releaseExclusiveLock(); } } /** * Indexes a value and save the index. Splits the value in single words and index each one. Save * of the index is responsibility of the caller. */ @Override public OIndexFullText put(Object key, final OIdentifiable value) { if (key == null) { return this; } final ORID rid = value.getIdentity(); if (!rid.isValid()) { if (value instanceof ORecord) { // EARLY SAVE IT ((ORecord) value).save(); } else { throw new IllegalArgumentException( "Cannot store non persistent RID as index value for key '" + key + "'"); } } key = getCollatingValue(key); final Set<String> words = splitIntoWords(key.toString()); ODatabaseDocumentInternal database = getDatabase(); if (database.getTransaction().isActive()) { OTransaction singleTx = database.getTransaction(); for (String word : words) { singleTx.addIndexEntry( this, super.getName(), OTransactionIndexChanges.OPERATION.PUT, word, value); } } else { database.begin(); OTransaction singleTx = database.getTransaction(); for (String word : words) { singleTx.addIndexEntry( this, super.getName(), OTransactionIndexChanges.OPERATION.PUT, word, value); } database.commit(); } return this; } /** * Splits passed in key on several words and remove records with keys equals to any item of split * result and values equals to passed in value. * * @param key Key to remove. * @param rid Value to remove. * @return <code>true</code> if at least one record is removed. */ @Override public boolean remove(Object key, final OIdentifiable rid) { if (key == null) { return false; } key = getCollatingValue(key); final Set<String> words = splitIntoWords(key.toString()); ODatabaseDocumentInternal database = getDatabase(); if (database.getTransaction().isActive()) { for (final String word : words) { database.getTransaction().addIndexEntry(this, super.getName(), OPERATION.REMOVE, word, rid); } } else { database.begin(); for (final String word : words) { database.getTransaction().addIndexEntry(this, super.getName(), OPERATION.REMOVE, word, rid); } database.commit(); } return true; } @Override public OIndexMultiValues create( OIndexMetadata metadata, boolean rebuild, OProgressListener progressListener) { if (metadata.getIndexDefinition().getFields().size() > 1) { throw new OIndexException(getType() + " indexes cannot be used as composite ones."); } super.create(metadata, rebuild, progressListener); return this; } @Override public ODocument updateConfiguration() { ODocument document = super.updateConfiguration(); document.field(CONFIG_SEPARATOR_CHARS, separatorChars); document.field(CONFIG_IGNORE_CHARS, ignoreChars); document.field(CONFIG_STOP_WORDS, stopWords); document.field(CONFIG_MIN_WORD_LEN, minWordLength); document.field(CONFIG_INDEX_RADIX, indexRadix); return document; } public boolean canBeUsedInEqualityOperators() { return false; } public boolean supportsOrderedIterations() { return false; } private void configWithMetadata(ODocument metadata) { if (metadata != null) { if (metadata.containsField(CONFIG_IGNORE_CHARS)) { ignoreChars = metadata.field(CONFIG_IGNORE_CHARS); } if (metadata.containsField(CONFIG_INDEX_RADIX)) { indexRadix = metadata.field(CONFIG_INDEX_RADIX); } if (metadata.containsField(CONFIG_SEPARATOR_CHARS)) { separatorChars = metadata.field(CONFIG_SEPARATOR_CHARS); } if (metadata.containsField(CONFIG_MIN_WORD_LEN)) { minWordLength = metadata.field(CONFIG_MIN_WORD_LEN); } if (metadata.containsField(CONFIG_STOP_WORDS)) { stopWords = new HashSet<>(metadata.field(CONFIG_STOP_WORDS)); } } } private void config() { ignoreChars = DEF_IGNORE_CHARS; indexRadix = DEF_INDEX_RADIX; separatorChars = DEF_SEPARATOR_CHARS; minWordLength = 3; stopWords = new HashSet<>(OStringSerializerHelper.split(DEF_STOP_WORDS, ' ')); } private Set<String> splitIntoWords(final String iKey) {<FILL_FUNCTION_BODY>} }
final Set<String> result = new HashSet<>(); final List<String> words = new ArrayList<>(); OStringSerializerHelper.split(words, iKey, 0, -1, separatorChars); final StringBuilder buffer = new StringBuilder(64); // FOREACH WORD CREATE THE LINK TO THE CURRENT DOCUMENT char c; boolean ignore; for (String word : words) { buffer.setLength(0); for (int i = 0; i < word.length(); ++i) { c = word.charAt(i); ignore = false; for (int k = 0; k < ignoreChars.length(); ++k) { if (c == ignoreChars.charAt(k)) { ignore = true; break; } } if (!ignore) { buffer.append(c); } } int length = buffer.length(); while (length >= minWordLength) { buffer.setLength(length); word = buffer.toString(); // CHECK IF IT'S A STOP WORD if (!stopWords.contains(word)) // ADD THE WORD TO THE RESULT SET { result.add(word); } if (indexRadix) { length--; } else { break; } } } return result;
1,666
366
2,032
/** * Abstract index implementation that supports multi-values for the same key. * @author Luca Garulli (l.garulli--(at)--orientdb.com) */ public abstract class OIndexMultiValues extends OIndexAbstract { OIndexMultiValues( OIndexMetadata im, final OStorage storage); @Deprecated @Override public Collection<ORID> get( Object key); @Override public Stream<ORID> getRidsIgnoreTx( Object key); @Override public Stream<ORID> getRids( Object key); public OIndexMultiValues put( Object key, final OIdentifiable singleValue); @Override public void doPut( OAbstractPaginatedStorage storage, Object key, ORID rid) throws OInvalidIndexEngineIdException; @Override public boolean isNativeTxSupported(); private static void doPutV0( final int indexId, final OAbstractPaginatedStorage storage, String valueContainerAlgorithm, String indexName, Object key, ORID identity) throws OInvalidIndexEngineIdException; private static void doPutV1( OAbstractPaginatedStorage storage, int indexId, Object key, ORID identity) throws OInvalidIndexEngineIdException; @Override public boolean remove( Object key, final OIdentifiable value); @Override public boolean doRemove( OAbstractPaginatedStorage storage, Object key, ORID rid) throws OInvalidIndexEngineIdException; private static boolean doRemoveV0( int indexId, OAbstractPaginatedStorage storage, Object key, OIdentifiable value) throws OInvalidIndexEngineIdException; private static boolean doRemoveV1( int indexId, OAbstractPaginatedStorage storage, Object key, OIdentifiable value) throws OInvalidIndexEngineIdException; @Override public Stream<ORawPair<Object,ORID>> streamEntriesBetween( Object fromKey, boolean fromInclusive, Object toKey, boolean toInclusive, boolean ascOrder); @Override public Stream<ORawPair<Object,ORID>> streamEntriesMajor( Object fromKey, boolean fromInclusive, boolean ascOrder); @Override public Stream<ORawPair<Object,ORID>> streamEntriesMinor( Object toKey, boolean toInclusive, boolean ascOrder); @Override public Stream<ORawPair<Object,ORID>> streamEntries( Collection<?> keys, boolean ascSortOrder); private Stream<ORawPair<Object,ORID>> txStramForKey( final OTransactionIndexChanges indexChanges, Object key); private Stream<ORawPair<Object,ORID>> streamForKey( Object key); public static Set<OIdentifiable> calculateTxValue( final Object key, OTransactionIndexChanges indexChanges); public long size(); @Override public Stream<ORawPair<Object,ORID>> stream(); private Stream<ORawPair<Object,ORID>> mergeTxAndBackedStreams( OTransactionIndexChanges indexChanges, Stream<ORawPair<Object,ORID>> txStream, Stream<ORawPair<Object,ORID>> backedStream, boolean ascOrder); private ORawPair<Object,ORID> calculateTxIndexEntry( Object key, final ORID backendValue, OTransactionIndexChanges indexChanges); @Override public Stream<ORawPair<Object,ORID>> descStream(); }
PlayEdu_PlayEdu
PlayEdu/playedu-common/src/main/java/xyz/playedu/common/service/impl/UserDepartmentServiceImpl.java
UserDepartmentServiceImpl
storeDepIds
class UserDepartmentServiceImpl extends ServiceImpl<UserDepartmentMapper, UserDepartment> implements UserDepartmentService { @Override public List<Integer> getUserIdsByDepIds(List<Integer> depIds) { return list(query().getWrapper().in("dep_id", depIds)).stream() .map(UserDepartment::getUserId) .toList(); } @Override public void storeDepIds(Integer userId, Integer[] depIds) {<FILL_FUNCTION_BODY>} @Override public void resetStoreDepIds(Integer userId, Integer[] depIds) { remove(query().getWrapper().eq("user_id", userId)); storeDepIds(userId, depIds); } }
if (depIds == null) { return; } List<UserDepartment> userDepartments = new ArrayList<>(); for (int i = 0; i < depIds.length; i++) { Integer depId = depIds[i]; userDepartments.add( new UserDepartment() { { setUserId(userId); setDepId(depId); } }); } saveBatch(userDepartments);
192
125
317
jeecgboot_jeecg-boot
jeecg-boot/jeecg-boot-base-core/src/main/java/org/jeecg/config/mybatis/ThreadLocalDataHelper.java
ThreadLocalDataHelper
get
class ThreadLocalDataHelper { /** * 线程的本地变量 */ private static final ThreadLocal<ConcurrentHashMap> REQUEST_DATA = new ThreadLocal<>(); /** * 存储本地参数 */ private static final ConcurrentHashMap DATA_MAP = new ConcurrentHashMap<>(); /** * 设置请求参数 * * @param key 参数key * @param value 参数值 */ public static void put(String key, Object value) { if(ObjectUtil.isNotEmpty(value)) { DATA_MAP.put(key, value); REQUEST_DATA.set(DATA_MAP); } } /** * 获取请求参数值 * * @param key 请求参数 * @return */ public static <T> T get(String key) {<FILL_FUNCTION_BODY>} /** * 获取请求参数 * * @return 请求参数 MAP 对象 */ public static void clear() { DATA_MAP.clear(); REQUEST_DATA.remove(); } }
ConcurrentHashMap dataMap = REQUEST_DATA.get(); if (CollectionUtils.isNotEmpty(dataMap)) { return (T) dataMap.get(key); } return null;
299
55
354
spring-cloud_spring-cloud-gateway
spring-cloud-gateway/spring-cloud-gateway-server-mvc/src/main/java/org/springframework/cloud/gateway/server/mvc/filter/AfterFilterFunctions.java
AfterFilterFunctions
dedupeHeaders
class AfterFilterFunctions { private AfterFilterFunctions() { } public static BiFunction<ServerRequest, ServerResponse, ServerResponse> addResponseHeader(String name, String... values) { return (request, response) -> { String[] expandedValues = MvcUtils.expandMultiple(request, values); response.headers().addAll(name, Arrays.asList(expandedValues)); return response; }; } public static BiFunction<ServerRequest, ServerResponse, ServerResponse> dedupeResponseHeader(String name) { return dedupeResponseHeader(name, DedupeStrategy.RETAIN_FIRST); } public static BiFunction<ServerRequest, ServerResponse, ServerResponse> dedupeResponseHeader(String name, DedupeStrategy strategy) { Assert.hasText(name, "name must not be null or empty"); Assert.notNull(strategy, "strategy must not be null"); return (request, response) -> { dedupeHeaders(response.headers(), name, strategy); return response; }; } private static void dedupeHeaders(HttpHeaders headers, String names, DedupeStrategy strategy) {<FILL_FUNCTION_BODY>} private static void dedupeHeader(HttpHeaders headers, String name, DedupeStrategy strategy) { List<String> values = headers.get(name); if (values == null || values.size() <= 1) { return; } switch (strategy) { case RETAIN_FIRST: headers.set(name, values.get(0)); break; case RETAIN_LAST: headers.set(name, values.get(values.size() - 1)); break; case RETAIN_UNIQUE: headers.put(name, new ArrayList<>(new LinkedHashSet<>(values))); break; default: break; } } public static BiFunction<ServerRequest, ServerResponse, ServerResponse> removeResponseHeader(String name) { return (request, response) -> { response.headers().remove(name); return response; }; } public static BiFunction<ServerRequest, ServerResponse, ServerResponse> rewriteLocationResponseHeader() { return RewriteLocationResponseHeaderFilterFunctions.rewriteLocationResponseHeader(config -> { }); } public static BiFunction<ServerRequest, ServerResponse, ServerResponse> rewriteLocationResponseHeader( Consumer<RewriteLocationResponseHeaderFilterFunctions.RewriteLocationResponseHeaderConfig> configConsumer) { return RewriteLocationResponseHeaderFilterFunctions.rewriteLocationResponseHeader(configConsumer); } public static BiFunction<ServerRequest, ServerResponse, ServerResponse> rewriteResponseHeader(String name, String regexp, String originalReplacement) { String replacement = originalReplacement.replace("$\\", "$"); Pattern pattern = Pattern.compile(regexp); return (request, response) -> { response.headers().computeIfPresent(name, (key, values) -> { List<String> rewrittenValues = values.stream() .map(value -> pattern.matcher(value).replaceAll(replacement)).toList(); return new ArrayList<>(rewrittenValues); }); return response; }; } public static BiFunction<ServerRequest, ServerResponse, ServerResponse> setResponseHeader(String name, String value) { return (request, response) -> { String expandedValue = MvcUtils.expand(request, value); response.headers().set(name, expandedValue); return response; }; } public static BiFunction<ServerRequest, ServerResponse, ServerResponse> setStatus(int statusCode) { return setStatus(new HttpStatusHolder(null, statusCode)); } public static BiFunction<ServerRequest, ServerResponse, ServerResponse> setStatus(String statusCode) { return setStatus(HttpStatusHolder.valueOf(statusCode)); } public static BiFunction<ServerRequest, ServerResponse, ServerResponse> setStatus(HttpStatusCode statusCode) { return setStatus(new HttpStatusHolder(statusCode, null)); } public static BiFunction<ServerRequest, ServerResponse, ServerResponse> setStatus(HttpStatusHolder statusCode) { return (request, response) -> { if (response instanceof GatewayServerResponse res) { res.setStatusCode(statusCode.resolve()); } return response; }; } public enum DedupeStrategy { /** * Default: Retain the first value only. */ RETAIN_FIRST, /** * Retain the last value only. */ RETAIN_LAST, /** * Retain all unique values in the order of their first encounter. */ RETAIN_UNIQUE } }
if (headers == null || names == null || strategy == null) { return; } String[] tokens = StringUtils.tokenizeToStringArray(names, " ", true, true); for (String name : tokens) { dedupeHeader(headers, name.trim(), strategy); }
1,221
78
1,299
logfellow_logstash-logback-encoder
logstash-logback-encoder/src/main/java/net/logstash/logback/marker/SingleFieldAppendingMarker.java
SingleFieldAppendingMarker
hashCode
class SingleFieldAppendingMarker extends LogstashMarker implements StructuredArgument { public static final String MARKER_NAME_PREFIX = LogstashMarker.MARKER_NAME_PREFIX + "APPEND_"; /** * Name of the field to append. * * Note that the value of the field is provided by subclasses via {@link #writeFieldValue(JsonGenerator)}. */ private final String fieldName; /** * Pattern to use when appending the field/value in {@link #toString()}. * <p> * {@link #getFieldName()} will be substituted in {0}. * {@link #getFieldValue()} will be substituted in {1}. */ private final String messageFormatPattern; public SingleFieldAppendingMarker(String markerName, String fieldName) { this(markerName, fieldName, StructuredArguments.DEFAULT_KEY_VALUE_MESSAGE_FORMAT_PATTERN); } public SingleFieldAppendingMarker(String markerName, String fieldName, String messageFormatPattern) { super(markerName); this.fieldName = Objects.requireNonNull(fieldName, "fieldName must not be null"); this.messageFormatPattern = Objects.requireNonNull(messageFormatPattern, "messageFormatPattern must not be null"); } public String getFieldName() { return fieldName; } public void writeTo(JsonGenerator generator) throws IOException { writeFieldName(generator); writeFieldValue(generator); } /** * Writes the field name to the generator. * * @param generator the generator to write JSON * @throws IOException if an I/O error occurs */ protected void writeFieldName(JsonGenerator generator) throws IOException { generator.writeFieldName(getFieldName()); } /** * Writes the field value to the generator. * * @param generator the generator to write JSON * @throws IOException if an I/O error occurs */ protected abstract void writeFieldValue(JsonGenerator generator) throws IOException; @Override public String toStringSelf() { final String fieldValueString = StructuredArguments.toString(getFieldValue()); /* * Optimize for commonly used messageFormatPattern */ if (StructuredArguments.VALUE_ONLY_MESSAGE_FORMAT_PATTERN.equals(messageFormatPattern)) { return fieldValueString; } if (StructuredArguments.DEFAULT_KEY_VALUE_MESSAGE_FORMAT_PATTERN.equals(messageFormatPattern)) { return getFieldName() + "=" + fieldValueString; } /* * Custom messageFormatPattern */ return MessageFormatCache.INSTANCE.getMessageFormat(this.messageFormatPattern) .format(new Object[] {getFieldName(), fieldValueString}); } /** * Return the value that should be included in the output of {@link #toString()}. * * @return the field value */ protected abstract Object getFieldValue(); @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (!super.equals(obj)) { return false; } if (!(obj instanceof SingleFieldAppendingMarker)) { return false; } SingleFieldAppendingMarker other = (SingleFieldAppendingMarker) obj; return this.fieldName.equals(other.fieldName); } @Override public int hashCode() {<FILL_FUNCTION_BODY>} }
final int prime = 31; int result = 1; result = prime * result + super.hashCode(); result = prime * result + this.fieldName.hashCode(); return result;
901
53
954
/** * A {@link Marker} that is known and understood by the logstash logback encoder.<p> In particular these markers are used to write data into the logstash json event via {@link #writeTo(JsonGenerator)}. */ @SuppressWarnings("serial") public abstract class LogstashMarker extends LogstashBasicMarker implements Iterable<Marker> { public static final String MARKER_NAME_PREFIX="LS_"; public LogstashMarker( String name); /** * Adds the given marker as a reference, and returns this marker. <p> This can be used to chain markers together fluently on a log line. For example: <pre> {@code import static net.logstash.logback.marker.Markers. logger.info(append("name1", "value1).and(append("name2", "value2")), "log message");}</pre> * @param < T > subtype of LogstashMarker * @param reference The marker to add * @return A marker with this marker and the given marker */ @SuppressWarnings("unchecked") public <T extends LogstashMarker>T and( Marker reference); /** * @param < T > subtype of LogstashMarker * @param reference The marker to add * @deprecated Use {@link #and(Marker)} instead * @see #and(Marker) * @return A marker with this marker and the given marker */ @Deprecated public <T extends LogstashMarker>T with( Marker reference); /** * Writes the data associated with this marker to the given {@link JsonGenerator}. * @param generator the generator to which to write the output of this marker. * @throws IOException if there was an error writing to the generator */ public abstract void writeTo( JsonGenerator generator) throws IOException ; @Override public void add( Marker reference); /** * Returns a String in the form of <pre> self, reference1, reference2, ... </pre> <p>Where <code>self</code> is the value returned by {@link #toStringSelf()}, and <code>reference*</code> are the <code>toString()</code> values of any references.</p> <p>It is recommended that subclasses only override {@link #toStringSelf()}, so that references are automatically included in the value returned from {@link #toString()}.</p> * @return a string representation of the object, which includes references */ @Override public String toString(); /** * Returns a string representation of this object, without including any references. <p>Subclasses should override {@link #toStringSelf()} instead of {@link #toString()}, since {@link #toString()} will automatically include the {@link #toStringSelf()} and references.</p> * @return a string representation of this object, without including any references. */ protected String toStringSelf(); }
jeecgboot_jeecg-boot
jeecg-boot/jeecg-boot-base-core/src/main/java/org/jeecg/config/WebSocketConfig.java
WebSocketConfig
getFilterRegistrationBean
class WebSocketConfig { /** * 注入ServerEndpointExporter, * 这个bean会自动注册使用了@ServerEndpoint注解声明的Websocket endpoint */ @Bean public ServerEndpointExporter serverEndpointExporter() { return new ServerEndpointExporter(); } @Bean public WebsocketFilter websocketFilter(){ return new WebsocketFilter(); } @Bean public FilterRegistrationBean getFilterRegistrationBean(){<FILL_FUNCTION_BODY>} }
FilterRegistrationBean bean = new FilterRegistrationBean(); bean.setFilter(websocketFilter()); //TODO 临时注释掉,测试下线上socket总断的问题 bean.addUrlPatterns("/taskCountSocket/*", "/websocket/*","/eoaSocket/*","/eoaNewChatSocket/*", "/newsWebsocket/*", "/vxeSocket/*"); return bean;
137
99
236
subhra74_snowflake
snowflake/muon-app/src/main/java/muon/app/ui/components/session/PuttyImporter.java
PuttyImporter
getKeyNames
class PuttyImporter { private static final String PuttyREGKey = "Software\\SimonTatham\\PuTTY\\Sessions"; public static Map<String, String> getKeyNames() {<FILL_FUNCTION_BODY>} public static void importSessions(DefaultMutableTreeNode node, List<String> keys) { // String[] keys = // Advapi32Util.registryGetKeys(WinReg.HKEY_CURRENT_USER, // PuttyREGKey); for (String key : keys) { if ("ssh".equals(RegUtil.regGetStr(WinReg.HKEY_CURRENT_USER, PuttyREGKey + "\\" + key, "Protocol"))) { String host = RegUtil.regGetStr(WinReg.HKEY_CURRENT_USER, PuttyREGKey + "\\" + key, "HostName"); int port = RegUtil.regGetInt(WinReg.HKEY_CURRENT_USER, PuttyREGKey + "\\" + key, "PortNumber"); String user = RegUtil.regGetStr(WinReg.HKEY_CURRENT_USER, PuttyREGKey + "\\" + key, "UserName"); String keyfile = RegUtil.regGetStr(WinReg.HKEY_CURRENT_USER, PuttyREGKey + "\\" + key, "PublicKeyFile"); String proxyHost = RegUtil.regGetStr(WinReg.HKEY_CURRENT_USER, PuttyREGKey + "\\" + key, "ProxyHost"); int proxyPort = RegUtil.regGetInt(WinReg.HKEY_CURRENT_USER, PuttyREGKey + "\\" + key, "ProxyPort"); String proxyUser = RegUtil.regGetStr(WinReg.HKEY_CURRENT_USER, PuttyREGKey + "\\" + key, "ProxyUsername"); String proxyPass = RegUtil.regGetStr(WinReg.HKEY_CURRENT_USER, PuttyREGKey + "\\" + key, "ProxyPassword"); int proxyType = RegUtil.regGetInt(WinReg.HKEY_CURRENT_USER, PuttyREGKey + "\\" + key, "ProxyMethod"); if (proxyType == 1) { proxyType = 2; } else if (proxyType == 2) { proxyType = 3; } else if (proxyType == 3) { proxyType = 1; } else { proxyType = 0; } SessionInfo info = new SessionInfo(); info.setName(key); info.setHost(host); info.setPort(port); info.setUser(user); info.setPrivateKeyFile(keyfile); info.setProxyHost(proxyHost); info.setProxyPort(proxyPort); info.setProxyUser(proxyUser); info.setProxyPassword(proxyPass); info.setProxyType(proxyType); DefaultMutableTreeNode node1 = new DefaultMutableTreeNode(info); node1.setAllowsChildren(false); node.add(node1); } } } }
Map<String, String> map = new HashMap<String, String>(); try { String[] keys = Advapi32Util .registryGetKeys(WinReg.HKEY_CURRENT_USER, PuttyREGKey); for (String key : keys) { String decodedKey = key.replace("%20", " "); map.put(key, decodedKey); } } catch (Exception e) { e.printStackTrace(); } return map;
880
146
1,026
graphhopper_graphhopper
graphhopper/core/src/main/java/com/graphhopper/routing/util/countryrules/europe/SanMarinoCountryRule.java
SanMarinoCountryRule
getToll
class SanMarinoCountryRule implements CountryRule { @Override public Toll getToll(ReaderWay readerWay, Toll currentToll) {<FILL_FUNCTION_BODY>} }
if (currentToll != Toll.MISSING) { return currentToll; } return Toll.NO;
53
39
92
jitsi_jitsi
jitsi/modules/plugin/notificationconfiguration/src/main/java/net/java/sip/communicator/plugin/notificationconfiguration/SoundFilter.java
SoundFilter
getDescription
class SoundFilter extends SipCommFileFilter { /** * All acceptable sound formats. If null, then this sound filter will accept * all sound formats available in SoundFileUtils. */ private String[] soundFormats = null; /** * Creates a new sound filter which accepts all sound format available in * SoundFileUtils. */ public SoundFilter() { super(); } /** * Creates a new sound filter which accepts only sound format corresponding * to the list given in parameter. * * @param soundFormats The list of sound format to accept. */ public SoundFilter(String[] soundFormats) { super(); if(soundFormats != null) { this.soundFormats = new String[soundFormats.length]; System.arraycopy( soundFormats, 0, this.soundFormats, 0, soundFormats.length); } } /** * Method which describes differents permits extensions and defines which * file or directory will be displayed in the filechoser. * * @param f file for the test * * @return boolean true if the File is a Directory or a sound file. And * return false in the other cases. */ @Override public boolean accept(File f) { // Tests if the file passed in argument is a directory. if (f.isDirectory()) { return true; } // Else, tests if the exension is correct. else { return SoundFileUtils.isSoundFile(f, this.soundFormats); } } /** * Method which describes, in the file chooser, the text representing the * permit extension files. * * @return String which is displayed in the sound file chooser. */ @Override public String getDescription() {<FILL_FUNCTION_BODY>} }
String desc = "Sound File ("; if(this.soundFormats != null) { for(int i = 0; i < this.soundFormats.length; ++i) { if(i != 0) { desc += ", "; } desc += "*." + this.soundFormats[i]; } } else { desc += "*.au, *.mid, *.mod, *.mp2, *.mp3, *.ogg, *.ram, *.wav, " + "*.wma"; } desc += ")"; return desc;
507
166
673
/** * The purpose of this interface is to provide an generic file filter type for the SipCommFileChooser, which is used either as an AWT FileDialog, either as a Swing JFileChooser. Both of these dialogs use their own filter type, FileFilter (class) for JFileChooser and FilenameFilter (interface) for FileDialog. SipCommFileFilter acts as both an implementation and an heritage from these two filters. To use a your own file filter with a SipCommFileChooser, you just have to extend from SipCommFileFilter and redefine at least the method 'public boolean accept(File f)' which is described in the Java FileFilter class. You won't have to redefine 'public boolean accept(File dir, String name)' from the Java FilenameFilter interface since it's done here: the method is transfered toward the accept method of Java FileFilter class. * @author Valentin Martinet */ public abstract class SipCommFileFilter extends FileFilter implements FilenameFilter { /** * Avoid to be obliged to implement 'public boolean accept(File dir, String name)' in your own file filter. * @param dir file's parent directory * @param name file's name * @return boolean if the file is accepted or not */ public boolean accept( File dir, String name); }
graphhopper_graphhopper
graphhopper/core/src/main/java/com/graphhopper/reader/osm/pbf/PbfDecoder.java
PbfDecoder
processBlobs
class PbfDecoder { private final PbfStreamSplitter streamSplitter; private final ExecutorService executorService; private final int maxPendingBlobs; private final Sink sink; private final Lock lock; private final Condition dataWaitCondition; private final Queue<PbfBlobResult> blobResults; private final SkipOptions skipOptions; /** * Creates a new instance. * <p> * * @param streamSplitter The PBF stream splitter providing the source of blobs to be decoded. * @param executorService The executor service managing the thread pool. * @param maxPendingBlobs The maximum number of blobs to have in progress at any point in time. * @param sink The sink to send all decoded entities to. */ public PbfDecoder(PbfStreamSplitter streamSplitter, ExecutorService executorService, int maxPendingBlobs, Sink sink, SkipOptions skipOptions) { this.streamSplitter = streamSplitter; this.executorService = executorService; this.maxPendingBlobs = maxPendingBlobs; this.sink = sink; this.skipOptions = skipOptions; // Create the thread synchronisation primitives. lock = new ReentrantLock(); dataWaitCondition = lock.newCondition(); // Create the queue of blobs being decoded. blobResults = new LinkedList<>(); } /** * Any thread can call this method when they wish to wait until an update has been performed by * another thread. */ private void waitForUpdate() { try { dataWaitCondition.await(); } catch (InterruptedException e) { throw new RuntimeException("Thread was interrupted.", e); } } /** * Any thread can call this method when they wish to signal another thread that an update has * occurred. */ private void signalUpdate() { dataWaitCondition.signal(); } private void sendResultsToSink(int targetQueueSize) { while (blobResults.size() > targetQueueSize) { // Get the next result from the queue and wait for it to complete. PbfBlobResult blobResult = blobResults.remove(); while (!blobResult.isComplete()) { // The thread hasn't finished processing yet so wait for an // update from another thread before checking again. waitForUpdate(); } if (!blobResult.isSuccess()) { throw new RuntimeException("A PBF decoding worker thread failed, aborting.", blobResult.getException()); } // Send the processed entities to the sink. We can release the lock // for the duration of processing to allow worker threads to post // their results. lock.unlock(); try { for (ReaderElement entity : blobResult.getEntities()) { sink.process(entity); } } finally { lock.lock(); } } } private void processBlobs() {<FILL_FUNCTION_BODY>} public void run() { lock.lock(); try { processBlobs(); } finally { lock.unlock(); } } }
// Process until the PBF stream is exhausted. while (streamSplitter.hasNext()) { // Obtain the next raw blob from the PBF stream. PbfRawBlob rawBlob = streamSplitter.next(); // Create the result object to capture the results of the decoded // blob and add it to the blob results queue. final PbfBlobResult blobResult = new PbfBlobResult(); blobResults.add(blobResult); // Create the listener object that will update the blob results // based on an event fired by the blob decoder. PbfBlobDecoderListener decoderListener = new PbfBlobDecoderListener() { @Override public void error(Exception ex) { lock.lock(); try { // System.out.println("ERROR: " + new Date()); blobResult.storeFailureResult(ex); signalUpdate(); } finally { lock.unlock(); } } @Override public void complete(List<ReaderElement> decodedEntities) { lock.lock(); try { blobResult.storeSuccessResult(decodedEntities); signalUpdate(); } finally { lock.unlock(); } } }; // Create the blob decoder itself and execute it on a worker thread. PbfBlobDecoder blobDecoder = new PbfBlobDecoder(rawBlob.getType(), rawBlob.getData(), decoderListener, skipOptions); executorService.execute(blobDecoder); // If the number of pending blobs has reached capacity we must begin // sending results to the sink. This method will block until blob // decoding is complete. sendResultsToSink(maxPendingBlobs - 1); } // There are no more entities available in the PBF stream, so send all remaining data to the sink. sendResultsToSink(0);
820
491
1,311
jeecgboot_jeecg-boot
jeecg-boot/jeecg-boot-base-core/src/main/java/org/jeecg/common/util/PasswordUtil.java
PasswordUtil
bytesToHexString
class PasswordUtil { /** * JAVA6支持以下任意一种算法 PBEWITHMD5ANDDES PBEWITHMD5ANDTRIPLEDES * PBEWITHSHAANDDESEDE PBEWITHSHA1ANDRC2_40 PBKDF2WITHHMACSHA1 * */ /** * 定义使用的算法为:PBEWITHMD5andDES算法 * 加密算法 */ public static final String ALGORITHM = "PBEWithMD5AndDES"; /** * 定义使用的算法为:PBEWITHMD5andDES算法 * 密钥 */ public static final String SALT = "63293188"; /** * 定义迭代次数为1000次 */ private static final int ITERATIONCOUNT = 1000; /** * 获取加密算法中使用的盐值,解密中使用的盐值必须与加密中使用的相同才能完成操作. 盐长度必须为8字节 * * @return byte[] 盐值 * */ public static byte[] getSalt() throws Exception { // 实例化安全随机数 SecureRandom random = new SecureRandom(); // 产出盐 return random.generateSeed(8); } public static byte[] getStaticSalt() { // 产出盐 return SALT.getBytes(); } /** * 根据PBE密码生成一把密钥 * * @param password * 生成密钥时所使用的密码 * @return Key PBE算法密钥 * */ private static Key getPbeKey(String password) { // 实例化使用的算法 SecretKeyFactory keyFactory; SecretKey secretKey = null; try { keyFactory = SecretKeyFactory.getInstance(ALGORITHM); // 设置PBE密钥参数 PBEKeySpec keySpec = new PBEKeySpec(password.toCharArray()); // 生成密钥 secretKey = keyFactory.generateSecret(keySpec); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } return secretKey; } /** * 加密明文字符串 * * @param plaintext * 待加密的明文字符串 * @param password * 生成密钥时所使用的密码 * @param salt * 盐值 * @return 加密后的密文字符串 * @throws Exception */ public static String encrypt(String plaintext, String password, String salt) { Key key = getPbeKey(password); byte[] encipheredData = null; PBEParameterSpec parameterSpec = new PBEParameterSpec(salt.getBytes(), ITERATIONCOUNT); try { Cipher cipher = Cipher.getInstance(ALGORITHM); cipher.init(Cipher.ENCRYPT_MODE, key, parameterSpec); //update-begin-author:sccott date:20180815 for:中文作为用户名时,加密的密码windows和linux会得到不同的结果 gitee/issues/IZUD7 encipheredData = cipher.doFinal(plaintext.getBytes("utf-8")); //update-end-author:sccott date:20180815 for:中文作为用户名时,加密的密码windows和linux会得到不同的结果 gitee/issues/IZUD7 } catch (Exception e) { } return bytesToHexString(encipheredData); } /** * 解密密文字符串 * * @param ciphertext * 待解密的密文字符串 * @param password * 生成密钥时所使用的密码(如需解密,该参数需要与加密时使用的一致) * @param salt * 盐值(如需解密,该参数需要与加密时使用的一致) * @return 解密后的明文字符串 * @throws Exception */ public static String decrypt(String ciphertext, String password, String salt) { Key key = getPbeKey(password); byte[] passDec = null; PBEParameterSpec parameterSpec = new PBEParameterSpec(salt.getBytes(), ITERATIONCOUNT); try { Cipher cipher = Cipher.getInstance(ALGORITHM); cipher.init(Cipher.DECRYPT_MODE, key, parameterSpec); passDec = cipher.doFinal(hexStringToBytes(ciphertext)); } catch (Exception e) { // TODO: handle exception } return new String(passDec); } /** * 将字节数组转换为十六进制字符串 * * @param src * 字节数组 * @return */ public static String bytesToHexString(byte[] src) {<FILL_FUNCTION_BODY>} /** * 将十六进制字符串转换为字节数组 * * @param hexString * 十六进制字符串 * @return */ public static byte[] hexStringToBytes(String hexString) { if (hexString == null || "".equals(hexString)) { return null; } hexString = hexString.toUpperCase(); int length = hexString.length() / 2; char[] hexChars = hexString.toCharArray(); byte[] d = new byte[length]; for (int i = 0; i < length; i++) { int pos = i * 2; d[i] = (byte) (charToByte(hexChars[pos]) << 4 | charToByte(hexChars[pos + 1])); } return d; } private static byte charToByte(char c) { return (byte) "0123456789ABCDEF".indexOf(c); } }
StringBuilder stringBuilder = new StringBuilder(""); if (src == null || src.length <= 0) { return null; } for (int i = 0; i < src.length; i++) { int v = src[i] & 0xFF; String hv = Integer.toHexString(v); if (hv.length() < 2) { stringBuilder.append(0); } stringBuilder.append(hv); } return stringBuilder.toString();
1,621
135
1,756
joelittlejohn_jsonschema2pojo
jsonschema2pojo/jsonschema2pojo-core/src/main/java/org/jsonschema2pojo/Jackson2Annotator.java
Jackson2Annotator
dateField
class Jackson2Annotator extends AbstractTypeInfoAwareAnnotator { private final JsonInclude.Include inclusionLevel; public Jackson2Annotator(GenerationConfig generationConfig) { super(generationConfig); switch (generationConfig.getInclusionLevel()) { case ALWAYS: inclusionLevel = JsonInclude.Include.ALWAYS; break; case NON_ABSENT: inclusionLevel = JsonInclude.Include.NON_ABSENT; break; case NON_DEFAULT: inclusionLevel = JsonInclude.Include.NON_DEFAULT; break; case NON_EMPTY: inclusionLevel = JsonInclude.Include.NON_EMPTY; break; case NON_NULL: inclusionLevel = JsonInclude.Include.NON_NULL; break; case USE_DEFAULTS: inclusionLevel = JsonInclude.Include.USE_DEFAULTS; break; default: inclusionLevel = JsonInclude.Include.NON_NULL; break; } } @Override public void propertyOrder(JDefinedClass clazz, JsonNode propertiesNode) { JAnnotationArrayMember annotationValue = clazz.annotate(JsonPropertyOrder.class).paramArray("value"); for (Iterator<String> properties = propertiesNode.fieldNames(); properties.hasNext();) { annotationValue.param(properties.next()); } } @Override public void propertyInclusion(JDefinedClass clazz, JsonNode schema) { clazz.annotate(JsonInclude.class).param("value", inclusionLevel); } @Override public void propertyField(JFieldVar field, JDefinedClass clazz, String propertyName, JsonNode propertyNode) { field.annotate(JsonProperty.class).param("value", propertyName); if (field.type().erasure().equals(field.type().owner().ref(Set.class))) { field.annotate(JsonDeserialize.class).param("as", LinkedHashSet.class); } if (propertyNode.has("javaJsonView")) { field.annotate(JsonView.class).param( "value", field.type().owner().ref(propertyNode.get("javaJsonView").asText())); } if (propertyNode.has("description")) { field.annotate(JsonPropertyDescription.class).param("value", propertyNode.get("description").asText()); } } @Override public void propertyGetter(JMethod getter, JDefinedClass clazz, String propertyName) { getter.annotate(JsonProperty.class).param("value", propertyName); } @Override public void propertySetter(JMethod setter, JDefinedClass clazz, String propertyName) { setter.annotate(JsonProperty.class).param("value", propertyName); } @Override public void anyGetter(JMethod getter, JDefinedClass clazz) { getter.annotate(JsonAnyGetter.class); } @Override public void anySetter(JMethod setter, JDefinedClass clazz) { setter.annotate(JsonAnySetter.class); } @Override public void enumCreatorMethod(JDefinedClass _enum, JMethod creatorMethod) { creatorMethod.annotate(JsonCreator.class); } @Override public void enumValueMethod(JDefinedClass _enum, JMethod valueMethod) { valueMethod.annotate(JsonValue.class); } @Override public void enumConstant(JDefinedClass _enum, JEnumConstant constant, String value) { } @Override public boolean isAdditionalPropertiesSupported() { return true; } @Override public void additionalPropertiesField(JFieldVar field, JDefinedClass clazz, String propertyName) { field.annotate(JsonIgnore.class); } @Override public void dateField(JFieldVar field, JDefinedClass clazz, JsonNode node) {<FILL_FUNCTION_BODY>} @Override public void timeField(JFieldVar field, JDefinedClass clazz, JsonNode node) { String pattern = null; if (node.has("customTimePattern")) { pattern = node.get("customTimePattern").asText(); } else if (node.has("customPattern")) { pattern = node.get("customPattern").asText(); } else if (isNotEmpty(getGenerationConfig().getCustomTimePattern())) { pattern = getGenerationConfig().getCustomTimePattern(); } else if (getGenerationConfig().isFormatDates()) { pattern = FormatRule.ISO_8601_TIME_FORMAT; } if (pattern != null && !field.type().fullName().equals("java.lang.String")) { field.annotate(JsonFormat.class).param("shape", JsonFormat.Shape.STRING).param("pattern", pattern); } } @Override public void dateTimeField(JFieldVar field, JDefinedClass clazz, JsonNode node) { String timezone = node.has("customTimezone") ? node.get("customTimezone").asText() : "UTC"; String pattern = null; if (node.has("customDateTimePattern")) { pattern = node.get("customDateTimePattern").asText(); } else if (node.has("customPattern")) { pattern = node.get("customPattern").asText(); } else if (isNotEmpty(getGenerationConfig().getCustomDateTimePattern())) { pattern = getGenerationConfig().getCustomDateTimePattern(); } else if (getGenerationConfig().isFormatDateTimes()) { pattern = FormatRule.ISO_8601_DATETIME_FORMAT; } if (pattern != null && !field.type().fullName().equals("java.lang.String")) { field.annotate(JsonFormat.class).param("shape", JsonFormat.Shape.STRING).param("pattern", pattern).param("timezone", timezone); } } protected void addJsonTypeInfoAnnotation(JDefinedClass jclass, String propertyName) { JAnnotationUse jsonTypeInfo = jclass.annotate(JsonTypeInfo.class); jsonTypeInfo.param("use", JsonTypeInfo.Id.CLASS); jsonTypeInfo.param("include", JsonTypeInfo.As.PROPERTY); // When not provided it will use default provided by "use" attribute if (StringUtils.isNotBlank(propertyName)) { jsonTypeInfo.param("property", propertyName); } } }
String pattern = null; if (node.has("customDatePattern")) { pattern = node.get("customDatePattern").asText(); } else if (node.has("customPattern")) { pattern = node.get("customPattern").asText(); } else if (isNotEmpty(getGenerationConfig().getCustomDatePattern())) { pattern = getGenerationConfig().getCustomDatePattern(); } else if (getGenerationConfig().isFormatDates()) { pattern = FormatRule.ISO_8601_DATE_FORMAT; } if (pattern != null && !field.type().fullName().equals("java.lang.String")) { field.annotate(JsonFormat.class).param("shape", JsonFormat.Shape.STRING).param("pattern", pattern); }
1,712
200
1,912
public abstract class AbstractTypeInfoAwareAnnotator extends AbstractAnnotator { public AbstractTypeInfoAwareAnnotator( GenerationConfig generationConfig); @Override public void typeInfo( JDefinedClass clazz, JsonNode node); @Override public boolean isPolymorphicDeserializationSupported( JsonNode node); abstract protected void addJsonTypeInfoAnnotation( JDefinedClass clazz, String propertyName); }
DerekYRC_mini-spring
mini-spring/src/main/java/org/springframework/core/io/ClassPathResource.java
ClassPathResource
getInputStream
class ClassPathResource implements Resource { private final String path; public ClassPathResource(String path) { this.path = path; } @Override public InputStream getInputStream() throws IOException {<FILL_FUNCTION_BODY>} }
InputStream is = this.getClass().getClassLoader().getResourceAsStream(this.path); if (is == null) { throw new FileNotFoundException(this.path + " cannot be opened because it does not exist"); } return is;
64
67
131
elunez_eladmin
eladmin/eladmin-common/src/main/java/me/zhengjie/config/FileProperties.java
FileProperties
getPath
class FileProperties { /** 文件大小限制 */ private Long maxSize; /** 头像大小限制 */ private Long avatarMaxSize; private ElPath mac; private ElPath linux; private ElPath windows; public ElPath getPath(){<FILL_FUNCTION_BODY>} @Data public static class ElPath{ private String path; private String avatar; } }
String os = System.getProperty("os.name"); if(os.toLowerCase().startsWith(ElConstant.WIN)) { return windows; } else if(os.toLowerCase().startsWith(ElConstant.MAC)){ return mac; } return linux;
118
76
194
qiujiayu_AutoLoadCache
AutoLoadCache/autoload-cache-common/src/main/java/com/jarvis/lib/util/StringUtil.java
StringUtil
containsText
class StringUtil { /** * Check whether the given {@code CharSequence} contains actual <em>text</em>. * <p>More specifically, this method returns {@code true} if the * {@code CharSequence} is not {@code null}, its length is greater than * 0, and it contains at least one non-whitespace character. * <p><pre class="code"> * StringUtils.hasText(null) = false * StringUtils.hasText("") = false * StringUtils.hasText(" ") = false * StringUtils.hasText("12345") = true * StringUtils.hasText(" 12345 ") = true * </pre> * @param str the {@code CharSequence} to check (may be {@code null}) * @return {@code true} if the {@code CharSequence} is not {@code null}, * its length is greater than 0, and it does not contain whitespace only * @see Character#isWhitespace */ public static boolean hasText(CharSequence str) { return (str != null && str.length() > 0 && containsText(str)); } /** * Check whether the given {@code String} contains actual <em>text</em>. * <p>More specifically, this method returns {@code true} if the * {@code String} is not {@code null}, its length is greater than 0, * and it contains at least one non-whitespace character. * @param str the {@code String} to check (may be {@code null}) * @return {@code true} if the {@code String} is not {@code null}, its * length is greater than 0, and it does not contain whitespace only * @see #hasText(CharSequence) */ public static boolean hasText(String str) { return (str != null && !str.isEmpty() && containsText(str)); } private static boolean containsText(CharSequence str) {<FILL_FUNCTION_BODY>} }
int strLen = str.length(); for (int i = 0; i < strLen; i++) { if (!Character.isWhitespace(str.charAt(i))) { return true; } } return false;
511
66
577
subhra74_snowflake
snowflake/muon-app/src/main/java/muon/app/ui/components/session/ImportDlg.java
ImportDlg
importSessionsFromWinScp
class ImportDlg extends JDialog { // private JComboBox<String> items; private JList<String> sessionList; private DefaultListModel<String> model; public ImportDlg(Window w, int index, DefaultMutableTreeNode node) { super(w); setSize(400, 300); setLocationRelativeTo(w); setModal(true); model = new DefaultListModel<>(); sessionList = new JList<>(model); sessionList.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION); switch (index) { case 0: importFromPutty(); break; case 1: importFromWinScp(); break; } JPanel panel = new JPanel(new BorderLayout()); panel.setBorder(new EmptyBorder(5, 5, 5, 5)); panel.add(new JScrollPane(sessionList)); add(panel); Box b2 = Box.createHorizontalBox(); b2.setBorder(new EmptyBorder(0, 5, 5, 5)); JButton btnSelect = new JButton("Select all"); btnSelect.addActionListener(e -> { int arr[] = new int[model.size()]; for (int i = 0; i < model.size(); i++) { arr[i] = i; } sessionList.setSelectedIndices(arr); }); JButton btnUnSelect = new JButton("Un-select all"); btnUnSelect.addActionListener(e -> { int arr[] = new int[0]; sessionList.setSelectedIndices(arr); }); b2.add(btnSelect); b2.add(Box.createRigidArea(new Dimension(5, 5))); b2.add(btnUnSelect); b2.add(Box.createHorizontalGlue()); JButton btnImport = new JButton("Import"); btnImport.addActionListener(e -> { switch (index) { case 0: importSessionsFromPutty(node); break; case 1: importSessionsFromWinScp(node); break; } dispose(); }); b2.add(btnImport); add(b2, BorderLayout.SOUTH); //importFromPutty(); } private void importFromPutty() { model.clear(); model.addAll(PuttyImporter.getKeyNames().keySet()); } private void importFromWinScp() { model.clear(); model.addAll(WinScpImporter.getKeyNames().keySet()); } private void importSessionsFromPutty(DefaultMutableTreeNode node) { List<String> list = new ArrayList<String>(); int arr[] = sessionList.getSelectedIndices(); if (arr != null) { for (int i = 0; i < arr.length; i++) { list.add(model.get(arr[i])); } } PuttyImporter.importSessions(node, list); // SessionFolder folder = SessionStore.load().getFolder(); // folder.getItems().addAll(sessions); // SessionStore.store(folder); } private void importSessionsFromWinScp(DefaultMutableTreeNode node) {<FILL_FUNCTION_BODY>} }
List<String> list = new ArrayList<String>(); int arr[] = sessionList.getSelectedIndices(); if (arr != null) { for (int i = 0; i < arr.length; i++) { list.add(model.get(arr[i])); } } WinScpImporter.importSessions(node, list); // SessionFolder folder = SessionStore.load().getFolder(); // folder.getItems().addAll(sessions); // SessionStore.store(folder);
1,032
158
1,190
orientechnologies_orientdb
orientdb/core/src/main/java/com/orientechnologies/orient/core/sql/OSQLScriptEngine.java
OSQLScriptEngine
eval
class OSQLScriptEngine implements ScriptEngine { public static final String NAME = "sql"; private ScriptEngineFactory factory; public OSQLScriptEngine(ScriptEngineFactory factory) { this.factory = factory; } @Override public Object eval(String script, ScriptContext context) throws ScriptException { return eval(script, (Bindings) null); } @Override public Object eval(Reader reader, ScriptContext context) throws ScriptException { return eval(reader, (Bindings) null); } @Override public Object eval(String script) throws ScriptException { return eval(script, (Bindings) null); } @Override public Object eval(Reader reader) throws ScriptException { return eval(reader, (Bindings) null); } @Override public Object eval(String script, Bindings n) throws ScriptException {<FILL_FUNCTION_BODY>} @SuppressWarnings("unchecked") protected Map<Object, Object> convertToParameters(Object... iArgs) { final Map<Object, Object> params; if (iArgs.length == 1 && iArgs[0] instanceof Map) { params = (Map<Object, Object>) iArgs[0]; } else { if (iArgs.length == 1 && iArgs[0] != null && iArgs[0].getClass().isArray() && iArgs[0] instanceof Object[]) iArgs = (Object[]) iArgs[0]; params = new HashMap<Object, Object>(iArgs.length); for (int i = 0; i < iArgs.length; ++i) { Object par = iArgs[i]; if (par instanceof OIdentifiable && ((OIdentifiable) par).getIdentity().isValid()) // USE THE RID ONLY par = ((OIdentifiable) par).getIdentity(); params.put(i, par); } } return params; } @Override public Object eval(Reader reader, Bindings n) throws ScriptException { final StringBuilder buffer = new StringBuilder(); try { while (reader.ready()) buffer.append((char) reader.read()); } catch (IOException e) { throw new ScriptException(e); } return new OCommandScript(buffer.toString()).execute(n); } @Override public void put(String key, Object value) {} @Override public Object get(String key) { return null; } @Override public Bindings getBindings(int scope) { return new SimpleBindings(); } @Override public void setBindings(Bindings bindings, int scope) {} @Override public Bindings createBindings() { return new SimpleBindings(); } @Override public ScriptContext getContext() { return null; } @Override public void setContext(ScriptContext context) {} @Override public ScriptEngineFactory getFactory() { return factory; } }
ODatabaseDocumentInternal db = ODatabaseRecordThreadLocal.instance().getIfDefined(); if (db == null) { throw new OCommandExecutionException("No database available in threadlocal"); } Map<Object, Object> params = convertToParameters(n); OResultSet queryResult; if (params.keySet().stream().anyMatch(x -> !(x instanceof String))) { queryResult = db.execute("sql", script, params); } else { queryResult = db.execute("sql", script, (Map) params); } try (OResultSet res = queryResult) { OLegacyResultSet finalResult = new OBasicLegacyResultSet(); res.stream().forEach(x -> finalResult.add(x)); return finalResult; }
792
200
992
orientechnologies_orientdb
orientdb/core/src/main/java/com/orientechnologies/orient/core/sql/parser/SimpleNode.java
SimpleNode
jjtAddChild
class SimpleNode implements Node { public static final String PARAMETER_PLACEHOLDER = "?"; protected Node parent; protected Node[] children; protected int id; protected Object value; protected OrientSql parser; protected Token firstToken; protected Token lastToken; public SimpleNode() { id = -1; } public SimpleNode(int i) { id = i; } public SimpleNode(OrientSql p, int i) { this(i); parser = p; } public void jjtOpen() {} public void jjtClose() {} public void jjtSetParent(Node n) { parent = n; } public Node jjtGetParent() { return parent; } public void jjtAddChild(Node n, int i) {<FILL_FUNCTION_BODY>} public Node jjtGetChild(int i) { return children[i]; } public int jjtGetNumChildren() { return (children == null) ? 0 : children.length; } public void jjtSetValue(Object value) { this.value = value; } public Object jjtGetValue() { return value; } public Token jjtGetFirstToken() { return firstToken; } public void jjtSetFirstToken(Token token) { this.firstToken = token; } public Token jjtGetLastToken() { return lastToken; } public void jjtSetLastToken(Token token) { this.lastToken = token; } /* * You can override these two methods in subclasses of SimpleNode to customize the way the node appears when the tree is dumped. * If your output uses more than one line you should override toString(String), otherwise overriding toString() is probably all * you need to do. */ public String toString() { StringBuilder result = new StringBuilder(); toString(null, result); return result.toString(); } public String toString(String prefix) { return prefix + toString(); } /* * Override this method if you want to customize how the node dumps out its children. */ public void dump(String prefix) { if (children != null) { for (int i = 0; i < children.length; ++i) { SimpleNode n = (SimpleNode) children[i]; if (n != null) { n.dump(prefix + " "); } } } } public static ODatabaseDocumentInternal getDatabase() { return ODatabaseRecordThreadLocal.instance().get(); } public abstract void toString(Map<Object, Object> params, StringBuilder builder); public abstract void toGenericStatement(StringBuilder builder); public String toGenericStatement() { StringBuilder builder = new StringBuilder(); toGenericStatement(builder); return builder.toString(); } public Object getValue() { return value; } public SimpleNode copy() { throw new UnsupportedOperationException(); } }
if (children == null) { children = new Node[i + 1]; } else if (i >= children.length) { Node c[] = new Node[i + 1]; System.arraycopy(children, 0, c, 0, children.length); children = c; } children[i] = n;
834
88
922
docker-java_docker-java
docker-java/docker-java-core/src/main/java/com/github/dockerjava/core/exec/LogSwarmObjectExec.java
LogSwarmObjectExec
execute0
class LogSwarmObjectExec extends AbstrAsyncDockerCmdExec<LogSwarmObjectCmd, Frame> implements LogSwarmObjectCmd.Exec { private String endpoint = ""; private static final Logger LOGGER = LoggerFactory.getLogger(LogSwarmObjectExec.class); public LogSwarmObjectExec(com.github.dockerjava.core.WebTarget baseResource, DockerClientConfig dockerClientConfig, String endpoint) { super(baseResource, dockerClientConfig); this.endpoint = endpoint; } @Override protected Void execute0(LogSwarmObjectCmd command, ResultCallback<Frame> resultCallback) {<FILL_FUNCTION_BODY>} }
WebTarget webTarget = getBaseResource().path("/" + endpoint + "/{id}/logs").resolveTemplate("id", command.getId()); if (command.getTail() != null) { webTarget = webTarget.queryParam("tail", command.getTail()); } else { webTarget = webTarget.queryParam("tail", "all"); } if (command.getSince() != null) { webTarget = webTarget.queryParam("since", command.getSince()); } webTarget = booleanQueryParam(webTarget, "timestamps", command.getTimestamps()); webTarget = booleanQueryParam(webTarget, "stdout", command.getStdout()); webTarget = booleanQueryParam(webTarget, "stderr", command.getStderr()); webTarget = booleanQueryParam(webTarget, "follow", command.getFollow()); LOGGER.trace("GET: {}", webTarget); webTarget.request().get(resultCallback); return null;
169
256
425
jeecgboot_jeecg-boot
jeecg-boot/jeecg-boot-base-core/src/main/java/org/jeecg/common/system/util/JeecgDataAutorUtils.java
JeecgDataAutorUtils
installDataSearchConditon
class JeecgDataAutorUtils { public static final String MENU_DATA_AUTHOR_RULES = "MENU_DATA_AUTHOR_RULES"; public static final String MENU_DATA_AUTHOR_RULE_SQL = "MENU_DATA_AUTHOR_RULE_SQL"; public static final String SYS_USER_INFO = "SYS_USER_INFO"; /** * 往链接请求里面,传入数据查询条件 * * @param request * @param dataRules */ public static synchronized void installDataSearchConditon(HttpServletRequest request, List<SysPermissionDataRuleModel> dataRules) { @SuppressWarnings("unchecked") // 1.先从request获取MENU_DATA_AUTHOR_RULES,如果存则获取到LIST List<SysPermissionDataRuleModel> list = (List<SysPermissionDataRuleModel>)loadDataSearchConditon(); if (list==null) { // 2.如果不存在,则new一个list list = new ArrayList<SysPermissionDataRuleModel>(); } for (SysPermissionDataRuleModel tsDataRule : dataRules) { list.add(tsDataRule); } // 3.往list里面增量存指 request.setAttribute(MENU_DATA_AUTHOR_RULES, list); } /** * 获取请求对应的数据权限规则 * * @return */ @SuppressWarnings("unchecked") public static synchronized List<SysPermissionDataRuleModel> loadDataSearchConditon() { return (List<SysPermissionDataRuleModel>) SpringContextUtils.getHttpServletRequest().getAttribute(MENU_DATA_AUTHOR_RULES); } /** * 获取请求对应的数据权限SQL * * @return */ public static synchronized String loadDataSearchConditonSqlString() { return (String) SpringContextUtils.getHttpServletRequest().getAttribute(MENU_DATA_AUTHOR_RULE_SQL); } /** * 往链接请求里面,传入数据查询条件 * * @param request * @param sql */ public static synchronized void installDataSearchConditon(HttpServletRequest request, String sql) {<FILL_FUNCTION_BODY>} /** * 将用户信息存到request * @param request * @param userinfo */ public static synchronized void installUserInfo(HttpServletRequest request, SysUserCacheInfo userinfo) { request.setAttribute(SYS_USER_INFO, userinfo); } /** * 将用户信息存到request * @param userinfo */ public static synchronized void installUserInfo(SysUserCacheInfo userinfo) { SpringContextUtils.getHttpServletRequest().setAttribute(SYS_USER_INFO, userinfo); } /** * 从request获取用户信息 * @return */ public static synchronized SysUserCacheInfo loadUserInfo() { return (SysUserCacheInfo) SpringContextUtils.getHttpServletRequest().getAttribute(SYS_USER_INFO); } }
String ruleSql = (String) loadDataSearchConditonSqlString(); if (!StringUtils.hasText(ruleSql)) { request.setAttribute(MENU_DATA_AUTHOR_RULE_SQL,sql); }
835
63
898
ainilili_ratel
ratel/landlords-server/src/main/java/org/nico/ratel/landlords/server/event/ServerEventListener_CODE_CLIENT_INFO_SET.java
ServerEventListener_CODE_CLIENT_INFO_SET
call
class ServerEventListener_CODE_CLIENT_INFO_SET implements ServerEventListener { private static final String DEFAULT_VERSION = "v1.2.8"; @Override public void call(ClientSide client, String info) {<FILL_FUNCTION_BODY>} }
Map<?,?> infos = JsonUtils.fromJson(info, Map.class); // Get client version client.setVersion(DEFAULT_VERSION); if (infos.containsKey("version")){ client.setVersion(String.valueOf(infos.get("version"))); }
67
81
148
pmd_pmd
pmd/pmd-core/src/main/java/net/sourceforge/pmd/internal/Slf4jSimpleConfiguration.java
Slf4jSimpleConfiguration
getDefaultLogLevel
class Slf4jSimpleConfiguration { private static final String SIMPLE_LOGGER_FACTORY_CLASS = "org.slf4j.impl.SimpleLoggerFactory"; private static final String SIMPLE_LOGGER_CLASS = "org.slf4j.impl.SimpleLogger"; private static final String SIMPLE_LOGGER_CONFIGURATION = "org.slf4j.impl.SimpleLoggerConfiguration"; private static final String PMD_ROOT_LOGGER = "net.sourceforge.pmd"; private Slf4jSimpleConfiguration() { } public static void reconfigureDefaultLogLevel(Level level) { if (!isSimpleLogger()) { // do nothing, not even set system properties, if not Simple Logger is in use return; } if (level != null) { System.setProperty("org.slf4j.simpleLogger.defaultLogLevel", level.toString()); } // Call SimpleLogger.init() by reflection. // Alternatively: move the CLI related classes into an own module, add // slf4j-simple as a compile dependency and create a PmdSlf4jSimpleFriend class in // the package org.slf4j.simple to gain access to this package-private init method. // // SimpleLogger.init() will reevaluate the configuration from the system properties or // simplelogger.properties file. ILoggerFactory loggerFactory = LoggerFactory.getILoggerFactory(); ClassLoader classLoader = loggerFactory.getClass().getClassLoader(); try { Class<?> simpleLoggerClass = classLoader.loadClass(SIMPLE_LOGGER_CLASS); Method initMethod = simpleLoggerClass.getDeclaredMethod("init"); initMethod.setAccessible(true); initMethod.invoke(null); int newDefaultLogLevel = getDefaultLogLevelInt(simpleLoggerClass); Field currentLogLevelField = simpleLoggerClass.getDeclaredField("currentLogLevel"); currentLogLevelField.setAccessible(true); Method levelStringMethod = simpleLoggerClass.getDeclaredMethod("recursivelyComputeLevelString"); levelStringMethod.setAccessible(true); Method stringToLevelMethod = classLoader.loadClass(SIMPLE_LOGGER_CONFIGURATION) .getDeclaredMethod("stringToLevel", String.class); stringToLevelMethod.setAccessible(true); // Change the logging level of loggers that were already created. // For this we fetch the map of name to logger that is stored in the logger factory, // then set the log level field of each logger via reflection. // The new log level is determined similar to the constructor of SimpleLogger, that // means, configuration params are being considered. Class<?> loggerFactoryClass = classLoader.loadClass(SIMPLE_LOGGER_FACTORY_CLASS); Field loggerMapField = loggerFactoryClass.getDeclaredField("loggerMap"); loggerMapField.setAccessible(true); // we checked previously, that loggerFactory instanceof SimpleLoggerFactory // see #isSimpleLogger() @SuppressWarnings("unchecked") Map<String, Logger> loggerMap = (Map<String, Logger>) loggerMapField.get(loggerFactory); for (Logger logger : loggerMap.values()) { if (logger.getName().startsWith(PMD_ROOT_LOGGER) && simpleLoggerClass.isAssignableFrom(logger.getClass())) { String newConfiguredLevel = (String) levelStringMethod.invoke(logger); int newLogLevel = newDefaultLogLevel; if (newConfiguredLevel != null) { newLogLevel = (int) stringToLevelMethod.invoke(null, newConfiguredLevel); } currentLogLevelField.set(logger, newLogLevel); } } } catch (ReflectiveOperationException | ClassCastException ex) { System.err.println("Error while initializing logging: " + ex); } } private static int getDefaultLogLevelInt(Class<?> simpleLoggerClass) throws ReflectiveOperationException { Field configParamsField = simpleLoggerClass.getDeclaredField("CONFIG_PARAMS"); configParamsField.setAccessible(true); Object configParams = configParamsField.get(null); Field defaultLogLevelField = configParams.getClass().getDeclaredField("defaultLogLevel"); defaultLogLevelField.setAccessible(true); return (int) defaultLogLevelField.get(configParams); } public static Level getDefaultLogLevel() {<FILL_FUNCTION_BODY>} public static void disableLogging(Class<?> clazz) { if (!isSimpleLogger()) { // do nothing, not even set system properties, if not Simple Logger is in use return; } System.setProperty("org.slf4j.simpleLogger.log." + clazz.getName(), "off"); } public static boolean isSimpleLogger() { try { ILoggerFactory loggerFactory = LoggerFactory.getILoggerFactory(); Class<?> loggerFactoryClass = loggerFactory.getClass().getClassLoader().loadClass(SIMPLE_LOGGER_FACTORY_CLASS); return loggerFactoryClass.isAssignableFrom(loggerFactory.getClass()); } catch (ClassNotFoundException e) { // not slf4j simple logger return false; } } public static void installJulBridge() { if (!SLF4JBridgeHandler.isInstalled()) { SLF4JBridgeHandler.removeHandlersForRootLogger(); // removes any existing ConsoleLogger SLF4JBridgeHandler.install(); } } }
Logger rootLogger = LoggerFactory.getLogger(PMD_ROOT_LOGGER); // check the lowest log level first if (rootLogger.isTraceEnabled()) { return Level.TRACE; } if (rootLogger.isDebugEnabled()) { return Level.DEBUG; } if (rootLogger.isInfoEnabled()) { return Level.INFO; } if (rootLogger.isWarnEnabled()) { return Level.WARN; } if (rootLogger.isErrorEnabled()) { return Level.ERROR; } return Level.INFO;
1,414
157
1,571
docker-java_docker-java
docker-java/docker-java-core/src/main/java/com/github/dockerjava/core/command/RemoveSwarmNodeCmdImpl.java
RemoveSwarmNodeCmdImpl
withSwarmNodeId
class RemoveSwarmNodeCmdImpl extends AbstrDockerCmd<RemoveSwarmNodeCmd, Void> implements RemoveSwarmNodeCmd { private String swarmNodeId; private Boolean force; public RemoveSwarmNodeCmdImpl(RemoveSwarmNodeCmd.Exec exec, String swarmNodeId) { super(exec); withSwarmNodeId(swarmNodeId); } @Override @CheckForNull public String getSwarmNodeId() { return swarmNodeId; } @Override @CheckForNull public Boolean hasForceEnabled() { return force; } @Override public RemoveSwarmNodeCmd withSwarmNodeId(@Nonnull String swarmNodeId) {<FILL_FUNCTION_BODY>} @Override public RemoveSwarmNodeCmd withForce(Boolean force) { this.force = force; return this; } /** * @throws NotFoundException No such swarmNode */ @Override public Void exec() throws NotFoundException { return super.exec(); } }
this.swarmNodeId = Objects.requireNonNull(swarmNodeId, "swarmNodeId was not specified"); return this;
281
35
316
google_truth
truth/extensions/proto/src/main/java/com/google/common/truth/extensions/proto/FieldNumberTree.java
FieldNumberTree
fromMessage
class FieldNumberTree { private static final FieldNumberTree EMPTY = new FieldNumberTree(); /** A {@code FieldNumberTree} with no children. */ static FieldNumberTree empty() { return EMPTY; } // Modified only during [factory] construction, never changed afterwards. private final Map<SubScopeId, FieldNumberTree> children = Maps.newHashMap(); /** Returns whether this {@code FieldNumberTree} has no children. */ boolean isEmpty() { return children.isEmpty(); } /** * Returns the {@code FieldNumberTree} corresponding to this sub-field. * * <p>{@code empty()} if there is none. */ FieldNumberTree child(SubScopeId subScopeId) { FieldNumberTree child = children.get(subScopeId); return child == null ? EMPTY : child; } /** Returns whether this tree has a child for this node. */ boolean hasChild(SubScopeId subScopeId) { return children.containsKey(subScopeId); } static FieldNumberTree fromMessage( Message message, TypeRegistry typeRegistry, ExtensionRegistry extensionRegistry) {<FILL_FUNCTION_BODY>} static FieldNumberTree fromMessages( Iterable<? extends Message> messages, TypeRegistry typeRegistry, ExtensionRegistry extensionRegistry) { FieldNumberTree tree = new FieldNumberTree(); for (Message message : messages) { if (message != null) { tree.merge(fromMessage(message, typeRegistry, extensionRegistry)); } } return tree; } private static FieldNumberTree fromUnknownFieldSet(UnknownFieldSet unknownFieldSet) { FieldNumberTree tree = new FieldNumberTree(); for (int fieldNumber : unknownFieldSet.asMap().keySet()) { UnknownFieldSet.Field unknownField = unknownFieldSet.asMap().get(fieldNumber); for (UnknownFieldDescriptor unknownFieldDescriptor : UnknownFieldDescriptor.descriptors(fieldNumber, unknownField)) { SubScopeId subScopeId = SubScopeId.of(unknownFieldDescriptor); FieldNumberTree childTree = new FieldNumberTree(); tree.children.put(subScopeId, childTree); if (unknownFieldDescriptor.type() == UnknownFieldDescriptor.Type.GROUP) { for (Object group : unknownFieldDescriptor.type().getValues(unknownField)) { childTree.merge(fromUnknownFieldSet((UnknownFieldSet) group)); } } } } return tree; } /** Adds the other tree onto this one. May destroy {@code other} in the process. */ private void merge(FieldNumberTree other) { for (SubScopeId subScopeId : other.children.keySet()) { FieldNumberTree value = other.children.get(subScopeId); if (!this.children.containsKey(subScopeId)) { this.children.put(subScopeId, value); } else { this.children.get(subScopeId).merge(value); } } } }
FieldNumberTree tree = new FieldNumberTree(); // Known fields. Map<FieldDescriptor, Object> knownFieldValues = message.getAllFields(); for (FieldDescriptor field : knownFieldValues.keySet()) { SubScopeId subScopeId = SubScopeId.of(field); FieldNumberTree childTree = new FieldNumberTree(); tree.children.put(subScopeId, childTree); if (field.equals(AnyUtils.valueFieldDescriptor())) { // Handle Any protos specially. Optional<Message> unpackedAny = AnyUtils.unpack(message, typeRegistry, extensionRegistry); if (unpackedAny.isPresent()) { tree.children.put( SubScopeId.ofUnpackedAnyValueType(unpackedAny.get().getDescriptorForType()), fromMessage(unpackedAny.get(), typeRegistry, extensionRegistry)); } } else { Object fieldValue = knownFieldValues.get(field); if (field.getJavaType() == FieldDescriptor.JavaType.MESSAGE) { if (field.isRepeated()) { List<?> valueList = (List<?>) fieldValue; for (Object value : valueList) { childTree.merge(fromMessage((Message) value, typeRegistry, extensionRegistry)); } } else { childTree.merge(fromMessage((Message) fieldValue, typeRegistry, extensionRegistry)); } } } } // Unknown fields. tree.merge(fromUnknownFieldSet(message.getUnknownFields())); return tree;
770
394
1,164
jitsi_jitsi
jitsi/modules/impl/gui/src/main/java/net/java/sip/communicator/impl/gui/main/chat/menus/ChatRightButtonMenu.java
ChatRightButtonMenu
dispose
class ChatRightButtonMenu extends SIPCommPopupMenu implements ActionListener, Skinnable { private ChatConversationPanel chatConvPanel; private JMenuItem copyMenuItem = new JMenuItem( GuiActivator.getResources().getI18NString("service.gui.COPY"), new ImageIcon(ImageLoader.getImage(ImageLoader.COPY_ICON))); private JMenuItem closeMenuItem = new JMenuItem( GuiActivator.getResources().getI18NString("service.gui.CLOSE"), new ImageIcon(ImageLoader.getImage(ImageLoader.CLOSE_ICON))); /** * Creates an instance of <tt>ChatRightButtonMenu</tt>. * * @param chatConvPanel The conversation panel, where this menu will apear. */ public ChatRightButtonMenu(ChatConversationPanel chatConvPanel) { super(); this.chatConvPanel = chatConvPanel; this.init(); } /** * Initializes the menu with all menu items. */ private void init() { this.add(copyMenuItem); this.addSeparator(); this.add(closeMenuItem); this.copyMenuItem.setName("copy"); this.closeMenuItem.setName("service.gui.CLOSE"); this.copyMenuItem.addActionListener(this); this.closeMenuItem.addActionListener(this); this.copyMenuItem.setMnemonic( GuiActivator.getResources().getI18nMnemonic("service.gui.COPY")); this.closeMenuItem.setMnemonic( GuiActivator.getResources().getI18nMnemonic("service.gui.CLOSE")); this.copyMenuItem.setAccelerator( KeyStroke.getKeyStroke(KeyEvent.VK_C, KeyEvent.CTRL_MASK)); } /** * Disables the copy item. */ public void disableCopy() { this.copyMenuItem.setEnabled(false); } /** * Enables the copy item. */ public void enableCopy() { this.copyMenuItem.setEnabled(true); } /** * Handles the <tt>ActionEvent</tt> when one of the menu items is selected. * * @param e the <tt>ActionEvent</tt> that notified us */ public void actionPerformed(ActionEvent e) { JMenuItem menuItem = (JMenuItem) e.getSource(); String itemText = menuItem.getName(); if (itemText.equalsIgnoreCase("copy")) { this.chatConvPanel.copyConversation(); } else if (itemText.equalsIgnoreCase("save")) { //TODO: Implement save to file. } else if (itemText.equalsIgnoreCase("print")) { //TODO: Implement print. } else if (itemText.equalsIgnoreCase("service.gui.CLOSE")) { Window window = this.chatConvPanel .getChatContainer().getConversationContainerWindow(); window.setVisible(false); window.dispose(); } } /** * Reloads menu icons. */ public void loadSkin() { copyMenuItem.setIcon(new ImageIcon( ImageLoader.getImage(ImageLoader.COPY_ICON))); closeMenuItem.setIcon(new ImageIcon( ImageLoader.getImage(ImageLoader.CLOSE_ICON))); } /** * Clear resources. */ public void dispose() {<FILL_FUNCTION_BODY>} }
this.chatConvPanel = null; copyMenuItem = null; closeMenuItem = null;
989
30
1,019
/** * A custom popup menu that detects parent focus lost. * @author Yana Stamcheva */ public class SIPCommPopupMenu extends JPopupMenu { /** * Serial version UID. */ private static final long serialVersionUID=0L; /** * Constructor. */ public SIPCommPopupMenu(); }
pmd_pmd
pmd/pmd-core/src/main/java/net/sourceforge/pmd/renderers/AbstractIncrementingRenderer.java
AbstractIncrementingRenderer
renderFileReport
class AbstractIncrementingRenderer extends AbstractRenderer { /** * Accumulated processing errors. */ protected List<Report.ProcessingError> errors = new LinkedList<>(); /** * Accumulated configuration errors. */ protected List<Report.ConfigurationError> configErrors = new LinkedList<>(); /** * Accumulated suppressed violations. */ protected List<Report.SuppressedViolation> suppressed = new LinkedList<>(); public AbstractIncrementingRenderer(String name, String description) { super(name, description); } @Override public void start() throws IOException { // does nothing - override if necessary } @Override public void startFileAnalysis(TextFile dataSource) { // does nothing - override if necessary } @Override public void renderFileReport(Report report) throws IOException {<FILL_FUNCTION_BODY>} /** * Render a series of {@link RuleViolation}s. * * @param violations * The iterator of violations to render. * @throws IOException */ public abstract void renderFileViolations(Iterator<RuleViolation> violations) throws IOException; @Override public void end() throws IOException { // does nothing - override if necessary } }
Iterator<RuleViolation> violations = report.getViolations().iterator(); if (violations.hasNext()) { renderFileViolations(violations); getWriter().flush(); } errors.addAll(report.getProcessingErrors()); configErrors.addAll(report.getConfigurationErrors()); if (showSuppressedViolations) { suppressed.addAll(report.getSuppressedViolations()); }
339
121
460
jitsi_jitsi
jitsi/modules/service/ui-service/src/main/java/net/java/sip/communicator/service/gui/call/CallPeerAdapter.java
CallPeerAdapter
propertyChange
class CallPeerAdapter extends net.java.sip.communicator.service.protocol.event.CallPeerAdapter implements CallPeerSecurityListener, PropertyChangeListener { /** * The <tt>CallPeer</tt> which is depicted by {@link #renderer}. */ private final CallPeer peer; /** * The <tt>CallPeerRenderer</tt> which is facilitated by this instance. */ private final CallPeerRenderer renderer; /** * Initializes a new <tt>CallPeerAdapter</tt> instance which is to listen to * a specific <tt>CallPeer</tt> on behalf of a specific * <tt>CallPeerRenderer</tt>. The new instance adds itself to the specified * <tt>CallPeer</tt> as a listener for each of the implemented listener * types. * * @param peer the <tt>CallPeer</tt> which the new instance is to listen to * on behalf of the specified <tt>renderer</tt> * @param renderer the <tt>CallPeerRenderer</tt> which is to be facilitated * by the new instance */ public CallPeerAdapter(CallPeer peer, CallPeerRenderer renderer) { this.peer = peer; this.renderer = renderer; this.peer.addCallPeerListener(this); this.peer.addCallPeerSecurityListener(this); this.peer.addPropertyChangeListener(this); } /** * Removes the listeners implemented by this instance from the associated * <tt>CallPeer</tt> and prepares it for garbage collection. */ public void dispose() { peer.removeCallPeerListener(this); peer.removeCallPeerSecurityListener(this); peer.removePropertyChangeListener(this); } /** * {@inheritDoc} */ @Override public void peerDisplayNameChanged(CallPeerChangeEvent ev) { if (peer.equals(ev.getSourceCallPeer())) renderer.setPeerName((String) ev.getNewValue()); } /** * {@inheritDoc} */ @Override public void peerImageChanged(CallPeerChangeEvent ev) { if (peer.equals(ev.getSourceCallPeer())) renderer.setPeerImage((byte[]) ev.getNewValue()); } /** * {@inheritDoc} */ @Override public void peerStateChanged(CallPeerChangeEvent ev) { CallPeer sourcePeer = ev.getSourceCallPeer(); if (!sourcePeer.equals(peer)) return; CallPeerState newState = (CallPeerState) ev.getNewValue(); CallPeerState oldState = (CallPeerState) ev.getOldValue(); String newStateString = sourcePeer.getState().getLocalizedStateString(); if (newState == CallPeerState.CONNECTED) { if (!CallPeerState.isOnHold(oldState)) { if (!renderer.getCallRenderer().isCallTimerStarted()) renderer.getCallRenderer().startCallTimer(); } else { renderer.setOnHold(false); renderer.getCallRenderer().updateHoldButtonState(); } } else if (newState == CallPeerState.DISCONNECTED) { // The call peer should be already removed from the call // see CallPeerRemoved } else if (newState == CallPeerState.FAILED) { // The call peer should be already removed from the call // see CallPeerRemoved } else if (CallPeerState.isOnHold(newState)) { renderer.setOnHold(true); renderer.getCallRenderer().updateHoldButtonState(); } renderer.setPeerState(oldState, newState, newStateString); String reasonString = ev.getReasonString(); if (reasonString != null) renderer.setErrorReason(reasonString); } /** * {@inheritDoc} */ public void propertyChange(PropertyChangeEvent ev) {<FILL_FUNCTION_BODY>} /** * {@inheritDoc} * * <tt>CallPeerAdapter</tt> does nothing. */ public void securityMessageRecieved(CallPeerSecurityMessageEvent ev) { } /** * {@inheritDoc} */ public void securityNegotiationStarted( CallPeerSecurityNegotiationStartedEvent ev) { if (peer.equals(ev.getSource())) renderer.securityNegotiationStarted(ev); } /** * {@inheritDoc} */ public void securityOff(CallPeerSecurityOffEvent ev) { if (peer.equals(ev.getSource())) renderer.securityOff(ev); } /** * {@inheritDoc} */ public void securityOn(CallPeerSecurityOnEvent ev) { if (peer.equals(ev.getSource())) renderer.securityOn(ev); } /** * {@inheritDoc} */ public void securityTimeout(CallPeerSecurityTimeoutEvent ev) { if (peer.equals(ev.getSource())) renderer.securityTimeout(ev); } }
String propertyName = ev.getPropertyName(); if (propertyName.equals(CallPeer.MUTE_PROPERTY_NAME)) { boolean mute = (Boolean) ev.getNewValue(); renderer.setMute(mute); }
1,435
72
1,507
/** * An abstract adapter class for receiving call peer (change) events. This class exists only as a convenience for creating listener objects. <p> Extend this class to create a <tt>CallPeerChangeEvent</tt> listener and override the methods for the events of interest. (If you implement the <tt>CallPeerListener</tt> interface, you have to define all of the methods in it. This abstract class defines null methods for them all, so you only have to define methods for events you care about.) </p> * @see CallPeerChangeEvent * @see CallPeerListener * @author Lubomir Marinov */ public abstract class CallPeerAdapter implements CallPeerListener { /** * Indicates that a change has occurred in the address of the source <tt>CallPeer</tt>. * @param evt the <tt>CallPeerChangeEvent</tt> instance containing thesource event as well as its previous and its new address */ public void peerAddressChanged( CallPeerChangeEvent evt); /** * Indicates that a change has occurred in the display name of the source <tt>CallPeer</tt>. * @param evt the <tt>CallPeerChangeEvent</tt> instance containing thesource event as well as its previous and its new display names */ public void peerDisplayNameChanged( CallPeerChangeEvent evt); /** * Indicates that a change has occurred in the image of the source <tt>CallPeer</tt>. * @param evt the <tt>CallPeerChangeEvent</tt> instance containing thesource event as well as its previous and its new image */ public void peerImageChanged( CallPeerChangeEvent evt); /** * Indicates that a change has occurred in the status of the source <tt>CallPeer</tt>. * @param evt the <tt>CallPeerChangeEvent</tt> instance containing thesource event as well as its previous and its new status */ public void peerStateChanged( CallPeerChangeEvent evt); /** * Indicates that a change has occurred in the transport address that we use to communicate with the source <tt>CallPeer</tt>. * @param evt the <tt>CallPeerChangeEvent</tt> instance containing thesource event as well as its previous and its new transport address */ public void peerTransportAddressChanged( CallPeerChangeEvent evt); }
YunaiV_ruoyi-vue-pro
ruoyi-vue-pro/yudao-framework/yudao-spring-boot-starter-mybatis/src/main/java/cn/iocoder/yudao/framework/datasource/core/filter/DruidAdRemoveFilter.java
DruidAdRemoveFilter
doFilterInternal
class DruidAdRemoveFilter extends OncePerRequestFilter { /** * common.js 的路径 */ private static final String COMMON_JS_ILE_PATH = "support/http/resources/js/common.js"; @Override protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws ServletException, IOException {<FILL_FUNCTION_BODY>} }
chain.doFilter(request, response); // 重置缓冲区,响应头不会被重置 response.resetBuffer(); // 获取 common.js String text = Utils.readFromResource(COMMON_JS_ILE_PATH); // 正则替换 banner, 除去底部的广告信息 text = text.replaceAll("<a.*?banner\"></a><br/>", ""); text = text.replaceAll("powered.*?shrek.wang</a>", ""); response.getWriter().write(text);
110
147
257
mapstruct_mapstruct
mapstruct/processor/src/main/java/org/mapstruct/ap/internal/processor/Jsr330ComponentProcessor.java
Jsr330ComponentProcessor
getTypeAnnotations
class Jsr330ComponentProcessor extends AnnotationBasedComponentModelProcessor { @Override protected String getComponentModelIdentifier() { return MappingConstantsGem.ComponentModelGem.JSR330; } @Override protected List<Annotation> getTypeAnnotations(Mapper mapper) {<FILL_FUNCTION_BODY>} @Override protected List<Annotation> getDecoratorAnnotations() { return Arrays.asList( singleton(), named() ); } @Override protected List<Annotation> getDelegatorReferenceAnnotations(Mapper mapper) { return Arrays.asList( inject(), namedDelegate( mapper ) ); } @Override protected List<Annotation> getMapperReferenceAnnotations() { return Collections.singletonList( inject() ); } @Override protected boolean requiresGenerationOfDecoratorClass() { return true; } private Annotation singleton() { return new Annotation( getType( "Singleton" ) ); } private Annotation named() { return new Annotation( getType( "Named" ) ); } private Annotation namedDelegate(Mapper mapper) { return new Annotation( getType( "Named" ), Collections.singletonList( new AnnotationElement( AnnotationElementType.STRING, Collections.singletonList( mapper.getPackageName() + "." + mapper.getName() ) ) ) ); } private Annotation inject() { return new Annotation( getType( "Inject" ) ); } private Type getType(String simpleName) { if ( getTypeFactory().isTypeAvailable( "javax.inject." + simpleName ) ) { return getTypeFactory().getType( "javax.inject." + simpleName ); } if ( getTypeFactory().isTypeAvailable( "jakarta.inject." + simpleName ) ) { return getTypeFactory().getType( "jakarta.inject." + simpleName ); } throw new AnnotationProcessingException( "Couldn't find any of the JSR330 or Jakarta Dependency Inject types." + " Are you missing a dependency on your classpath?" ); } }
if ( mapper.getDecorator() == null ) { return Arrays.asList( singleton(), named() ); } else { return Arrays.asList( singleton(), namedDelegate( mapper ) ); }
584
63
647
/** * An {@link ModelElementProcessor} which converts the given {@link Mapper} object into an annotation based componentmodel in case a matching model is selected as target component model for this mapper. * @author Gunnar Morling * @author Andreas Gudian * @author Kevin Grüneberg */ public abstract class AnnotationBasedComponentModelProcessor implements ModelElementProcessor<Mapper,Mapper> { private TypeFactory typeFactory; @Override public Mapper process( ProcessorContext context, TypeElement mapperTypeElement, Mapper mapper); protected void adjustDecorator( Mapper mapper, InjectionStrategyGem injectionStrategy); private List<MapperReference> toMapperReferences( List<Field> fields); private void buildSetters( Mapper mapper); private void buildConstructors( Mapper mapper); private AnnotatedConstructor buildAnnotatedConstructorForMapper( Mapper mapper); private AnnotatedConstructor buildAnnotatedConstructorForDecorator( Decorator decorator); /** * Removes duplicate constructor parameter annotations. If an annotation is already present on the constructor, it does not have be defined on the constructor parameter, too. For example, for CDI, the javax.inject.Inject annotation is on the constructor and does not need to be on the constructor parameters. * @param annotationMapperReferences annotations to annotate the constructor parameter with * @param mapperReferenceAnnotations annotations to annotate the constructor with */ private void removeDuplicateAnnotations( List<AnnotationMapperReference> annotationMapperReferences, List<Annotation> mapperReferenceAnnotations); /** * Extract all annotations from {@code annotations} that do not have a type in {@code annotationTypes}. * @param annotations the annotations from which we need to extract information * @param annotationTypes the annotation types to ignore * @return the annotations that are not in the {@code annotationTypes} */ private List<Annotation> extractMissingAnnotations( List<Annotation> annotations, Set<Type> annotationTypes); protected boolean additionalPublicEmptyConstructor(); protected List<Annotation> getDelegatorReferenceAnnotations( Mapper mapper); /** * @param originalReference the reference to be replaced * @param annotations the list of annotations * @param injectionStrategy strategy for injection * @return the mapper reference replacing the original one */ protected Field replacementMapperReference( Field originalReference, List<Annotation> annotations, InjectionStrategyGem injectionStrategy); /** * @return the component model identifier */ protected abstract String getComponentModelIdentifier(); /** * @param mapper the mapper * @return the annotation(s) to be added at the mapper type implementation */ protected abstract List<Annotation> getTypeAnnotations( Mapper mapper); /** * @return the annotation(s) to be added at the decorator of the mapper */ protected List<Annotation> getDecoratorAnnotations(); /** * @return the annotation of the field for the mapper reference */ protected abstract List<Annotation> getMapperReferenceAnnotations(); /** * @return if a decorator (sub-)class needs to be generated or not */ protected abstract boolean requiresGenerationOfDecoratorClass(); @Override public int getPriority(); protected TypeFactory getTypeFactory(); }
PlayEdu_PlayEdu
PlayEdu/playedu-api/src/main/java/xyz/playedu/api/listener/UserCourseHourFinishedListener.java
UserCourseHourFinishedListener
userCourseProgressUpdate
class UserCourseHourFinishedListener { @Autowired private UserCourseRecordService userCourseRecordService; @Autowired private UserCourseHourRecordService userCourseHourRecordService; @Autowired private CourseHourService hourService; @EventListener public void userCourseProgressUpdate(UserCourseHourFinishedEvent evt) {<FILL_FUNCTION_BODY>} }
Integer hourCount = hourService.getCountByCourseId(evt.getCourseId()); Integer finishedCount = userCourseHourRecordService.getFinishedHourCount( evt.getUserId(), evt.getCourseId()); userCourseRecordService.storeOrUpdate( evt.getUserId(), evt.getCourseId(), hourCount, finishedCount);
109
102
211
jitsi_jitsi
jitsi/modules/plugin/desktoputil/src/main/java/net/java/sip/communicator/plugin/desktoputil/ScreenInformation.java
ScreenInformation
getScreenBounds
class ScreenInformation { /** * Calculates the bounding box of all available screens. This method is * highly inaccurate when screens of different sizes are used or not evenly * aligned. A correct implementation should generate a polygon. * * @return A polygon of the usable screen area. */ public static Rectangle getScreenBounds() {<FILL_FUNCTION_BODY>} /** * Checks whether the top edge of the rectangle is contained in any of the * available screens. * * @param window The bounding box of the window. * @return True when the top edge is in a visible screen area; false * otherwise */ public static boolean isTitleOnScreen(Rectangle window) { final GraphicsEnvironment ge = GraphicsEnvironment .getLocalGraphicsEnvironment(); boolean leftInside = false; boolean rightInside = false; Point topLeft = new Point(window.x, window.y); Point topRight = new Point(window.x + window.width, window.y); for(GraphicsDevice gd : ge.getScreenDevices()) { GraphicsConfiguration gc = gd.getDefaultConfiguration(); if(gc.getBounds().contains(topLeft)) leftInside = true; if(gc.getBounds().contains(topRight)) rightInside = true; if(leftInside && rightInside) return true; } return leftInside && rightInside; } }
final GraphicsEnvironment ge = GraphicsEnvironment .getLocalGraphicsEnvironment(); Rectangle bounds = new Rectangle(); for(GraphicsDevice gd : ge.getScreenDevices()) { GraphicsConfiguration gc = gd.getDefaultConfiguration(); bounds = bounds.union(gc.getBounds()); } return bounds;
380
88
468
graphhopper_graphhopper
graphhopper/core/src/main/java/com/graphhopper/routing/ch/NodeBasedWitnessPathSearcher.java
NodeBasedWitnessPathSearcher
findUpperBound
class NodeBasedWitnessPathSearcher { private final PrepareGraphEdgeExplorer outEdgeExplorer; private final double[] weights; private final IntArrayList changedNodes; private final IntFloatBinaryHeap heap; private int ignoreNode = -1; private int settledNodes = 0; public NodeBasedWitnessPathSearcher(CHPreparationGraph graph) { outEdgeExplorer = graph.createOutEdgeExplorer(); weights = new double[graph.getNodes()]; Arrays.fill(weights, Double.POSITIVE_INFINITY); heap = new IntFloatBinaryHeap(1000); changedNodes = new IntArrayList(); } /** * Sets up a search for given start node and an ignored node. The shortest path tree will be re-used for different * target nodes until this method is called again. */ public void init(int startNode, int ignoreNode) { reset(); this.ignoreNode = ignoreNode; weights[startNode] = 0; changedNodes.add(startNode); heap.insert(0, startNode); } /** * Runs or continues a Dijkstra search starting at the startNode and ignoring the ignoreNode given in init(). * If the shortest path is found we return its weight. However, this method also returns early if any path was * found for which the weight is below or equal to the given acceptedWeight, or the given maximum number of settled * nodes is exceeded. In these cases the returned weight can be larger than the actual weight of the shortest path. * In any case we get an upper bound for the real shortest path weight. * * @param targetNode the target of the search. if this node is settled we return the weight of the shortest path * @param acceptedWeight once we find a path with weight smaller than or equal to this we return the weight. the * returned weight might be larger than the weight of the real shortest path. if there is * no path with weight smaller than or equal to this we stop the search and return the best * path we found. * @param maxSettledNodes once the number of settled nodes exceeds this number we return the currently found best * weight path. in this case we might not have found a path at all. * @return the weight of the found path or {@link Double#POSITIVE_INFINITY} if no path was found */ public double findUpperBound(int targetNode, double acceptedWeight, int maxSettledNodes) {<FILL_FUNCTION_BODY>} public int getSettledNodes() { return settledNodes; } private void reset() { for (IntCursor c : changedNodes) weights[c.value] = Double.POSITIVE_INFINITY; changedNodes.elementsCount = 0; heap.clear(); ignoreNode = -1; settledNodes = 0; } /** * @return currently used memory in MB (approximately) */ public String getMemoryUsageAsString() { return (8L * weights.length + changedNodes.buffer.length * 4L + heap.getMemoryUsage() ) / Helper.MB + "MB"; } }
// todo: for historic reasons we count the number of settled nodes for each call of this method // *not* the total number of settled nodes since starting the search (which corresponds // to the size of the settled part of the shortest path tree). it's probably worthwhile // to change this in the future. while (!heap.isEmpty() && settledNodes < maxSettledNodes && heap.peekKey() <= acceptedWeight) { if (weights[targetNode] <= acceptedWeight) // we found *a* path to the target node (not necessarily the shortest), and the weight is acceptable, so we stop return weights[targetNode]; int node = heap.poll(); PrepareGraphEdgeIterator iter = outEdgeExplorer.setBaseNode(node); while (iter.next()) { int adjNode = iter.getAdjNode(); if (adjNode == ignoreNode) continue; double weight = weights[node] + iter.getWeight(); if (Double.isInfinite(weight)) continue; double adjWeight = weights[adjNode]; if (adjWeight == Double.POSITIVE_INFINITY) { weights[adjNode] = weight; heap.insert(weight, adjNode); changedNodes.add(adjNode); } else if (weight < adjWeight) { weights[adjNode] = weight; heap.update(weight, adjNode); } } settledNodes++; if (node == targetNode) // we have settled the target node, we now know the exact weight of the shortest path and return return weights[node]; } return weights[targetNode];
811
414
1,225
obsidiandynamics_kafdrop
kafdrop/src/main/java/kafdrop/config/KafkaConfiguration.java
KafkaConfiguration
applyCommon
class KafkaConfiguration { private static final Logger LOG = LoggerFactory.getLogger(KafkaConfiguration.class); private String brokerConnect; private String saslMechanism; private String securityProtocol; private String truststoreFile; private String propertiesFile; private String keystoreFile; public void applyCommon(Properties properties) {<FILL_FUNCTION_BODY>} }
properties.setProperty(CommonClientConfigs.BOOTSTRAP_SERVERS_CONFIG, brokerConnect); if (securityProtocol.equals("SSL")) { properties.put(CommonClientConfigs.SECURITY_PROTOCOL_CONFIG, securityProtocol); } LOG.info("Checking truststore file {}", truststoreFile); if (new File(truststoreFile).isFile()) { LOG.info("Assigning truststore location to {}", truststoreFile); properties.put("ssl.truststore.location", truststoreFile); } LOG.info("Checking keystore file {}", keystoreFile); if (new File(keystoreFile).isFile()) { LOG.info("Assigning keystore location to {}", keystoreFile); properties.put("ssl.keystore.location", keystoreFile); } LOG.info("Checking properties file {}", propertiesFile); final var propertiesFile = new File(this.propertiesFile); if (propertiesFile.isFile()) { LOG.info("Loading properties from {}", this.propertiesFile); final var propertyOverrides = new Properties(); try (var propsReader = new BufferedReader(new FileReader(propertiesFile))) { propertyOverrides.load(propsReader); } catch (IOException e) { throw new KafkaConfigurationException(e); } properties.putAll(propertyOverrides); }
106
361
467
eirslett_frontend-maven-plugin
frontend-maven-plugin/frontend-maven-plugin/src/main/java/com/github/eirslett/maven/plugins/frontend/mojo/BunMojo.java
BunMojo
getProxyConfig
class BunMojo extends AbstractFrontendMojo { private static final String NPM_REGISTRY_URL = "npmRegistryURL"; /** * bun arguments. Default is "install". */ @Parameter(defaultValue = "", property = "frontend.bun.arguments", required = false) private String arguments; @Parameter(property = "frontend.bun.bunInheritsProxyConfigFromMaven", required = false, defaultValue = "true") private boolean bunInheritsProxyConfigFromMaven; /** * Registry override, passed as the registry option during npm install if set. */ @Parameter(property = NPM_REGISTRY_URL, required = false, defaultValue = "") private String npmRegistryURL; @Parameter(property = "session", defaultValue = "${session}", readonly = true) private MavenSession session; @Component private BuildContext buildContext; @Component(role = SettingsDecrypter.class) private SettingsDecrypter decrypter; /** * Skips execution of this mojo. */ @Parameter(property = "skip.bun", defaultValue = "${skip.bun}") private boolean skip; @Override protected boolean skipExecution() { return this.skip; } @Override public synchronized void execute(FrontendPluginFactory factory) throws TaskRunnerException { File packageJson = new File(this.workingDirectory, "package.json"); if (this.buildContext == null || this.buildContext.hasDelta(packageJson) || !this.buildContext.isIncremental()) { ProxyConfig proxyConfig = getProxyConfig(); factory.getBunRunner(proxyConfig, getRegistryUrl()).execute(this.arguments, this.environmentVariables); } else { getLog().info("Skipping bun install as package.json unchanged"); } } private ProxyConfig getProxyConfig() {<FILL_FUNCTION_BODY>} private String getRegistryUrl() { // check to see if overridden via `-D`, otherwise fallback to pom value return System.getProperty(NPM_REGISTRY_URL, this.npmRegistryURL); } }
if (this.bunInheritsProxyConfigFromMaven) { return MojoUtils.getProxyConfig(this.session, this.decrypter); } else { getLog().info("bun not inheriting proxy config from Maven"); return new ProxyConfig(Collections.<ProxyConfig.Proxy>emptyList()); }
584
89
673
public abstract class AbstractFrontendMojo extends AbstractMojo { @Component protected MojoExecution execution; /** * Whether you should skip while running in the test phase (default is false) */ @Parameter(property="skipTests",required=false,defaultValue="false") protected Boolean skipTests; /** * Set this to true to ignore a failure during testing. Its use is NOT RECOMMENDED, but quite convenient on occasion. * @since 1.4 */ @Parameter(property="maven.test.failure.ignore",defaultValue="false") protected boolean testFailureIgnore; /** * The base directory for running all Node commands. (Usually the directory that contains package.json) */ @Parameter(defaultValue="${basedir}",property="workingDirectory",required=false) protected File workingDirectory; /** * The base directory for installing node and npm. */ @Parameter(property="installDirectory",required=false) protected File installDirectory; /** * Additional environment variables to pass to the build. */ @Parameter protected Map<String,String> environmentVariables; @Parameter(defaultValue="${project}",readonly=true) private MavenProject project; @Parameter(defaultValue="${repositorySystemSession}",readonly=true) private RepositorySystemSession repositorySystemSession; /** * Determines if this execution should be skipped. */ private boolean skipTestPhase(); /** * Determines if the current execution is during a testing phase (e.g., "test" or "integration-test"). */ private boolean isTestingPhase(); protected abstract void execute( FrontendPluginFactory factory) throws FrontendException ; /** * Implemented by children to determine if this execution should be skipped. */ protected abstract boolean skipExecution(); @Override public void execute() throws MojoFailureException; }
elunez_eladmin
eladmin/eladmin-system/src/main/java/me/zhengjie/AppRun.java
AppRun
main
class AppRun { public static void main(String[] args) {<FILL_FUNCTION_BODY>} @Bean public SpringContextHolder springContextHolder() { return new SpringContextHolder(); } /** * 访问首页提示 * * @return / */ @AnonymousGetMapping("/") public String index() { return "Backend service started successfully"; } }
SpringApplication springApplication = new SpringApplication(AppRun.class); // 监控应用的PID,启动时可指定PID路径:--spring.pid.file=/home/eladmin/app.pid // 或者在 application.yml 添加文件路径,方便 kill,kill `cat /home/eladmin/app.pid` springApplication.addListeners(new ApplicationPidFileWriter()); springApplication.run(args);
113
113
226
pmd_pmd
pmd/pmd-compat6/src/main/java/net/sourceforge/pmd/util/filter/OrFilter.java
OrFilter
filter
class OrFilter<T> extends AbstractCompoundFilter<T> { public OrFilter() { super(); } public OrFilter(Filter<T>... filters) { super(filters); } @Override public boolean filter(T obj) {<FILL_FUNCTION_BODY>} @Override protected String getOperator() { return "or"; } }
boolean match = false; for (Filter<T> filter : filters) { if (filter.filter(obj)) { match = true; break; } } return match;
107
55
162
orientechnologies_orientdb
orientdb/distributed/src/main/java/com/orientechnologies/orient/server/distributed/impl/OSynchronizedTaskWrapper.java
OSynchronizedTaskWrapper
execute
class OSynchronizedTaskWrapper extends OAbstractRemoteTask { private boolean usesDatabase; private CountDownLatch latch; private ORemoteTask task; public OSynchronizedTaskWrapper( final CountDownLatch iLatch, final String iNodeName, final ORemoteTask iTask) { this.latch = iLatch; this.task = iTask; this.task.setNodeSource(iNodeName); this.usesDatabase = true; } public OSynchronizedTaskWrapper(final CountDownLatch iLatch) { latch = iLatch; usesDatabase = false; } @Override public String getName() { return null; } @Override public OCommandDistributedReplicateRequest.QUORUM_TYPE getQuorumType() { return null; } @Override public Object execute( ODistributedRequestId requestId, OServer iServer, ODistributedServerManager iManager, ODatabaseDocumentInternal database) throws Exception {<FILL_FUNCTION_BODY>} @Override public int getFactoryId() { return 0; } @Override public String toString() { return "(" + (task != null ? task.toString() : "-") + ")"; } @Override public boolean isUsingDatabase() { return usesDatabase; } @Override public boolean hasResponse() { if (task == null) return super.hasResponse(); else return task.hasResponse(); } }
try { if (task != null) return task.execute(requestId, iServer, iManager, database); return null; } finally { // RELEASE ALL PENDING WORKERS latch.countDown(); }
403
65
468
/** * Base class for Tasks to be executed remotely. * @author Luca Garulli (l.garulli--at--orientdb.com) */ public abstract class OAbstractRemoteTask implements ORemoteTask { protected transient String nodeSource; /** * Constructor used from unmarshalling. */ public OAbstractRemoteTask(); @Override public long getDistributedTimeout(); @Override public long getSynchronousTimeout( final int iSynchNodes); @Override public long getTotalTimeout( final int iTotalNodes); @Override public boolean hasResponse(); @Override public RESULT_STRATEGY getResultStrategy(); @Override public String toString(); @Override public String getNodeSource(); @Override public void setNodeSource( String nodeSource); @Override public boolean isIdempotent(); @Override public boolean isNodeOnlineRequired(); @Override public boolean isUsingDatabase(); @Override public void toStream( DataOutput out) throws IOException; @Override public void fromStream( DataInput in, ORemoteTaskFactory factory) throws IOException; }
google_truth
truth/core/src/main/java/com/google/common/truth/LazyMessage.java
LazyMessage
evaluateAll
class LazyMessage { private final String format; private final @Nullable Object[] args; LazyMessage(String format, @Nullable Object... args) { this.format = format; this.args = args; int placeholders = countPlaceholders(format); checkArgument( placeholders == args.length, "Incorrect number of args (%s) for the given placeholders (%s) in string template:\"%s\"", args.length, placeholders, format); } @Override public String toString() { return lenientFormat(format, args); } @VisibleForTesting static int countPlaceholders(String template) { int index = 0; int count = 0; while (true) { index = template.indexOf("%s", index); if (index == -1) { break; } index++; count++; } return count; } static ImmutableList<String> evaluateAll(ImmutableList<LazyMessage> messages) {<FILL_FUNCTION_BODY>} }
ImmutableList.Builder<String> result = ImmutableList.builder(); for (LazyMessage message : messages) { result.add(message.toString()); } return result.build();
286
53
339
mapstruct_mapstruct
mapstruct/processor/src/main/java/org/mapstruct/ap/internal/model/assignment/WrapperForCollectionsAndMaps.java
WrapperForCollectionsAndMaps
getThrownTypes
class WrapperForCollectionsAndMaps extends AssignmentWrapper { private final List<Type> thrownTypesToExclude; private final String nullCheckLocalVarName; private final Type nullCheckLocalVarType; public WrapperForCollectionsAndMaps(Assignment rhs, List<Type> thrownTypesToExclude, Type targetType, boolean fieldAssignment) { super( rhs, fieldAssignment ); this.thrownTypesToExclude = thrownTypesToExclude; if ( rhs.getType() == AssignmentType.DIRECT && rhs.getSourceType() != null ) { this.nullCheckLocalVarType = rhs.getSourceType(); } else { this.nullCheckLocalVarType = targetType; } this.nullCheckLocalVarName = rhs.createUniqueVarName( nullCheckLocalVarType.getName() ); } @Override public List<Type> getThrownTypes() {<FILL_FUNCTION_BODY>} public String getNullCheckLocalVarName() { return nullCheckLocalVarName; } public Type getNullCheckLocalVarType() { return nullCheckLocalVarType; } }
List<Type> parentThrownTypes = super.getThrownTypes(); List<Type> result = new ArrayList<>( parentThrownTypes ); for ( Type thrownTypeToExclude : thrownTypesToExclude ) { for ( Type parentThrownType : parentThrownTypes ) { if ( parentThrownType.isAssignableTo( thrownTypeToExclude ) ) { result.remove( parentThrownType ); } } } return result;
309
120
429
/** * Base class for decorators (wrappers). Decorator pattern is used to decorate assignments. * @author Sjaak Derksen */ public abstract class AssignmentWrapper extends ModelElement implements Assignment { private final Assignment decoratedAssignment; protected final boolean fieldAssignment; public AssignmentWrapper( Assignment decoratedAssignment, boolean fieldAssignment); @Override public Set<Type> getImportTypes(); @Override public List<Type> getThrownTypes(); @Override public void setAssignment( Assignment assignment); public Assignment getAssignment(); @Override public String getSourceReference(); @Override public boolean isSourceReferenceParameter(); @Override public PresenceCheck getSourcePresenceCheckerReference(); @Override public Type getSourceType(); @Override public String getSourceLocalVarName(); @Override public void setSourceLocalVarName( String sourceLocalVarName); @Override public String getSourceLoopVarName(); @Override public void setSourceLoopVarName( String sourceLoopVarName); @Override public String getSourceParameterName(); @Override public AssignmentType getType(); @Override public boolean isCallingUpdateMethod(); @Override public String createUniqueVarName( String desiredName); /** * @return {@code true} if the wrapper is for field assignment */ public boolean isFieldAssignment(); }
elunez_eladmin
eladmin/eladmin-system/src/main/java/me/zhengjie/modules/mnt/service/impl/DeployHistoryServiceImpl.java
DeployHistoryServiceImpl
download
class DeployHistoryServiceImpl implements DeployHistoryService { private final DeployHistoryRepository deployhistoryRepository; private final DeployHistoryMapper deployhistoryMapper; @Override public PageResult<DeployHistoryDto> queryAll(DeployHistoryQueryCriteria criteria, Pageable pageable){ Page<DeployHistory> page = deployhistoryRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder),pageable); return PageUtil.toPage(page.map(deployhistoryMapper::toDto)); } @Override public List<DeployHistoryDto> queryAll(DeployHistoryQueryCriteria criteria){ return deployhistoryMapper.toDto(deployhistoryRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder))); } @Override public DeployHistoryDto findById(String id) { DeployHistory deployhistory = deployhistoryRepository.findById(id).orElseGet(DeployHistory::new); ValidationUtil.isNull(deployhistory.getId(),"DeployHistory","id",id); return deployhistoryMapper.toDto(deployhistory); } @Override @Transactional(rollbackFor = Exception.class) public void create(DeployHistory resources) { resources.setId(IdUtil.simpleUUID()); deployhistoryRepository.save(resources); } @Override @Transactional(rollbackFor = Exception.class) public void delete(Set<String> ids) { for (String id : ids) { deployhistoryRepository.deleteById(id); } } @Override public void download(List<DeployHistoryDto> queryAll, HttpServletResponse response) throws IOException {<FILL_FUNCTION_BODY>} }
List<Map<String, Object>> list = new ArrayList<>(); for (DeployHistoryDto deployHistoryDto : queryAll) { Map<String,Object> map = new LinkedHashMap<>(); map.put("部署编号", deployHistoryDto.getDeployId()); map.put("应用名称", deployHistoryDto.getAppName()); map.put("部署IP", deployHistoryDto.getIp()); map.put("部署时间", deployHistoryDto.getDeployDate()); map.put("部署人员", deployHistoryDto.getDeployUser()); list.add(map); } FileUtil.downloadExcel(list, response);
469
172
641
orientechnologies_orientdb
orientdb/core/src/main/java/com/orientechnologies/orient/core/sql/executor/OIfExecutionPlan.java
OIfExecutionPlan
toResult
class OIfExecutionPlan implements OInternalExecutionPlan { private String location; private final OCommandContext ctx; @Override public OCommandContext getContext() { return ctx; } protected IfStep step; public OIfExecutionPlan(OCommandContext ctx) { this.ctx = ctx; } @Override public void reset(OCommandContext ctx) { // TODO throw new UnsupportedOperationException(); } @Override public void close() { step.close(); } @Override public OExecutionStream start() { return step.start(ctx); } @Override public String prettyPrint(int depth, int indent) { StringBuilder result = new StringBuilder(); result.append(step.prettyPrint(depth, indent)); return result.toString(); } public void chain(IfStep step) { this.step = step; } @Override public List<OExecutionStep> getSteps() { // TODO do a copy of the steps return Collections.singletonList(step); } public void setSteps(List<OExecutionStepInternal> steps) { this.step = (IfStep) steps.get(0); } @Override public OResult toResult() {<FILL_FUNCTION_BODY>} @Override public long getCost() { return 0l; } @Override public boolean canBeCached() { return false; } public OExecutionStepInternal executeUntilReturn() { OScriptExecutionPlan plan = step.producePlan(ctx); if (plan != null) { return plan.executeUntilReturn(); } else { return null; } } public boolean containsReturn() { return step.containsReturn(); } }
OResultInternal result = new OResultInternal(); result.setProperty("type", "IfExecutionPlan"); result.setProperty("javaType", getClass().getName()); result.setProperty("cost", getCost()); result.setProperty("prettyPrint", prettyPrint(0, 2)); result.setProperty("steps", Collections.singletonList(step.toResult())); return result;
485
100
585
pmd_pmd
pmd/pmd-kotlin/src/main/java/net/sourceforge/pmd/lang/kotlin/ast/KotlinInnerNode.java
KotlinInnerNode
acceptVisitor
class KotlinInnerNode extends BaseAntlrInnerNode<KotlinNode> implements KotlinNode { KotlinInnerNode(ParserRuleContext parent, int invokingStateNumber) { super(parent, invokingStateNumber); } @Override public <P, R> R acceptVisitor(AstVisitor<? super P, ? extends R> visitor, P data) {<FILL_FUNCTION_BODY>} @Override // override to make visible in package protected PmdAsAntlrInnerNode<KotlinNode> asAntlrNode() { return super.asAntlrNode(); } @Override public String getXPathNodeName() { return KotlinParser.DICO.getXPathNameOfRule(getRuleIndex()); } }
if (visitor instanceof KotlinVisitor) { // some of the generated antlr nodes have no accept method... return ((KotlinVisitor<? super P, ? extends R>) visitor).visitKotlinNode(this, data); } return visitor.visitNode(this, data);
204
81
285
pmd_pmd
pmd/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/types/internal/infer/ast/BaseFunctionalMirror.java
BaseFunctionalMirror
setFunctionalMethod
class BaseFunctionalMirror<N extends FunctionalExpression> extends BasePolyMirror<N> implements FunctionalExprMirror { private JMethodSig inferredMethod; BaseFunctionalMirror(JavaExprMirrors mirrors, N myNode, @Nullable ExprMirror parent, MirrorMaker subexprMaker) { super(mirrors, myNode, parent, subexprMaker); } @Override public void setFunctionalMethod(JMethodSig methodType) {<FILL_FUNCTION_BODY>} protected JMethodSig getInferredMethod() { return inferredMethod; } }
this.inferredMethod = methodType; if (mayMutateAst()) { InternalApiBridge.setFunctionalMethod(myNode, methodType); }
166
46
212
javamelody_javamelody
javamelody/javamelody-core/src/main/java/net/bull/javamelody/internal/model/TomcatInformations.java
TomcatInformations
buildTomcatInformationsList
class TomcatInformations implements Serializable { // cette classe utilise la même technique avec les MBeans Tomcat que la webapp manager de Tomcat // http://svn.apache.org/repos/asf/tomcat/trunk/java/org/apache/catalina/manager/StatusManagerServlet.java // http://svn.apache.org/repos/asf/tomcat/trunk/java/org/apache/catalina/manager/StatusTransformer.java // http://svn.apache.org/repos/asf/tomcat/trunk/webapps/manager/xform.xsl private static final boolean TOMCAT_USED = System.getProperty("catalina.home") != null; private static final long serialVersionUID = -6145865427461051370L; @SuppressWarnings("all") private static final List<ObjectName> THREAD_POOLS = new ArrayList<>(); @SuppressWarnings("all") private static final List<ObjectName> GLOBAL_REQUEST_PROCESSORS = new ArrayList<>(); private static int mbeansInitAttemps; private final String name; private final int maxThreads; private final int currentThreadCount; private final int currentThreadsBusy; private final long bytesReceived; private final long bytesSent; private final int requestCount; private final int errorCount; private final long processingTime; private final long maxTime; private TomcatInformations(ObjectName threadPool) throws JMException { super(); name = threadPool.getKeyProperty("name"); maxThreads = MBeansAccessor.getAttribute(threadPool, "maxThreads"); currentThreadCount = MBeansAccessor.getAttribute(threadPool, "currentThreadCount"); currentThreadsBusy = MBeansAccessor.getAttribute(threadPool, "currentThreadsBusy"); ObjectName grp = null; for (final ObjectName globalRequestProcessor : GLOBAL_REQUEST_PROCESSORS) { if (name.equals(globalRequestProcessor.getKeyProperty("name"))) { grp = globalRequestProcessor; break; } } if (grp != null) { bytesReceived = MBeansAccessor.getAttribute(grp, "bytesReceived"); bytesSent = MBeansAccessor.getAttribute(grp, "bytesSent"); requestCount = MBeansAccessor.getAttribute(grp, "requestCount"); errorCount = MBeansAccessor.getAttribute(grp, "errorCount"); processingTime = MBeansAccessor.getAttribute(grp, "processingTime"); maxTime = MBeansAccessor.getAttribute(grp, "maxTime"); } else { bytesReceived = 0; bytesSent = 0; requestCount = 0; errorCount = 0; processingTime = 0; maxTime = 0; } } static List<TomcatInformations> buildTomcatInformationsList() {<FILL_FUNCTION_BODY>} // visibilité package pour réinitialisation en test unitaire public static void initMBeans() { // rq: en général, il y a 2 connecteurs (http et ajp 1.3) définis dans server.xml et donc // 2 threadPools et 2 globalRequestProcessors de même nom : http-8080 et jk-8009 (ajp13) THREAD_POOLS.clear(); GLOBAL_REQUEST_PROCESSORS.clear(); THREAD_POOLS.addAll(MBeansAccessor.getTomcatThreadPools()); GLOBAL_REQUEST_PROCESSORS.addAll(MBeansAccessor.getTomcatGlobalRequestProcessors()); } public String getName() { return name; } public int getMaxThreads() { return maxThreads; } int getCurrentThreadCount() { return currentThreadCount; } public int getCurrentThreadsBusy() { return currentThreadsBusy; } public long getBytesReceived() { return bytesReceived; } public long getBytesSent() { return bytesSent; } public int getRequestCount() { return requestCount; } public int getErrorCount() { return errorCount; } public long getProcessingTime() { return processingTime; } public long getMaxTime() { return maxTime; } /** {@inheritDoc} */ @Override public String toString() { return getClass().getSimpleName() + "[name=" + getName() + ", maxThreads=" + getMaxThreads() + ", currentThreadCount=" + getCurrentThreadCount() + ", currentThreadsBusy=" + getCurrentThreadsBusy() + ", bytesReceived=" + getBytesReceived() + ", bytesSent=" + getBytesSent() + ", requestCount=" + getRequestCount() + ", errorCount=" + getErrorCount() + ", processingTime=" + getProcessingTime() + ", maxTime=" + getMaxTime() + ']'; } }
if (!TOMCAT_USED) { return Collections.emptyList(); } try { synchronized (THREAD_POOLS) { if ((THREAD_POOLS.isEmpty() || GLOBAL_REQUEST_PROCESSORS.isEmpty()) && mbeansInitAttemps < 10) { // lors du premier appel dans Tomcat lors du déploiement de la webapp, // ce initMBeans ne fonctionne pas car les MBeans n'existent pas encore, // donc il faut réessayer plus tard initMBeans(); // issue 406, Tomcat mbeans never found in jboss eap 6.2, // we must stop initMBeans at some point mbeansInitAttemps++; } } final List<TomcatInformations> tomcatInformationsList = new ArrayList<>( THREAD_POOLS.size()); // rq: le processor correspondant au threadPool peut se retrouver selon // threadPool.getKeyProperty("name").equals(globalRequestProcessor.getKeyProperty("name")) for (final ObjectName threadPool : THREAD_POOLS) { tomcatInformationsList.add(new TomcatInformations(threadPool)); } return tomcatInformationsList; } catch (final InstanceNotFoundException | AttributeNotFoundException e) { // catch InstanceNotFoundException nécessaire pour JBoss 6.0 quand appelé depuis MonitoringFilter.destroy via // writeHtmlToLastShutdownFile // issue 220 and end of issue 133: // AttributeNotFoundException: No attribute called maxThreads (in some JBossAS or JBossWeb) return Collections.emptyList(); } catch (final JMException e) { // n'est pas censé arriver throw new IllegalStateException(e); }
1,448
535
1,983
PlayEdu_PlayEdu
PlayEdu/playedu-api/src/main/java/xyz/playedu/api/controller/frontend/CourseController.java
CourseController
detail
class CourseController { @Autowired private CourseService courseService; @Autowired private CourseChapterService chapterService; @Autowired private CourseHourService hourService; @Autowired private CourseAttachmentService attachmentService; @Autowired private ResourceService resourceService; @Autowired private UserCourseRecordService userCourseRecordService; @Autowired private UserCourseHourRecordService userCourseHourRecordService; @Autowired private CourseAttachmentDownloadLogService courseAttachmentDownloadLogService; @GetMapping("/{id}") @SneakyThrows public JsonResponse detail(@PathVariable(name = "id") Integer id) {<FILL_FUNCTION_BODY>} @GetMapping("/{courseId}/attach/{id}/download") @SneakyThrows public JsonResponse attachmentDownload( @PathVariable(name = "courseId") Integer courseId, @PathVariable(name = "id") Integer id) { CourseAttachment attachment = attachmentService.findOrFail(id, courseId); Resource resource = resourceService.findOrFail(attachment.getRid()); HashMap<String, Object> data = new HashMap<>(); data.put("download_url", resource.getUrl()); courseAttachmentDownloadLogService.save( new CourseAttachmentDownloadLog() { { setUserId(FCtx.getId()); setCourseId(attachment.getCourseId()); setCourserAttachmentId(attachment.getId()); setRid(resource.getId()); setTitle(attachment.getTitle()); setIp(IpUtil.getIpAddress()); setCreatedAt(new Date()); } }); return JsonResponse.data(data); } }
Course course = courseService.findOrFail(id); List<CourseHour> courseHours = hourService.getHoursByCourseId(course.getId()); List<CourseAttachment> attachments = attachmentService.getAttachmentsByCourseId(course.getId()); if (null != attachments && !attachments.isEmpty()) { Map<Integer, Resource> resourceMap = resourceService .chunks(attachments.stream().map(CourseAttachment::getRid).toList()) .stream() .collect(Collectors.toMap(Resource::getId, Function.identity())); attachments.forEach( courseAttachment -> { Resource resource = resourceMap.get(courseAttachment.getRid()); if (null != resource) { courseAttachment.setExt(resource.getExtension()); } }); } HashMap<String, Object> data = new HashMap<>(); data.put("course", course); data.put("chapters", chapterService.getChaptersByCourseId(course.getId())); data.put( "hours", courseHours.stream().collect(Collectors.groupingBy(CourseHour::getChapterId))); data.put("learn_record", userCourseRecordService.find(FCtx.getId(), course.getId())); data.put( "learn_hour_records", userCourseHourRecordService.getRecords(FCtx.getId(), course.getId()).stream() .collect(Collectors.toMap(UserCourseHourRecord::getHourId, e -> e))); data.put("attachments", attachments); return JsonResponse.data(data);
456
435
891
qiujiayu_AutoLoadCache
AutoLoadCache/autoload-cache-spring-boot-starter/src/main/java/com/jarvis/cache/interceptor/CacheDeleteInterceptor.java
CacheDeleteInterceptor
invoke
class CacheDeleteInterceptor implements MethodInterceptor { private static final Logger logger = LoggerFactory.getLogger(CacheDeleteInterceptor.class); private final CacheHandler cacheHandler; private final AutoloadCacheProperties config; public CacheDeleteInterceptor(CacheHandler cacheHandler, AutoloadCacheProperties config) { this.cacheHandler = cacheHandler; this.config = config; } @Override public Object invoke(MethodInvocation invocation) throws Throwable {<FILL_FUNCTION_BODY>} }
if (!this.config.isEnable()) { return invocation.proceed(); } Method method = invocation.getMethod(); // if (method.getDeclaringClass().isInterface()) { Class<?> cls = AopUtil.getTargetClass(invocation.getThis()); if (!cls.equals(invocation.getThis().getClass())) { if (logger.isDebugEnabled()) { logger.debug(invocation.getThis().getClass() + "-->" + cls); } return invocation.proceed(); } // } Object result = invocation.proceed(); if (method.isAnnotationPresent(CacheDelete.class)) { CacheDelete cacheDelete = method.getAnnotation(CacheDelete.class); if (logger.isDebugEnabled()) { logger.debug(invocation.getThis().getClass().getName() + "." + method.getName() + "-->@CacheDelete"); } cacheHandler.deleteCache(new DeleteCacheAopProxy(invocation), cacheDelete, result); } else { Method specificMethod = AopUtils.getMostSpecificMethod(method, invocation.getThis().getClass()); if (specificMethod.isAnnotationPresent(CacheDelete.class)) { CacheDelete cacheDelete = specificMethod.getAnnotation(CacheDelete.class); if (logger.isDebugEnabled()) { logger.debug(invocation.getThis().getClass().getName() + "." + specificMethod.getName() + "-->@CacheDelete"); } cacheHandler.deleteCache(new DeleteCacheAopProxy(invocation), cacheDelete, result); } } return result;
141
414
555
obsidiandynamics_kafdrop
kafdrop/src/main/java/kafdrop/controller/BrokerController.java
BrokerController
brokerDetails
class BrokerController { private final KafkaMonitor kafkaMonitor; public BrokerController(KafkaMonitor kafkaMonitor) { this.kafkaMonitor = kafkaMonitor; } @RequestMapping("/broker/{id}") public String brokerDetails(@PathVariable("id") int brokerId, Model model) {<FILL_FUNCTION_BODY>} @Operation(summary = "getBroker", description = "Get details for a specific Kafka broker") @ApiResponses(value = { @ApiResponse(responseCode = "200", description = "Success"), @ApiResponse(responseCode = "404", description = "Invalid Broker ID") }) @GetMapping(path = "/broker/{id}", produces = MediaType.APPLICATION_JSON_VALUE) public @ResponseBody BrokerVO brokerDetailsJson(@PathVariable("id") int brokerId) { return kafkaMonitor.getBroker(brokerId).orElseThrow(() -> new BrokerNotFoundException("No such broker " + brokerId)); } @Operation(summary = "getAllBrokers", description = "Get details for all known Kafka brokers") @ApiResponses(value = { @ApiResponse(responseCode = "200", description = "Success") }) @GetMapping(path = "/broker", produces = MediaType.APPLICATION_JSON_VALUE) public @ResponseBody List<BrokerVO> brokerDetailsJson() { return kafkaMonitor.getBrokers(); } }
model.addAttribute("broker", kafkaMonitor.getBroker(brokerId) .orElseThrow(() -> new BrokerNotFoundException("No such broker " + brokerId))); model.addAttribute("topics", kafkaMonitor.getTopics()); return "broker-detail";
393
78
471
graphhopper_graphhopper
graphhopper/core/src/main/java/com/graphhopper/routing/InstructionsOutgoingEdges.java
InstructionsOutgoingEdges
isLeavingCurrentStreet
class InstructionsOutgoingEdges { private final EdgeIteratorState prevEdge; private final EdgeIteratorState currentEdge; // Outgoing edges that we would be allowed to turn on private final List<EdgeIteratorState> allowedAlternativeTurns; // All outgoing edges, including oneways in the wrong direction private final List<EdgeIteratorState> visibleAlternativeTurns; private final DecimalEncodedValue maxSpeedEnc; private final EnumEncodedValue<RoadClass> roadClassEnc; private final BooleanEncodedValue roadClassLinkEnc; private final NodeAccess nodeAccess; private final Weighting weighting; public InstructionsOutgoingEdges(EdgeIteratorState prevEdge, EdgeIteratorState currentEdge, Weighting weighting, DecimalEncodedValue maxSpeedEnc, EnumEncodedValue<RoadClass> roadClassEnc, BooleanEncodedValue roadClassLinkEnc, EdgeExplorer allExplorer, NodeAccess nodeAccess, int prevNode, int baseNode, int adjNode) { this.prevEdge = prevEdge; this.currentEdge = currentEdge; this.weighting = weighting; this.maxSpeedEnc = maxSpeedEnc; this.roadClassEnc = roadClassEnc; this.roadClassLinkEnc = roadClassLinkEnc; this.nodeAccess = nodeAccess; visibleAlternativeTurns = new ArrayList<>(); allowedAlternativeTurns = new ArrayList<>(); EdgeIterator edgeIter = allExplorer.setBaseNode(baseNode); while (edgeIter.next()) { if (edgeIter.getAdjNode() != prevNode && edgeIter.getAdjNode() != adjNode) { if (Double.isFinite(weighting.calcEdgeWeight(edgeIter, false))) { EdgeIteratorState tmpEdge = edgeIter.detach(false); allowedAlternativeTurns.add(tmpEdge); visibleAlternativeTurns.add(tmpEdge); } else if (Double.isFinite(weighting.calcEdgeWeight(edgeIter, true))) { visibleAlternativeTurns.add(edgeIter.detach(false)); } } } } /** * This method calculates the number of allowed outgoing edges, which could be considered the number of possible * roads one might take at the intersection. This excludes the road you are coming from and inaccessible roads. */ public int getAllowedTurns() { return 1 + allowedAlternativeTurns.size(); } /** * This method calculates the number of all outgoing edges, which could be considered the number of roads you see * at the intersection. This excludes the road you are coming from and also inaccessible roads. */ public int getVisibleTurns() { return 1 + visibleAlternativeTurns.size(); } /** * Checks if the outgoing edges are slower by the provided factor. If they are, this indicates, that we are staying * on the prominent street that one would follow anyway. */ public boolean outgoingEdgesAreSlowerByFactor(double factor) { double tmpSpeed = getSpeed(currentEdge); double pathSpeed = getSpeed(prevEdge); // speed change indicates that we change road types if (Math.abs(pathSpeed - tmpSpeed) >= 1) { return false; } double maxSurroundingSpeed = -1; for (EdgeIteratorState edge : allowedAlternativeTurns) { tmpSpeed = getSpeed(edge); if (tmpSpeed > maxSurroundingSpeed) { maxSurroundingSpeed = tmpSpeed; } } // surrounding streets need to be slower by a factor and call round() so that tiny differences are ignored return Math.round(maxSurroundingSpeed * factor) < Math.round(pathSpeed); } /** * Will return the tagged maxspeed, if available, if not, we use the average speed * TODO: Should we rely only on the tagged maxspeed? */ private double getSpeed(EdgeIteratorState edge) { double maxSpeed = edge.get(maxSpeedEnc); if (Double.isInfinite(maxSpeed)) return edge.getDistance() / weighting.calcEdgeMillis(edge, false) * 3600; return maxSpeed; } /** * Returns an edge that has more or less in the same orientation as the prevEdge, but is not the currentEdge. * If there is one, this indicates that we might need an instruction to help finding the correct edge out of the different choices. * If there is none, return null. */ public EdgeIteratorState getOtherContinue(double prevLat, double prevLon, double prevOrientation) { int tmpSign; for (EdgeIteratorState edge : allowedAlternativeTurns) { GHPoint point = InstructionsHelper.getPointForOrientationCalculation(edge, nodeAccess); tmpSign = InstructionsHelper.calculateSign(prevLat, prevLon, point.getLat(), point.getLon(), prevOrientation); if (Math.abs(tmpSign) <= 1) { return edge; } } return null; } /** * If the name and prevName changes this method checks if either the current street is continued on a * different edge or if the edge we are turning onto is continued on a different edge. * If either of these properties is true, we can be quite certain that a turn instruction should be provided. */ public boolean isLeavingCurrentStreet(String prevName, String name) {<FILL_FUNCTION_BODY>} private boolean isTheSameRoadClassAndLink(EdgeIteratorState edge1, EdgeIteratorState edge2) { return edge1.get(roadClassEnc) == edge2.get(roadClassEnc) && edge1.get(roadClassLinkEnc) == edge2.get(roadClassLinkEnc); } }
if (InstructionsHelper.isNameSimilar(name, prevName)) { return false; } boolean roadClassOrLinkChange = !isTheSameRoadClassAndLink(prevEdge, currentEdge); for (EdgeIteratorState edge : allowedAlternativeTurns) { String edgeName = edge.getName(); // leave the current street if (InstructionsHelper.isNameSimilar(prevName, edgeName) || (roadClassOrLinkChange && isTheSameRoadClassAndLink(prevEdge, edge))) { return true; } // enter a different street if (InstructionsHelper.isNameSimilar(name, edgeName) || (roadClassOrLinkChange && isTheSameRoadClassAndLink(currentEdge, edge))) { return true; } } return false;
1,467
200
1,667
pmd_pmd
pmd/pmd-core/src/main/java/net/sourceforge/pmd/cpd/SimpleRenderer.java
SimpleRenderer
renderOn
class SimpleRenderer implements CPDReportRenderer { private String separator; private boolean trimLeadingWhitespace; public static final String DEFAULT_SEPARATOR = "====================================================================="; public SimpleRenderer() { this(false); } public SimpleRenderer(boolean trimLeadingWhitespace) { this(DEFAULT_SEPARATOR); this.trimLeadingWhitespace = trimLeadingWhitespace; } public SimpleRenderer(String theSeparator) { separator = theSeparator; } @Override public void render(CPDReport report, Writer writer0) throws IOException { PrintWriter writer = new PrintWriter(writer0); Iterator<Match> matches = report.getMatches().iterator(); if (matches.hasNext()) { renderOn(report, writer, matches.next()); } while (matches.hasNext()) { Match match = matches.next(); writer.println(separator); renderOn(report, writer, match); } writer.flush(); } private void renderOn(CPDReport report, PrintWriter writer, Match match) throws IOException {<FILL_FUNCTION_BODY>} }
writer.append("Found a ").append(String.valueOf(match.getLineCount())).append(" line (").append(String.valueOf(match.getTokenCount())) .append(" tokens) duplication in the following files: ").println(); for (Mark mark : match) { FileLocation loc = mark.getLocation(); writer.append("Starting at line ") .append(String.valueOf(loc.getStartLine())) .append(" of ").append(report.getDisplayName(loc.getFileId())) .println(); } writer.println(); // add a line to separate the source from the desc above Chars source = report.getSourceCodeSlice(match.getFirstMark()); if (trimLeadingWhitespace) { for (Chars line : StringUtil.linesWithTrimIndent(source)) { line.writeFully(writer); writer.println(); } return; } source.writeFully(writer); writer.println();
308
260
568
orientechnologies_orientdb
orientdb/server/src/main/java/com/orientechnologies/orient/server/security/OSelfSignedCertificate.java
OSelfSignedCertificate
composeSelfSignedCertificate
class OSelfSignedCertificate { public static final String DEFAULT_CERTIFICATE_ALGORITHM = "RSA"; public static final int DEFAULT_CERTIFICATE_KEY_SIZE = 2048; public static final int DEFAULT_CERTIFICATE_VALIDITY = 365; public static final String DEFAULT_CERTIFICATE_OWNER = "CN=SelfSigenedOrientDBtestOnly, OU=SAP HANA Core, O=SAP SE, L=Walldorf, C=DE"; public static final String DEFAULT_CERTIFICATE_NAME = "ssl"; private String algorithm; private int key_size; private int validity; private KeyPair keyPair = null; private X509Certificate certificate = null; private String certificateName; private BigInteger certificateSN; private String ownerFDN; public OSelfSignedCertificate() { this.certificateSN = computeRandomSerialNumber(); } public String getAlgorithm() { return algorithm; } public void setAlgorithm(String algorithm) { if ((algorithm == null) || (algorithm.isEmpty())) { this.algorithm = DEFAULT_CERTIFICATE_ALGORITHM; } else { this.algorithm = algorithm; } } public int getKey_size() { return key_size; } public void setKey_size(int key_size) { if (key_size >= 128) { this.key_size = key_size; } else { this.key_size = DEFAULT_CERTIFICATE_KEY_SIZE; } } public void setValidity(int validity) { this.validity = validity; } public String getCertificateName() { return certificateName; } public void setCertificateName(String certificateName) { this.certificateName = certificateName; } public void setCertificateSN(long certificateSN) throws SwitchToDefaultParamsException { if (certificateSN <= 11) { BigInteger sn = computeRandomSerialNumber(); this.certificateSN = sn; throw new SwitchToDefaultParamsException( "the value " + certificateSN + " culd not be used as a Certificate Serial Nuber, the value will be set to:" + sn); } else { this.certificateSN = BigInteger.valueOf(certificateSN); } } public static BigInteger computeRandomSerialNumber() { SecureRandom sr = new SecureRandom(); return BigInteger.valueOf(sr.nextLong()); } public void setOwnerFDN(String ownerFDN) { this.ownerFDN = ownerFDN; } /** * Generate and Return a key pair. * * <p>If this KeyPairGenerator has not been initialized explicitly, provider-specific defaults * will be used for the size and other (algorithm-specific) values of the generated keys.Our * People * * <p>This method will computes and returns a new key pair every time it is called. * * @return a new key pair * @throws NoSuchAlgorithmException if the algorithm String not match with the supported key * generation schemes. */ public static KeyPair computeKeyPair(String algorithm, int keySize) throws NoSuchAlgorithmException { KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance(algorithm); keyPairGenerator.initialize(keySize, new SecureRandom()); return keyPairGenerator.generateKeyPair(); } /** * recompute a new key pair FOR INTERNAL OSelfSignedCertificate class USE. * * <p>This method is functionally equivalent to {@link #computeKeyPair * computeKeyPair(this.algorithm,this.key_size)}. It uses the value pair * (DEFAULT_CERTIFICATE_ALGORITHM,DEFAULT_CERTIFICATE_KEY_SIZE) if the setted fields are not * valid. * * @throws NoSuchAlgorithmException if the algorithm String not match with the supported key * generation schemes. */ public void generateCertificateKeyPair() throws NoSuchAlgorithmException, SwitchToDefaultParamsException { try { this.keyPair = computeKeyPair(this.algorithm, this.key_size); } catch (NoSuchAlgorithmException e) { this.keyPair = computeKeyPair(DEFAULT_CERTIFICATE_ALGORITHM, DEFAULT_CERTIFICATE_KEY_SIZE); SwitchToDefaultParamsException tmpe = new SwitchToDefaultParamsException(); tmpe.addSuppressed(e); throw tmpe; } } public PublicKey getPublicKey() { if (keyPair == null) { throw new NullPointerException("generate the Key Pair"); } return keyPair.getPublic(); } public void composeSelfSignedCertificate() {<FILL_FUNCTION_BODY>} public static X509Certificate generateSelfSignedCertificate( KeyPair keypair, int validity, String ownerFDN, BigInteger certSN) throws CertificateException, IOException, NoSuchAlgorithmException { X500Name owner; owner = new X500Name(ownerFDN); Date from, to; Calendar c = Calendar.getInstance(); c.add(Calendar.DAY_OF_YEAR, 0); from = c.getTime(); c.add(Calendar.DAY_OF_YEAR, validity); to = c.getTime(); var certBuilder = new X509v3CertificateBuilder( owner, certSN, from, to, owner, SubjectPublicKeyInfo.getInstance(keypair.getPublic().getEncoded())); try { var certHolder = certBuilder.build( new JcaContentSignerBuilder("SHA256WithRSA").build(keypair.getPrivate())); return new JcaX509CertificateConverter().getCertificate(certHolder); } catch (OperatorCreationException e) { throw new RuntimeException(e); } } public X509Certificate getCertificate() throws CertificateException { if (this.certificate == null) { throw new CertificateException( "The Self-Signed Certificate han not been genetated! " + "You have to invoke the composeSelfSignedCertificate() before get it."); } return this.certificate; } public static void checkCertificate(X509Certificate cert, PublicKey publicKey, Date date) throws NoSuchProviderException, CertificateException, NoSuchAlgorithmException, InvalidKeyException, SignatureException { cert.checkValidity(date); cert.verify(publicKey); } public void checkThisCertificate() throws NoSuchAlgorithmException, CertificateException, NoSuchProviderException, InvalidKeyException, SignatureException { checkCertificate( this.certificate, this.keyPair.getPublic(), new Date(System.currentTimeMillis())); } public PrivateKey getPrivateKey() { return this.keyPair.getPrivate(); } }
try { this.certificate = generateSelfSignedCertificate( this.keyPair, this.validity, this.ownerFDN, this.certificateSN); } catch (CertificateException | IOException | NoSuchAlgorithmException e) { throw new RuntimeException(e); }
1,875
78
1,953
orientechnologies_orientdb
orientdb/server/src/main/java/com/orientechnologies/orient/server/distributed/operation/NodeOperationTask.java
NodeOperationFactory
createOperationResponse
class NodeOperationFactory { private Callable<NodeOperation> request; private Callable<NodeOperationResponse> response; public NodeOperationFactory( Callable<NodeOperation> request, Callable<NodeOperationResponse> response) { this.request = request; this.response = response; } } public static void register( int messageId, Callable<NodeOperation> requestFactory, Callable<NodeOperationResponse> responseFactory) { MESSAGES.put(messageId, new NodeOperationFactory(requestFactory, responseFactory)); } public static NodeOperationResponse createOperationResponse(int messageId) {<FILL_FUNCTION_BODY>
NodeOperationFactory factory = MESSAGES.get(messageId); if (factory != null) { try { return factory.response.call(); } catch (Exception e) { OLogManager.instance() .warn(null, "Cannot create node operation response from id %d", messageId); return null; } } else { return null; }
172
102
274
jeecgboot_jeecg-boot
jeecg-boot/jeecg-module-system/jeecg-system-biz/src/main/java/org/jeecg/modules/cas/util/CasServiceUtil.java
CasServiceUtil
createHttpClientWithNoSsl
class CasServiceUtil { public static void main(String[] args) { String serviceUrl = "https://cas.8f8.com.cn:8443/cas/p3/serviceValidate"; String service = "http://localhost:3003/user/login"; String ticket = "ST-5-1g-9cNES6KXNRwq-GuRET103sm0-DESKTOP-VKLS8B3"; String res = getStValidate(serviceUrl,ticket, service); System.out.println("---------res-----"+res); } /** * 验证ST */ public static String getStValidate(String url, String st, String service){ try { url = url+"?service="+service+"&ticket="+st; CloseableHttpClient httpclient = createHttpClientWithNoSsl(); HttpGet httpget = new HttpGet(url); HttpResponse response = httpclient.execute(httpget); String res = readResponse(response); return res == null ? null : (res == "" ? null : res); } catch (Exception e) { e.printStackTrace(); } return ""; } /** * 读取 response body 内容为字符串 * * @param response * @return * @throws IOException */ private static String readResponse(HttpResponse response) throws IOException { BufferedReader in = new BufferedReader(new InputStreamReader(response.getEntity().getContent())); String result = new String(); String line; while ((line = in.readLine()) != null) { result += line; } return result; } /** * 创建模拟客户端(针对 https 客户端禁用 SSL 验证) * * @param cookieStore 缓存的 Cookies 信息 * @return * @throws Exception */ private static CloseableHttpClient createHttpClientWithNoSsl() throws Exception {<FILL_FUNCTION_BODY>} }
// Create a trust manager that does not validate certificate chains TrustManager[] trustAllCerts = new TrustManager[]{ new X509TrustManager() { @Override public X509Certificate[] getAcceptedIssuers() { return null; } @Override public void checkClientTrusted(X509Certificate[] certs, String authType) { // don't check } @Override public void checkServerTrusted(X509Certificate[] certs, String authType) { // don't check } } }; SSLContext ctx = SSLContext.getInstance("TLS"); ctx.init(null, trustAllCerts, null); LayeredConnectionSocketFactory sslSocketFactory = new SSLConnectionSocketFactory(ctx); return HttpClients.custom() .setSSLSocketFactory(sslSocketFactory) .build();
544
234
778
zhkl0228_unidbg
unidbg/unidbg-android/src/main/java/com/github/unidbg/linux/file/DumpFileIO.java
DumpFileIO
write
class DumpFileIO extends BaseAndroidFileIO implements AndroidFileIO { private final int fd; public DumpFileIO(int fd) { super(0); this.fd = fd; } @Override public int write(byte[] data) {<FILL_FUNCTION_BODY>} @Override public void close() { } @Override public FileIO dup2() { return this; } @Override public int fstat(Emulator<?> emulator, com.github.unidbg.file.linux.StatStructure stat) { throw new UnsupportedOperationException(); } @Override public int getdents64(Pointer dirp, int size) { throw new UnsupportedOperationException(); } }
Inspector.inspect(data, "Dump for fd: " + fd); return data.length;
211
32
243
public abstract class BaseAndroidFileIO extends BaseFileIO implements AndroidFileIO { public BaseAndroidFileIO( int oflags); @Override public int fstat( Emulator<?> emulator, StatStructure stat); @Override public int getdents64( Pointer dirp, int size); @Override public AndroidFileIO accept( Pointer addr, Pointer addrlen); @Override public int statfs( StatFS statFS); @Override protected void setFlags( long arg); }
jitsi_jitsi
jitsi/modules/service/netaddr/src/main/java/net/java/sip/communicator/impl/netaddr/NetaddrActivator.java
NetaddrActivator
startWithServices
class NetaddrActivator extends DependentActivator { /** * The OSGi bundle context. */ private static BundleContext bundleContext = null; /** * The network address manager implementation. */ private NetworkAddressManagerServiceImpl networkAMS = null; /** * The configuration service. */ private static ConfigurationService configurationService = null; /** * The OSGi <tt>PacketLoggingService</tt> in * {@link #bundleContext} and used for debugging. */ private static PacketLoggingService packetLoggingService = null; public NetaddrActivator() { super( ConfigurationService.class, PacketLoggingService.class ); } @Override public void startWithServices(BundleContext bundleContext) {<FILL_FUNCTION_BODY>} /** * Returns a reference to a ConfigurationService implementation currently * registered in the bundle context or null if no such implementation was * found. * * @return a currently valid implementation of the ConfigurationService. */ public static ConfigurationService getConfigurationService() { return configurationService; } /** * Returns a reference to the <tt>PacketLoggingService</tt> implementation * currently registered in the bundle context or null if no such * implementation was found. * * @return a reference to a <tt>PacketLoggingService</tt> implementation * currently registered in the bundle context or null if no such * implementation was found. */ public static PacketLoggingService getPacketLogging() { return packetLoggingService; } /** * Stops the Network Address Manager bundle * * @param bundleContext the OSGI bundle context * */ public void stop(BundleContext bundleContext) { if(networkAMS != null) networkAMS.stop(); if (logger.isInfoEnabled()) logger.info("Network Address Manager Service ...[STOPPED]"); configurationService = null; packetLoggingService = null; } /** * Returns a reference to the bundle context that we were started with. * * @return a reference to the BundleContext instance that we were started * with. */ static BundleContext getBundleContext() { return bundleContext; } }
NetaddrActivator.bundleContext = bundleContext; configurationService = getService(ConfigurationService.class); packetLoggingService = getService(PacketLoggingService.class); //in here we load static properties that should be else where //System.setProperty("java.net.preferIPv4Stack", "false"); //System.setProperty("java.net.preferIPv6Addresses", "true"); //end ugly property set //Create and start the network address manager. networkAMS = new NetworkAddressManagerServiceImpl(); // give references to the NetworkAddressManager implementation networkAMS.start(); if (logger.isInfoEnabled()) logger.info("Network Address Manager ...[ STARTED ]"); bundleContext.registerService( NetworkAddressManagerService.class.getName(), networkAMS, null); MetaconfigSettings.Companion.setCacheEnabled(false); MetaconfigSettings.Companion.setLogger(new MetaconfigLogger() { @Override public void warn(Function0<String> function0) { if (logger.isWarnEnabled()) logger.warn(function0.invoke()); } @Override public void error(Function0<String> function0) { if (logger.isErrorEnabled()) logger.error(function0.invoke()); } @Override public void debug(Function0<String> function0) { if (logger.isDebugEnabled()) logger.debug(function0.invoke()); } }); ConfigSource defaults = new TypesafeConfigSource("defaults", ConfigFactory .defaultReference(AgentConfig.class.getClassLoader())); JitsiConfig.Companion.useDebugNewConfig(defaults); logger.info("Network Address Manager Service ...[REGISTERED]");
620
466
1,086
/** * Bundle activator that will start the bundle when the requested dependent services are available. */ public abstract class DependentActivator implements BundleActivator, ServiceTrackerCustomizer<Object,Object> { private static final Map<BundleActivator,Set<Class<?>>> openTrackers=Collections.synchronizedMap(new HashMap<>()); private final Logger logger=LoggerFactory.getLogger(getClass()); private final Map<Class<?>,ServiceTracker<?,?>> dependentServices=new HashMap<>(); private final Set<Object> runningServices=new HashSet<>(); private BundleContext bundleContext; protected DependentActivator( Iterable<Class<?>> dependentServices); protected DependentActivator( Class<?>... dependentServices); /** * Starts the bundle. * @param bundleContext the currently valid <tt>BundleContext</tt>. */ @Override public final void start( BundleContext bundleContext); @Override public void stop( BundleContext context) throws Exception; @Override public Object addingService( ServiceReference<Object> reference); @SuppressWarnings("unchecked") protected <T>T getService( Class<T> serviceClass); @Override public void modifiedService( ServiceReference<Object> reference, Object service); @Override public void removedService( ServiceReference<Object> reference, Object service); protected abstract void startWithServices( BundleContext bundleContext) throws Exception ; }
pmd_pmd
pmd/pmd-plsql/src/main/java/net/sourceforge/pmd/lang/plsql/symboltable/VariableNameDeclaration.java
VariableNameDeclaration
getScope
class VariableNameDeclaration extends AbstractNameDeclaration { private static final Logger LOG = LoggerFactory.getLogger(VariableNameDeclaration.class); public VariableNameDeclaration(ASTVariableOrConstantDeclaratorId node) { super(node); } @Override public Scope getScope() {<FILL_FUNCTION_BODY>} public ASTVariableOrConstantDeclaratorId getDeclaratorId() { return (ASTVariableOrConstantDeclaratorId) node; } @Override public boolean equals(Object o) { if (!(o instanceof VariableNameDeclaration)) { return false; } VariableNameDeclaration n = (VariableNameDeclaration) o; try { return n.getImage().equals(this.getImage()); } catch (Exception e) { LOG.error(e.getMessage(), e); LOG.debug("n.node={}", n.node); LOG.debug("n.getImage={}", n.getImage()); LOG.debug("node={}", node); LOG.debug("this.getImage={}", this.getImage()); return false; } } @Override public int hashCode() { try { return this.getImage().hashCode(); } catch (Exception e) { LOG.error(e.getMessage(), e); LOG.debug("VariableNameDeclaration: node={}", node); LOG.debug("VariableNameDeclaration: node,getImage={}", this.getImage()); return 0; } } @Override public String toString() { return "Variable: image = '" + node.getImage() + "', line = " + node.getBeginLine(); } }
try { return node.getScope().getEnclosingScope(ClassScope.class); } catch (Exception e) { LOG.trace("This Node does not have an enclosing Class: {}/{} => {}", node.getBeginLine(), node.getBeginColumn(), this.getImage()); return null; // @TODO SRT a cop-out }
437
97
534
/** * Base class for all name declarations. */ public abstract class AbstractNameDeclaration implements NameDeclaration { protected ScopedNode node; public AbstractNameDeclaration( ScopedNode node); @Override public ScopedNode getNode(); @Override public String getImage(); @Override public Scope getScope(); @Override public String getName(); }
qiujiayu_AutoLoadCache
AutoLoadCache/autoload-cache-common/src/main/java/com/jarvis/cache/reflect/generics/ParameterizedTypeImpl.java
ParameterizedTypeImpl
validateConstructorArguments
class ParameterizedTypeImpl implements ParameterizedType { private Type[] actualTypeArguments; private Class<?> rawType; private Type ownerType; private ParameterizedTypeImpl(Class<?> paramClass, Type[] paramArrayOfType, Type paramType) { this.actualTypeArguments = paramArrayOfType; this.rawType = paramClass; if (paramType != null) { this.ownerType = paramType; } else { this.ownerType = paramClass.getDeclaringClass(); } validateConstructorArguments(); } private void validateConstructorArguments() {<FILL_FUNCTION_BODY>} public static ParameterizedTypeImpl make(Class<?> paramClass, Type[] paramArrayOfType, Type paramType) { return new ParameterizedTypeImpl(paramClass, paramArrayOfType, paramType); } @Override public Type[] getActualTypeArguments() { return (Type[]) this.actualTypeArguments.clone(); } @Override public Class<?> getRawType() { return this.rawType; } @Override public Type getOwnerType() { return this.ownerType; } @Override public boolean equals(Object paramObject) { if ((paramObject instanceof ParameterizedType)) { ParameterizedType localParameterizedType = (ParameterizedType) paramObject; if (this == localParameterizedType) { return true; } Type localType1 = localParameterizedType.getOwnerType(); Type localType2 = localParameterizedType.getRawType(); return (this.ownerType == null ? localType1 == null : this.ownerType.equals(localType1)) && (this.rawType == null ? localType2 == null : this.rawType.equals(localType2)) && (Arrays.equals(this.actualTypeArguments, localParameterizedType.getActualTypeArguments())); } return false; } @Override public int hashCode() { return Arrays.hashCode(this.actualTypeArguments) ^ (this.ownerType == null ? 0 : this.ownerType.hashCode()) ^ (this.rawType == null ? 0 : this.rawType.hashCode()); } @Override public String toString() { StringBuilder localStringBuilder = new StringBuilder(); if (this.ownerType != null) { if ((this.ownerType instanceof Class<?>)) localStringBuilder.append(((Class<?>) this.ownerType).getName()); else { localStringBuilder.append(this.ownerType.toString()); } localStringBuilder.append("."); if ((this.ownerType instanceof ParameterizedTypeImpl)) { localStringBuilder.append(this.rawType.getName() .replace(((ParameterizedTypeImpl) this.ownerType).rawType.getName() + "$", "")); } else { localStringBuilder.append(this.rawType.getName()); } } else { localStringBuilder.append(this.rawType.getName()); } if ((this.actualTypeArguments != null) && (this.actualTypeArguments.length > 0)) { localStringBuilder.append("<"); int i = 1; for (Type localType : this.actualTypeArguments) { if (i == 0) { localStringBuilder.append(", "); } if ((localType instanceof Class<?>)) { localStringBuilder.append(((Class<?>) localType).getName()); } else { // if(null!=localType){ localStringBuilder.append(localType.toString()); // } } i = 0; } localStringBuilder.append(">"); } return localStringBuilder.toString(); } }
@SuppressWarnings("rawtypes") TypeVariable[] arrayOfTypeVariable = this.rawType.getTypeParameters(); if (arrayOfTypeVariable.length != this.actualTypeArguments.length) { throw new MalformedParameterizedTypeException(); } // for(int i=0; i < this.actualTypeArguments.length; i++);
976
93
1,069
javamelody_javamelody
javamelody/javamelody-core/src/main/java/net/bull/javamelody/JspWrapper.java
HttpRequestWrapper
startAsync
class HttpRequestWrapper extends HttpServletRequestWrapper { private final HttpServletResponse response; /** * Constructs a request object wrapping the given request. * @param request HttpServletRequest * @param response HttpServletResponse */ HttpRequestWrapper(HttpServletRequest request, HttpServletResponse response) { super(request); this.response = response; } /** {@inheritDoc} */ @Override public RequestDispatcher getRequestDispatcher(String path) { final RequestDispatcher requestDispatcher = super.getRequestDispatcher(path); if (requestDispatcher == null) { return null; } // il n'est pas dit que path soit non null final InvocationHandler invocationHandler = new JspWrapper(String.valueOf(path), requestDispatcher); return JdbcWrapper.createProxy(requestDispatcher, invocationHandler); } @Override public AsyncContext startAsync() {<FILL_FUNCTION_BODY>} }
// issue 217: after MonitoringFilter.doFilter, response is instance of CounterServletResponseWrapper, // and if response.getWriter() has been called before calling request.startAsync(), // then asyncContext.getResponse() should return the instance of CounterServletResponseWrapper // and not the initial response without the wrapper, // otherwise asyncContext.getResponse().getWriter() will throw something like // "IllegalStateException: getOutputStream() has already been called for this response" return super.startAsync(this, response);
285
139
424
houbb_sensitive-word
sensitive-word/src/main/java/com/github/houbb/sensitive/word/support/format/WordFormatInit.java
WordFormatInit
format
class WordFormatInit implements IWordFormat { /** * 初始化列表 * * @param pipeline 当前列表泳道 * @since 0.0.13 */ protected abstract void init(final Pipeline<IWordFormat> pipeline); @Override public char format(char original, IWordContext context) {<FILL_FUNCTION_BODY>} }
Pipeline<IWordFormat> pipeline = new DefaultPipeline<>(); init(pipeline); char result = original; // 循环执行 List<IWordFormat> charFormats = pipeline.list(); for(IWordFormat charFormat : charFormats) { result = charFormat.format(result, context); } return result;
105
95
200
orientechnologies_orientdb
orientdb/core/src/main/java/com/orientechnologies/common/collection/closabledictionary/OClosableLRUList.java
OClosableLRUList
remove
class OClosableLRUList<K, V extends OClosableItem> implements Iterable<OClosableEntry<K, V>> { private int size; private OClosableEntry<K, V> head; private OClosableEntry<K, V> tail; void remove(OClosableEntry<K, V> entry) {<FILL_FUNCTION_BODY>} boolean contains(OClosableEntry<K, V> entry) { return entry.getNext() != null || entry.getPrev() != null || entry == head; } void moveToTheTail(OClosableEntry<K, V> entry) { if (tail == entry) { assert entry.getNext() == null; return; } final OClosableEntry<K, V> next = entry.getNext(); final OClosableEntry<K, V> prev = entry.getPrev(); boolean newEntry = !(next != null || prev != null || entry == head); if (prev != null) { assert prev.getNext() == entry; } if (next != null) { assert next.getPrev() == entry; } if (prev != null) { prev.setNext(next); } if (next != null) { next.setPrev(prev); } if (head == entry) { assert entry.getPrev() == null; head = next; } entry.setPrev(tail); entry.setNext(null); if (tail != null) { assert tail.getNext() == null; tail.setNext(entry); tail = entry; } else { tail = head = entry; } if (newEntry) size++; } int size() { return size; } OClosableEntry<K, V> poll() { if (head == null) return null; final OClosableEntry<K, V> entry = head; OClosableEntry<K, V> next = head.getNext(); assert next == null || next.getPrev() == head; head = next; if (next != null) { next.setPrev(null); } assert head == null || head.getPrev() == null; if (head == null) tail = null; entry.setNext(null); assert entry.getPrev() == null; size--; return entry; } /** @return Iterator to iterate from head to the tail. */ public Iterator<OClosableEntry<K, V>> iterator() { return new Iterator<OClosableEntry<K, V>>() { private OClosableEntry<K, V> next = head; private OClosableEntry<K, V> current = null; @Override public boolean hasNext() { return next != null; } @Override public OClosableEntry<K, V> next() { if (next == null) { throw new NoSuchElementException(); } current = next; next = next.getNext(); return current; } @Override public void remove() { if (current == null) { throw new IllegalStateException("Method next was not called"); } OClosableLRUList.this.remove(current); current = null; } }; } boolean assertForwardStructure() { if (head == null) return tail == null; OClosableEntry<K, V> current = head; while (current.getNext() != null) { OClosableEntry<K, V> prev = current.getPrev(); OClosableEntry<K, V> next = current.getNext(); if (prev != null) { assert prev.getNext() == current; } if (next != null) { assert next.getPrev() == current; } current = current.getNext(); } return current == tail; } boolean assertBackwardStructure() { if (tail == null) return head == null; OClosableEntry<K, V> current = tail; while (current.getPrev() != null) { OClosableEntry<K, V> prev = current.getPrev(); OClosableEntry<K, V> next = current.getNext(); if (prev != null) { assert prev.getNext() == current; } if (next != null) { assert next.getPrev() == current; } current = current.getPrev(); } return current == head; } }
final OClosableEntry<K, V> next = entry.getNext(); final OClosableEntry<K, V> prev = entry.getPrev(); if (!(next != null || prev != null || entry == head)) return; if (prev != null) { assert prev.getNext() == entry; } if (next != null) { assert next.getPrev() == entry; } if (next != null) { next.setPrev(prev); } if (prev != null) { prev.setNext(next); } if (head == entry) { assert entry.getPrev() == null; head = next; } if (tail == entry) { assert entry.getNext() == null; tail = prev; } entry.setNext(null); entry.setPrev(null); size--;
1,253
246
1,499
mapstruct_mapstruct
mapstruct/processor/src/main/java/org/mapstruct/ap/internal/model/source/builtin/JodaLocalTimeToXmlGregorianCalendar.java
JodaLocalTimeToXmlGregorianCalendar
getImportTypes
class JodaLocalTimeToXmlGregorianCalendar extends AbstractToXmlGregorianCalendar { private final Parameter parameter; private final Set<Type> importTypes; public JodaLocalTimeToXmlGregorianCalendar(TypeFactory typeFactory) { super( typeFactory ); this.parameter = new Parameter( "dt", typeFactory.getType( JodaTimeConstants.LOCAL_TIME_FQN ) ); this.importTypes = asSet( parameter.getType(), typeFactory.getType( XmlConstants.JAVAX_XML_DATATYPE_CONSTANTS ) ); } @Override public Set<Type> getImportTypes() {<FILL_FUNCTION_BODY>} @Override public Parameter getParameter() { return parameter; } }
Set<Type> result = super.getImportTypes(); result.addAll( importTypes ); return result;
211
32
243
/** * @author Sjaak Derksen */ public abstract class AbstractToXmlGregorianCalendar extends BuiltInMethod { private final Type returnType; private final Set<Type> importTypes; private final Type dataTypeFactoryType; public AbstractToXmlGregorianCalendar( TypeFactory typeFactory); @Override public Set<Type> getImportTypes(); @Override public Type getReturnType(); @Override public FieldReference getFieldReference(); @Override public ConstructorFragment getConstructorFragment(); }
Kong_unirest-java
unirest-java/unirest/src/main/java/kong/unirest/core/Path.java
Path
baseUrl
class Path { private String url; private String rawPath; Path(String url, String defaultBasePath) { if(defaultBasePath != null && url != null && !url.toLowerCase().startsWith("http")){ String full = defaultBasePath + url; this.url = full; this.rawPath = full; } else { this.url = url; this.rawPath = url; } } public Path(String url) { this(url, null); } public void param(Map<String, Object> params) { params.forEach((key, value) -> param(key, String.valueOf(value))); } public void param(String name, String value) { Matcher matcher = Pattern.compile("\\{" + name + "\\}").matcher(url); if (!matcher.find()) { throw new UnirestException("Can't find route parameter name \"" + name + "\""); } this.url = matcher.replaceAll(encodePath(value)); } private String encodePath(String value) { if(value == null){ return ""; } return Util.encode(value).replaceAll("\\+", "%20"); } public void queryString(String name, Collection<?> value){ for (Object cur : value) { queryString(name, cur); } } public void queryString(String name, Object value) { StringBuilder queryString = new StringBuilder(); if (url.contains("?")) { queryString.append("&"); } else { queryString.append("?"); } try { queryString.append(URLEncoder.encode(name, "UTF-8")); if(value != null) { queryString.append("=").append(URLEncoder.encode(String.valueOf(value), "UTF-8")); } } catch (UnsupportedEncodingException e) { throw new UnirestException(e); } url += queryString.toString(); } public void queryString(Map<String, Object> parameters) { if (parameters != null) { for (Map.Entry<String, Object> param : parameters.entrySet()) { queryString(param.getKey(), param.getValue()); } } } @Override public String toString() { return escape(url); } private String escape(String string) { return string.replaceAll(" ", "%20").replaceAll("\t", "%09"); } public String rawPath() { return rawPath; } public String baseUrl() {<FILL_FUNCTION_BODY>} public String getQueryString(){ return url.substring(url.indexOf("?")+1); } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } Path path = (Path) o; return Objects.equals(url, path.url); } @Override public int hashCode() { return Objects.hash(url); } }
if(url != null && url.contains("?")){ return url.substring(0, url.indexOf("?")); } return url;
840
42
882
docker-java_docker-java
docker-java/docker-java-api/src/main/java/com/github/dockerjava/api/model/VolumeRW.java
VolumeRW
fromPrimitive
class VolumeRW implements Serializable { private static final long serialVersionUID = 1L; private Volume volume; private AccessMode accessMode = AccessMode.rw; public VolumeRW(Volume volume) { this.volume = volume; } public VolumeRW(Volume volume, AccessMode accessMode) { this.volume = volume; this.accessMode = accessMode; } public Volume getVolume() { return volume; } public AccessMode getAccessMode() { return accessMode; } /** * Returns a string representation of this {@link VolumeRW} suitable for inclusion in a JSON message. The returned String is simply the * container path, {@link #getPath()}. * * @return a string representation of this {@link VolumeRW} */ @Override public String toString() { return getVolume() + ":" + getAccessMode(); } @JsonCreator public static VolumeRW fromPrimitive(Map<String, Boolean> map) {<FILL_FUNCTION_BODY>} @JsonValue public Map<String, Boolean> toPrimitive() { return Collections.singletonMap(volume.getPath(), accessMode.toBoolean()); } }
Entry<String, Boolean> entry = map.entrySet().iterator().next(); return new VolumeRW(new Volume(entry.getKey()), AccessMode.fromBoolean(entry.getValue()));
324
48
372
mapstruct_mapstruct
mapstruct/processor/src/main/java/org/mapstruct/ap/internal/util/Nouns.java
Nouns
singularize
class Nouns { private Nouns() { } private static final List<ReplaceRule> SINGULAR_RULES = Arrays.asList( new ReplaceRule( "(equipment|information|rice|money|species|series|fish|sheep)$", "$1" ), new ReplaceRule( "(f)eet$", "$1oot" ), new ReplaceRule( "(t)eeth$", "$1ooth" ), new ReplaceRule( "(g)eese$", "$1oose" ), new ReplaceRule( "(s)tadiums$", "$1tadium" ), new ReplaceRule( "(m)oves$", "$1ove" ), new ReplaceRule( "(s)exes$", "$1ex" ), new ReplaceRule( "(c)hildren$", "$1hild" ), new ReplaceRule( "(m)en$", "$1an" ), new ReplaceRule( "(p)eople$", "$1erson" ), new ReplaceRule( "(quiz)zes$", "$1" ), new ReplaceRule( "(matr)ices$", "$1ix" ), new ReplaceRule( "(vert|ind)ices$", "$1ex" ), new ReplaceRule( "^(ox)en", "$1" ), new ReplaceRule( "(alias|status)$", "$1" ), // already singular, but ends in 's' new ReplaceRule( "(alias|status)es$", "$1" ), new ReplaceRule( "(octop|vir)us$", "$1us" ), // already singular, but ends in 's' new ReplaceRule( "(octop|vir)i$", "$1us" ), new ReplaceRule( "(cris|ax|test)es$", "$1is" ), new ReplaceRule( "(cris|ax|test)is$", "$1is" ), // already singular, but ends in 's' new ReplaceRule( "(shoe)s$", "$1" ), new ReplaceRule( "(o)es$", "$1" ), new ReplaceRule( "(bus)es$", "$1" ), new ReplaceRule( "([m|l])ice$", "$1ouse" ), new ReplaceRule( "(x|ch|ss|sh)es$", "$1" ), new ReplaceRule( "(m)ovies$", "$1ovie" ), new ReplaceRule( "(s)eries$", "$1eries" ), new ReplaceRule( "([^aeiouy]|qu)ies$", "$1y" ), new ReplaceRule( "([lr])ves$", "$1f" ), new ReplaceRule( "(tive)s$", "$1" ), new ReplaceRule( "(hive)s$", "$1" ), new ReplaceRule( "([^f])ves$", "$1fe" ), new ReplaceRule( "(^analy)sis$", "$1sis" ), // already singular, but ends in 's' new ReplaceRule( "(^analy)ses$", "$1sis" ), new ReplaceRule( "((a)naly|(b)a|(d)iagno|(p)arenthe|(p)rogno|(s)ynop|(t)he)ses$", "$1$2sis" ), new ReplaceRule( "([ti])a$", "$1um" ), new ReplaceRule( "(n)ews$", "$1ews" ), new ReplaceRule( "(s|si|u)s$", "$1s" ), // '-us' and '-ss' are already singular new ReplaceRule( "s$", "" ) ); /** * Replacement rules based on the routine applied by the <a href="http://www.eclipse.org/webtools/dali/">Dali</a> * project. Applied as a fallback if the other rules didn't yield a match. */ private static final List<ReplaceRule> SINGULAR_DALI_RULES = Arrays.asList( new ReplaceRule( "(us|ss)$", "$1" ), new ReplaceRule( "(ch|s)es$", "$1" ), new ReplaceRule( "([^aeiouy])ies$", "$1y" ) ); /** * Converts given pluralized noun into the singular form. If no singular form could be determined, the given word * itself is returned. * * @param plural plural word * @return singular form, if available */ public static String singularize(String plural) {<FILL_FUNCTION_BODY>} private static final class ReplaceRule { private final String regexp; private final String replacement; private final Pattern pattern; private ReplaceRule(String regexp, String replacement) { this.regexp = regexp; this.replacement = replacement; this.pattern = Pattern.compile( this.regexp, Pattern.CASE_INSENSITIVE ); } private String apply(String input) { String result = null; Matcher matcher = this.pattern.matcher( input ); if ( matcher.find() ) { result = matcher.replaceAll( this.replacement ); } return result; } @Override public String toString() { return "'" + regexp + "' -> '" + replacement; } } }
for ( ReplaceRule replaceRule : SINGULAR_RULES ) { String match = replaceRule.apply( plural ); if ( match != null ) { return match; } } for ( ReplaceRule replaceRule : SINGULAR_DALI_RULES ) { String match = replaceRule.apply( plural ); if ( match != null ) { return match; } } return plural;
1,440
120
1,560
logfellow_logstash-logback-encoder
logstash-logback-encoder/src/main/java/net/logstash/logback/pattern/EnhancedPropertyConverter.java
EnhancedPropertyConverter
start
class EnhancedPropertyConverter extends ClassicConverter { /** * Regex pattern used to extract the optional default value from the key name (split * at the first :-). */ private static final Pattern PATTERN = Pattern.compile("(.+?):-(.*)"); /** * The property name. */ private String propertyName; /** * The default value to use when the property is not defined. */ private String defaultValue = ""; public void start() {<FILL_FUNCTION_BODY>} @Override public String convert(ILoggingEvent event) { LoggerContextVO lcvo = event.getLoggerContextVO(); Map<String, String> map = lcvo.getPropertyMap(); String val = map.get(propertyName); if (val == null) { val = System.getProperty(propertyName); } if (val == null) { val = defaultValue; } return val; } }
String optStr = getFirstOption(); if (optStr != null) { propertyName = optStr; super.start(); } if (propertyName == null) { throw new IllegalStateException("Property name is not specified"); } Matcher matcher = PATTERN.matcher(propertyName); if (matcher.matches()) { propertyName = matcher.group(1); defaultValue = matcher.group(2); }
266
125
391
houbb_sensitive-word
sensitive-word/src/main/java/com/github/houbb/sensitive/word/support/check/WordCheckWord.java
WordCheckWord
getActualLength
class WordCheckWord extends AbstractWordCheck { /** * @since 0.3.0 */ private static final IWordCheck INSTANCE = new WordCheckWord(); public static IWordCheck getInstance() { return INSTANCE; } @Override protected Class<? extends IWordCheck> getSensitiveCheckClass() { return WordCheckWord.class; } @Override protected int getActualLength(int beginIndex, InnerSensitiveWordContext innerContext) {<FILL_FUNCTION_BODY>} @Override protected String getType() { return WordTypeEnum.WORD.getCode(); } }
final String txt = innerContext.originalText(); final Map<Character, Character> formatCharMapping = innerContext.formatCharMapping(); final WordValidModeEnum wordValidModeEnum = innerContext.modeEnum(); final IWordContext context = innerContext.wordContext(); // 采用 ThreadLocal 应该可以提升性能,减少对象的创建。 int actualLength = 0; final IWordData wordData = context.wordData(); // 前一个条件 StringBuilder stringBuilder = new StringBuilder(); char[] rawChars = txt.toCharArray(); final ISensitiveWordCharIgnore wordCharIgnore = context.charIgnore(); int tempLen = 0; for(int i = beginIndex; i < rawChars.length; i++) { // 判断是否跳过? if(wordCharIgnore.ignore(i, rawChars, innerContext)) { tempLen++; continue; } // 映射处理 final char currentChar = rawChars[i]; char mappingChar = formatCharMapping.get(currentChar); stringBuilder.append(mappingChar); tempLen++; // 判断是否存在 WordContainsTypeEnum wordContainsTypeEnum = wordData.contains(stringBuilder, innerContext); if(WordContainsTypeEnum.CONTAINS_END.equals(wordContainsTypeEnum)) { actualLength = tempLen; // 是否遍历全部匹配的模式 if(WordValidModeEnum.FAIL_FAST.equals(wordValidModeEnum)) { break; } } // 如果不包含,则直接返回。后续遍历无意义 if(WordContainsTypeEnum.NOT_FOUND.equals(wordContainsTypeEnum)) { break; } } return actualLength;
172
449
621
/** * 抽象实现策略 * @author binbin.hou * @since 0.4.0 */ @ThreadSafe public abstract class AbstractWordCheck implements IWordCheck { /** * 获取校验类 * @return 类 * @since 0.3.2 */ protected abstract Class<? extends IWordCheck> getSensitiveCheckClass(); /** * 获取确切的长度 * @param beginIndex 开始 * @param checkContext 上下文 * @return 长度 * @since 0.4.0 */ protected abstract int getActualLength( int beginIndex, final InnerSensitiveWordContext checkContext); /** * 获取类别 * @return 类别 * @since 0.14.0 */ protected abstract String getType(); @Override public WordCheckResult sensitiveCheck( int beginIndex, final InnerSensitiveWordContext checkContext); }
docker-java_docker-java
docker-java/docker-java-api/src/main/java/com/github/dockerjava/api/model/VolumeBinds.java
VolumeBinds
fromPrimitive
class VolumeBinds implements Serializable { private static final long serialVersionUID = 1L; private final VolumeBind[] binds; public VolumeBinds(VolumeBind... binds) { this.binds = binds; } public VolumeBind[] getBinds() { return binds; } @JsonCreator public static VolumeBinds fromPrimitive(Map<String, String> primitive) {<FILL_FUNCTION_BODY>} @JsonValue public Map<String, String> toPrimitive() { return Stream.of(binds).collect(Collectors.toMap( VolumeBind::getContainerPath, VolumeBind::getHostPath )); } }
return new VolumeBinds( primitive.entrySet().stream() .map(it -> new VolumeBind(it.getValue(), it.getKey())) .toArray(VolumeBind[]::new) );
186
56
242
subhra74_snowflake
snowflake/muon-app/src/main/java/util/FormatUtils.java
FormatUtils
humanReadableByteCount
class FormatUtils { public static String humanReadableByteCount(long bytes, boolean si) {<FILL_FUNCTION_BODY>} public static final String formatDate(LocalDateTime dateTime) { return dateTime.format(DateTimeFormatter.ofPattern("MM/dd/yyyy hh:mm a")); } }
int unit = si ? 1000 : 1024; if (bytes < unit) return bytes + " B"; int exp = (int) (Math.log(bytes) / Math.log(unit)); String pre = (si ? "kMGTPE" : "KMGTPE").charAt(exp - 1) + (si ? "" : "i"); return String.format("%.1f %s", bytes / Math.pow(unit, exp), pre);
89
133
222
zhkl0228_unidbg
unidbg/unidbg-android/src/main/java/com/github/unidbg/linux/struct/IFReq.java
IFReq
setName
class IFReq extends UnidbgStructure { static final int IFNAMSIZ = 16; public static IFReq createIFReq(Emulator<?> emulator, Pointer pointer) { return emulator.is64Bit() ? new IFReq64(pointer) : new IFReq32(pointer); } IFReq(Pointer p) { super(p); } public Pointer getAddrPointer() { return getPointer().share(IFNAMSIZ); } public void setName(String name) {<FILL_FUNCTION_BODY>} public byte[] ifrn_name = new byte[IFNAMSIZ]; }
byte[] data = name.getBytes(StandardCharsets.UTF_8); if (data.length >= IFNAMSIZ) { throw new IllegalStateException("name=" + name); } ifrn_name = Arrays.copyOf(data, IFNAMSIZ);
182
75
257
public abstract class UnidbgStructure extends Structure implements PointerArg { /** * Placeholder pointer to help avoid auto-allocation of memory where a Structure needs a valid pointer but want to avoid actually reading from it. */ private static final Pointer PLACEHOLDER_MEMORY=new UnidbgPointer(null,null){ @Override public UnidbgPointer share( long offset, long sz); } ; public static int calculateSize( Class<? extends UnidbgStructure> type); private static class ByteArrayPointer extends UnidbgPointer { private final Emulator<?> emulator; private final byte[] data; public ByteArrayPointer( Emulator<?> emulator, byte[] data); @Override public UnidbgPointer share( long offset, long sz); } protected UnidbgStructure( Emulator<?> emulator, byte[] data); protected UnidbgStructure( byte[] data); protected UnidbgStructure( Pointer p); private void checkPointer( Pointer p); @Override protected int getNativeSize( Class<?> nativeType, Object value); @Override protected int getNativeAlignment( Class<?> type, Object value, boolean isFirstElement); private boolean isPlaceholderMemory( Pointer p); public void pack(); public void unpack(); /** * @param debug If true, will include a native memory dump of theStructure's backing memory. * @return String representation of this object. */ public String toString( boolean debug); private String format( Class<?> type); private String toString( int indent, boolean showContents, boolean dumpMemory); /** * Obtain the value currently in the Java field. Does not read from native memory. * @param field field to look up * @return current field value (Java-side only) */ private Object getFieldValue( Field field); private static final Field FIELD_STRUCT_FIELDS; static { try { FIELD_STRUCT_FIELDS=Structure.class.getDeclaredField("structFields"); FIELD_STRUCT_FIELDS.setAccessible(true); } catch ( NoSuchFieldException e) { throw new IllegalStateException(e); } } /** * Return all fields in this structure (ordered). This represents the layout of the structure, and will be shared among Structures of the same class except when the Structure can have a variable size. NOTE: {@link #ensureAllocated()} <em>must</em> be called prior tocalling this method. * @return {@link Map} of field names to field representations. */ @SuppressWarnings("unchecked") private Map<String,StructField> fields(); }
subhra74_snowflake
snowflake/muon-app/src/main/java/util/FontUtils.java
FontUtils
loadTerminalFont
class FontUtils { public static final Map<String, String> TERMINAL_FONTS = new CollectionHelper.OrderedDict<String, String>() .putItem("DejaVuSansMono", "DejaVu Sans Mono").putItem("FiraCode-Regular", "Fira Code Regular") .putItem("Inconsolata-Regular", "Inconsolata Regular").putItem("NotoMono-Regular", "Noto Mono"); public static Font loadFont(String path) { try (InputStream is = AppSkin.class.getResourceAsStream(path)) { Font font = Font.createFont(Font.TRUETYPE_FONT, is); GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment(); ge.registerFont(font); System.out.println("Font loaded: " + font.getFontName() + " of family: " + font.getFamily()); return font.deriveFont(Font.PLAIN, 12.0f); } catch (Exception e) { e.printStackTrace(); } return null; } public static Font loadTerminalFont(String name) {<FILL_FUNCTION_BODY>} }
System.out.println("Loading font: "+name); try (InputStream is = AppSkin.class.getResourceAsStream(String.format("/fonts/terminal/%s.ttf", name))) { Font font = Font.createFont(Font.TRUETYPE_FONT, is); GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment(); ge.registerFont(font); System.out.println("Font loaded: " + font.getFontName() + " of family: " + font.getFamily()); return font.deriveFont(Font.PLAIN, 12.0f); } catch (Exception e) { e.printStackTrace(); } return null;
329
194
523
pmd_pmd
pmd/pmd-velocity/src/main/java/net/sourceforge/pmd/lang/velocity/rule/bestpractices/UnusedMacroParameterRule.java
UnusedMacroParameterRule
formatNameVariations
class UnusedMacroParameterRule extends AbstractVtlRule { @Override public Object visit(final ASTDirective node, final Object data) { if ("macro".equals(node.getDirectiveName())) { final Set<String> paramNames = new HashSet<>(); for (final ASTReference param : node.children(ASTReference.class)) { paramNames.add(param.literal()); } final ASTBlock macroBlock = node.firstChild(ASTBlock.class); if (macroBlock != null) { for (final ASTReference referenceInMacro : macroBlock.descendants(ASTReference.class)) { checkForParameter(paramNames, referenceInMacro.literal()); } for (final ASTStringLiteral literalInMacro : macroBlock.descendants(ASTStringLiteral.class)) { final String text = literalInMacro.literal(); checkForParameter(paramNames, text); } } if (!paramNames.isEmpty()) { asCtx(data).addViolation(node, paramNames.toString()); } } return super.visit(node, data); } private void checkForParameter(final Set<String> paramNames, final String nameToSearch) { final Set<String> paramsContained = new HashSet<>(); for (final String param : paramNames) { if (containsAny(nameToSearch, formatNameVariations(param))) { paramsContained.add(param); } } paramNames.removeAll(paramsContained); } private boolean containsAny(final String text, final String[] formatNameVariations) { for (final String formattedName : formatNameVariations) { if (text.contains(formattedName)) { return true; } } return false; } private String[] formatNameVariations(final String param) {<FILL_FUNCTION_BODY>} }
final String actualName = param.substring(1); return new String[] { param, "${" + actualName + "}", "${" + actualName + ".", "$!" + actualName, "$!{" + actualName + ".", "$!{" + actualName + "}", };
491
76
567
jeecgboot_jeecg-boot
jeecg-boot/jeecg-boot-base-core/src/main/java/org/jeecg/config/sign/util/SignUtil.java
SignUtil
getParamsSign
class SignUtil { public static final String X_PATH_VARIABLE = "x-path-variable"; /** * @param params * 所有的请求参数都会在这里进行排序加密 * @return 验证签名结果 */ public static boolean verifySign(SortedMap<String, String> params,String headerSign) { if (params == null || StringUtils.isEmpty(headerSign)) { return false; } // 把参数加密 String paramsSign = getParamsSign(params); log.info("Param Sign : {}", paramsSign); return !StringUtils.isEmpty(paramsSign) && headerSign.equals(paramsSign); } /** * @param params * 所有的请求参数都会在这里进行排序加密 * @return 得到签名 */ public static String getParamsSign(SortedMap<String, String> params) {<FILL_FUNCTION_BODY>} }
//去掉 Url 里的时间戳 params.remove("_t"); String paramsJsonStr = JSONObject.toJSONString(params); log.info("Param paramsJsonStr : {}", paramsJsonStr); //设置签名秘钥 JeecgBaseConfig jeecgBaseConfig = SpringContextUtils.getBean(JeecgBaseConfig.class); String signatureSecret = jeecgBaseConfig.getSignatureSecret(); String curlyBracket = SymbolConstant.DOLLAR + SymbolConstant.LEFT_CURLY_BRACKET; if(oConvertUtils.isEmpty(signatureSecret) || signatureSecret.contains(curlyBracket)){ throw new JeecgBootException("签名密钥 ${jeecg.signatureSecret} 缺少配置 !!"); } try { //【issues/I484RW】2.4.6部署后,下拉搜索框提示“sign签名检验失败” return DigestUtils.md5DigestAsHex((paramsJsonStr + signatureSecret).getBytes("UTF-8")).toUpperCase(); } catch (UnsupportedEncodingException e) { log.error(e.getMessage(),e); return null; }
242
303
545
jeecgboot_jeecg-boot
jeecg-boot/jeecg-module-system/jeecg-system-biz/src/main/java/org/jeecg/modules/quartz/job/SampleParamJob.java
SampleParamJob
execute
class SampleParamJob implements Job { /** * 若参数变量名修改 QuartzJobController中也需对应修改 */ private String parameter; public void setParameter(String parameter) { this.parameter = parameter; } @Override public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {<FILL_FUNCTION_BODY>} }
log.info(" Job Execution key:"+jobExecutionContext.getJobDetail().getKey()); log.info( String.format("welcome %s! Jeecg-Boot 带参数定时任务 SampleParamJob ! 时间:" + DateUtils.now(), this.parameter));
97
74
171
graphhopper_graphhopper
graphhopper/core/src/main/java/com/graphhopper/routing/util/parsers/CarAccessParser.java
CarAccessParser
handleWayTags
class CarAccessParser extends AbstractAccessParser implements TagParser { protected final Set<String> trackTypeValues = new HashSet<>(); protected final Set<String> highwayValues = new HashSet<>(); protected final BooleanEncodedValue roundaboutEnc; public CarAccessParser(EncodedValueLookup lookup, PMap properties) { this( lookup.getBooleanEncodedValue(VehicleAccess.key("car")), lookup.getBooleanEncodedValue(Roundabout.KEY), properties, TransportationMode.CAR ); } public CarAccessParser(BooleanEncodedValue accessEnc, BooleanEncodedValue roundaboutEnc, PMap properties, TransportationMode transportationMode) { super(accessEnc, transportationMode); this.roundaboutEnc = roundaboutEnc; restrictedValues.add("agricultural"); restrictedValues.add("forestry"); restrictedValues.add("delivery"); blockPrivate(properties.getBool("block_private", true)); blockFords(properties.getBool("block_fords", false)); intendedValues.add("yes"); intendedValues.add("designated"); intendedValues.add("permissive"); barriers.add("kissing_gate"); barriers.add("fence"); barriers.add("bollard"); barriers.add("stile"); barriers.add("turnstile"); barriers.add("cycle_barrier"); barriers.add("motorcycle_barrier"); barriers.add("block"); barriers.add("bus_trap"); barriers.add("sump_buster"); barriers.add("jersey_barrier"); highwayValues.addAll(Arrays.asList("motorway", "motorway_link", "trunk", "trunk_link", "primary", "primary_link", "secondary", "secondary_link", "tertiary", "tertiary_link", "unclassified", "residential", "living_street", "service", "road", "track")); trackTypeValues.addAll(Arrays.asList("grade1", "grade2", "grade3", null)); } public WayAccess getAccess(ReaderWay way) { // TODO: Ferries have conditionals, like opening hours or are closed during some time in the year String highwayValue = way.getTag("highway"); int firstIndex = way.getFirstIndex(restrictionKeys); String firstValue = firstIndex < 0 ? "" : way.getTag(restrictionKeys.get(firstIndex), ""); if (highwayValue == null) { if (FerrySpeedCalculator.isFerry(way)) { if (restrictedValues.contains(firstValue)) return WayAccess.CAN_SKIP; if (intendedValues.contains(firstValue) || // implied default is allowed only if foot and bicycle is not specified: firstValue.isEmpty() && !way.hasTag("foot") && !way.hasTag("bicycle") || // if hgv is allowed then smaller trucks and cars are allowed too way.hasTag("hgv", "yes")) return WayAccess.FERRY; } return WayAccess.CAN_SKIP; } if ("service".equals(highwayValue) && "emergency_access".equals(way.getTag("service"))) return WayAccess.CAN_SKIP; if ("track".equals(highwayValue) && !trackTypeValues.contains(way.getTag("tracktype"))) return WayAccess.CAN_SKIP; if (!highwayValues.contains(highwayValue)) return WayAccess.CAN_SKIP; if (way.hasTag("impassable", "yes") || way.hasTag("status", "impassable")) return WayAccess.CAN_SKIP; // multiple restrictions needs special handling if (firstIndex >= 0) { String[] restrict = firstValue.split(";"); for (String value : restrict) { if (restrictedValues.contains(value) && !hasTemporalRestriction(way, firstIndex, restrictionKeys)) return WayAccess.CAN_SKIP; if (intendedValues.contains(value)) return WayAccess.WAY; } } if (isBlockFords() && ("ford".equals(highwayValue) || way.hasTag("ford"))) return WayAccess.CAN_SKIP; return WayAccess.WAY; } @Override public void handleWayTags(int edgeId, EdgeIntAccess edgeIntAccess, ReaderWay way) {<FILL_FUNCTION_BODY>} /** * make sure that isOneway is called before */ protected boolean isBackwardOneway(ReaderWay way) { return way.hasTag("oneway", "-1") || way.hasTag("vehicle:forward", restrictedValues) || way.hasTag("motor_vehicle:forward", restrictedValues); } /** * make sure that isOneway is called before */ protected boolean isForwardOneway(ReaderWay way) { return !way.hasTag("oneway", "-1") && !way.hasTag("vehicle:forward", restrictedValues) && !way.hasTag("motor_vehicle:forward", restrictedValues); } protected boolean isOneway(ReaderWay way) { return way.hasTag("oneway", oneways) || way.hasTag("vehicle:backward", restrictedValues) || way.hasTag("vehicle:forward", restrictedValues) || way.hasTag("motor_vehicle:backward", restrictedValues) || way.hasTag("motor_vehicle:forward", restrictedValues); } }
WayAccess access = getAccess(way); if (access.canSkip()) return; if (!access.isFerry()) { boolean isRoundabout = roundaboutEnc.getBool(false, edgeId, edgeIntAccess); if (isOneway(way) || isRoundabout) { if (isForwardOneway(way)) accessEnc.setBool(false, edgeId, edgeIntAccess, true); if (isBackwardOneway(way)) accessEnc.setBool(true, edgeId, edgeIntAccess, true); } else { accessEnc.setBool(false, edgeId, edgeIntAccess, true); accessEnc.setBool(true, edgeId, edgeIntAccess, true); } } else { accessEnc.setBool(false, edgeId, edgeIntAccess, true); accessEnc.setBool(true, edgeId, edgeIntAccess, true); } if (way.hasTag("gh:barrier_edge")) { List<Map<String, Object>> nodeTags = way.getTag("node_tags", Collections.emptyList()); handleBarrierEdge(edgeId, edgeIntAccess, nodeTags.get(0)); }
1,450
305
1,755
public abstract class AbstractAccessParser implements TagParser { static final Collection<String> ONEWAYS=Arrays.asList("yes","true","1","-1"); static final Collection<String> INTENDED=Arrays.asList("yes","designated","official","permissive"); protected final List<String> restrictionKeys=new ArrayList<>(5); protected final Set<String> restrictedValues=new HashSet<>(5); protected final Set<String> intendedValues=new HashSet<>(INTENDED); protected final Set<String> oneways=new HashSet<>(ONEWAYS); protected final Set<String> barriers=new HashSet<>(5); protected final BooleanEncodedValue accessEnc; private boolean blockFords=true; protected AbstractAccessParser( BooleanEncodedValue accessEnc, TransportationMode transportationMode); public boolean isBlockFords(); protected void blockFords( boolean blockFords); protected void blockPrivate( boolean blockPrivate); protected void handleBarrierEdge( int edgeId, EdgeIntAccess edgeIntAccess, Map<String,Object> nodeTags); @Override public void handleWayTags( int edgeId, EdgeIntAccess edgeIntAccess, ReaderWay way, IntsRef relationFlags); public abstract void handleWayTags( int edgeId, EdgeIntAccess edgeIntAccess, ReaderWay way); /** * @return true if the given OSM node blocks access for the specified restrictions, false otherwise */ public boolean isBarrier( ReaderNode node); public final BooleanEncodedValue getAccessEnc(); public final List<String> getRestrictionKeys(); public final String getName(); @Override public String toString(); }
elunez_eladmin
eladmin/eladmin-tools/src/main/java/me/zhengjie/rest/AliPayController.java
AliPayController
returnPage
class AliPayController { private final AlipayUtils alipayUtils; private final AliPayService alipayService; @GetMapping public ResponseEntity<AlipayConfig> queryAliConfig() { return new ResponseEntity<>(alipayService.find(), HttpStatus.OK); } @Log("配置支付宝") @ApiOperation("配置支付宝") @PutMapping public ResponseEntity<Object> updateAliPayConfig(@Validated @RequestBody AlipayConfig alipayConfig) { alipayService.config(alipayConfig); return new ResponseEntity<>(HttpStatus.OK); } @Log("支付宝PC网页支付") @ApiOperation("PC网页支付") @PostMapping(value = "/toPayAsPC") public ResponseEntity<String> toPayAsPc(@Validated @RequestBody TradeVo trade) throws Exception { AlipayConfig aliPay = alipayService.find(); trade.setOutTradeNo(alipayUtils.getOrderCode()); String payUrl = alipayService.toPayAsPc(aliPay, trade); return ResponseEntity.ok(payUrl); } @Log("支付宝手机网页支付") @ApiOperation("手机网页支付") @PostMapping(value = "/toPayAsWeb") public ResponseEntity<String> toPayAsWeb(@Validated @RequestBody TradeVo trade) throws Exception { AlipayConfig alipay = alipayService.find(); trade.setOutTradeNo(alipayUtils.getOrderCode()); String payUrl = alipayService.toPayAsWeb(alipay, trade); return ResponseEntity.ok(payUrl); } @ApiIgnore @AnonymousGetMapping("/return") @ApiOperation("支付之后跳转的链接") public ResponseEntity<String> returnPage(HttpServletRequest request, HttpServletResponse response) {<FILL_FUNCTION_BODY>} @ApiIgnore @RequestMapping("/notify") @AnonymousAccess @ApiOperation("支付异步通知(要公网访问),接收异步通知,检查通知内容app_id、out_trade_no、total_amount是否与请求中的一致,根据trade_status进行后续业务处理") public ResponseEntity<Object> notify(HttpServletRequest request) { AlipayConfig alipay = alipayService.find(); Map<String, String[]> parameterMap = request.getParameterMap(); //内容验签,防止黑客篡改参数 if (alipayUtils.rsaCheck(request, alipay)) { //交易状态 String tradeStatus = new String(request.getParameter("trade_status").getBytes(StandardCharsets.ISO_8859_1), StandardCharsets.UTF_8); // 商户订单号 String outTradeNo = new String(request.getParameter("out_trade_no").getBytes(StandardCharsets.ISO_8859_1), StandardCharsets.UTF_8); //支付宝交易号 String tradeNo = new String(request.getParameter("trade_no").getBytes(StandardCharsets.ISO_8859_1), StandardCharsets.UTF_8); //付款金额 String totalAmount = new String(request.getParameter("total_amount").getBytes(StandardCharsets.ISO_8859_1), StandardCharsets.UTF_8); //验证 if (tradeStatus.equals(AliPayStatusEnum.SUCCESS.getValue()) || tradeStatus.equals(AliPayStatusEnum.FINISHED.getValue())) { // 验证通过后应该根据业务需要处理订单 } return new ResponseEntity<>(HttpStatus.OK); } return new ResponseEntity<>(HttpStatus.BAD_REQUEST); } }
AlipayConfig alipay = alipayService.find(); response.setContentType("text/html;charset=" + alipay.getCharset()); //内容验签,防止黑客篡改参数 if (alipayUtils.rsaCheck(request, alipay)) { //商户订单号 String outTradeNo = new String(request.getParameter("out_trade_no").getBytes(StandardCharsets.ISO_8859_1), StandardCharsets.UTF_8); //支付宝交易号 String tradeNo = new String(request.getParameter("trade_no").getBytes(StandardCharsets.ISO_8859_1), StandardCharsets.UTF_8); System.out.println("商户订单号" + outTradeNo + " " + "第三方交易号" + tradeNo); // 根据业务需要返回数据,这里统一返回OK return new ResponseEntity<>("payment successful", HttpStatus.OK); } else { // 根据业务需要返回数据 return new ResponseEntity<>(HttpStatus.BAD_REQUEST); }
962
286
1,248
houbb_sensitive-word
sensitive-word/src/main/java/com/github/houbb/sensitive/word/support/result/AbstractWordResultHandler.java
AbstractWordResultHandler
handle
class AbstractWordResultHandler<R> implements IWordResultHandler<R> { protected abstract R doHandle(IWordResult wordResult, IWordContext wordContext, String originalText); @Override public R handle(IWordResult wordResult, IWordContext wordContext, String originalText) {<FILL_FUNCTION_BODY>} }
if(wordResult == null) { return null; } return doHandle(wordResult, wordContext, originalText);
86
37
123
eirslett_frontend-maven-plugin
frontend-maven-plugin/frontend-maven-plugin/src/main/java/com/github/eirslett/maven/plugins/frontend/mojo/InstallNodeAndYarnMojo.java
InstallNodeAndYarnMojo
execute
class InstallNodeAndYarnMojo extends AbstractFrontendMojo { private static final String YARNRC_YAML_FILE_NAME = ".yarnrc.yml"; /** * Where to download Node.js binary from. Defaults to https://nodejs.org/dist/ */ @Parameter(property = "nodeDownloadRoot", required = false) private String nodeDownloadRoot; /** * Where to download Yarn binary from. Defaults to https://github.com/yarnpkg/yarn/releases/download/... */ @Parameter(property = "yarnDownloadRoot", required = false, defaultValue = YarnInstaller.DEFAULT_YARN_DOWNLOAD_ROOT) private String yarnDownloadRoot; /** * The version of Node.js to install. IMPORTANT! Most Node.js version names start with 'v', for example * 'v0.10.18' */ @Parameter(property = "nodeVersion", required = true) private String nodeVersion; /** * The version of Yarn to install. IMPORTANT! Most Yarn names start with 'v', for example 'v0.15.0'. */ @Parameter(property = "yarnVersion", required = true) private String yarnVersion; /** * Server Id for download username and password */ @Parameter(property = "serverId", defaultValue = "") private String serverId; @Parameter(property = "session", defaultValue = "${session}", readonly = true) private MavenSession session; /** * Skips execution of this mojo. */ @Parameter(property = "skip.installyarn", alias = "skip.installyarn", defaultValue = "${skip.installyarn}") private boolean skip; @Component(role = SettingsDecrypter.class) private SettingsDecrypter decrypter; @Override protected boolean skipExecution() { return this.skip; } /** * Checks whether a .yarnrc.yml file exists at the project root (in multi-module builds, it will be the Reactor project) * * @return true if the .yarnrc.yml file exists, false otherwise */ private boolean isYarnrcYamlFilePresent() { Stream<File> filesToCheck = Stream.of( new File(session.getCurrentProject().getBasedir(), YARNRC_YAML_FILE_NAME), new File(session.getRequest().getMultiModuleProjectDirectory(), YARNRC_YAML_FILE_NAME), new File(session.getExecutionRootDirectory(), YARNRC_YAML_FILE_NAME) ); return filesToCheck .anyMatch(File::exists); } @Override public void execute(FrontendPluginFactory factory) throws InstallationException {<FILL_FUNCTION_BODY>} }
ProxyConfig proxyConfig = MojoUtils.getProxyConfig(this.session, this.decrypter); Server server = MojoUtils.decryptServer(this.serverId, this.session, this.decrypter); if (null != server) { factory.getNodeInstaller(proxyConfig).setNodeDownloadRoot(this.nodeDownloadRoot) .setNodeVersion(this.nodeVersion).setPassword(server.getPassword()) .setUserName(server.getUsername()).install(); factory.getYarnInstaller(proxyConfig).setYarnDownloadRoot(this.yarnDownloadRoot) .setYarnVersion(this.yarnVersion).setUserName(server.getUsername()) .setPassword(server.getPassword()).setIsYarnBerry(isYarnrcYamlFilePresent()).install(); } else { factory.getNodeInstaller(proxyConfig).setNodeDownloadRoot(this.nodeDownloadRoot) .setNodeVersion(this.nodeVersion).install(); factory.getYarnInstaller(proxyConfig).setYarnDownloadRoot(this.yarnDownloadRoot) .setYarnVersion(this.yarnVersion).setIsYarnBerry(isYarnrcYamlFilePresent()).install(); }
741
309
1,050
public abstract class AbstractFrontendMojo extends AbstractMojo { @Component protected MojoExecution execution; /** * Whether you should skip while running in the test phase (default is false) */ @Parameter(property="skipTests",required=false,defaultValue="false") protected Boolean skipTests; /** * Set this to true to ignore a failure during testing. Its use is NOT RECOMMENDED, but quite convenient on occasion. * @since 1.4 */ @Parameter(property="maven.test.failure.ignore",defaultValue="false") protected boolean testFailureIgnore; /** * The base directory for running all Node commands. (Usually the directory that contains package.json) */ @Parameter(defaultValue="${basedir}",property="workingDirectory",required=false) protected File workingDirectory; /** * The base directory for installing node and npm. */ @Parameter(property="installDirectory",required=false) protected File installDirectory; /** * Additional environment variables to pass to the build. */ @Parameter protected Map<String,String> environmentVariables; @Parameter(defaultValue="${project}",readonly=true) private MavenProject project; @Parameter(defaultValue="${repositorySystemSession}",readonly=true) private RepositorySystemSession repositorySystemSession; /** * Determines if this execution should be skipped. */ private boolean skipTestPhase(); /** * Determines if the current execution is during a testing phase (e.g., "test" or "integration-test"). */ private boolean isTestingPhase(); protected abstract void execute( FrontendPluginFactory factory) throws FrontendException ; /** * Implemented by children to determine if this execution should be skipped. */ protected abstract boolean skipExecution(); @Override public void execute() throws MojoFailureException; }
YunaiV_ruoyi-vue-pro
ruoyi-vue-pro/yudao-module-system/yudao-module-system-biz/src/main/java/cn/iocoder/yudao/module/system/service/mail/MailLogServiceImpl.java
MailLogServiceImpl
updateMailSendResult
class MailLogServiceImpl implements MailLogService { @Resource private MailLogMapper mailLogMapper; @Override public PageResult<MailLogDO> getMailLogPage(MailLogPageReqVO pageVO) { return mailLogMapper.selectPage(pageVO); } @Override public MailLogDO getMailLog(Long id) { return mailLogMapper.selectById(id); } @Override public Long createMailLog(Long userId, Integer userType, String toMail, MailAccountDO account, MailTemplateDO template, String templateContent, Map<String, Object> templateParams, Boolean isSend) { MailLogDO.MailLogDOBuilder logDOBuilder = MailLogDO.builder(); // 根据是否要发送,设置状态 logDOBuilder.sendStatus(Objects.equals(isSend, true) ? MailSendStatusEnum.INIT.getStatus() : MailSendStatusEnum.IGNORE.getStatus()) // 用户信息 .userId(userId).userType(userType).toMail(toMail) .accountId(account.getId()).fromMail(account.getMail()) // 模板相关字段 .templateId(template.getId()).templateCode(template.getCode()).templateNickname(template.getNickname()) .templateTitle(template.getTitle()).templateContent(templateContent).templateParams(templateParams); // 插入数据库 MailLogDO logDO = logDOBuilder.build(); mailLogMapper.insert(logDO); return logDO.getId(); } @Override public void updateMailSendResult(Long logId, String messageId, Exception exception) {<FILL_FUNCTION_BODY>} }
// 1. 成功 if (exception == null) { mailLogMapper.updateById(new MailLogDO().setId(logId).setSendTime(LocalDateTime.now()) .setSendStatus(MailSendStatusEnum.SUCCESS.getStatus()).setSendMessageId(messageId)); return; } // 2. 失败 mailLogMapper.updateById(new MailLogDO().setId(logId).setSendTime(LocalDateTime.now()) .setSendStatus(MailSendStatusEnum.FAILURE.getStatus()).setSendException(getRootCauseMessage(exception)));
433
152
585
mapstruct_mapstruct
mapstruct/processor/src/main/java/org/mapstruct/ap/spi/ImmutablesAccessorNamingStrategy.java
ImmutablesAccessorNamingStrategy
isFluentSetter
class ImmutablesAccessorNamingStrategy extends DefaultAccessorNamingStrategy { @Override protected boolean isFluentSetter(ExecutableElement method) {<FILL_FUNCTION_BODY>} private boolean isPutterWithUpperCase4thCharacter(ExecutableElement method) { return isPutterMethod( method ) && Character.isUpperCase( method.getSimpleName().toString().charAt( 3 ) ); } public boolean isPutterMethod(ExecutableElement method) { String methodName = method.getSimpleName().toString(); return methodName.startsWith( "put" ) && methodName.length() > 3; } }
return super.isFluentSetter( method ) && !method.getSimpleName().toString().equals( "from" ) && !isPutterWithUpperCase4thCharacter( method );
169
52
221
/** * The default JavaBeans-compliant implementation of the {@link AccessorNamingStrategy} service provider interface. * @author Christian Schuster, Sjaak Derken */ public class DefaultAccessorNamingStrategy implements AccessorNamingStrategy { private static final Pattern JAVA_JAVAX_PACKAGE=Pattern.compile("^javax?\\..*"); protected Elements elementUtils; protected Types typeUtils; @Override public void init( MapStructProcessingEnvironment processingEnvironment); @Override public MethodType getMethodType( ExecutableElement method); /** * Returns {@code true} when the {@link ExecutableElement} is a getter method. A method is a getter when ithas no parameters, starts with 'get' and the return type is any type other than {@code void}, OR the getter starts with 'is' and the type returned is a primitive or the wrapper for {@code boolean}. NOTE: the latter does strictly not comply to the bean convention. The remainder of the name is supposed to reflect the property name. <p> The calling MapStruct code guarantees that the given method has no arguments. * @param method to be analyzed * @return {@code true} when the method is a getter. */ public boolean isGetterMethod( ExecutableElement method); /** * Returns {@code true} when the {@link ExecutableElement} is a setter method. A setter starts with 'set'. Theremainder of the name is supposed to reflect the property name. <p> The calling MapStruct code guarantees that there's only one argument. * @param method to be analyzed * @return {@code true} when the method is a setter. */ public boolean isSetterMethod( ExecutableElement method); protected boolean isFluentSetter( ExecutableElement method); /** * Checks that the method is an adder with an upper case 4th character. The reason for this is that methods such as {@code address(String address)} are considered as setter and {@code addName(String name)} too. We need tomake sure that {@code addName} is considered as an adder and {@code address} is considered as a setter. * @param method the method that needs to be checked * @return {@code true} if the method is an adder with an upper case 4h character, {@code false} otherwise */ private boolean isAdderWithUpperCase4thCharacter( ExecutableElement method); /** * Returns {@code true} when the {@link ExecutableElement} is an adder method. An adder method starts with 'add'.The remainder of the name is supposed to reflect the <em>singular</em> property name (as opposed to plural) of its corresponding property. For example: property "children", but "addChild". See also {@link #getElementName(ExecutableElement) }. <p> The calling MapStruct code guarantees there's only one argument. <p> * @param method to be analyzed * @return {@code true} when the method is an adder method. */ public boolean isAdderMethod( ExecutableElement method); /** * Returns {@code true} when the {@link ExecutableElement} is a <em>presence check</em> method that checks if thecorresponding property is present (e.g. not null, not nil, ..). A presence check method method starts with 'has'. The remainder of the name is supposed to reflect the property name. <p> The calling MapStruct code guarantees there's no argument and that the return type is boolean or a {@link Boolean} * @param method to be analyzed * @return {@code true} when the method is a presence check method. */ public boolean isPresenceCheckMethod( ExecutableElement method); /** * Analyzes the method (getter or setter) and derives the property name. See {@link #isGetterMethod(ExecutableElement)} {@link #isSetterMethod(ExecutableElement)}. The first three ('get' / 'set' scenario) characters are removed from the simple name, or the first 2 characters ('is' scenario). From the remainder the first character is made into small case (to counter camel casing) and the result forms the property name. * @param getterOrSetterMethod getter or setter method. * @return the property name. */ @Override public String getPropertyName( ExecutableElement getterOrSetterMethod); /** * Adder methods are used to add elements to collections on a target bean. A typical use case is JPA. The convention is that the element name will be equal to the remainder of the add method. Example: 'addElement' element name will be 'element'. * @param adderMethod getter or setter method. * @return the property name. */ @Override public String getElementName( ExecutableElement adderMethod); /** * Helper method, to obtain the fully qualified name of a type. * @param type input type * @return fully qualified name of type when the type is a {@link DeclaredType}, null when otherwise. */ protected static String getQualifiedName( TypeMirror type); @Override public String getCollectionGetterName( String property); }
docker-java_docker-java
docker-java/docker-java-core/src/main/java/com/github/dockerjava/core/exec/VersionCmdExec.java
VersionCmdExec
execute
class VersionCmdExec extends AbstrSyncDockerCmdExec<VersionCmd, Version> implements VersionCmd.Exec { private static final Logger LOGGER = LoggerFactory.getLogger(VersionCmdExec.class); public VersionCmdExec(WebTarget baseResource, DockerClientConfig dockerClientConfig) { super(baseResource, dockerClientConfig); } @Override protected Version execute(VersionCmd command) {<FILL_FUNCTION_BODY>} }
WebTarget webResource = getBaseResource().path("/version"); LOGGER.trace("GET: {}", webResource); return webResource.request().accept(MediaType.APPLICATION_JSON).get(new TypeReference<Version>() { });
116
65
181