auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public void createLabelAndProperty() throws Exception { TokenWriteOperations tokenWrites = tokenWriteOperationsInNewTransaction(); labelId = tokenWrites.labelGetOrCreateForName( LABEL ); propertyKeyId = tokenWrites.propertyKeyGetOrCreateForName( PROPERTY_KEY ); final int labelId1 = labelId; final int[] propertyKeyIds = new int[]{propertyKeyId}; START descriptor = SchemaDescriptorFactory.forLabel( labelId1, propertyKeyIds ); END commit(); } Another one

Target:
public void createLabelAndProperty() throws Exception { TokenWriteOperations tokenWrites = tokenWriteOperationsInNewTransaction(); labelId = tokenWrites.labelGetOrCreateForName( LABEL ); propertyKeyId = tokenWrites.propertyKeyGetOrCreateForName( PROPERTY_KEY ); descriptor = SchemaDescriptorFactory.forLabel( labelId, propertyKeyId ); commit(); }
Source:
public PopulationProgress indexGetPopulationProgress( LabelSchemaDescriptor descriptor ) throws IndexNotFoundKernelException { START return indexService.getIndexProxy( NewIndexDescriptorFactory.forSchema( descriptor ) ).getIndexPopulationProgress(); END } This is only called for general indexes, because unique index population is synchronous?

Target:
public PopulationProgress indexGetPopulationProgress( LabelSchemaDescriptor descriptor ) throws IndexNotFoundKernelException { return indexService.getIndexProxy( descriptor ).getIndexPopulationProgress(); }
Source:
private boolean isIgnoringSomething() { START return ignoreBadRelationships | ignoreDuplicateNodes | ignoreExtraColumns; END } Is there a reason why you want to do bitwise OR here instead of `||` Did you want to explicitly avoid short-circuiting?

Target:
private boolean isIgnoringSomething() { return ignoreBadRelationships || ignoreDuplicateNodes || ignoreExtraColumns; }
Source:
public void exceptionWhenStartingNewTransactionOnShutdownInstance() throws Throwable { KernelTransactions kernelTransactions = newKernelTransactions(); SecurityContext securityContext = mock( SecurityContext.class ); availabilityGuard.shutdown(); t2.execute( (OtherThreadExecutor.WorkerCommand<Void,Void>) state -> { stopKernelTransactions( kernelTransactions ); return null; } ); expectedException.expect( DatabaseShutdownException.class ); START kernelTransactions.newInstance( KernelTransaction.Type.explicit, securityContext, 0L ); END } Won't this exception now be racing with the worker thread started above, now that you removed the `get` on the future?

Target:
public void exceptionWhenStartingNewTransactionOnShutdownInstance() throws Throwable { KernelTransactions kernelTransactions = newKernelTransactions(); SecurityContext securityContext = mock( SecurityContext.class ); availabilityGuard.shutdown(); expectedException.expect( DatabaseShutdownException.class ); kernelTransactions.newInstance( KernelTransaction.Type.explicit, securityContext, 0L ); }
Source:
public String evidenceMessage( TokenNameLookup tokenNameLookup, LabelSchemaDescriptor schema ) { START assert schema.getPropertyIds().length == propertyValues.values().length; END String labelName = tokenNameLookup.labelGetName( schema.getLabelId() ); if ( addedNodeId == NO_SUCH_NODE ) { return format( "Node(%d) already exists with label `%s` and %s", existingNodeId, labelName, propertyString( tokenNameLookup, schema.getPropertyIds() ) ); } else { return format( "Both Node(%d) and Node(%d) have the label `%s` and %s", existingNodeId, addedNodeId, labelName, propertyString( tokenNameLookup, schema.getPropertyIds() ) ); } } since we already have a specific value object for property values i think it's super strange that we fall back to backing array to get that would propose to have propertyValues.size() method instead

Target:
public String evidenceMessage( TokenNameLookup tokenNameLookup, LabelSchemaDescriptor schema ) { assert schema.getPropertyIds().length == propertyValues.size(); String labelName = tokenNameLookup.labelGetName( schema.getLabelId() ); if ( addedNodeId == NO_SUCH_NODE ) { return format( "Node(%d) already exists with label `%s` and %s", existingNodeId, labelName, propertyString( tokenNameLookup, schema.getPropertyIds() ) ); } else { return format( "Both Node(%d) and Node(%d) have the label `%s` and %s", existingNodeId, addedNodeId, labelName, propertyString( tokenNameLookup, schema.getPropertyIds() ) ); } }
Source:
public Object getSinglePropertyValue() { assert propertyValues.values().length == 1; START return propertyValues.values()[0]; END } also here why not provide method to get single method in helper class

Target:
public Object getSinglePropertyValue() { return propertyValues.getSinglePropertyValue(); }
Source:
private void setValues( Object... values ) { removeAllValueFields(); for ( int i = 0; i < values.length; i++ ) { ValueEncoding encoding = ValueEncoding.forValue( values[i] ); Field reusableField = getFieldWithValue( i, "composite", encoding, values[i] ); document.add( reusableField ); } START } END Keeping existing indexes working? 👍

Target:
private void setValues( Object... values ) { removeAllValueFields(); for ( int i = 0; i < values.length; i++ ) { ValueEncoding encoding = ValueEncoding.forValue( values[i] ); Field reusableField = getFieldWithValue( i, encoding, values[i] ); document.add( reusableField ); } }
Source:
private void setValues( Object... values ) { if( values.length == 1 ) { setValue( values[0] ); return; START } END removeAllValueFields(); for ( int i = 0; i < values.length; i++ ) { ValueEncoding encoding = ValueEncoding.forValue( values[i] ); Field reusableField = getFieldWithValue( i, "composite", encoding, values[i] ); document.add( reusableField ); } } Aha, _this_ is how single-property indexes retain their format. Very good.

Target:
private void setValues( Object... values ) { removeAllValueFields(); for ( int i = 0; i < values.length; i++ ) { ValueEncoding encoding = ValueEncoding.forValue( values[i] ); Field reusableField = getFieldWithValue( i, encoding, values[i] ); document.add( reusableField ); } }
Source:
private void insert( Collection<PropertyValue> data ) throws IOException { PropertyValue[] dataArray = data.toArray( new PropertyValue[data.size()] ); for ( int i = 0; i < dataArray.length; i++ ) { START Document doc = LuceneDocumentStructure.documentRepresentingProperties( (long) i, dataArray[i].value ); END index.getIndexWriter().addDocument( doc ); } index.maybeRefreshBlocking(); } Why this cast to `long`? It should automatically coerce. Similarly in `SimpleUniquenessVerifierTest`. Not a big issue, though.

Target:
private void insert( Collection<PropertyValue> data ) throws IOException { PropertyValue[] dataArray = data.toArray( new PropertyValue[data.size()] ); for ( int i = 0; i < dataArray.length; i++ ) { Document doc = LuceneDocumentStructure.documentRepresentingProperties( i, dataArray[i].value ); index.getIndexWriter().addDocument( doc ); } index.maybeRefreshBlocking(); }
Source:
private Object[] arraysOfDepth( int n ) { START return n == 0 ? new Object[]{"hej"} : arraysOfDepth( n-1 ); END } This doesn't wrap or nest any arrays. It just returns the array at the recursion base case.

Target:
private Object[] arraysOfDepth( int n ) { return n == 0 ? new Object[]{"hej"} : new Object[]{arraysOfDepth( n-1 )}; }
Source:
public KeyValueFileReader(final File keyValueFile) { try { this.reader = new BufferedReader(new FileReader(keyValueFile)); this.fileName = keyValueFile.getName(); } catch (FileNotFoundException ex) { START throw new OsmosisRuntimeException("Unable to read from key.value file " + fileName + ".", ex); END } } The conversion to OsmosisRuntimeExceptions should happen in the task itself, not in the helper class (as someone might use that helper class in an unrelated context).

Target:
public KeyValueFileReader(final File keyValueFile) throws FileNotFoundException { this.reader = new BufferedReader(new FileReader(keyValueFile)); }
Source:
START private File getLogsRoot() { END final String overriddenLogsRoot = System.getProperty("hudson.triggers.SafeTimerTask.logsTargetDir"); if (overriddenLogsRoot == null) { return new File(Jenkins.get().getRootDir(), "logs"); } else { return new File(overriddenLogsRoot); } } Maybe the common stuff could be moved into a utility class or something that avoids repeated code.

Target:
protected static File getLogsRoot() { final String overriddenLogsRoot = System.getProperty("hudson.triggers.SafeTimerTask.logsTargetDir"); if (overriddenLogsRoot == null) { return new File(Jenkins.get().getRootDir(), "logs"); } else { return new File(overriddenLogsRoot); } }
Source:
public DirectoryComponent(String includes, String excludes, boolean defaultExcludes, int maxDepth) { setExcludes(excludes); setIncludes(includes); START setDefaultExcludes(defaultExcludes); END setMaxDepth(maxDepth); } No super?

Target:
public DirectoryComponent(String includes, String excludes, boolean defaultExcludes, int maxDepth) { super(); setExcludes(excludes); setIncludes(includes); setDefaultExcludes(defaultExcludes); setMaxDepth(maxDepth); }
Source:
private static Set<String> getAllAsciiCharacters() { final int SPACE = ' '; //20 final int TILDE = '~'; //126 Set<String> singleChars = new HashSet<>(TILDE - SPACE + 1); START for (int i = SPACE; i <= TILDE; i++) { END singleChars.add(Character.toString((char) i)); } return singleChars; } ```suggestion for (char i = SPACE; i <= TILDE; i++) { ``` Can you do that? Can remove need for casting below, and can make SPACE and TILDE chars.

Target:
private static Set<String> getAllAsciiCharacters() { final int SPACE = ' '; //20 final int TILDE = '~'; //126 Set<String> singleChars = new HashSet<>(TILDE - SPACE + 1); for (char i = SPACE; i <= TILDE; i++) { singleChars.add(Character.toString(i)); } return singleChars; }
Source:
public abstract void writeTo(OutputStream os, ContentFilter filter) throws IOException; @Override START public boolean shouldBeFiltered() { END return false; } Could this be declared final?

Target:
public abstract void writeTo(OutputStream os, ContentFilter filter) throws IOException; @Override public final boolean shouldBeFiltered() { return false; }
Source:
public void addContents(@NonNull Container container) { START Jenkins j = Jenkins.getActiveInstance(); END addUnixContents(container, j); for (Node node : j.getNodes()) { addUnixContents(container, node); } } :NIT: should be part of a different PR (I assume it's safe to use and should just get rid of the helper version and just use the one in the `Jenkins` class.

Target:
public void addContents(@NonNull Container container) { Jenkins j = Jenkins.getInstance(); addUnixContents(container, j); for (Node node : j.getNodes()) { addUnixContents(container, node); } }
Source:
START public static String isRetrospectiveVisit(Visit visit) { END String retrospective = "false"; for (Encounter e : visit.getEncounters()) { if (e.getEncounterType().getUuid().equals(MetadataConstants.HIV_RETROSPECTIVE_ENCOUNTER_TYPE_UUID)) { retrospective = "true"; break; } } return retrospective; } This should be a boolean... no reason to use Strings

Target:
public static boolean isRetrospectiveVisit(Visit visit) { boolean retrospective = false; for (Encounter e : visit.getEncounters()) { if (e.getEncounterType().getUuid().equals(MetadataConstants.HIV_RETROSPECTIVE_ENCOUNTER_TYPE_UUID)) { retrospective = true; break; } } return retrospective; }
Source:
public FileSystemWatcher createFileSystemWatcher(String name, OptionMap options) { boolean useWatchService = options.get(Options.USE_WATCH_SERVICE, true); boolean daemonThread = options.get(Options.THREAD_DAEMON, true); if(useWatchService) { try { return new WatchServiceFileSystemWatcher(name, daemonThread); } catch (LinkageError e) { //ignore } START } END int pollInterval = options.get(Options.WATCHER_POLL_INTERVAL, 5000); return new PollingFileSystemWatcher(name, pollInterval, daemonThread); } here you'd delegate up to super.createFileSystemWatcher()

Target:
public FileSystemWatcher createFileSystemWatcher(String name, OptionMap options) { try { boolean daemonThread = options.get(Options.THREAD_DAEMON, true); return new WatchServiceFileSystemWatcher(name, daemonThread); } catch (LinkageError e) { //ignore } return super.createFileSystemWatcher(name, options); }
Source:
private static String urlEncode(String s) { try { return URLEncoder.encode(s, Charsets.UTF_8.name()) START .replace("+", "%20").replace("*", "%2A").replace("%7E", "~"); END } catch (UnsupportedEncodingException e) { throw new RuntimeException(e); // should not happen } } How about we switch this to `.replace("+", "%20")` as it appears the only problematic character is the space.

Target:
private static String urlEncode(String s) { try { return URLEncoder.encode(s, Charsets.UTF_8.name()) .replace("+", "%20").replace("*", "%2A"); } catch (UnsupportedEncodingException e) { throw new RuntimeException(e); // should not happen } }
Source:
public Subscriptions getSubscriptions(final SubscriptionState state, final QueryParams params) { START if (state != null) params.put("state", state.getType()); END return doGET(Subscriptions.SUBSCRIPTIONS_RESOURCE, Subscriptions.class, params); } Nit: explicit braces.

Target:
public Subscriptions getSubscriptions(final SubscriptionState state, final QueryParams params) { if (state != null) { params.put("state", state.getType()); } return doGET(Subscriptions.SUBSCRIPTIONS_RESOURCE, Subscriptions.class, params); }
Source:
public int hashCode() { return Objects.hash( account, plan, uuid, unitAmountInCents, currency, quantity, activatedAt, canceledAt, START expiresAt, END currentPeriodStartedAt, currentPeriodEndsAt, trialStartedAt, trialEndsAt, addOns, pendingSubscription, startsAt, collectionMethod, netTerms, poNumber ); } Odd that state was left out? We should re-introduce it.

Target:
public int hashCode() { return Objects.hashCode( account, plan, uuid, state, unitAmountInCents, currency, quantity, activatedAt, canceledAt, expiresAt, currentPeriodStartedAt, currentPeriodEndsAt, trialStartedAt, trialEndsAt, addOns, pendingSubscription, startsAt, collectionMethod, netTerms, poNumber ); }
Source:
START protected void refreshInputKinds() { END List<String> basePath = new ArrayList<String>(); Set<InputKind> kinds = assembleInputKindSet(basePath); this.inputKinds.clear(); this.inputKinds.addAll(kinds); } Could this be private?

Target:
private void refreshInputKinds() { List<String> basePath = new ArrayList<String>(); Set<InputKind> kinds = assembleInputKindSet(basePath); this.inputKinds.clear(); this.inputKinds.addAll(kinds); }
Source:
public InputKind(String relpath, Class inputClass) { this( START relpath, END inputClass, relpath.contains("data/inputs") ? relpath.substring(relpath.indexOf("data/inputs") + 12) : relpath ); } Nit: Unnecessary extra level of indentation.

Target:
private InputKind(String relpath, Class inputClass) { this( relpath, inputClass, relpath ); }
Source:
START public InputKind(String relpath, Class inputClass, String kind) { END this.relpath = relpath; this.inputClass = inputClass; this.kind = kind; knownKinds.put(kind, this); } Definitely SDK-internal. Package access please.

Target:
private InputKind(String relpath, Class inputClass, String kind) { this.relpath = relpath; this.inputClass = inputClass; this.kind = kind; knownKinds.put(kind, this); }
Source:
START public InputKind(String relpath, Class inputClass) { END this( relpath, inputClass, Util.substringAfter(relpath, "data/inputs/", relpath) ); } Probably want this to be package access as well. Every other entity constructor is.

Target:
private InputKind(String relpath, Class inputClass) { this( relpath, inputClass, relpath ); }
Source:
START public String getBucketRebuildMemoryHint() throws OperationNotSupportedException { END if (this.service.versionCompare("5.0") < 0) { // We're on 4.x, which doesn't support this. throw new OperationNotSupportedException("bucketRebuildMemoryHint unavailable before Splunk 5.0"); } else { return getString("bucketRebuildMemoryHint"); } } When migrating to use UnsupportedOperationException, please remove the throws clauses on the method declarations. UOE is a runtime exception so the clauses are not necessary.

Target:
public String getBucketRebuildMemoryHint() { return getString("bucketRebuildMemoryHint"); }
Source:
private String getStoriesId() { Stories stories = getAnnotation(Stories.class); START if(stories == null || stories.id().isEmpty()) { END return null; } else { return stories.id(); } } Mmm.. I guess you need 3 checks then: `if(stories == null || stories.id() == null || stories.id().isEmpty())`

Target:
private String getStoriesId() { Stories stories = getAnnotation(Stories.class); if(stories == null || stories.id() == null || stories.id().isEmpty()) { return null; } else { return stories.id(); } }
Source:
public String getIgnoredMessage(Description description) { Ignore ignore = description.getAnnotation(Ignore.class); START return ignore == null ? "Test ignored (without reason)!" : ignore.value(); END } think you should add it as method somewhere

Target:
public String getIgnoredMessage(Description description) { Ignore ignore = description.getAnnotation(Ignore.class); return ignore == null || ignore.value().isEmpty() ? "Test ignored (without reason)!" : ignore.value(); }
Source:
private void logError(LifecycleListener listener, Exception e) { START logger.error("Error for listener " + listener, e); END } maybe get class of listener?

Target:
private void logError(LifecycleListener listener, Exception e) { logger.error("Error for listener " + listener.getClass(), e); }
Source:
private static void copy(JarFile jar, JarEntry from, File to) throws IOException { START InputStream is = jar.getInputStream(from); END FileOutputStream os = new FileOutputStream(to); IOUtils.copy(is, os); os.close(); is.close(); } may be try-with-resources?

Target:
private static void copy(JarFile jar, JarEntry from, File to) throws IOException { try (InputStream is = jar.getInputStream(from); FileOutputStream os = new FileOutputStream(to)) { IOUtils.copy(is, os); } }
Source:
private static void copy(JarFile jar, JarEntry from, File to) throws IOException { InputStream is = null; FileOutputStream os = null; START try { END is = jar.getInputStream(from); os = new FileOutputStream(to); IOUtils.copy(is, os); } finally { if (is != null) { is.close(); } if (os != null) { os.close(); } } } if jar not null, all be ok. Read the link ive wrote

Target:
private static void copy(JarFile jar, JarEntry from, File to) throws IOException { try (InputStream is = jar.getInputStream(from); FileOutputStream os = new FileOutputStream(to)) { IOUtils.copy(is, os); } }
Source:
public static String getMessageMask(String message) { START return message.replaceAll("\\s\\d+\\s", " {number} ").replaceAll("\\s+", " "); END } а что потом происходит с `{number}`?

Target:
public static String getMessageMask(String message) { return message.replaceAll("\\s+", " "); }
Source:
public void register() { if (!registered.get() && registered.compareAndSet(false, true)) { DubboShutdownHook dubboShutdownHook = getDubboShutdownHook(); Runtime.getRuntime().addShutdownHook(dubboShutdownHook); dispatch(new DubboShutdownHookRegisteredEvent(dubboShutdownHook)); START ShutdownHookCallbacks.INSTANCE.addCallback(() -> { END // backward compatibility: make sure shutdown logic takes effect when DubboBootstrap is not used. AbstractRegistryFactory.destroyAll(); this.destroyProtocols(); }); } } If `DubboBootstrap` is enabled, will it also register the `DubboShutdownHook` and repeatedly call these destroy operations?

Target:
public void register() { if (!registered.get() && registered.compareAndSet(false, true)) { DubboShutdownHook dubboShutdownHook = getDubboShutdownHook(); Runtime.getRuntime().addShutdownHook(dubboShutdownHook); dispatch(new DubboShutdownHookRegisteredEvent(dubboShutdownHook)); } }
Source:
private void log(String accessLog, AccessLogData accessLogData) { Set<AccessLogData> logSet = LOG_ENTRIES.computeIfAbsent(accessLog, k -> new ConcurrentHashSet<>()); START if (logSet.size() >= LOG_MAX_BUFFER) { END logSet.add(accessLogData); } else { logger.warn("AccessLog buffer is full. Do a force writing to file to clear buffer."); //just write current logSet to file. writeLogSetToFile(accessLog, logSet); //after force writing, add accessLogData to current logSet logSet.add(accessLogData); } } Shouldn't this comparator be "<", which means we can only add new item to logSet when it's size does not exceed `LOG_MAX_BUFFER `?

Target:
private void log(String accessLog, AccessLogData accessLogData) { Set<AccessLogData> logSet = LOG_ENTRIES.computeIfAbsent(accessLog, k -> new ConcurrentHashSet<>()); if (logSet.size() < LOG_MAX_BUFFER) { logSet.add(accessLogData); } else { logger.warn("AccessLog buffer is full. Do a force writing to file to clear buffer."); //just write current logSet to file. writeLogSetToFile(accessLog, logSet); //after force writing, add accessLogData to current logSet logSet.add(accessLogData); } }
Source:
public static boolean isValidGenericValue(String generic) { START return isGeneric(generic) || Boolean.FALSE.toString().equals(generic); END } Boolean.FALSE.toString() need to ignore upcase?

Target:
public static boolean isValidGenericValue(String generic) { return isGeneric(generic) || Boolean.FALSE.toString().equalsIgnoreCase(generic); }
Source:
protected void updatePortIfAbsent(Integer value) { START if (value != null && port == null) { END this.port = value; } } change to `if (value != null && value > 0 && port == null) {`

Target:
protected void updatePortIfAbsent(Integer value) { if (value != null && value > 0 && port == null) { this.port = value; } }
Source:
private void putPropertyIfAbsent(URL url, Properties properties, String propertyName) { String propertyValue = url.getParameter(propertyName); START if (propertyValue != null && propertyValue.length() != 0) { END properties.setProperty(propertyName, propertyValue); } } perhaps you need to `trim` first ?

Target:
private void putPropertyIfAbsent(URL url, Properties properties, String propertyName) { String propertyValue = url.getParameter(propertyName); if (propertyValue != null && propertyValue.trim().length() != 0) { properties.setProperty(propertyName, propertyValue); } }
Source:
private NacosConfigListener createTargetListener(String key, String group) { START String normalizedKey = normalizedKey(key); END NacosConfigListener configListener = new NacosConfigListener(); configListener.fillContext(normalizedKey, group); return configListener; } duplicate call of `normalizedKey(key)`, the caller of createTargetListener() has already called the same method, so the key passed in is a normalized one.

Target:
private NacosConfigListener createTargetListener(String key, String group) { NacosConfigListener configListener = new NacosConfigListener(); configListener.fillContext(key, group); return configListener; }
Source:
public void run(Timeout timeout) { DefaultFuture future = DefaultFuture.getFuture(requestID); START if (future.isDone()) { END return; } // create exception response. Response timeoutResponse = new Response(future.getId()); // set timeout status. timeoutResponse.setStatus(future.isSent() ? Response.SERVER_TIMEOUT : Response.CLIENT_TIMEOUT); timeoutResponse.setErrorMessage(future.getTimeoutMessage(true)); // handle response. DefaultFuture.received(future.getChannel(), timeoutResponse, true); } Seems like we should judge null for future since the normal response will have called `DefaultFuture.remove`.

Target:
public void run(Timeout timeout) { DefaultFuture future = DefaultFuture.getFuture(requestID); if (future == null || future.isDone()) { return; } // create exception response. Response timeoutResponse = new Response(future.getId()); // set timeout status. timeoutResponse.setStatus(future.isSent() ? Response.SERVER_TIMEOUT : Response.CLIENT_TIMEOUT); timeoutResponse.setErrorMessage(future.getTimeoutMessage(true)); // handle response. DefaultFuture.received(future.getChannel(), timeoutResponse, true); }
Source:
public boolean accept(Type type, Class<?> clazz) { if (clazz == null) { return false; } START if (GeneratedMessageV3.class.isAssignableFrom(clazz)) { END return true; } return false; } pls. simplify it to 'return GeneratedMessageV3.class.isAssignableFrom(clazz);'

Target:
public boolean accept(Type type, Class<?> clazz) { if (clazz == null) { return false; } return GeneratedMessageV3.class.isAssignableFrom(clazz); }
Source:
public void innerReceive(String dataId, String group, String configInfo) { String oldValue = cacheData.get(dataId); ConfigChangeEvent event = new ConfigChangeEvent(dataId, configInfo, getChangeType(configInfo, oldValue)); START cacheData.put(dataId, configInfo); END listeners.forEach(listener -> listener.process(event)); } if `configInfo` is null, which means a config has been deleted. This line will throw NPE: ```java java.lang.NullPointerException at java.base/java.util.concurrent.ConcurrentHashMap.putVal(ConcurrentHashMap.java:1011) at java.base/java.util.concurrent.ConcurrentHashMap.put(ConcurrentHashMap.java:1006) at org.apache.dubbo.configcenter.support.nacos.NacosDynamicConfiguration$NacosConfigListener.innerReceive(NacosDynamicConfiguration.java:229) at com.alibaba.nacos.api.config.listener.AbstractSharedListener.receiveConfigInfo(AbstractSharedListener.java:37) at com.alibaba.nacos.client.config.impl.CacheData$1.run(CacheData.java:188) at com.alibaba.nacos.client.config.impl.CacheData.safeNotifyListener(CacheData.java:209) at com.alibaba.nacos.client.config.impl.CacheData.checkListenerMd5(CacheData.java:160) at com.alibaba.nacos.client.config.impl.ClientWorker$LongPollingRunnable.run(ClientWorker.java:505) at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1128) at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:628) at java.base/java.lang.Thread.run(Thread.java:834) ``` In order to avoid that, it is necessary to remove the dataID from cacheDate.

Target:
public void innerReceive(String dataId, String group, String configInfo) { String oldValue = cacheData.get(dataId); ConfigChangeEvent event = new ConfigChangeEvent(dataId, configInfo, getChangeType(configInfo, oldValue)); if (configInfo == null) { cacheData.remove(dataId); } else { cacheData.put(dataId, configInfo); } listeners.forEach(listener -> listener.process(event)); }
Source:
public void setProtocol(String protocol) { START this.protocols = new ArrayList<>(Arrays.asList(new ProtocolConfig[]{new ProtocolConfig(protocol)})); END } This can be simplified as `new ArrayList<>(Arrays.asList(new ProtocolConfig(protocol)))`

Target:
public void setProtocol(String protocol) { this.protocols = new ArrayList<>(Arrays.asList(new ProtocolConfig(protocol))); }
Source:
public boolean isAllowable() { long now = System.currentTimeMillis(); if (now > lastResetTime + interval) { token = buildLongAdder(rate); lastResetTime = now; } boolean flag = false; START while (token.sum() > 0 && !flag) { END token.decrement(); flag = true; } return flag; } `token.sum()` can be replaced with `getToken()`

Target:
public boolean isAllowable() { long now = System.currentTimeMillis(); if (now > lastResetTime + interval) { token = buildLongAdder(rate); lastResetTime = now; } if (token.sum() < 0) { return false; } token.decrement(); return true; }
Source:
public static String getSimpleClassName(String qualifiedName) { START int i = qualifiedName.lastIndexOf('.'); END return i < 0 ? qualifiedName : qualifiedName.substring(i + 1); } Better to check and have check for non empty or null string `org.apache.dubbo.common.utils.Assert.notEmptyString(qualifiedName, "Name can't be null or blank");`

Target:
public static String getSimpleClassName(String qualifiedName) { if (null == qualifiedName) { return null; } int i = qualifiedName.lastIndexOf('.'); return i < 0 ? qualifiedName : qualifiedName.substring(i + 1); }
Source:
public static int getHeartbeat(URL url) { String dubbo = url.getParameter(Constants.DUBBO_VERSION_KEY); return url.getParameter(Constants.HEARTBEAT_KEY, dubbo != null && START dubbo.startsWith("1.0.") ? Constants.DEFAULT_HEARTBEAT : 0); END } Since `2.0.x` has been widely adopted, keep the `1.0.x` compatible code may be unnecessary and remove it may make code cleaner. What do you think?

Target:
public static int getHeartbeat(URL url) { return url.getParameter(Constants.HEARTBEAT_KEY, Constants.DEFAULT_HEARTBEAT); }
Source:
public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception { NettyChannel channel = NettyChannel.getOrAddChannel(ctx.channel(), url, handler); try { START if (evt instanceof IdleStateEvent) { END logger.info("IdleStateEvent triggered, close channel " + channel); channel.close(); } super.userEventTriggered(ctx, evt); } finally { NettyChannel.removeChannelIfDisconnected(ctx.channel()); } } Seems like we should keep the logic same with NettyClientHandler. We can call `NettyChannel.getOrAddChannel` after `if (evt instanceof IdleStateEvent)`

Target:
public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception { if (evt instanceof IdleStateEvent) { NettyChannel channel = NettyChannel.getOrAddChannel(ctx.channel(), url, handler); try { logger.info("IdleStateEvent triggered, close channel " + channel); channel.close(); } finally { NettyChannel.removeChannelIfDisconnected(ctx.channel()); } } super.userEventTriggered(ctx, evt); }
Source:
public void doDestroy() { if (!destroyed.compareAndSet(false, true)) { return; } // unregister the shutdownHook START unregister(); END // destroy all the registries AbstractRegistryFactory.destroyAll(); // destroy all the protocols destroyProtocols(); } don't call `unregister` here. When shutdown hook runs, it will lead to IllegalStateException if we try to remove the hook. ```java static synchronized void add(Thread hook) { if(hooks == null) throw new IllegalStateException("Shutdown in progress"); if (hook.isAlive()) throw new IllegalArgumentException("Hook already running"); if (hooks.containsKey(hook)) throw new IllegalArgumentException("Hook previously registered"); hooks.put(hook, hook); } ```

Target:
public void doDestroy() { if (!destroyed.compareAndSet(false, true)) { return; } // destroy all the registries AbstractRegistryFactory.destroyAll(); // destroy all the protocols destroyProtocols(); }
Source:
private void processWithAccessKeyLogger(Set<AccessLogData> logSet, File file) throws IOException { FileWriter writer = new FileWriter(file, true); try { for (Iterator<AccessLogData> iterator = logSet.iterator(); iterator.hasNext(); START iterator.remove()) { END writer.write(iterator.next().getLogMessage()); writer.write("\r\n"); } writer.flush(); } finally { writer.close(); } } need formation here.

Target:
private void processWithAccessKeyLogger(Set<AccessLogData> logSet, File file) throws IOException { try (FileWriter writer = new FileWriter(file, true)) { for (Iterator<AccessLogData> iterator = logSet.iterator(); iterator.hasNext(); iterator.remove()) { writer.write(iterator.next().getLogMessage()); writer.write("\r\n"); } writer.flush(); } }
Source:
private static void append(StringBuilder builder, String value) { if (StringUtils.hasText(value)) { START builder.append(value).append(SEPARATOR); END } } why not use builder.append(SEPARATOR).append(value) . In this way , there is no need to remove last ":" in build method.

Target:
private static void append(StringBuilder builder, String value) { if (StringUtils.hasText(value)) { builder.append(SEPARATOR).append(value); } }
Source:
public String doGetContent(String path) { try { byte[] dataBytes = client.getData().forPath(path); if (dataBytes == null || dataBytes.length == 0) { return null; } START return new String(dataBytes, charset); END } catch (NodeExistsException e) { } catch (NoNodeException e) { } catch (Exception e) { throw new IllegalStateException(e.getMessage(), e); } return null; } can be rewritten as `return (dataBytes == null || dataBytes.length == 0) ? null : new String(dataBytes, charset);`

Target:
public String doGetContent(String path) { try { byte[] dataBytes = client.getData().forPath(path); return (dataBytes == null || dataBytes.length == 0) ? null : new String(dataBytes, charset); } catch (NoNodeException e) { // ignore NoNode Exception. } catch (Exception e) { throw new IllegalStateException(e.getMessage(), e); } return null; }
Source:
public String doGetContent(String path) { try { byte[] dataBytes = client.getData().forPath(path); return (dataBytes == null || dataBytes.length == 0) ? null : new String(dataBytes, charset); START } catch (NodeExistsException e) { END } catch (NoNodeException e) { } catch (Exception e) { throw new IllegalStateException(e.getMessage(), e); } return null; } pls. add `// ignore`

Target:
public String doGetContent(String path) { try { byte[] dataBytes = client.getData().forPath(path); return (dataBytes == null || dataBytes.length == 0) ? null : new String(dataBytes, charset); } catch (NoNodeException e) { // ignore NoNode Exception. } catch (Exception e) { throw new IllegalStateException(e.getMessage(), e); } return null; }
Source:
private boolean hasProviderProtocol() { START return getProvider() != null && getProvider().getProtocols() != null && getProvider().getProtocols().isEmpty(); END } should be `!getProvider().getProtocols().isEmpty()`

Target:
private boolean hasProviderProtocol() { return getProvider() != null && getProvider().getProtocols() != null && !getProvider().getProtocols().isEmpty(); }
Source:
static boolean isValidAddress(InetAddress address) { if (address == null || address.isLoopbackAddress()) { return false; } String name = address.getHostAddress(); return (name != null && !Constants.ANYHOST_VALUE.equals(name) && !Constants.LOCALHOST_VALUE.equals(name) START && IP_PATTERN.matcher(name).matches()); END } @CrazyHZM I think once the **name** is not null the rest of two evaulation ``` !Constants.ANYHOST_VALUE.equals(name) && !Constants.LOCALHOST_VALUE.equals(name) ``` most likely be evaluates to **true** for non localhost so the chances of this whole condition to become true depends on **IP_PATTERN.matcher(name).matches()**. So from better understanding and performance point of view I think it would be better if we change it to ``` (name != null && IP_PATTERN.matcher(name).matches() && !Constants.ANYHOST_VALUE.equals(name) && !Constants.LOCALHOST_VALUE.equals(name)); ``` What do yu say?

Target:
static boolean isValidAddress(InetAddress address) { if (address == null || address.isLoopbackAddress()) { return false; } String name = address.getHostAddress(); return (name != null && IP_PATTERN.matcher(name).matches() && !Constants.ANYHOST_VALUE.equals(name) && !Constants.LOCALHOST_VALUE.equals(name)); }
Source:
default Object getProperty(String key, Object defaultValue) { Object value = getInternalProperty(key); if (value == null) { value = defaultValue; } START return value; END } can be simplified with `return value!=null? value : defaultValue?`

Target:
default Object getProperty(String key, Object defaultValue) { Object value = getInternalProperty(key); return value != null ? value : defaultValue; }
Source:
public static boolean isProvider(URL url) { return PROVIDERS_CATEGORY.equals(url.getParameter(Constants.CATEGORY_KEY, PROVIDERS_CATEGORY)) && !OVERRIDE_PROTOCOL.equals(url.getProtocol()) START && !ROUTE_PROTOCOL.equals(url.getProtocol()); END } may be we can apply the same approach here.

Target:
public static boolean isProvider(URL url) { return !OVERRIDE_PROTOCOL.equals(url.getProtocol()) && !ROUTE_PROTOCOL.equals(url.getProtocol()) && PROVIDERS_CATEGORY.equals(url.getParameter(CATEGORY_KEY, PROVIDERS_CATEGORY)); }
Source:
public Semaphore getActivesSemaphore(int maxThreadNum) { START if(maxThreadNum <= 0) { END return null; } if (activesLimit == null || activesPermits != maxThreadNum) { synchronized (this) { if (activesLimit == null || activesPermits != maxThreadNum) { activesLimit = new Semaphore(maxThreadNum); activesPermits = maxThreadNum; } } } return activesLimit; } format your code, pls.

Target:
public Semaphore getActivesSemaphore(int maxThreadNum) { if (activesLimit == null || activesPermits != maxThreadNum) { synchronized (this) { if (activesLimit == null || activesPermits != maxThreadNum) { activesLimit = new Semaphore(maxThreadNum); activesPermits = maxThreadNum; } } } return activesLimit; }
Source:
START public void setLevel(Level level) { END } `SetLevel` method isn't implemented,

Target:
public void setLevel(Level level) { this.level = level; }
Source:
START public void testRegister() { END //test one url abstractRegistry.register(mockUrl); assert abstractRegistry.getRegistered().contains(mockUrl); //test multiple urls abstractRegistry.getRegistered().clear(); List<URL> urlList = getList(); for (URL url : urlList) { abstractRegistry.register(url); } Assert.assertThat(abstractRegistry.getRegistered().size(), Matchers.equalTo(urlList.size())); } pls. consider to enhance `registerTest`, `unregisterTest`, `subscribeTest`, `unsubsribeTest`, etc, instead of introducing new test methods. But your method naming is more recommended, pls. stick to it.

Target:
public void testRegister() throws Exception { //test one url abstractRegistry.register(mockUrl); assert abstractRegistry.getRegistered().contains(mockUrl); //test multiple urls abstractRegistry.getRegistered().clear(); List<URL> urlList = getList(); for (URL url : urlList) { abstractRegistry.register(url); } Assert.assertThat(abstractRegistry.getRegistered().size(), Matchers.equalTo(urlList.size())); }
Source:
START private String pullRequestBaseToDisplayName(@Nullable String pullRequestBase) { END return pullRequestBase != null ? pullRequestBase : "default branch"; } ![Code Smell](https://sonarsource.github.io/sonar-github/code_smell.png 'Code Smell') Code Smell: Make "pullRequestBaseToDisplayName" a "static" method. ([squid:S2325](https://next.sonarqube.com/sonarqube/coding_rules#rule_key=squid%3AS2325)) [See it in SonarQube](https://next.sonarqube.com/sonarqube/project/issues?id=org.sonarsource.sonarqube%3Asonarqube&branch=feature%2Fjanos%2FSONAR-10365%2Fmigrate-data&issues=AWF65MK3GUleEzPZFu4E&open=AWF65MK3GUleEzPZFu4E) [ISSUE_KEY]: AWF65MK3GUleEzPZFu4E

Target:
private static String pullRequestBaseToDisplayName(@Nullable String pullRequestBase) { return pullRequestBase != null ? pullRequestBase : "default branch"; }
Source:
START public Long getCreatedAt() { END return createdAt; } should be primitive `long`

Target:
public long getCreatedAt() { return createdAt; }
Source:
private static Map<String, String> fromJson(String json) { START Gson gson = new GsonBuilder().disableHtmlEscaping().setPrettyPrinting().create(); END try { return gson.fromJson(decode(json, UTF_8.name()), JSON_MAP_TYPE); } catch (UnsupportedEncodingException e) { throw new IllegalStateException(e); } } is pretty printing really needed ?

Target:
private static Map<String, String> fromJson(String json) { Gson gson = new GsonBuilder().create(); try { return gson.fromJson(decode(json, UTF_8.name()), JSON_MAP_TYPE); } catch (UnsupportedEncodingException e) { throw new IllegalStateException(e); } }
Source:
private void doDefinition(WebService.NewAction action) { action.setDescription("Search for a collection of relevant rules matching a specified query.<br/>" + "Since 5.5, following fields in the response have been deprecated :" + "<ul>" + "<li>\"effortToFixDescription\" becomes \"gapDescription\"</li>" + "<li>\"debtRemFnCoeff\" becomes \"remFnGapMultiplier\"</li>" + "<li>\"defaultDebtRemFnCoeff\" becomes \"defaultRemFnGapMultiplier\"</li>" + "<li>\"debtRemFnOffset\" becomes \"remFnBaseEffort\"</li>" + "<li>\"defaultDebtRemFnOffset\" becomes \"defaultRemFnBaseEffort\"</li>" + "<li>\"debtOverloaded\" becomes \"remFnOverloaded\"</li>" + "</ul>" + START "In 7.1, a new field 'scope' has been added to the response.") END .setResponseExample(getClass().getResource("search-example.json")) .setSince("4.4") .setHandler(this); // Rule-specific search parameters defineRuleSearchParameters(action); } Please move this line to the changelog of the action : ``` action.setDescription("Search for a collection...") .setChangelog(new Change("7.1", "new field 'scope' has been added to the response") .setChangelog(new Change("7.1", "field 'scope' has been added to 'f' parameter") ```

Target:
private void doDefinition(WebService.NewAction action) { action.setDescription("Search for a collection of relevant rules matching a specified query.<br/>" + "Since 5.5, following fields in the response have been deprecated :" + "<ul>" + "<li>\"effortToFixDescription\" becomes \"gapDescription\"</li>" + "<li>\"debtRemFnCoeff\" becomes \"remFnGapMultiplier\"</li>" + "<li>\"defaultDebtRemFnCoeff\" becomes \"defaultRemFnGapMultiplier\"</li>" + "<li>\"debtRemFnOffset\" becomes \"remFnBaseEffort\"</li>" + "<li>\"defaultDebtRemFnOffset\" becomes \"defaultRemFnBaseEffort\"</li>" + "<li>\"debtOverloaded\" becomes \"remFnOverloaded\"</li>" + "</ul>") .setResponseExample(getClass().getResource("search-example.json")) .setSince("4.4") .setHandler(this); // Rule-specific search parameters defineRuleSearchParameters(action); }
Source:
private Optional<ScmInfo> getScmInfoForComponent(Component component) { ScannerReport.Changesets changesets = scannerReportReader.readChangesets(component.getReportAttributes().getRef()); if (changesets != null) { if (changesets.getChangesetCount() == 0) { return generateAndMergeDb(component, changesets.getCopyFromPrevious()); } return getScmInfoFromReport(component, changesets); } LOGGER.trace("No SCM info for file '{}'", component.getKey()); START return generateAndMergeDb(component, false); END } Why `false` ? If the scanner does not send any SCM information, why the DB data could not be reused ?

Target:
private Optional<ScmInfo> getScmInfoForComponent(Component component) { ScannerReport.Changesets changesets = scannerReportReader.readChangesets(component.getReportAttributes().getRef()); if (changesets == null) { LOGGER.trace("No SCM info for file '{}'", component.getKey()); // SCM not available. It might have been available before - don't keep author and revision. return generateAndMergeDb(component, false); } // will be empty if the flag "copy from previous" is set, or if the file is empty. if (changesets.getChangesetCount() == 0) { return generateAndMergeDb(component, changesets.getCopyFromPrevious()); } return getScmInfoFromReport(component, changesets); }
Source:
private Organization loadOrganization(ScannerReport.Metadata reportMetadata) { try (DbSession dbSession = dbClient.openSession(false)) { START analysisMetadata.setOrganizationsEnabled(organizationFlags.isEnabled(dbSession)); END Organization organization = toOrganization(dbSession, ceTask.getOrganizationUuid()); checkOrganizationKeyConsistency(reportMetadata, organization); analysisMetadata.setOrganization(organization); return organization; } } minor: I would not call `organizationFlags.isEnabled` before `checkOrganizationKeyConsistency`, if the check fails, we uselessly made a call to DB

Target:
private Organization loadOrganization(ScannerReport.Metadata reportMetadata) { try (DbSession dbSession = dbClient.openSession(false)) { Organization organization = toOrganization(dbSession, ceTask.getOrganizationUuid()); checkOrganizationKeyConsistency(reportMetadata, organization); analysisMetadata.setOrganization(organization); analysisMetadata.setOrganizationsEnabled(organizationFlags.isEnabled(dbSession)); return organization; } }
Source:
private Organization toOrganization(DbSession dbSession, String organizationUuid) { START analysisMetadata.setOrganizationsEnabled(organizationFlags.isEnabled(dbSession)); END Optional<OrganizationDto> organizationDto = dbClient.organizationDao().selectByUuid(dbSession, organizationUuid); checkState(organizationDto.isPresent(), "Organization with uuid '%s' can't be found", organizationUuid); return Organization.from(organizationDto.get()); } `analysisMetadata.setOrganizationsEnabled` is already called on line 117 and it really does not belong to a method called `toOrganization` which really should be static

Target:
private Organization toOrganization(DbSession dbSession, String organizationUuid) { Optional<OrganizationDto> organizationDto = dbClient.organizationDao().selectByUuid(dbSession, organizationUuid); checkState(organizationDto.isPresent(), "Organization with uuid '%s' can't be found", organizationUuid); return Organization.from(organizationDto.get()); }
Source:
START public void setQualityGate(QualityGate g) { END // fail fast requireNonNull(g); checkState(qualityGate == null, "QualityGateHolder can be initialized only once"); this.qualityGate = Optional.of(g); } ![MAJOR](https://sonarsource.github.io/sonar-github/severity-major.png 'Severity: MAJOR') Remove this null-check of an "Optional". [![rule](https://sonarsource.github.io/sonar-github/rule.png)](https://next.sonarqube.com/sonarqube/coding_rules#rule_key=squid%3AS2789)

Target:
public void setQualityGate(QualityGate g) { // fail fast requireNonNull(g); checkState(qualityGate == null, "QualityGateHolder can be initialized only once"); this.qualityGate = g; }
Source:
private void validateQualityGate(DbSession dbSession, OrganizationDto organizationDto, String name) { List<String> errors = new ArrayList<>(); checkQualityGateDoesNotAlreadyExist(dbSession, organizationDto, name, errors); START checkRequest(errors.isEmpty(), errors); END } Please remove checkRequest => it's no more needed as there's now only one error that can be generated in `checkQualityGateDoesNotAlreadyExist`. Moreoever, `checkQualityGateDoesNotAlreadyExist` should then directly throw an IllegalArgumentException instead of adding an error to the list of error.

Target:
private void validateQualityGate(DbSession dbSession, OrganizationDto organizationDto, String name) { checkQualityGateDoesNotAlreadyExist(dbSession, organizationDto, name); }
Source:
public QualityGateDto selectBuiltIn(DbSession dbSession) { QualityGateDto qualityGateDto = mapper(dbSession).selectBuiltIn(); START checkState(qualityGateDto != null, "Builtin quality gate is missing."); END return qualityGateDto; } AFAIK, such check should not be in DAO (it probably should be in QualityGateFinder).

Target:
public QualityGateDto selectBuiltIn(DbSession dbSession) { return mapper(dbSession).selectBuiltIn(); }
Source:
public void after() { underTest.stop(); START db.executeUpdateSql("delete from metrics"); END db.commit(); } Why are you removing metrics at the end ? It's not already done by DbTester ?

Target:
public void after() { underTest.stop(); }
Source:
public void define(Context context) { START System.err.println("Fake GOV WS being setup: " + actions.length); END NewController controller = context.createController("api/fake_gov"); Arrays.stream(actions).forEach(action -> action.define(controller)); controller.done(); } Shouldn't this be in a Logger (so we may see it in web.log during a test ?)

Target:
public void define(Context context) { NewController controller = context.createController("api/fake_gov"); Arrays.stream(actions).forEach(action -> action.define(controller)); controller.done(); }
Source:
private void uninstallPlugins(Set<String> pluginsToRemove) { START for (String pluginKey : pluginsToRemove) { END editionPluginUninstaller.uninstall(pluginKey); } } can't `foreach` be used here?

Target:
private void uninstallPlugins(Set<String> pluginsToRemove) { pluginsToRemove.stream().forEach(editionPluginUninstaller::uninstall); }
Source:
START public boolean hasDownloads() { END return !getDownloadedPluginFilenames().isEmpty(); } why public?

Target:
boolean hasDownloads() { return !getDownloadedPluginFilenames().isEmpty(); }
Source:
START public List<String> getDownloadedPluginFilenames() { END List<String> names = new ArrayList<>(); for (File file : listPlugins(this.downloadDir)) { names.add(file.getName()); } return names; } why public?

Target:
List<String> getDownloadedPluginFilenames() { List<String> names = new ArrayList<>(); for (File file : listPlugins(this.downloadDir)) { names.add(file.getName()); } return names; }
Source:
START protected void ensurePluginIsInstalled(String key) { END if (!serverPluginRepository.hasPlugin(key)) { throw new IllegalArgumentException(format("Plugin [%s] is not installed", key)); } } should be private

Target:
private void ensurePluginIsInstalled(String key) { if (!serverPluginRepository.hasPlugin(key)) { throw new IllegalArgumentException(format("Plugin [%s] is not installed", key)); } }