auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public void deleteDocument(Exchange exchange) throws Exception { validateRequiredHeader(exchange, CamelCMISConstants.CMIS_OBJECT_ID); Message message = exchange.getIn(); String objectId = message.getHeader(CamelCMISConstants.CMIS_OBJECT_ID, String.class); START Boolean allVersions = Boolean.valueOf(message.getHeader(CamelCMISConstants.ALL_VERSIONS, String.class)); END Document document = (Document) getSessionFacade().getObjectById(objectId); document.delete(allVersions); } You can just say message.getHeader(xxx, Boolean.class)

Target:
public void deleteDocument(Exchange exchange) throws Exception { validateRequiredHeader(exchange, CamelCMISConstants.CMIS_OBJECT_ID); Message message = exchange.getIn(); String objectId = message.getHeader(CamelCMISConstants.CMIS_OBJECT_ID, String.class); Boolean allVersions = message.getHeader(CamelCMISConstants.ALL_VERSIONS, Boolean.class); Document document = (Document) getSessionFacade().getObjectById(objectId); document.delete(allVersions); }
Source:
public void setCacheContainer(BasicCacheContainer cacheContainer) { this.cacheContainer = cacheContainer; this.setCacheFromComponent = true; START System.out.println("===========<created"); END } Remove

Target:
public void setCacheContainer(BasicCacheContainer cacheContainer) { this.cacheContainer = cacheContainer; this.setCacheFromComponent = true; }
Source:
START public boolean isAllowed(Set<String> roles, List<String> allowedRoles) throws Exception { END for (String role : allowedRoles) { if (roles.contains(role)) { return true; } } return false; } Is there reason for `throws Exception` in signature?

Target:
public boolean isAllowed(Set<String> roles, List<String> allowedRoles) { for (String role : allowedRoles) { if (roles.contains(role)) { return true; } } return false; }
Source:
protected CamelContext createCamelContext() throws Exception { CamelContext context = super.createCamelContext(); context.getPropertiesComponent().setLocation("ref:prop"); ((ElytronComponent) context.getComponent("elytron")).setSecurityDomainBuilder(getSecurityDomainBuilder()); ((ElytronComponent) context.getComponent("elytron")).setMechanismName(getMechanismName()); START ((ElytronComponent) context.getComponent("elytron")).setElytronProvider(getElytronProvider()); END return context; } nit: `context.getComponent("elytron", ElytronComponent.class).setXXX` looks a bit nicer than casting.

Target:
protected CamelContext createCamelContext() throws Exception { CamelContext context = super.createCamelContext(); context.getPropertiesComponent().setLocation("ref:prop"); context.getComponent("elytron", ElytronComponent.class).setSecurityDomainBuilder(getSecurityDomainBuilder()); context.getComponent("elytron", ElytronComponent.class).setMechanismName(getMechanismName()); context.getComponent("elytron", ElytronComponent.class).setElytronProvider(getElytronProvider()); return context; }
Source:
private void doCreateTable(Exchange exchange, String tableName) throws KuduException { LOG.trace("Creating table {}", tableName); KuduClient connection = endpoint.getKuduClient(); try { Schema schema = (Schema) exchange.getIn().getHeader(KuduConstants.CAMEL_KUDU_SCHEMA); CreateTableOptions builder = (CreateTableOptions) exchange.getIn() .getHeader(KuduConstants.CAMEL_KUDU_TABLE_OPTIONS); connection.createTable(tableName, schema, builder); START } catch (Throwable t) { END t.printStackTrace(); throw t; } } Since you are added checked exception `KuduException` to the method signature, you don't need to catch and re-throw it again

Target:
private void doCreateTable(Exchange exchange, String tableName) throws KuduException { LOG.trace("Creating table {}", tableName); KuduClient connection = endpoint.getKuduClient(); Schema schema = (Schema) exchange.getIn().getHeader(KuduConstants.CAMEL_KUDU_SCHEMA); CreateTableOptions builder = (CreateTableOptions) exchange.getIn() .getHeader(KuduConstants.CAMEL_KUDU_TABLE_OPTIONS); connection.createTable(tableName, schema, builder); }
Source:
protected void createAuthorizationUser() { MongoDatabase admin = mongo.getDatabase("admin"); MongoCollection<Document> usersCollection = admin.getCollection("system.users"); if (usersCollection.count() == 0) { START usersCollection.insertOne(Document.parse("{\n" + " \"_id\": \"admin.test-user\",\n" END + " \"user\": \"test-user\",\n" + " \"db\": \"admin\",\n" + " \"credentials\": {\n" + " \"SCRAM-SHA-1\": {\n" + " \"iterationCount\": 10000,\n" + " \"salt\": \"gmmPAoNdvFSWCV6PGnNcAw==\",\n" + " \"storedKey\": \"qE9u1Ax7Y40hisNHL2b8/LAvG7s=\",\n" + " \"serverKey\": \"RefeJcxClt9JbOP/VnrQ7YeQh6w=\"\n" + " }\n" + " },\n" + " \"roles\": [\n" + " {\n" + " \"role\": \"readWrite\",\n" + " \"db\": \"test\"\n" + " }\n" + " ]\n" + "}" + "")); } } Is it possible to fix the ident of the Json string here?

Target:
protected void createAuthorizationUser() { MongoDatabase admin = mongo.getDatabase("admin"); MongoCollection<Document> usersCollection = admin.getCollection("system.users"); if (usersCollection.count() == 0) { usersCollection.insertOne(Document.parse("{\n" + " \"_id\": \"admin.test-user\",\n" + " \"user\": \"test-user\",\n" + " \"db\": \"admin\",\n" + " \"credentials\": {\n" + " \"SCRAM-SHA-1\": {\n" + " \"iterationCount\": 10000,\n" + " \"salt\": \"gmmPAoNdvFSWCV6PGnNcAw==\",\n" + " \"storedKey\": \"qE9u1Ax7Y40hisNHL2b8/LAvG7s=\",\n" + " \"serverKey\": \"RefeJcxClt9JbOP/VnrQ7YeQh6w=\"\n" + " }\n" + " },\n" + " \"roles\": [\n" + " {\n" + " \"role\": \"readWrite\",\n" + " \"db\": \"test\"\n" + " }\n" + " ]\n" + "}")); } }
Source:
public void add(String... values) { START for (String value : values) { END arguments.add(value); } } Do you think is better to replace it with `Collection.addAll`? ```suggestion arguments.addAll(Arrays.asList(values)); ```

Target:
public void add(String... values) { arguments.addAll(Arrays.asList(values)); }
Source:
START private boolean isSchemaAStructSchema(final Schema schema){ END return schema.type().equals(Schema.Type.STRUCT); } Please run build with `sourcecheck` profile

Target:
private boolean isSchemaAStructSchema(final Schema schema) { return schema != null && schema.type().equals(Schema.Type.STRUCT); }
Source:
protected static boolean isFieldValueNotSet(final Object field) { START return field == null || ObjectHelper.isEmpty(field); END } `ObjectHelper#isEmpty` already contains null check. ```suggestion return ObjectHelper.isEmpty(field); ```

Target:
protected static boolean isFieldValueNotSet(final Object field) { return ObjectHelper.isEmpty(field); }
Source:
public static void main(String[] args) throws Exception { START System.out.println("Camel is started. Ready to run Any23 example!"); END CamelContext context = new DefaultCamelContext(); context.start(); context.addRoutes(new Any23RouteBuilder()); context.addStartupListener(new Any23StartupMessage()); } It is a bit nitpicking, but Camel is not started yet at the time of this message :-)

Target:
public static void main(String[] args) throws Exception { CamelContext context = new DefaultCamelContext(); context.addRoutes(new Any23RouteBuilder()); context.start(); context.addStartupListener(new Any23StartupMessage()); }
Source:
public Asset() { START super(); END getAttributes().setType("Asset"); } Nitpicking ```suggestion ```

Target:
public Asset() { getAttributes().setType("Asset"); }
Source:
START public void copyChildren(Folder destinationFolder, Folder toCopyFolder) { END ItemIterable<CmisObject> immediateChildren = toCopyFolder.getChildren(); for (CmisObject child : immediateChildren) { if (child instanceof Document) { ((Document) child).copy(destinationFolder); } else if (child instanceof Folder) { copyFolderRecursive(destinationFolder, (Folder) child); } } } this method can be private

Target:
private void copyChildren(Folder destinationFolder, Folder toCopyFolder) { ItemIterable<CmisObject> immediateChildren = toCopyFolder.getChildren(); for (CmisObject child : immediateChildren) { if (child instanceof Document) { ((Document) child).copy(destinationFolder); } else if (child instanceof Folder) { copyFolderRecursive(destinationFolder, (Folder) child); } } }
Source:
private IPFSClient ipfs() { START IPFSClient client = getComponent().getIPFSClient(); END if (!client.hasConnection()) client.connect(); return client; } Okay this is better where it can self-heal and reconnect. Fix checkstyle issue however!

Target:
private IPFSClient ipfs() { if (!client.hasConnection()) { client.connect(); } return client; }
Source:
START public String sendChat(String input) throws ChatScriptDeliveryException { END if (!initialized) { return init(null); } ChatScriptMessage g = new ChatScriptMessage(this.userName, this.botName, input); return doMessage(g.toCSFormat()); } You need to create own exception, when requires to change the default behavior. Please use a standard one for your use-case.

Target:
public String sendChat(String input) throws Exception { if (!initialized) { return init(null); } ChatScriptMessage g = new ChatScriptMessage(this.userName, this.botName, input); return doMessage(g.toCSFormat()); }
Source:
private ChatScriptMessage createMessage(String message) throws InvalidInputMessage { ChatScriptMessage ret = null; try { ret = mapper.readValue(message, ChatScriptMessage.class); } catch (Exception e) { e.printStackTrace(); START throw new InvalidInputMessage("Unable to parse the input message. Error Message" + e.getMessage()); END } return ret; } You need to create own exception, when requires to change the default behavior. Please use a standard one for your use-case.

Target:
private ChatScriptMessage createMessage(String message) throws Exception { ChatScriptMessage ret = null; try { ret = mapper.readValue(message, ChatScriptMessage.class); } catch (Exception e) { e.printStackTrace(); throw new Exception("Unable to parse the input message. Error Message" + e.getMessage()); } return ret; }
Source:
public void onApplicationEvent(ApplicationEvent event) { LOG.debug("onApplicationEvent: {}", event); START if (event instanceof ContextRefreshedEvent && ((ContextRefreshedEvent) event).getApplicationContext().getId().equals(this.applicationContext.getId())) { END // nominally we would prefer to use Lifecycle interface that // would invoke start() method, but in order to do that // SpringCamelContext needs to implement SmartLifecycle // (look at DefaultLifecycleProcessor::startBeans), but it // cannot implement it as it already implements // RuntimeConfiguration, and both SmartLifecycle and // RuntimeConfiguration declare isAutoStartup method but // with boolean and Boolean return types, and covariant // methods with primitive types are not allowed by the JLS // so we need to listen for ContextRefreshedEvent and start // on its reception start(); } if (eventComponent != null) { eventComponent.onApplicationEvent(event); } } We should watch out for `ApplicationContext::getId` returning `null` ```suggestion if (event instanceof ContextRefreshedEvent && ((ContextRefreshedEvent) event).getApplicationContext() == this.applicationContext) { ```

Target:
public void onApplicationEvent(ApplicationEvent event) { LOG.debug("onApplicationEvent: {}", event); if (event instanceof ContextRefreshedEvent && ((ContextRefreshedEvent) event).getApplicationContext() == this.applicationContext) { // nominally we would prefer to use Lifecycle interface that // would invoke start() method, but in order to do that // SpringCamelContext needs to implement SmartLifecycle // (look at DefaultLifecycleProcessor::startBeans), but it // cannot implement it as it already implements // RuntimeConfiguration, and both SmartLifecycle and // RuntimeConfiguration declare isAutoStartup method but // with boolean and Boolean return types, and covariant // methods with primitive types are not allowed by the JLS // so we need to listen for ContextRefreshedEvent and start // on its reception start(); } if (eventComponent != null) { eventComponent.onApplicationEvent(event); } }
Source:
public void serialize() { byte[] result = serializer.serialize("someKey", value); START System.out.println(Arrays.toString(result)); END assertArrayEquals(expectedResult, result); } Use a log and don't print on standard out please

Target:
public void serialize() { byte[] result = serializer.serialize("someKey", value); assertArrayEquals(expectedResult, result); }
Source:
public void setUp() { START filteringXmlStreamWriter = new FilteringXmlStreamWriter(xmlStreamWriterMock, null); END filteringXmlStreamWriter.nonXmlCharFilterer = nonXmlCharFiltererMock; when(nonXmlCharFiltererMock.filter("value")).thenReturn("filteredValue"); } Could be avoided by removing the API break mentioned earlier.

Target:
public void setUp() { filteringXmlStreamWriter = new FilteringXmlStreamWriter(xmlStreamWriterMock); filteringXmlStreamWriter.nonXmlCharFilterer = nonXmlCharFiltererMock; when(nonXmlCharFiltererMock.filter("value")).thenReturn("filteredValue"); }
Source:
public boolean isFifoQueue() { // AWS docs suggest this is valid derivation. // FIFO queue names must end with .fifo, and standard queues cannot START if (queueName.endsWith(".fifo")) { END return true; } return false; } Please create a constant and also put it on the left side of the comparison. Thanks.

Target:
boolean isFifoQueue() { // AWS docs suggest this is valid derivation. // FIFO queue names must end with .fifo, and standard queues cannot if (queueName.endsWith(".fifo")) { return true; } return false; }
Source:
public DropboxFileUploadResult put(String localPath, String remotePath, DropboxUploadMode mode) throws DropboxException { // in case the remote path is not specified, the remotePath = localPath String dropboxPath = remotePath == null ? localPath : remotePath; UploadUploader entry; try { START entry = client.files().upload(localPath); END } catch (DbxException e) { throw new DropboxException(dropboxPath + " does not exist or can't obtain metadata"); } if (localPath != null) { return putFile(localPath, mode, dropboxPath, entry); } else { return putBody(exchange, mode, dropboxPath, entry); } } Should be `dropboxPath`

Target:
public DropboxFileUploadResult put(String localPath, String remotePath, DropboxUploadMode mode) throws DropboxException { // in case the remote path is not specified, the remotePath = localPath String dropboxPath = remotePath == null ? localPath : remotePath; UploadUploader entry; try { entry = client.files().upload(dropboxPath); } catch (DbxException e) { throw new DropboxException(dropboxPath + " does not exist or can't obtain metadata"); } if (localPath != null) { return putFile(localPath, mode, dropboxPath, entry); } else { return putBody(exchange, mode, dropboxPath, entry); } }
Source:
public ASN1DataFormat() { START super(); END this.usingIterator = false; } Those 3 implicit super() calls could be removed.

Target:
public ASN1DataFormat() { this.usingIterator = false; }
Source:
public String resetRoute(String id) throws Exception { ManagedRouteMBean managedRouteMBean = camelContext.getManagedRoute(id, ManagedRouteMBean.class); if (managedRouteMBean != null) { managedRouteMBean.reset(true); } else { String description = "The provided route id does not exists :" + camelContext.getRoute(id); ResponseEntity<?> responseEntity = ResponseEntity.status(HttpStatus.BAD_REQUEST).body(description); ObjectMapper objectMapper = new ObjectMapper(); return objectMapper.writeValueAsString(responseEntity); } START return null; END } Not sure if this method should return anything as in fact in the Mvc endpoint the return value is used for logging purpose only

Target:
public void resetRoute(String id) throws Exception { ManagedRouteMBean managedRouteMBean = camelContext.getManagedRoute(id, ManagedRouteMBean.class); if (managedRouteMBean != null) { managedRouteMBean.reset(true); } }
Source:
public InputStream getContentStreamFor(QueryResult item) { Document document = getDocument(item); START ContentStream contentStream = document.getContentStream(); END if (document != null && contentStream != null) { return contentStream.getStream(); } return null; } Won't it generate a NullPointerException when `document `is null ? Perhaps a 2 steps check or an Optional would make it.

Target:
public InputStream getContentStreamFor(QueryResult item) { Document document = getDocument(item); if(document != null) { ContentStream contentStream = document.getContentStream(); if (contentStream != null) { return contentStream.getStream(); } } return null; }
Source:
public boolean managedCheckConnection() { boolean isValid = true; try { checkConnection(); } catch (IOException ioEx) { isValid = false; START log.error("JMX check connection: {}", ioEx); END } return isValid; } Are you sure that you want to log an error there ? At first read, it's like this is just nominal case.

Target:
public boolean managedCheckConnection() { boolean isValid = true; try { checkConnection(); } catch (IOException ioEx) { isValid = false; log.debug("JMX check connection: {}", ioEx); } return isValid; }
Source:
START protected void afterConfigureProperties() { END // create connection eagerly, a good way to validate configuration getZendesk(); } Is this not better to do in doStart instead?

Target:
protected void afterConfigureProperties() { }
Source:
public static synchronized CamelReactiveStreams get(CamelContext context) { if (!instances.containsKey(context)) { CamelReactiveStreamsService service = resolveReactiveStreamsService(context); try { context.addService(service, true, true); } catch (Exception ex) { throw new IllegalStateException("Cannot add the CamelReactiveStreamsService to the Camel context", ex); } instances.put(context, new CamelReactiveStreams(service)); } START return instances.get(context); END } I think we can use ConcurrentHashMap::computeIfAbsent to replace synchronized and containsKey

Target:
public static CamelReactiveStreamsService get(CamelContext context) { return get(context, null); }
Source:
ReferenceId(@JsonProperty("referenceId") final String referenceId, @JsonProperty("id") final String id, @JsonProperty("errors") final List<RestError> errors) { this.referenceId = referenceId; this.id = id; START this.errors = Optional.ofNullable(errors).orElse(Collections.emptyList()); END } I would make errors unmodifiable

Target:
ReferenceId(@JsonProperty("referenceId") final String referenceId, @JsonProperty("id") final String id, @JsonProperty("errors") final List<RestError> errors) { this.referenceId = referenceId; this.id = id; this.errors = errors; }
Source:
public boolean containsKey(Object key){ START return cache.containsKey(key); END } you are looking only in the cache, you need to see if this value can be loaded also. There is also a persistedCache, is persistedCache a subset of the ache or do we need to look into both?

Target:
public boolean containsKey(Object key){ if(cache != null) return cache.containsKey(key); else return false; }
Source:
public static Expression dateExpression(final String command) { START return dateExpression(command, TimeZone.getDefault().getID(), ""); END } Can we use null as default timezone instead, which is the current behavior

Target:
public static Expression dateExpression(final String command) { return dateExpression(command, null, null); }
Source:
public Source resolve(String href, String base) throws TransformerException { InputStream stream = ClassPathURIResolver.class.getClassLoader() .getResourceAsStream(rulesDir.concat(File.separator).concat(href)); START if (null != stream) { END return new StreamSource(stream); } else { if (null != clientUriResolver) { return clientUriResolver.resolve(href, base); } else { return new StreamSource(stream); } } } Flip the if as we do X != null style in Camel

Target:
public Source resolve(String href, String base) throws TransformerException { InputStream stream = ClassPathURIResolver.class.getClassLoader() .getResourceAsStream(rulesDir.concat(File.separator).concat(href)); if (stream != null) { return new StreamSource(stream); } else { if (clientUriResolver != null) { return clientUriResolver.resolve(href, base); } else { return new StreamSource(stream); } } }
Source:
public Producer createProducer() throws Exception { if (endpointType == EndpointType.dataset) { return new DataSetFlinkProducer(this); } START else if (endpointType == EndpointType.datastream) { END return new DataStreamFlinkProducer(this); } else return null; } Run from command line this goal: mvn install -Psourcecheck in the camel-flink directory and then fix those checkstyle issues it reports

Target:
public Producer createProducer() throws Exception { if (endpointType == EndpointType.dataset) { return new DataSetFlinkProducer(this); } else if (endpointType == EndpointType.datastream) { return new DataStreamFlinkProducer(this); } else { return null; } }
Source:
private CMISSessionFacade getSessionFacade() throws Exception { if (sessionFacade == null) { sessionFacade = sessionFacadeFactory.create(); sessionFacade.initSession(); } START LOG.info("getSessionFacade {}", sessionFacade); END return sessionFacade; } Reduce the logging level to debug or trace

Target:
private CMISSessionFacade getSessionFacade() throws Exception { if (sessionFacade == null) { sessionFacade = sessionFacadeFactory.create(); sessionFacade.initSession(); } return sessionFacade; }
Source:
public Builder(String rootServerURL) { START pushConfiguration = new PushConfiguration(); END if (isEmpty(rootServerURL)) { throw new IllegalStateException("server can not be null"); } pushConfiguration.setServerUrl(!rootServerURL.endsWith("/") ? rootServerURL + '/' : rootServerURL); } is this the only usage for the ctor? if so, perhaps we don't wanna make it public

Target:
private Builder(String rootServerURL) { pushConfiguration = new PushConfiguration(); if (isEmpty(rootServerURL)) { throw new IllegalStateException("server can not be null"); } pushConfiguration.setServerUrl(!rootServerURL.endsWith("/") ? rootServerURL + '/' : rootServerURL); }
Source:
public void testSelectorWidget() { final Button b1 = new Button("Button click"); RootPanel.get().add(b1); GQuery g = $(b1); START assertTrue($(b1).isVisible()); END g.hide(); assertFalse($(b1).isVisible()); b1.removeFromParent(); } nit: should be g.isVisible, reusing the instance is a gquery (and jquery) good-practice for performance reasons, the same above

Target:
public void testSelectorWidget() { final Button b1 = new Button("Button click"); RootPanel.get().add(b1); GQuery g = $(b1); assertTrue(g.isVisible()); g.hide(); assertFalse(g.isVisible()); b1.removeFromParent(); }
Source:
public final <J extends IsProperties> J strip() { START return getDataImpl(); END } It should return this

Target:
public final <J extends IsProperties> J strip() { return (J)this; }
Source:
public static Path createTempFile(String suffix) { try { START Path path = Files.createTempFile("jadx-tmp-", System.nanoTime() + '-' + suffix); END path.toFile().deleteOnExit(); return path; } catch (IOException e) { throw new JadxRuntimeException("Failed to create temp file with suffix: " + suffix); } } Looks like `System.nanoTime()` not needed here, and was not needed in the previous version :)

Target:
public static Path createTempFile(String suffix) { try { Path path = Files.createTempFile("jadx-tmp-", suffix); path.toFile().deleteOnExit(); return path; } catch (IOException e) { throw new JadxRuntimeException("Failed to create temp file with suffix: " + suffix); } }
Source:
public ApkSignature(File openFile) { START super(); END this.openFile = openFile; } `super()` can be removed

Target:
public ApkSignature(File openFile) { this.openFile = openFile; }
Source:
public static synchronized void storeInteractionForCurrentAppVersion(Context context, String name) { START storeRecordForCurrentAppVersion(context, false, name); END } should the second arg be true here?

Target:
public static synchronized void storeInteractionForCurrentAppVersion(Context context, String name) { storeRecordForCurrentAppVersion(context, true, name); }
Source:
START public ComparableComparator getInstance(){ END return INSTANCE; } have a look [https://github.com/spring-projects/spring-framework/pull/25478/files](here). This class should be deprecated and no longer be updated, at all.

Target:
public static ComparableComparator getInstance(){ return INSTANCE; }
Source:
private Object createHelper() { preValidate(); Object key = KEY_FACTORY.newInstance((superclass != null) ? superclass.getName() : null, ReflectUtils.getNames(interfaces), filter == ALL_ZERO ? null : new WeakCacheKey<CallbackFilter>(filter), callbackTypes, useFactory, interceptDuringConstruction, serialVersionUID); this.currentKey = key; START return super.create(key); END } Please revert this according to our policy: > Please refrain from modifying classes under `org.springframework.asm`, `org.springframework.cglib`, and `org.springframework.objenesis`. Those include repackaged forks of the third-party libraries ASM, CGLIB, and Objenesis. Any refactoring to those classes should take place upstream in the originating repository. The Spring Framework will then pick up the changes when syncing with official updates of the forked third-party libraries.

Target:
private Object createHelper() { preValidate(); Object key = KEY_FACTORY.newInstance((superclass != null) ? superclass.getName() : null, ReflectUtils.getNames(interfaces), filter == ALL_ZERO ? null : new WeakCacheKey<CallbackFilter>(filter), callbackTypes, useFactory, interceptDuringConstruction, serialVersionUID); this.currentKey = key; Object result = super.create(key); return result; }
Source:
protected Object unwrapCachedValue(Object cached) { if (currentKey instanceof EnhancerKey) { START return ((WeakReference<EnhancerFactoryData>) cached).get(); END } return super.unwrapCachedValue(cached); } Please revert this according to our policy: > Please refrain from modifying classes under `org.springframework.asm`, `org.springframework.cglib`, and `org.springframework.objenesis`. Those include repackaged forks of the third-party libraries ASM, CGLIB, and Objenesis. Any refactoring to those classes should take place upstream in the originating repository. The Spring Framework will then pick up the changes when syncing with official updates of the forked third-party libraries.

Target:
protected Object unwrapCachedValue(Object cached) { if (currentKey instanceof EnhancerKey) { EnhancerFactoryData data = ((WeakReference<EnhancerFactoryData>) cached).get(); return data; } return super.unwrapCachedValue(cached); }
Source:
private boolean isMultipartRequest(WebRequest request) { String contentType = request.getHeader("Content-Type"); START return StringUtils.startsWithIgnoreCase(contentType, "multipart"); END } Good catch

Target:
private boolean isMultipartRequest(WebRequest request) { String contentType = request.getHeader("Content-Type"); return (contentType != null && StringUtils.startsWithIgnoreCase(contentType, "multipart")); }
Source:
private boolean skipDispatch(HttpServletRequest request) { if (isAsyncDispatch(request) && shouldNotFilterAsyncDispatch()) { return true; } START return request.getAttribute(WebUtils.ERROR_REQUEST_URI_ATTRIBUTE) != null && shouldNotFilterErrorDispatch(); END } Although the proposed changed is technically correct, please revert this for the sake of readability.

Target:
private boolean skipDispatch(HttpServletRequest request) { if (isAsyncDispatch(request) && shouldNotFilterAsyncDispatch()) { return true; } if (request.getAttribute(WebUtils.ERROR_REQUEST_URI_ATTRIBUTE) != null && shouldNotFilterErrorDispatch()) { return true; } return false; }
Source:
public boolean isReadOnly(ELContext elContext, @Nullable Object base, Object property) throws ELException { if (base == null) { String beanName = property.toString(); WebApplicationContext wac = getWebApplicationContext(elContext); START return wac.containsBean(beanName); END } return false; } Although the proposed changed is technically correct, please revert this for the sake of readability.

Target:
public boolean isReadOnly(ELContext elContext, @Nullable Object base, Object property) throws ELException { if (base == null) { String beanName = property.toString(); WebApplicationContext wac = getWebApplicationContext(elContext); if (wac.containsBean(beanName)) { return true; } } return false; }
Source:
protected void registerAfterCompletionWithExistingTransaction( Object transaction, List<TransactionSynchronization> synchronizations) throws TransactionException { START if(logger.isDebugEnabled()){ logger.debug("Cannot register Spring after-completion synchronization with existing transaction - " + "processing Spring after-completion callbacks immediately, with outcome status 'unknown'"); } END invokeAfterCompletion(synchronizations, TransactionSynchronization.STATUS_UNKNOWN); } No need for the `isDebugEnabled()` check since this is effectively a constant string. In other words, there is nothing dynamic about this string concatenation which should be converted to a single string by the compiler. ```suggestion logger.debug("Cannot register Spring after-completion synchronization with existing transaction - " + "processing Spring after-completion callbacks immediately, with outcome status 'unknown'"); ```

Target:
protected void registerAfterCompletionWithExistingTransaction( Object transaction, List<TransactionSynchronization> synchronizations) throws TransactionException { logger.debug("Cannot register Spring after-completion synchronization with existing transaction - " + "processing Spring after-completion callbacks immediately, with outcome status 'unknown'"); invokeAfterCompletion(synchronizations, TransactionSynchronization.STATUS_UNKNOWN); }
Source:
public static BodyBuilder method(HttpMethod method, String uri) { START return new DefaultBodyBuilder(method, new UriTemplate(uri)); END } But why go to `UriTemplate` here, only to go back to `String` in the end in `getUrl()`? There is no benefit nor reason to create a `UriTemplate` at any point in this class.

Target:
public static BodyBuilder method(HttpMethod method, String uri) { return new DefaultBodyBuilder(method, uri); }
Source:
private Message.Builder getMessageBuilder(Class<?> clazz) { START try { END assert supports(clazz); Method method = methodCache.get(clazz); if (method == null) { method = clazz.getMethod("newBuilder"); methodCache.put(clazz, method); } return (Message.Builder) method.invoke(clazz); } catch (Exception ex) { throw new MessageConversionException( "Invalid Protobuf Message type: no invocable newBuilder() method on " + clazz, ex); } } Please check [our guidelines](https://github.com/spring-projects/spring-framework/wiki/Code-Style#formatting) on source code style.

Target:
private Message.Builder getMessageBuilder(Class<?> clazz) { try { Method method = methodCache.get(clazz); if (method == null) { method = clazz.getMethod("newBuilder"); methodCache.put(clazz, method); } return (Message.Builder) method.invoke(clazz); } catch (Exception ex) { throw new MessageConversionException( "Invalid Protobuf Message type: no invocable newBuilder() method on " + clazz, ex); } }
Source:
public EhCacheCacheManager(net.sf.ehcache.CacheManager cacheManager) { START this(false, cacheManager); END } While I am not denying the setter is confusing, this is not the scope of this PR to change that.

Target:
public EhCacheCacheManager(net.sf.ehcache.CacheManager cacheManager) { this.cacheManager = cacheManager; }
Source:
public HttpMethod getMethod() { HttpMethod method = HttpMethod.resolve(this.jettyRequest.getMethod()); START Assert.notNull(method, "Method must not be null"); END return method; } Seems like `Assert.state` is more suitable here, because `notNull` results in an `IllegalArgumentException`.

Target:
public HttpMethod getMethod() { HttpMethod method = HttpMethod.resolve(this.jettyRequest.getMethod()); Assert.state(method != null, "Method must not be null"); return method; }
Source:
public SimpMessageType getMessageType() { START return (simpMessageType != null) ? simpMessageType : SimpMessageType.OTHER; END } Instead of checking for null here, why not just pass SimpMessageType.OTHER instead of null to the constructors?

Target:
public SimpMessageType getMessageType() { return simpMessageType; }
Source:
protected void prepareContext(ConfigurableApplicationContext context, MergedContextConfiguration mergedConfig) { context.getEnvironment().setActiveProfiles(mergedConfig.getActiveProfiles()); TestPropertySourceUtils.addPropertiesFilesToEnvironment(context, mergedConfig.getPropertySourceLocations()); TestPropertySourceUtils.addInlinedPropertiesToEnvironment(context, mergedConfig.getPropertySourceProperties()); invokeApplicationContextInitializers(context, mergedConfig); for (ContextCustomizer contextCustomizer : mergedConfig.getContextCustomizers()) { contextCustomizer.prepareContext(context, mergedConfig); START } END } I'm not very comfortable having a `ContextCustomizer` being called from a `prepareContext()` method when a `customizeContext()` method exists as well (even if the latter is in a subclass).

Target:
protected void prepareContext(ConfigurableApplicationContext context, MergedContextConfiguration mergedConfig) { context.getEnvironment().setActiveProfiles(mergedConfig.getActiveProfiles()); TestPropertySourceUtils.addPropertiesFilesToEnvironment(context, mergedConfig.getPropertySourceLocations()); TestPropertySourceUtils.addInlinedPropertiesToEnvironment(context, mergedConfig.getPropertySourceProperties()); invokeApplicationContextInitializers(context, mergedConfig); }
Source:
public List<TriggerTask> getTriggerTaskList() { START return this.triggerTasks; END } Regardless of whether we want to do this or not, we shouldn't expose the raw mutable list. This also means that your tests must be rewritten. Before doing that, let's discuss on the Jira issue what we want to do here. Thanks!

Target:
public List<TriggerTask> getTriggerTaskList() { List<TriggerTask> result = new ArrayList<TriggerTask>(); synchronized (this.triggerTasks) { result.addAll(this.triggerTasks); } return result; }
Source:
protected FluentList<FluentWebElement> find() { FluentListImpl<FluentWebElement> elements = new FluentListImpl<>(); START if (this.untilElements != null) { END for (FluentWebElement untilElement : this.untilElements) { try { untilElement.getTagName(); elements.add(untilElement); } catch (NoSuchElementException e) { // untilElement is a proxy element and is not found. } } } return elements; } is `this` operator required here

Target:
protected FluentList<FluentWebElement> find() { FluentListImpl<FluentWebElement> elements = new FluentListImpl<>(); if (untilElements != null) { for (FluentWebElement untilElement : untilElements) { try { untilElement.getTagName(); elements.add(untilElement); } catch (NoSuchElementException e) { // untilElement is a proxy element and is not found. } } } return elements; }
Source:
private UrlUtil() { START throw new UnsupportedOperationException("No instances allowed"); END } making this class final should be OK without this exception.

Target:
private UrlUtil() { // No instances allowed }
Source:
public long length() throws IOException { START return exists() ? writeRaf().length() : -1; END } Conceptually, this should be `readRaf()` since querying the length is a "read" operation. (I realize that in practice, it won't matter due to the `exists()` check beforehand, but the code looks strange/wrong with `writeRaf()` here.)

Target:
public long length() throws IOException { return exists() ? reader().length() : -1; }
Source:
public long offset() throws IOException { START return exists() ? writer().getFilePointer() : 0; END } This should be `reader()`.

Target:
public long offset() throws IOException { return exists() ? reader().getFilePointer() : 0; }
Source:
public void show(final Object o) { final UserInterface defaultUI = getDefaultUI(); START if (defaultUI == null) { END return; } defaultUI.show(o); } Please use the more compact one-line syntax: ``` java if (defaultUI == null) return; ``` for consistency with the other blocks of code in these here parts.

Target:
public void show(final Object o) { getDefaultUI().show(o); }
Source:
public UsageStats getUsage(final Object o) { START if (!(o instanceof Identifiable) || !(o instanceof Locatable)) { END // only track objects with an identifier and a location return null; } final String id = ((Identifiable) o).getIdentifier(); final String url = ((Locatable) o).getLocation(); if (!stats.containsKey(id)) stats.put(id, new UsageStats(id, url)); return stats.get(id); } This is a really nitty picky nit pick: I find `!(o instanceof Identifiable && o instanceof Locatable)` slightly clearer...

Target:
public UsageStats getUsage(final Object o) { if (!(o instanceof Identifiable && o instanceof Locatable)) { // only track objects with an identifier and a location return null; } final String id = ((Identifiable) o).getIdentifier(); final String url = ((Locatable) o).getLocation(); if (!stats.containsKey(id)) stats.put(id, new UsageStats(id, url)); return stats.get(id); }
Source:
public static void logMetricForSum(String name, double sum, int quantity) { START logMetricInternal(name, "S,C", String.format("%s,%.2f", sum, quantity)); END } logMetricInternal(name, "S,C", String.format("%s,%.2f", quantity, sum)); 应该改为这个

Target:
public static void logMetricForSum(String name, double sum, int quantity) { logMetricInternal(name, "S,C", String.format("%s,%.2f", quantity, sum)); }
Source:
public int compare(AbstractComponent o1, AbstractComponent o2) { // Handles null situations if(o1.getComponentId() == null) { START if(o2.getComponentId() == null) END return 0; //equal else return -1; // null is before other strings } else { if(o2.getComponentId() == null) return 1; // all other strings are after null else return o1.getComponentId().compareTo(o2.getComponentId()); } } This is a nit, but (at least here in the PR) the white space looks a little off (looks like one if was indented by tabs, the other by spaces, or similar) Also, I'd add curly-braces to the nested ifs (for consistency), or express them as ternary conditionals

Target:
public int compare(AbstractComponent o1, AbstractComponent o2) { // Handles null situations if (o1.getComponentId() == null) { if (o2.getComponentId() == null) { return 0; // equal } else { return -1; // null is before other strings } } else { if (o2.getComponentId() == null) { return 1; // all other strings are after null } else { return o1.getComponentId().compareTo(o2.getComponentId()); } } }
Source:
private static void log(Level level, Throwable ex, String msg, Object... data) { START modLog.log(level, () -> data == null ? msg : String.format(msg, data), ex); END } modLog might be `null` here

Target:
private static void log(Level level, Throwable ex, String msg, Object... data) { LOGGER.log(level, () -> data == null ? msg : String.format(msg, data), ex); }
Source:
public static int[] unsignedByteToIntArray(Object array) { if (array instanceof int[]) START return (int[])array; END else if (array instanceof byte[]) return unsignedByteToIntArray((byte[])array); else return new int[0]; } Please add the `{}` even for one-liners

Target:
public static int[] unsignedByteToIntArray(Object array) { if (array instanceof int[]) { return (int[]) array; } else if (array instanceof byte[]) { return unsignedByteToIntArray((byte[])array); } else { return new int[0]; } }
Source:
private String[] toStringArray(Object content){ String[] valueArray = null; if(content instanceof List){ valueArray = from((List<String>)content).toArray(String.class); }else{ valueArray = new String[]{(String)content}; } START return valueArray; END } Try to not use else. ``` java if (content instanceof List) { return from((List<String>)content).toArray(String.class) } return new String[]{(String)content} ``` BTW valueArray is not a good name and values is better.

Target:
private String[] toStringArray(Object content){ if(content instanceof List){ return from((List<String>)content).toArray(String.class); } return new String[]{(String)content}; }
Source:
public void setClientCapabilites(List<String> clientCapabilites){ START this.mClientCapabilites = clientCapabilites; END } this. is not required

Target:
public void setClientCapabilites(List<String> clientCapabilites){ mClientCapabilites = clientCapabilites; }
Source:
START public static InstanceDiscoveryMetadata getCachedInstanceDiscoveryMetadata(final URL authorityUrl) { END return sAadAuthorityHostMetadata.get(authorityUrl.getHost().toLowerCase(Locale.US)); } This class isn't `public` but these methods are.... 🤔

Target:
static InstanceDiscoveryMetadata getCachedInstanceDiscoveryMetadata(final URL authorityUrl) { return sAadAuthorityHostMetadata.get(authorityUrl.getHost().toLowerCase(Locale.US)); }
Source:
private void logReturnedToken(final AuthenticationResult result) { if (result != null && result.getAccessToken() != null) { String accessTokenHash = getTokenHash(result.getAccessToken()); String refreshTokenHash = getTokenHash(result.getRefreshToken()); START Logger.i(TAG, "Access tokenID and refresh tokenID returned. ", String.format( END "Access TokenID: %s and Refresh TokenID: %s .", accessTokenHash, refreshTokenHash)); } } delete this function, we should not log tokens

Target:
private void logReturnedToken(final AuthenticationResult result) { if (result != null && result.getAccessToken() != null) { Logger.i(TAG, "Access tokenID and refresh tokenID returned. ", null); } }
Source:
} catch (URISyntaxException e) { // will not throw START throw new RuntimeException(e); END } Can we throw an IllegalArgumentException instead?

Target:
} catch (URISyntaxException e) { // will not throw throw new IllegalArgumentException(e); }
Source:
START public void registerDispatcher(final IDispatcher dispatcher, final boolean aggregationRequired) { END if (aggregationRequired) { mDispatcher = new AggregatedDispatcher(dispatcher); } else { mDispatcher = new DefaultDispatcher(dispatcher); } } aren't `mDispatcher` should be syncronized? #Resolved

Target:
public synchronized void registerDispatcher(final IDispatcher dispatcher, final boolean aggregationRequired) { if (aggregationRequired) { mDispatcher = new AggregatedDispatcher(dispatcher); } else { mDispatcher = new DefaultDispatcher(dispatcher); } }
Source:
public UserInfo[] getBrokerUsers() throws OperationCanceledException, AuthenticatorException, IOException { // Calling this on main thread will cause exception since this is // waiting on AccountManagerFuture if (Looper.myLooper() == Looper.getMainLooper()) { throw new IllegalArgumentException("Calling getBrokerUsers on main thread"); } if (isBrokerAccountServiceSupported()) { return BrokerAccountServiceHandler.getInstance().getBrokerUsers(mContext); START } else { END return getUserInfoFromAccountManager(); } } >else [](start = 10, length = 4) else is not required #Resolved

Target:
public UserInfo[] getBrokerUsers() throws OperationCanceledException, AuthenticatorException, IOException { // Calling this on main thread will cause exception since this is // waiting on AccountManagerFuture if (Looper.myLooper() == Looper.getMainLooper()) { throw new IllegalArgumentException("Calling getBrokerUsers on main thread"); } if (isBrokerAccountServiceSupported()) { return BrokerAccountServiceHandler.getInstance().getBrokerUsers(mContext); } return getUserInfoFromAccountManager(); }
Source:
AcquireTokenInteractiveRequest(final Context context, final AuthenticationRequest authRequest, final TokenCacheAccessor tokenCacheAccessor) { mContext = context; mTokenCacheAccessor = tokenCacheAccessor; mAuthRequest = authRequest; if (mTokenCacheAccessor != null) { START mTokenCacheAccessor.setAuthRequest(authRequest); END } } ah? why token cache accessor needs to know auth request? #Closed

Target:
AcquireTokenInteractiveRequest(final Context context, final AuthenticationRequest authRequest, final TokenCacheAccessor tokenCacheAccessor) { mContext = context; mTokenCacheAccessor = tokenCacheAccessor; mAuthRequest = authRequest; }
Source:
void receive(final String requestId, final IEvents events) { List<IEvents> eventsList = getObjectToBeDispatched(requestId); if (eventsList == null) { eventsList = new ArrayList<>(); } eventsList.add(events); getObjectsToBeDispatched().put(requestId, eventsList); START flush(); END } > flush() [](start = 4, length = 11) flush? #Closed

Target:
void receive(final String requestId, final IEvents events) { List<IEvents> eventsList = getObjectsToBeDispatched().get(requestId); if (eventsList == null) { eventsList = new ArrayList<>(); } eventsList.add(events); getObjectsToBeDispatched().put(requestId, eventsList); }
Source:
TokenCacheItem getRegularRefreshTokenCacheItem(final String resource, final String clientId, final String user) { START CacheEvent cacheEvent = startCacheTelemetryRequest(EventStrings.TOKEN_TYPE_RT); END final String cacheKey = CacheKey.createCacheKeyForRTEntry(mAuthority, resource, clientId, user); final TokenCacheItem item = mTokenCacheStore.getItem(cacheKey); if (item != null) { cacheEvent.setTokenTypeRT(true); } Telemetry.getInstance().stopEvent(mTelemetryRequestId, cacheEvent, EventStrings.TOKEN_CACHE_LOOKUP); return item; } > CacheEvent cacheEvent [](start = 8, length = 21) line 94 and line 111 :) #Closed

Target:
TokenCacheItem getRegularRefreshTokenCacheItem(final String resource, final String clientId, final String user) { final CacheEvent cacheEvent = startCacheTelemetryRequest(EventStrings.TOKEN_TYPE_RT); final String cacheKey = CacheKey.createCacheKeyForRTEntry(mAuthority, resource, clientId, user); final TokenCacheItem item = mTokenCacheStore.getItem(cacheKey); if (item != null) { cacheEvent.setTokenTypeRT(true); } Telemetry.getInstance().stopEvent(mTelemetryRequestId, cacheEvent, EventStrings.TOKEN_CACHE_LOOKUP); return item; }
Source:
private IWindowComponent wrapActivity(final Activity activity) { if (activity == null) { throw new IllegalArgumentException("activity"); } return new IWindowComponent() { //CHECKSTYLE:OFF: checkstyle:MemberName //CHECKSTYLE:OFF: checkstyle:VisibilityModifier START Activity mRefActivity = activity; END @Override public void startActivityForResult(Intent intent, int requestCode) { // if user closed an app or switched to another activity // mRefActivity can die before this method got invoked if (mRefActivity != null) { mRefActivity.startActivityForResult(intent, requestCode); } } //CHECKSTYLE:ON: checkstyle:MemberName //CHECKSTYLE:ON: checkstyle:VisibilityModifier }; } sorry about this, but how about just making this private? does it break anything? #Closed

Target:
private IWindowComponent wrapActivity(final Activity activity) { if (activity == null) { throw new IllegalArgumentException("activity"); } return new IWindowComponent() { private Activity mRefActivity = activity; @Override public void startActivityForResult(Intent intent, int requestCode) { // if user closed an app or switched to another activity // mRefActivity can die before this method got invoked if (mRefActivity != null) { mRefActivity.startActivityForResult(intent, requestCode); } } }; }
Source:
private AuthenticationRequest getAuthenticationRequest(final String authority, final String resource, final String clientId, final boolean isExtendedLifetimeEnabled) { final AuthenticationRequest authRequest = new AuthenticationRequest(authority, resource, clientId, isExtendedLifetimeEnabled); START return authRequest; END } aren't you getting a warning about collapsing these 2 lines? #Closed

Target:
private AuthenticationRequest getAuthenticationRequest(final String authority, final String resource, final String clientId, final boolean isExtendedLifetimeEnabled) { return new AuthenticationRequest(authority, resource, clientId, isExtendedLifetimeEnabled); }
Source:
public void testIsNullOrBlankEmpty() throws IllegalArgumentException, IllegalAccessException, InvocationTargetException, ClassNotFoundException, NoSuchMethodException, InstantiationException { assertTrue("empty", StringExtensions.isNullOrBlank("")); START assertTrue("empty", StringExtensions.isNullOrBlank(" ")); END assertTrue("empty", StringExtensions.isNullOrBlank(" ")); } For line 56 and lien 58, what is the difference between the two? It's all testing the trim, no need to have two. #Closed

Target:
public void testIsNullOrBlankEmpty() throws IllegalArgumentException, IllegalAccessException, InvocationTargetException, ClassNotFoundException, NoSuchMethodException, InstantiationException { assertTrue("empty", StringExtensions.isNullOrBlank("")); assertTrue("empty", StringExtensions.isNullOrBlank(" ")); }