auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public T parse(String value) { if (value == null || value.isEmpty() || value.equalsIgnoreCase("NULL")) return null; if (!Strings.isQuoted(value)) throw new IllegalArgumentException("JSON strings must be enclosed by single quotes"); String json = Strings.unquote(value); try { return (T) objectMapper.readValue(json, toJacksonJavaType()); } catch (IOException e) { throw new IllegalArgumentException(e.getMessage(), e); } }

Target:
In driver 4 the contribution guidelines mandate that if/for/while blocks must be enclosed with braces. Same thing for the line below.
Source:
private boolean isAuthFailure(Throwable error) { boolean authFailure = true; if (error instanceof AllNodesFailedException) { Collection<Throwable> errors = ((AllNodesFailedException) error).getErrors().values(); for (Throwable nodeError : errors) { if (!(nodeError instanceof AuthenticationException)) { authFailure = false; break; } } } return authFailure; }

Target:
if `getErrors()` will return empty connection we will treat it as the `AuthFailure`. Is it ok for us? Is it possible?
Source:
private boolean isFullyFetched() { return currentPage.hasMorePages(); }

Target:
Should be `!currentPage.hasMorePages()`.
Source:
public BatchStatement build() { return new DefaultBatchStatement( batchType, statementsBuilder.build(), executionProfileName, executionProfile, keyspace, routingKeyspace, routingKey, routingToken, buildCustomPayload(), idempotent, tracing, timestamp, pagingState, pageSize, consistencyLevel, serialConsistencyLevel, timeout, null); }

Target:
The last argument should be `node` (inherited from the parent builder) instead of `null`.
Source:
private Builder() { try { this.configDirectory = Files.createTempDirectory("ccm"); } catch (IOException e) { // change to unchecked for now. throw new RuntimeException(e); } // disable auto_snapshot by default to reduce disk usage when destroying schema. withCassandraConfiguration("auto_snapshot", "false"); // mark the ccm temp directories for deletion when the JVM exits if (this.configDirectory != null) { this.configDirectory.toFile().deleteOnExit(); } }

Target:
Are we sure this directory will be empty? If not, I suggest doing the following instead: ``` Runtime.getRuntime() .addShutdownHook( new Thread( () -> { try (Stream<Path> walk = Files.walk(configDirectory)) { walk.sorted(Comparator.reverseOrder()) .map(Path::toFile) .forEach(File::delete); } catch (IOException e) { logger.error("Could not walk " + configDirectory, e); } })); ```
Source:
private static File createTempStore(String storePath) { File f = null; try (OutputStream os = new FileOutputStream(f = File.createTempFile("server", ".store"))) { Resources.copy(CcmBridge.class.getResource(storePath), os); } catch (IOException e) { logger.warn("Failure to write keystore, SSL-enabled servers may fail to start.", e); } finally { // ensure the temp store files are deleted when the JVM exits if (f != null) { f.deleteOnExit(); } } return f; }

Target:
Imo this could be simplified to just `f.deleteOnExit();` placed right after the try block start, since `f` cannot be null at that point. But this way is OK too.
Source:
public static <T> void shuffleHead(@NonNull T[] elements, int n) { shuffleHead(elements, n, ThreadLocalRandom.current()::nextInt); }

Target:
There's probably a small overhead to translate the method reference on each call. I'm not sure if it's significant or not, but we can avoid it altogether by passing the `ThreadLocalRandom` itself instead of the method. Then you can mock it in the test: ```java ThreadLocalRandom random = Mockito.mock(ThreadLocalRandom.class); Mockito.when(random.nextInt(Mockito.anyInt())).thenAnswer((invocation) -> { int i = invocation.getArgument(0); return i - 2; }); ```
Source:
boolean errorDuringInit() { if (isInit && initException != null) { return true; } return false; }

Target:
This can be simplified as `return (isInit && initException != null);`
Source:
KeyspaceMetadata(String name, boolean durableWrites, Map<String, String> replication) { this.name = name; this.durableWrites = durableWrites; this.replication = replication; this.strategy = ReplicationStrategy.create(replication); this.isVirtual=false; }

Target:
Would be preferable for this constructor should reuse the new one (i.e. `this(name, durableWrites, replication, false)`). Should also mark this constructor as deprecated as it looks like existing uses of it were updated to use the new one.
Source:
public Class<?> getRawType() { return token.getRawType(); }

Target:
Shouldn't this be `<? super T>`?
Source:
public DefaultNode(InetSocketAddress connectAddress, InternalDriverContext context) { this.connectAddress = connectAddress; // We leak a reference to a partially constructed object (this), but in practice this won't be a // problem because the node updater only needs the connect address to initialize. this.metricUpdater = context.metricUpdaterFactory().newNodeUpdater(this); this.state = NodeState.UNKNOWN; this.distance = NodeDistance.IGNORED; this.rawTokens = Collections.emptySet(); this.extras = Collections.emptyMap(); }

Target:
it seems a little worse than that, I see that the constructor of `DefaultNodeUpdater` also tries to do the following: ``` ChannelPool pool = context.poolManager().getPools().get(node); ```
Source:
void validate(QueryType qt, MappingManager manager) { checkArgument(qt == QueryType.SAVE || qt == QueryType.DEL || qt == QueryType.GET, "Consistency level option is only allowed in save, delete and get queries"); }

Target:
Just noticed: this check is useless, these is no other `QueryType` at this moment.
Source:
public void should_hash_consistently() { ByteBuffer byteBuffer = Bytes.fromHexString("0xCAFEBABE"); Token tokenA = factory.hash(byteBuffer); Token tokenB = factory.hash(byteBuffer); assertThat(tokenA).isEqualTo(factory.fromString("59959303159920881837560881824507314222")); assertThat(tokenA).isEqualTo(tokenB); }

Target:
Trivial: you could have chained the `isEqualTo` calls.
Source:
public PreparedStatement addPrepared(PreparedStatement stmt) { PreparedStatement previous = preparedQueries.putIfAbsent(stmt.getPreparedId().boundValuesMetadata.id, stmt); if (previous != null) { logger.warn("Re-preparing already prepared query is generally an anti-pattern and will likely affect performance. " + "Consider preparing the statement only once. Query='{}'", stmt.getQueryString()); // The one object in the cache will get GCed once it's not referenced by the client anymore since we use a weak reference. // So we need to make sure that the instance we do return to the user is the one that is in the cache. if (com.google.common.base.Objects.equal(previous.getPreparedId().resultSetMetadata.id, stmt.getPreparedId().resultSetMetadata.id)) return previous; } return stmt; }

Target:
I don't think it's the right way to fix the issue you described. We're returning the correct PreparedStatement to the caller of this method, but leaving the cached instance with the old result metadata. Rather it should be: ```java previous.getPreparedId().resultSetMetadata = stmt.getPreparedId().resultSetMetadata; return previous; ```
Source:
String keyspace() { SetKeyspaceAttempt currentAttempt = targetKeyspace.get(); return currentAttempt == null ? null : currentAttempt.keyspace; }

Target:
targetKeyspace gets set to null if the future fails, should it not do that? The reason it does it is if set keyspace fails, we want to provide another opportunity to set the same keyspace.
Source:
public void getMessage_should_return_message_if_address_is_null() { assertEquals("[null] Test message", new ConnectionException(null, "Test message").getMessage()); }

Target:
We might as well remove `[null]` altogether in that case, that is have the message `"Test message"`.
Source:
static <T extends Annotation> T getTypeAnnotation(Class<T> annotation, Class<?> annotatedClass) { T instance = annotatedClass.getAnnotation(annotation); if (instance == null) throw new IllegalStateException(String.format("@%s annotation was not found on %s", annotation.getSimpleName(), annotatedClass)); // Check that no other mapping annotations are present validateAnnotations(annotatedClass, annotation); return instance; }

Target:
Admittedly `IllegalArgumentException` isn't the most appropriate type for mapper annotation misuse, but `IllegalStateException` isn't either: - `IllegalArgumentException`: _Thrown to indicate that a method has been passed an illegal or inappropriate argument_ - `IllegalStateException`: _Signals that a method has been invoked at an illegal or inappropriate time_ Between the two, I'd rather keep IAE for the sake of backward compatibility.
Source:
private String joinJvmArgs() { StringBuilder allJvmArgs = new StringBuilder(""); for (String jvmArg : jvmArgs) { // Windows requires jvm arguments to be quoted, while *nix requires unquoted. String quote = isWindows() ? "\"" : ""; allJvmArgs.append(" "); allJvmArgs.append(quote); allJvmArgs.append("--jvm_arg="); allJvmArgs.append(randomizePorts(jvmArg)); allJvmArgs.append(quote); } return allJvmArgs.toString(); }

Target:
This could be moved outside the for loop.
Source:
private <V> V as(TypeToken<V> javaType) { if (OBJECT_TYPE.equals(javaType)) { // we're handling a getObject() call @SuppressWarnings("unchecked") V v = (V)asObject(); // Since V is Object, this is a safe cast return v; } else { // we're handling a typed getter call assert javaType != null; return with(codecFor(javaType)); } }

Target:
That's a good point, but my plan was to move OBJECT_TYPE to TypeTokens and make it public, which in theory allows users to pass it to get(). So it might be better to use `null` to indicate getObject (as you initially did).
Source:
public void indexerTest() throws Exception { // add triples sparqlIndexer.update(uri, createDefaultModel().read( new StringReader(fooRDF), "", "N3")); waitForTriples(3); // triples should be present in the triplestore assertEquals("Triples should be present!", 3, countDescribeTriples(uri)); // SPARQL search should work final String sparqlQuery = "PREFIX fcrepo: <http://fedora.info/definitions/v4/repository#> \n" + "SELECT ?p \n" + "WHERE \n" + "{ ?p fcrepo:hasParent ?c }"; assertEquals("Triple should return from search!", 3, countQueryTriples(sparqlQuery)); // remove object sparqlIndexer.remove(uri); waitForTriples(0); // triples should not be present in the triplestore assertTrue("Triples should not be present!", countDescribeTriples(uri) == 0); }

Target:
This update causes my build to fail.
Source:
public void bitwise() { counter trueCount = new Counter(true); counter falseCount = new Counter(false); String x = "Hai"; if (trueCount.count() | falseCount.count()) { x = "kthxbai"; } assertEquals(x, __); assertEquals(trueCount.count, __); assertEquals(falseCount.count, __); }

Target:
Shouldn't the `Counter `class contain a suitable constructor to initialize the `returnValue `attribute? ` public Counter(boolean b) { this.returnValue = b; }`
Source:
public static boolean isTransientError(int code) { // Note: Status.NOT_ACCEPTABLE = 406, Status.REQUEST_TIMEOUT = 408 return code == 406 || code == 408 || code == 500 || code == 502 || code == 503 || code == 504; }

Target:
In general a transient error means that it's temporary and recoverable. For 406 with CouchDB, is it recoverable?
Source:
public boolean isOpen() { return (open.get() && !closing.get()) || opening.get(); }

Target:
If opening is true, doesn't it mean it's still opening but not done opening yet?
Source:
public CustomFuture submit(boolean gzip) { com.couchbase.lite.replicator.RemoteRequest request = generateRemoteRequest(); if (gzip) request.setCompressedRequest(true); synchronized (requestExecutor) { if (!requestExecutor.isShutdown()) { Future future = requestExecutor.submit(request); pendingRequests.add(future); runnables.put(future, request); } } return this; }

Target:
Can't we just have `RemoteRequest`?
Source:
private void pruneFailedDownload(String docId) { Log.e(TAG, "pruneFailedDownload: " + docId); try { getLocalDatabase().deleteLocalDocument(docId); } catch (CouchbaseLiteException e) { Log.w(TAG, "Failed to delete local document: " + docId, e); } }

Target:
Shouldn't be Log.e.
Source:
protected void setError(Throwable throwable) { // TODO - needs to port //if (error.code == NSURLErrorCancelled && $equal(error.domain, NSURLErrorDomain)) // return; if (throwable != this.error) { Log.e(Log.TAG_SYNC, "%s: Progress: set error = %s", this, throwable); parentReplication.setLastError(throwable); this.error = throwable; // if permanent error, stop immediately if(Utils.isPermanentError(this.error)) { stop(); } // iOS version sends notification from stop() method, but java version does not. // following codes are always executed. { Replication.ChangeEvent changeEvent = new Replication.ChangeEvent(this); changeEvent.setError(this.error); notifyChangeListeners(changeEvent); } } }

Target:
{ here is not necessary.
Source:
protected void stop() { if (!isRunning()) return; // clear batcher batcher.clear(); // set non-continuous setLifecycle(Replication.Lifecycle.ONESHOT); // cancel if middle of retry cancelRetryFuture(); // cancel all pending future tasks. while (!pendingFutures.isEmpty()) { Future future = pendingFutures.poll(); if (future != null && !future.isCancelled() && future.isDone()) { future.cancel(true); } } }

Target:
should it be `!future.isDone()`?
Source:
public E take() throws InterruptedException { E e = super.take(); if(listener != null) listener.changed(BlockingQueueListener.EventType.TAKE, e, this); return e; }

Target:
Can you wrap this in curly braces? ``` if(listener != null) { listener.changed(BlockingQueueListener.EventType.TAKE, e, this); } ```
Source:
public T convert(ArgumentParser parser, Argument arg, String value) throws ArgumentParserException { for (T t : type_.getEnumConstants()) { if (t.toString().equals(value)) { return t; } } String choices = TextHelper.concat(type_.getEnumConstants(), 0, ",", "{", "}"); throw new ArgumentParserException(String.format( TextHelper.LOCALE_ROOT, "could not convert '%s' (choose from %s)", value, choices), null, parser, arg); }

Target:
We can omit null here, since we have that overload.
Source:
private static final IModelAccessFacade getModelAccess() { return Utils.getComponent(IModelAccessFacade.class); }

Target:
why needs this method to be static?
Source:
private static final XWikiContext getContext() { return getModelContext().getXWikiContext(); }

Target:
why needs this method to be static?
Source:
public void setValue(String content) { this.content = Optional.fromNullable(content); }

Target:
Optional should be used in interfaces. Use `null` as internal value.
Source:
public String getValue() { return content.orNull(); }

Target:
why not returning a Optional<String>?
Source:
public @NotNull MetaTag getCharsetMetaTag(@NotNull String charsetStr) { ECharset charset = ECharset.getCharset(charsetStr).get(); if (charset != null) { return new MetaTag(charset); } return new MetaTag(ECharset.ATTRIB_NAME, charsetStr, null); }

Target:
This could cause a NPE, instead resolve Optionals by checking present() first
Source:
public @NotNull MetaTag getCharsetMetaTag(@NotNull String charsetStr) { if (ECharset.getCharset(charsetStr).isPresent()) { ECharset charset = ECharset.getCharset(charsetStr).get(); if (charset != null) { return new MetaTag(charset); } } return new MetaTag(ECharset.ATTRIB_NAME, charsetStr, null); }

Target:
null check unnecessary
Source:
public Optional<BaseObject> getXObject(XWikiDocument doc, DocumentReference classRef, int objectNumber) { BaseObject bObj = null; List<BaseObject> objs = getXObjects(doc, classRef); for (BaseObject baseObject : objs) { if (baseObject.getNumber() == objectNumber) { bObj = baseObject; } } return Optional.fromNullable(bObj); }

Target:
add break statement
Source:
public Optional<IPageTypeCategoryRole> getTypeCategoryForCatName(String categoryName) { loadTypeNameToCategoryMap(); return Optional.fromNullable(getTypeNameToCategoryMapIncludeDeprecated().get(categoryName)); }

Target:
additional loadTypeNameToCategoryMap not needed.
Source:
void checkNotTranslation(XWikiDocument doc) { String msg = "Trying to access XObjects on translation ''{0}'' of doc ''{1}''"; checkState(!isTranslation(doc), MessageFormat.format(msg, doc.getLanguage(), doc.getDocumentReference())); }

Target:
please extract to constant
Source:
private DocumentReference createDocRef(DocumentReference baseDocRef, long num) { String name = baseDocRef.getName() + num; SpaceReference parent = References.extractRef(baseDocRef, SpaceReference.class).get(); return References.create(DocumentReference.class, name, parent); }

Target:
Please use StringBuilder
Source:
public String getLayoutType(SpaceReference layoutSpaceRef) { BaseObject layoutPropertyObj = getLayoutPropertyObj(layoutSpaceRef); if ((layoutPropertyObj != null) && (layoutPropertyObj.getStringValue( ICellsClassConfig.LAYOUT_TYPE_FIELD) != null)) { return layoutPropertyObj.getStringValue(ICellsClassConfig.LAYOUT_TYPE_FIELD); } return ICellsClassConfig.PAGE_LAYOUT_VALUE; }

Target:
afaik `com.xpn.xwiki.objects.BaseCollection.getStringValue(String)` never returns null
Source:
public boolean isActivated(String name) { for (IClassCollectionRole classCollection : classCollections) { if (classCollection.getConfigName().equals(name)) { return classCollection.isActivated(); } } try { return Utils.getComponentManager().lookup(ClassPackage.class, name).isActivated(); } catch (ComponentLookupException exc) { LOGGER.debug("ClassDefinitionPackage '{}' doesn't exist", name); return false; } }

Target:
please move "lookup" before the for loop
Source:
public boolean sameObject(DocFormRequestKey other) { System.out.println("compare " + this); System.out.println("with " + other); return (this.classRef != null) && (this.objNb != null) && (this.objNb >= 0) && ObjectUtils.equals(this.classRef, other.classRef) && ObjectUtils.equals(this.objNb, other.objNb); }

Target:
Please change to log or remove.
Source:
public ZonedDateTime parse(String string) throws Exception { ZonedDateTime date; DateTimeFormatter df = this.getDateFormat(); ObjectHelper.notNull(this.pattern, "pattern"); date = ZonedDateTime.parse(string, df); return date; }

Target:
I'd change this to initialize `date` directly unless there was another reason perhaps?: ```suggestion ZonedDateTime date = ZonedDateTime.parse(string, df); ```
Source:
private Map<String, Float> classify(Model model, Translator translator, File input) throws Exception { try { return classify(model, translator, ImageIO.read(input)); } catch (IOException e) { LOG.error("Couldn't transform input into a BufferedImage"); throw new Exception("Couldn't transform input into a BufferedImage", e); } }

Target:
I'd favour to narrow down the exception being thrown here, `Exception` is too generic. Perhaps anything that inherits or it is `RuntimeExceptioon`.
Source:
public UndertowSecurityProvider getSecurityProvider() { if (this.securityProvider == null) { return getComponent().getSecurityProvider(); } return this.securityProvider; }

Target:
getter/setters should be plain, not these tricks. Instead when creating the endpoint in the component, then set the security provider on the endpoint correctly
Source:
protected Endpoint createEndpoint(String uri, String remaining, Map<String, Object> parameters) throws Exception { WorkdayConfiguration workdayConfiguration = new WorkdayConfiguration(); setProperties(workdayConfiguration, parameters); this.httpClient = createHttpClient(workdayConfiguration); this.workdayConfiguration = workdayConfiguration; Endpoint endpoint = new WorkdayEndpoint(uri, this); setProperties(endpoint, parameters); return endpoint; }

Target:
This shouldn't be done, we just need to setProperties on the endpoint, so the second one should be sufficient, take a look at the other components.
Source:
protected String getEndpointId(Endpoint ep) { String answer = doGetEndpointId(ep); boolean sanitize = camelContext != null && camelContext.getManagementStrategy().getManagementAgent().getMask(); if (sanitize != null && sanitize) { // use xxxxxx as replacements as * has to be quoted for MBean names answer = URISupport.sanitizeUri(answer); } return answer; }

Target:
primitive boolean cannot be compared with null.
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); Boolean allVersions = Boolean.valueOf(message.getHeader(CamelCMISConstants.ALL_VERSIONS, String.class)); Document document = (Document) getSessionFacade().getObjectById(objectId); document.delete(allVersions); }

Target:
You can just say message.getHeader(xxx, Boolean.class)
Source:
public void setCacheContainer(BasicCacheContainer cacheContainer) { this.cacheContainer = cacheContainer; this.setCacheFromComponent = true; System.out.println("===========<created"); }

Target:
Remove
Source:
public boolean isAllowed(Set<String> roles, List<String> allowedRoles) throws Exception { for (String role : allowedRoles) { if (roles.contains(role)) { return true; } } return false; }

Target:
Is there reason for `throws Exception` in signature?
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()); ((ElytronComponent) context.getComponent("elytron")).setElytronProvider(getElytronProvider()); return context; }

Target:
nit: `context.getComponent("elytron", ElytronComponent.class).setXXX` looks a bit nicer than casting.
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); } catch (Throwable t) { t.printStackTrace(); throw t; } }

Target:
Since you are added checked exception `KuduException` to the method signature, you don't need to catch and re-throw it again
Source:
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" + "}" + "")); } }

Target:
Is it possible to fix the ident of the Json string here?
Source:
public void add(String... values) { for (String value : values) { arguments.add(value); } }

Target:
Do you think is better to replace it with `Collection.addAll`? ```suggestion arguments.addAll(Arrays.asList(values)); ```
Source:
private boolean isSchemaAStructSchema(final Schema schema){ return schema.type().equals(Schema.Type.STRUCT); }

Target:
Please run build with `sourcecheck` profile
Source:
protected static boolean isFieldValueNotSet(final Object field) { return field == null || ObjectHelper.isEmpty(field); }

Target:
`ObjectHelper#isEmpty` already contains null check. ```suggestion return ObjectHelper.isEmpty(field); ```
Source:
public static void main(String[] args) throws Exception { System.out.println("Camel is started. Ready to run Any23 example!"); CamelContext context = new DefaultCamelContext(); context.start(); context.addRoutes(new Any23RouteBuilder()); context.addStartupListener(new Any23StartupMessage()); }

Target:
It is a bit nitpicking, but Camel is not started yet at the time of this message :-)
Source:
public Asset() { super(); getAttributes().setType("Asset"); }

Target:
Nitpicking ```suggestion ```
Source:
public 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); } } }

Target:
this method can be private
Source:
private IPFSClient ipfs() { IPFSClient client = getComponent().getIPFSClient(); if (!client.hasConnection()) client.connect(); return client; }

Target:
Okay this is better where it can self-heal and reconnect. Fix checkstyle issue however!
Source:
public String sendChat(String input) throws ChatScriptDeliveryException { if (!initialized) { return init(null); } ChatScriptMessage g = new ChatScriptMessage(this.userName, this.botName, input); return doMessage(g.toCSFormat()); }

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

Target:
You need to create own exception, when requires to change the default behavior. Please use a standard one for your use-case.
Source:
public void onApplicationEvent(ApplicationEvent event) { LOG.debug("onApplicationEvent: {}", event); if (event instanceof ContextRefreshedEvent && ((ContextRefreshedEvent) event).getApplicationContext().getId().equals(this.applicationContext.getId())) { // 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); } }

Target:
We should watch out for `ApplicationContext::getId` returning `null` ```suggestion if (event instanceof ContextRefreshedEvent && ((ContextRefreshedEvent) event).getApplicationContext() == this.applicationContext) { ```
Source:
public void serialize() { byte[] result = serializer.serialize("someKey", value); System.out.println(Arrays.toString(result)); assertArrayEquals(expectedResult, result); }

Target:
Use a log and don't print on standard out please
Source:
public void setUp() { filteringXmlStreamWriter = new FilteringXmlStreamWriter(xmlStreamWriterMock, null); filteringXmlStreamWriter.nonXmlCharFilterer = nonXmlCharFiltererMock; when(nonXmlCharFiltererMock.filter("value")).thenReturn("filteredValue"); }

Target:
Could be avoided by removing the API break mentioned earlier.
Source:
public 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; }

Target:
Please create a constant and also put it on the left side of the comparison. Thanks.
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 { entry = client.files().upload(localPath); } 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); } }

Target:
Should be `dropboxPath`
Source:
public ASN1DataFormat() { super(); this.usingIterator = false; }

Target:
Those 3 implicit super() calls could be removed.
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); } return null; }

Target:
Not sure if this method should return anything as in fact in the Mvc endpoint the return value is used for logging purpose only
Source:
public InputStream getContentStreamFor(QueryResult item) { Document document = getDocument(item); ContentStream contentStream = document.getContentStream(); if (document != null && contentStream != null) { return contentStream.getStream(); } return null; }

Target:
Won't it generate a NullPointerException when `document `is null ? Perhaps a 2 steps check or an Optional would make it.
Source:
public boolean managedCheckConnection() { boolean isValid = true; try { checkConnection(); } catch (IOException ioEx) { isValid = false; log.error("JMX check connection: {}", ioEx); } return isValid; }

Target:
Are you sure that you want to log an error there ? At first read, it's like this is just nominal case.
Source:
protected void afterConfigureProperties() { // create connection eagerly, a good way to validate configuration getZendesk(); }

Target:
Is this not better to do in doStart instead?
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)); } return instances.get(context); }

Target:
I think we can use ConcurrentHashMap::computeIfAbsent to replace synchronized and containsKey
Source:
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 = Optional.ofNullable(errors).orElse(Collections.emptyList()); }

Target:
I would make errors unmodifiable
Source:
public boolean containsKey(Object key){ return cache.containsKey(key); }

Target:
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?
Source:
public static Expression dateExpression(final String command) { return dateExpression(command, TimeZone.getDefault().getID(), ""); }

Target:
Can we use null as default timezone instead, which is the current behavior
Source:
public Source resolve(String href, String base) throws TransformerException { InputStream stream = ClassPathURIResolver.class.getClassLoader() .getResourceAsStream(rulesDir.concat(File.separator).concat(href)); if (null != stream) { return new StreamSource(stream); } else { if (null != clientUriResolver) { return clientUriResolver.resolve(href, base); } else { return new StreamSource(stream); } } }

Target:
Flip the if as we do X != null style in Camel
Source:
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; }

Target:
Run from command line this goal: mvn install -Psourcecheck in the camel-flink directory and then fix those checkstyle issues it reports
Source:
private CMISSessionFacade getSessionFacade() throws Exception { if (sessionFacade == null) { sessionFacade = sessionFacadeFactory.create(); sessionFacade.initSession(); } LOG.info("getSessionFacade {}", sessionFacade); return sessionFacade; }

Target:
Reduce the logging level to debug or trace
Source:
public Builder(String rootServerURL) { pushConfiguration = new PushConfiguration(); if (isEmpty(rootServerURL)) { throw new IllegalStateException("server can not be null"); } pushConfiguration.setServerUrl(!rootServerURL.endsWith("/") ? rootServerURL + '/' : rootServerURL); }

Target:
is this the only usage for the ctor? if so, perhaps we don't wanna make it public
Source:
public void testSelectorWidget() { final Button b1 = new Button("Button click"); RootPanel.get().add(b1); GQuery g = $(b1); assertTrue($(b1).isVisible()); g.hide(); assertFalse($(b1).isVisible()); b1.removeFromParent(); }

Target:
nit: should be g.isVisible, reusing the instance is a gquery (and jquery) good-practice for performance reasons, the same above
Source:
public final <J extends IsProperties> J strip() { return getDataImpl(); }

Target:
It should return this
Source:
public static Path createTempFile(String suffix) { try { Path path = Files.createTempFile("jadx-tmp-", System.nanoTime() + '-' + suffix); path.toFile().deleteOnExit(); return path; } catch (IOException e) { throw new JadxRuntimeException("Failed to create temp file with suffix: " + suffix); } }

Target:
Looks like `System.nanoTime()` not needed here, and was not needed in the previous version :)
Source:
public ApkSignature(File openFile) { super(); this.openFile = openFile; }

Target:
`super()` can be removed
Source:
public static synchronized void storeInteractionForCurrentAppVersion(Context context, String name) { storeRecordForCurrentAppVersion(context, false, name); }

Target:
should the second arg be true here?
Source:
public ComparableComparator getInstance(){ return INSTANCE; }

Target:
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.
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; return super.create(key); }

Target:
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.
Source:
protected Object unwrapCachedValue(Object cached) { if (currentKey instanceof EnhancerKey) { return ((WeakReference<EnhancerFactoryData>) cached).get(); } return super.unwrapCachedValue(cached); }

Target:
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.
Source:
private boolean isMultipartRequest(WebRequest request) { String contentType = request.getHeader("Content-Type"); return StringUtils.startsWithIgnoreCase(contentType, "multipart"); }

Target:
Good catch
Source:
private boolean skipDispatch(HttpServletRequest request) { if (isAsyncDispatch(request) && shouldNotFilterAsyncDispatch()) { return true; } return request.getAttribute(WebUtils.ERROR_REQUEST_URI_ATTRIBUTE) != null && shouldNotFilterErrorDispatch(); }

Target:
Although the proposed changed is technically correct, please revert this for the sake of readability.
Source:
public boolean isReadOnly(ELContext elContext, @Nullable Object base, Object property) throws ELException { if (base == null) { String beanName = property.toString(); WebApplicationContext wac = getWebApplicationContext(elContext); return wac.containsBean(beanName); } return false; }

Target:
Although the proposed changed is technically correct, please revert this for the sake of readability.
Source:
protected void registerAfterCompletionWithExistingTransaction( Object transaction, List<TransactionSynchronization> synchronizations) throws TransactionException { if(logger.isDebugEnabled()){ 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); }

Target:
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'"); ```
Source:
public static BodyBuilder method(HttpMethod method, String uri) { return new DefaultBodyBuilder(method, new UriTemplate(uri)); }

Target:
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.
Source:
private Message.Builder getMessageBuilder(Class<?> clazz) { try { 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); } }

Target:
Please check [our guidelines](https://github.com/spring-projects/spring-framework/wiki/Code-Style#formatting) on source code style.
Source:
public EhCacheCacheManager(net.sf.ehcache.CacheManager cacheManager) { this(false, cacheManager); }

Target:
While I am not denying the setter is confusing, this is not the scope of this PR to change that.
Source:
public HttpMethod getMethod() { HttpMethod method = HttpMethod.resolve(this.jettyRequest.getMethod()); Assert.notNull(method, "Method must not be null"); return method; }

Target:
Seems like `Assert.state` is more suitable here, because `notNull` results in an `IllegalArgumentException`.
Source:
public SimpMessageType getMessageType() { return (simpMessageType != null) ? simpMessageType : SimpMessageType.OTHER; }

Target:
Instead of checking for null here, why not just pass SimpMessageType.OTHER instead of null to the constructors?
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); } }

Target:
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).
Source:
public List<TriggerTask> getTriggerTaskList() { return this.triggerTasks; }

Target:
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!
Source:
protected FluentList<FluentWebElement> find() { FluentListImpl<FluentWebElement> elements = new FluentListImpl<>(); if (this.untilElements != null) { 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; }

Target:
is `this` operator required here
Source:
private UrlUtil() { throw new UnsupportedOperationException("No instances allowed"); }

Target:
making this class final should be OK without this exception.
Source:
public long length() throws IOException { return exists() ? writeRaf().length() : -1; }

Target:
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.)
Source:
public long offset() throws IOException { return exists() ? writer().getFilePointer() : 0; }

Target:
This should be `reader()`.
Source:
public void show(final Object o) { final UserInterface defaultUI = getDefaultUI(); if (defaultUI == null) { return; } defaultUI.show(o); }

Target:
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.
Source:
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); }

Target:
This is a really nitty picky nit pick: I find `!(o instanceof Identifiable && o instanceof Locatable)` slightly clearer...
Source:
public static void logMetricForSum(String name, double sum, int quantity) { logMetricInternal(name, "S,C", String.format("%s,%.2f", sum, quantity)); }

Target:
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) { 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()); } }

Target:
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
Source:
private static void log(Level level, Throwable ex, String msg, Object... data) { modLog.log(level, () -> data == null ? msg : String.format(msg, data), ex); }

Target:
modLog might be `null` here
Source:
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]; }

Target:
Please add the `{}` even for one-liners
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}; } return valueArray; }

Target:
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.
Source:
public void setClientCapabilites(List<String> clientCapabilites){ this.mClientCapabilites = clientCapabilites; }

Target:
this. is not required
Source:
public static InstanceDiscoveryMetadata getCachedInstanceDiscoveryMetadata(final URL authorityUrl) { return sAadAuthorityHostMetadata.get(authorityUrl.getHost().toLowerCase(Locale.US)); }

Target:
This class isn't `public` but these methods are.... 🤔
Source:
private void logReturnedToken(final AuthenticationResult result) { if (result != null && result.getAccessToken() != null) { String accessTokenHash = getTokenHash(result.getAccessToken()); String refreshTokenHash = getTokenHash(result.getRefreshToken()); Logger.i(TAG, "Access tokenID and refresh tokenID returned. ", String.format( "Access TokenID: %s and Refresh TokenID: %s .", accessTokenHash, refreshTokenHash)); } }

Target:
delete this function, we should not log tokens
Source:
} catch (URISyntaxException e) { // will not throw throw new RuntimeException(e); }

Target:
Can we throw an IllegalArgumentException instead?
Source:
public void registerDispatcher(final IDispatcher dispatcher, final boolean aggregationRequired) { if (aggregationRequired) { mDispatcher = new AggregatedDispatcher(dispatcher); } else { mDispatcher = new DefaultDispatcher(dispatcher); } }

Target:
aren't `mDispatcher` should be syncronized? #Resolved
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); } else { return getUserInfoFromAccountManager(); } }

Target:
>else [](start = 10, length = 4) else is not required #Resolved
Source:
AcquireTokenInteractiveRequest(final Context context, final AuthenticationRequest authRequest, final TokenCacheAccessor tokenCacheAccessor) { mContext = context; mTokenCacheAccessor = tokenCacheAccessor; mAuthRequest = authRequest; if (mTokenCacheAccessor != null) { mTokenCacheAccessor.setAuthRequest(authRequest); } }

Target:
ah? why token cache accessor needs to know auth request? #Closed
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); flush(); }

Target:
> flush() [](start = 4, length = 11) flush? #Closed
Source:
TokenCacheItem getRegularRefreshTokenCacheItem(final String resource, final String clientId, final String user) { 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; }

Target:
> CacheEvent cacheEvent [](start = 8, length = 21) line 94 and line 111 :) #Closed
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 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); } } //CHECKSTYLE:ON: checkstyle:MemberName //CHECKSTYLE:ON: checkstyle:VisibilityModifier }; }

Target:
sorry about this, but how about just making this private? does it break anything? #Closed