auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
MimeBodyPart multipart(String type, BodyPart... subParts) throws MessagingException { MimeMultipart multiPart = new MimeMultipart(); multiPart.setSubType(type); for (BodyPart subPart : subParts) { multiPart.addBodyPart(subPart); } MimeBodyPart resultPart = new MimeBodyPart(multiPart); createdMultiparts.add(resultPart); return resultPart; }

Target:
Instead of using `createdMultiparts` I think tests would be easier to read if `message` were used to retrieve a reference to the desired child part. Maybe with a helper method that makes addressing parts easier, e.g. ``` java Part signaturePart = getPart(message, "1.1"); ``` to get the `application/pgp-signature` from ``` java Message message = messageFromBody( multipart("mixed", bodypart("text/plain"), multipart("signed", bodypart("text/plain"), bodypart("application/pgp-signature") ) ) ); ``` (Not that we need a reference to the signed part. Just makes for a better example.)
Source:
private Message buildLargeNewMessage() { Message message = mock(Message.class); when(message.olderThan(any(Date.class))).thenReturn(false); when(message.getSize()).thenReturn(MAXIMUM_SMALL_MESSAGE_SIZE+1); return message; }

Target:
Code style issue: spaces missing in expression; should be `MAXIMUM_SMALL_MESSAGE_SIZE + 1`
Source:
public abstract void setSentDate(Date sentDate, boolean hideTimeZone) throws MessagingException; public abstract Address[] getRecipients(RecipientType type) throws MessagingException; public abstract Address[] getListPost(); public abstract void setRecipients(RecipientType type, Address[] addresses) throws MessagingException; public void setRecipient(RecipientType type, Address address) throws MessagingException { setRecipients(type, new Address[] { address }); }

Target:
Please don't add more utility methods to `Message`. Instead you could create a method `ListHeaders.getListPostAddress(Message)` that gets the appropriate header from the message.
Source:
MimeBodyPart(MimeHeader header, Body body) throws MessagingException { this(body); mHeader = header; }

Target:
If you make the other constructors call this one, you can keep `mHeader` as `final`
Source:
private String combineFlags(Iterable<Flag> flags) { List<String> flagNames = new ArrayList<String>(); for (Flag flag : flags) { // client's can't add the RECENT flag! if( !flag.equals(Flag.RECENT) ) flagNames.add(flag.realName()); } return combine(flagNames.toArray(new String[flagNames.size()]), ' '); }

Target:
curly brackets avoid goto fail :-)
Source:
public void splitCompleteUserIdShouldReturnAll3Components() throws Exception { OpenPgpUtils.UserInfo info = OpenPgpUtils.splitUserId("Max Mustermann (this is a comment) <max@example.com>"); assertEquals(info.name, "Max Mustermann"); assertEquals(info.comment, "this is a comment"); assertEquals(info.email, "max@example.com"); }

Target:
the `assertEquals` param order is `expected, actual`, so this (and all other assertions) should be written as ``` java assertEquals("Max Mustermann", info.name); ```
Source:
public boolean equals(Object o) { if (!(o instanceof ObjectProperty)) { return false; } ObjectProperty that = (ObjectProperty) o; if (properties != null ? !properties.equals(that.properties) : that.properties != null) { return false; } return super.equals(o); }

Target:
can you possibly just add ``` if (this == o) { return true; } ```
Source:
public Operation response(int key, Response response) { this.addResponse(String.valueOf(key),response); this.addResponseObject(String.valueOf(key),response); return this; }

Target:
only add to responseObject
Source:
public Operation defaultResponse(Response response) { this.addResponse("default",response); this.addResponseObject("default",response); return this; }

Target:
only add to responseObject
Source:
public void setResponses(Map<String, Response> responses) { this.responses = responses; if (this.responsesObject == null && responses != null) { this.responsesObject = new Responses(); for (String key : responses.keySet()) { this.responsesObject.put(key, responses.get(key)); } } }

Target:
remove all added logic, as such logic is handled in the getter
Source:
public void setResponsesObject(Responses responsesObject) { this.responsesObject = responsesObject; if (responses == null && responsesObject != null) { responses = new LinkedHashMap<String, Response>(); for (String key : this.responsesObject.keySet()) { responses.put(key, responsesObject.get(key)); } } }

Target:
remove all added logic, as such logic is handled in the getter
Source:
public static void main(String[] args) { try { new StartMain(args).go(); System.exit(0); } catch (Throwable t) { StreamSupport.stream(exceptionHandlerLoader.spliterator(), false) .filter(eh -> eh.supports(t)) .findFirst() .orElse(new DefaultExceptionHandler()) .handle(t); System.exit(1); } }

Target:
I think there is no need to use streams here...
Source:
public String toString() { return "Configurator observer method [Bean class = " + getBeanClass().toString() + ", type = " + getObservedType() + ", qualifiers =" + Formats.formatAnnotations(getObservedQualifiers()) + ", priority =" + getPriority() + ", async =" + isAsync() + ", reception =" + getReception() + ", transaction phase =" + getTransactionPhase() + "]"; }

Target:
I'm not sure why but we allow to set `null` bean class. If you remove `toString()` here, then this method should not throw NPE and the resulting string should be the same.
Source:
public <X> WeldInstance<X> select(Type subtype, Annotation... qualifiers) { // verify if this was invoked on WeldInstance<Object> if (!this.getType().getTypeName().equals(Object.class.getName())) { throw BeanLogger.LOG.selectByTypeOnlyWorksOnObject(); } // This cast should be safe, we make sure that this method is only invoked on WeldInstance<Object> // and any type X will always extend Object return (WeldInstance<X>)selectInstance(subtype, qualifiers); }

Target:
`!this.getType().equals(Object.class)` should be fine...
Source:
public ScheduledExecutorService getTimerExecutor() { if (timerExecutor == null) { timerExecutor = Executors.newScheduledThreadPool(1, new DaemonThreadFactory(new ThreadGroup("weld-workers"), "weld-timer-")); } return timerExecutor; }

Target:
I would extract "weld-workers" to a constant on the `DaemonThreadFactory`.
Source:
public static Archive<?> createTestArchive() { return ClassPath.builder().add(ShrinkWrap.create(BeanArchive.class, Utils.getDeploymentNameAsHash(WeldInstanceTest.class)) .addPackage(ParallelNotificationModeTest.class.getPackage())).build(); }

Target:
Just noticed the minor here - referencing another test in `Utils.getDeploymentNameAsHash`
Source:
static void processAnnotatedType(@Observes ProcessAnnotatedType<?> pat) { pat.veto(); }

Target:
Please remove this invocation. Right now, the test would pass even without your `ExtensionBeanDeployer` modification. If you remove the invocation, the test would fail without the modification. Otherwise looks good now.
Source:
private void fireContainerInitializedEvent() { beanManager().fireEvent(new ContainerInitialized(id), Initialized.Literal.APPLICATION); WeldSELogger.LOG.weldContainerInitialized(id); }

Target:
Hm, don't move the message - it should be logged before the event, otherwise it will never appear if a `ContainerInitialized` observer blocks...
Source:
public void vetoedAlternativesShouldBeRejected() { try { deployer.deploy("VetoedAlternativeWithoutPropertyWar"); Assert.fail("A web application deployed successfuly with a vetoed bean defined as an alternative in the beans.xml and the property org.jboss.weld.bootstrap.allowExcludedAlternatives was left as it's default value"); } catch (Exception e) { Assert.assertTrue(e.getMessage().contains("WELD-001422")); } }

Target:
This assertion probably fails because when running in-container Arquillian tests the `DeploymentExceptionTransformer` is used to extract the final exception and message (see also https://github.com/weld/core/blob/master/tests-arquillian/src/test/java/org/jboss/weld/tests/util/WildFly8DeploymentExceptionTransformer.java). I would leave out this assertion completely. Also I would replace the `Deployer` API with `@org.jboss.arquillian.container.test.api.ShouldThrowException`.
Source:
public void mockAlternativeIsVetoed() { Assert.assertEquals(getUniqueBean(PaymentProcessor.class).getName(), "paymentProcessorImpl"); }

Target:
You should swap the method arguments I guess. Testng use different order than JUnit. Same for other `assertEquals` mehtods.
Source:
private static boolean isAlternativeStereotype(BeanManagerImpl beanManager, Class<? extends Annotation> stereotype) { final StereotypeModel<? extends Annotation> model = beanManager.getServices().get(MetaAnnotationStore.class).getStereotype(stereotype); if (model.isValid() && model.isAlternative()) { return true; } return false; }

Target:
Is there a reason to have this `static`? If not, I would remove it.
Source:
FastAnnotatedTypeLoader(BeanManagerImpl manager, ClassTransformer transformer, ClassFileServices classFileServices, ContainerLifecycleEvents events, FastProcessAnnotatedTypeResolver resolver) { super(manager, transformer, events); this.fallback = new AnnotatedTypeLoader(manager, transformer, events); this.classFileServices = classFileServices; this.resolver = resolver; this.checkTypeModifiers = initCheckTypeModifiers(); if (!checkTypeModifiers) { BootstrapLogger.LOG.usingOldJandexVersion(); } }

Target:
I would move the log message inside the catch block on line 139.
Source:
public ClassFileInfo getClassFileInfo(String className) { if (!jandexStaticCheckAvailable) { throw new ClassFileInfoException("Using old Jandex version."); } return new JandexClassFileInfo(className, index, annotationClassAnnotationsCache, classLoader); }

Target:
Altough it seems logical to throw exception here, I'd rather throw it in `ClassFileInfo.getModifiers()`. The reason is performance - `FastAnnotatedTypeLoader` can sucessfully "skip" many classes (annotation, `@Vetoed`... see also `FastAnnotatedTypeLoader.loadAnnotatedType()`)
Source:
public Set<Type> getTypes() { HashSet<Type> types = new HashSet<Type>(); types.add(BuilderInterceptorInstance.class); types.add(Object.class); return types; }

Target:
As I already said - this should be an immutable set cached in a private static final field.
Source:
public BeanBuilder<T> addInjectionPoints(Set<InjectionPoint> injectionPoints) { checkArgumentNotNull(injectionPoints, ARG_INJECTION_POINTS); Collections.addAll(this.injectionPoints, injectionPoints.toArray(new InjectionPoint[injectionPoints.size()])); return this; }

Target:
`this.injectionPoints.addAll(injectionPoints)`?
Source:
public void close() throws Exception { shutdown(); }

Target:
We should make this less restrictive and remove the "throws Exception" clause.
Source:
private Map<String, ManagedConversation> getConversationMap() { checkIsAssociated(); checkContextInitialized(); R request = getRequest(); Object attribute = getRequestAttribute(getRequest(), CONVERSATIONS_ATTRIBUTE_NAME); if (attribute == null || !(attribute instanceof Map)) { throw ConversationLogger.LOG.unableToLoadConversations(CONVERSATIONS_ATTRIBUTE_NAME, attribute, request); } return cast(attribute); }

Target:
reduntant `getRequest()` call
Source:
public static <T> Class<T> loadClass(String className, ResourceLoader resourceLoader) { try { return cast(resourceLoader.classForName(className)); } catch (ResourceLoadingException e) { return null; } catch (AccessControlException e) { return null; } catch (SecurityException e) { return null; } }

Target:
ACE is a subclass of SecurityException
Source:
public String[] getParameterTypes() { return parameterTypes.clone(); }

Target:
This is not necessary as we have the control, suppress.
Source:
public ParameterizedTypeImpl(Type rawType, Type[] actualTypeArguments, Type ownerType) { this.actualTypeArguments = actualTypeArguments.clone(); this.rawType = rawType; this.ownerType = ownerType; }

Target:
This is not necessary as we have the control, suppress.
Source:
public Type[] getActualTypeArguments() { return actualTypeArguments.clone(); }

Target:
This is not really necessary as we have the control. We should suppress the warning here instead.
Source:
private boolean hasDeadlineExpired(final Date deadline) { if (deadline != null) { return System.currentTimeMillis() > deadline.getTime(); } else { return false; } }

Target:
It seems like these two deadline-related methods could be `static`.
Source:
public Field notFound(Class<?> type, boolean isInstanceField) throws FieldNotFoundException { throw new FieldNotFoundException(String.format( "No %s field of type \"%s\" could be found in the class hierarchy of %s.", isInstanceField ? "instance" : "static", expectedFieldType.getName(), type.getName())); }

Target:
Hmm, what would you like to achieve keeping `void` in the interface?
Source:
public PartialUpdate<T> del(String path) { Assert.hasText(path, "Path to remove must not be null or empty!"); propertyUpdates.add(new PropertyUpdate(UpdateCommand.DEL, path)); return new PartialUpdate<T>(this.id, this.target, this.value, this.refreshTtl, this.propertyUpdates); }

Target:
`PartialUpdate` changes its own state and creates a new instance.
Source:
public List<Float> apply(Iterable<String> values) throws InvalidAttributeValueException { ImmutableList.Builder<Float> floats = ImmutableList.builder(); for (String value : values) { try { floats.add(Float.valueOf(value)); } catch (NumberFormatException nfe) { throw new InvalidAttributeValueException(value); } } return floats.build(); }

Target:
Not to be a little female dog, but generally good style to include the cause in the exception you throw.
Source:
public void unlock(T id) { log.trace("{} trying to unlock {}", Thread.currentThread().getName(), id.toString()); synchronized (locked) { if (locked.remove(id)) { log.trace("{} unlocked {}", Thread.currentThread().getName(), id.toString()); idsLocked.update(-1); locked.notifyAll(); } } }

Target:
`idsLocked` is a histogram that records how many Ids are locked at a time every time someones calls lock(). It's not a counter. This statement effectively means that someone tried to lock -1 ids.
Source:
protected void removeColumn(ColumnListMutation<String> mutation, String column) { mutation.deleteColumn(column); }

Target:
Don't you just love it when someone extracts an interface that can only ever be implemented by an Astyanax driver using Protobuf? :D
Source:
public void write(@Nonnull PriorityScoreReasons entity, @Nonnull FieldWriter writer, @Nonnull OutputContext ctxt) throws IOException { writer.writeList( "positive", "positive", entity.getPositive() != null ? entity.getPositive() : null, ctxt ); writer.writeList( "negative", "negative", entity.getNegative() != null ? entity.getNegative() : null, ctxt ); }

Target:
This is pointless, it's equivalent to just passing `entity.getPositive()`.
Source:
public ListenableFuture<ResolvedEquivalents<E>> resolveIds(Iterable<Id> ids, ApplicationSources sources, Set<Annotation> activeAnnotations) { if(!activeAnnotations.contains(Annotation.NON_MERGED)) { ListenableFuture<ResolvedEquivalents<E>> unmerged = resolver.resolveIds(ids, sources.getEnabledReadSources(), activeAnnotations); return Futures.transform(unmerged, mergeUsing(sources)); } else { return resolver.resolveIdsWithoutEquivalence(ids, sources.getEnabledReadSources(), activeAnnotations); } }

Target:
Best avoid negative conditions where it's reasonable. Positive assertions are a bit easier to reason about and that "!" can easily be missed. Here you can just flip the if.
Source:
private boolean hasHigherPrecedence(Publisher currentPublisher, Publisher existingPublisher, Iterable<Publisher> publisherPrecedence) { for (Publisher publisher : publisherPrecedence) { if (publisher == existingPublisher) { return false; } if (publisher == currentPublisher) { return true; } } // This should never happen as the delegate uses the same publishers for the query LOG.warn("Delegate content index returned publisher that was not asked for." + " Requested publishers: {}", currentPublisher, publisherPrecedence); return false; }

Target:
If this should really **never** **ever** happen, we should probably log it as an error, not warning.
Source:
public CassandraSegmentStore(CassandraDataStaxClient cassandra, String keyspace, String tableName, AliasIndex<Segment> aliasIndex, IdGenerator idGenerator, Equivalence<? super Segment> equivalence, MessageSender<ResourceUpdatedMessage> sender) { super(idGenerator, equivalence, sender, new SystemClock()); this.cassandra = checkNotNull(cassandra); this.aliasIndex = checkNotNull(aliasIndex); this.keyspace = checkNotNull(keyspace); this.tableName = checkNotNull(tableName); }

Target:
this should probably be private
Source:
public ModelAndView contextJSONLD(@RequestParam(value = "callback", required = false) String callback) { String jsonld = null; try { jsonld = com.github.jsonldjava.utils.JsonUtils.toString(jsonldContext); } catch (IOException e) { LOG.error("Error in Json serialization", e); } return JsonUtils.toJson(jsonld, callback); }

Target:
removed
Source:
public void turtleWriterTest() throws IOException { InputStream rdfInput = TurtleRecordWriter.class.getClassLoader().getResourceAsStream(RDF_INPUT_TEST); Model modelResult = ModelFactory.createDefaultModel().read(rdfInput, "", "RDF/XML"); OutputStream outputStream = new ByteArrayOutputStream(); TurtleRecordWriter writer= new TurtleRecordWriter(outputStream); writer.write(modelResult); //check if null Assert.assertNotNull(outputStream); outputStream.close(); }

Target:
closed
Source:
public long getSize() { return size; }

Target:
etc. for the rest
Source:
private String convertBoolean(final String value) { String result = value; if (result.equals("true")) { result = "Yes"; } if (result.equals("false")) { result = "No"; } return result; }

Target:
I would recommend an `else if` here to avoid comparing against a string unnecessarily.
Source:
public boolean isSuccess(CompletionStage<Void> future) { try { FunctionalTestUtils.await(future); return true; } catch (Error e) { return false; } }

Target:
Why not ```catch Throwable``` ? I have strange gut feelings for Error
Source:
public void validate(GlobalConfiguration globalConfig) { Attribute<String> location = attributes.attribute(LOCATION); if (location.isNull() && !globalConfig.globalState().enabled()) { Log.CONFIG.storeLocationRequired(); } super.validate(globalConfig); }

Target:
We can remove this as the error will always be thrown on startup via `PersistenceUtil#getLocation`.
Source:
public AutoCloseable scheduleWithFixedDelay(Supplier<CompletionStage<?>> supplier, long initialDelay, long delay, TimeUnit unit) { ReschedulingTask task = new ReschedulingTask(supplier, delay, unit); task.future = scheduler.schedule(task, initialDelay, unit); return task; }

Target:
synchronize? if `initialDelay` is zero, the scheduler may run the "task" before the `future`is set.
Source:
private CompletionStage<Void> awaitQuiescence() { CompletionStage<Void> stage; synchronized (this) { stage = batchFuture; } if (stage == null) { return CompletableFutures.completedNull(); } if (trace) { log.tracef("Must wait until prior batch completes for %s", actual); } return batchFuture.thenCompose(ignore -> awaitQuiescence()); }

Target:
```suggestion return stage.thenCompose(ignore -> awaitQuiescence()); ```
Source:
public ForkedServer start() { boolean isServerStarted; ProcessBuilder pb = new ProcessBuilder(); pb.command(commands); try { process = pb.start(); isServerStarted = runWithTimeout(this::checkServerLog, START_PATTERN); if (!isServerStarted) { throw new IllegalStateException("The server couldn't start"); } } catch (Exception e) { log.error(e); } log.info("SERVER STARTED!"); return this; }

Target:
No need for this.
Source:
AttributeChangeTracker(AttributeSet attributeSet) { attributeSet.attributes().forEach(a -> a.addListener((attr, oldVal) -> { if (this.isTracking) { String name = attr.name(); Object value = attr.get(); changedAttributes.add(name.concat("=").concat(value == null ? "" : value.toString())); } })); }

Target:
Why calling concat here? I would worry this would prevent StringBuilder optimization for +'s.
Source:
public void listPatches(Path target, boolean verbose) { List<PatchInfo> installedPatches = getInstalledPatches(target); if (installedPatches.size() == 0) { out.println(MSG.patchNoPatchesInstalled()); } else { for (PatchInfo patchInfo : installedPatches) { out.println(MSG.patchInfo(patchInfo)); if (verbose) { patchInfo.getOperations().forEach(op -> out.println(" " + op)); } } } }

Target:
```suggestion if (installedPatches.isEmpty()) { ```
Source:
private boolean identifiedByName(Class<?> type) { return Map.class.equals(type) || byte[].class.equals(type); }

Target:
I think this `Map.class.equals(type)` is a remnant from a previous implementation and can be removed?
Source:
public void addItem(Object key, Object value, CompletableFuture<?> future) { // This is what HS5 currently does, but introduce chunking could be a good idea. future.whenComplete((result, exception) -> { if (exception != null) { notifier.notifyEntityIndexingFailure(value.getClass(), key, exception); } else { notifier.notifyDocumentsAdded(1); } }).thenCombine(lastFuture, (ignored1, ignored2) -> null); }

Target:
You forgot to update `lastFuture`.
Source:
protected EmbeddedCacheManager createCacheManager() throws Exception { ConfigurationBuilder builder = new ConfigurationBuilder(); builder.indexing().enable() .addProperty(SearchConfig.DIRECTORY_TYPE, SearchConfig.HEAP); return TestCacheManagerFactory.createCacheManager(builder); }

Target:
Why does it need to be HEAP?
Source:
public <T, U> InternalRemoteCache<T, U> withDataFormat(DataFormat dataFormat) { InternalRemoteCache<T, U> newCache = delegate.withDataFormat(dataFormat); if (newCache != delegate) { return newDelegatingCache(newCache); } return (InternalRemoteCache) this; }

Target:
Remove the warning from IDE ```suggestion //noinspection unchecked return (InternalRemoteCache<T, U>) this; ```
Source:
public static <K, V, C> Function<CacheEntry<K, V>, CacheEntry<K, C>> converterToFunction(KeyValueFilterConverter<? super K, ? super V, C> filterConverter) { return new FilterConverterAsCacheEntryFunction<K, V, C>(filterConverter); }

Target:
IntelliJ says the type parameters are not needed
Source:
public boolean isConversionSupported(MediaType mediaType) { if (encoderRegistry == null) return false; return encoderRegistry.isConversionSupported(storageMediaType, mediaType); }

Target:
I just updated https://github.com/infinispan/infinispan/pull/8196
Source:
private CacheEventFilter<Object, String> filter(Object keyToFilter) { return (Serializable & CacheEventFilter<Object, String>) (k, oldValue, oldMetadata, newValue, newMetadata, eventType) -> { boolean retVal = Objects.equals(k, keyToFilter); return retVal; }; }

Target:
Can make this one line and remove brackets now.
Source:
public void testSingleServer() { ConfigurationBuilder builder = new ConfigurationBuilder(); builder.clientIntelligence(ClientIntelligence.BASIC); RemoteCache<String, String> cache = SERVER_TEST.hotrod().withClientConfiguration(builder).withCacheMode(CacheMode.DIST_SYNC).create(); cache.put("k1", "v1"); assertEquals(1, cache.size()); assertEquals("v1", cache.get("k1")); }

Target:
Wrong indent, and the previous line should be wrapped
Source:
Object extractValue(DocumentExtractor extractor, int docIndex) { Object[] projection; try { projection = extractor.extract(docIndex).getProjection(); } catch (IOException e) { throw new SearchException("Error while extracting projection", e); } if (projection == null) { Object key = extractKey(extractor, docIndex); return cache.get(fromStorage(key)); } return projection; }

Target:
Here too, if the cache injected in components has request media type == storage media type, then the conversion isn't necessary. Edit: You would still have to convert the value to the request media type, but I would rather make that conversion explicit here instead of converting the key back and forth.
Source:
public RepeatableReadEntry(Object key, Object value, Metadata metadata) { super(key, value, metadata); this.oldMetadata = metadata; }

Target:
I think you need to move the `oldMetadata` to `ReadCommittedEntry`
Source:
public void serialize(Appender appender, JsonGenerator json, SerializerProvider serializerProvider) throws IOException { json.writeStartObject(); json.writeStringField("name", appender.getName()); Layout<? extends Serializable> layout = appender.getLayout(); json.writeEndObject(); }

Target:
layout isn't used.
Source:
public void segmentsFinished(byte[] finishedSegments) { if (trackSegments) { if (finishedSegments != null) { BitSet bitSet = BitSet.valueOf(finishedSegments); if (trace) log.tracef("Removing completed segments %s", bitSet); bitSet.stream().forEach(seg -> keysPerSegment.set(seg, null)); } } }

Target:
nitpick: `if (trackeSegments && finishedSegments != null)`
Source:
public IndexingConfigurationBuilder index(Index index) { if (index != Index.NONE) enabled(true); attributes.attribute(INDEX).set(index); return this; }

Target:
The conditional thing seems wrong. This should probably be just ```enabled(index !=null && index != Index.NON);```
Source:
public TaskParameter(String key, String value) { this.key = key; this.value = value; }

Target:
Class and constructor can be package-private as only used internally.
Source:
public CompletableFuture<Object> invokeAsync(InvocationContext ctx, VisitableCommand command) { try { command.init(componentRegistry); Object result = firstInterceptor.visitCommand(ctx, command); if (result instanceof InvocationStage) { return ((InvocationStage) result).toCompletableFuture(); } else { // Don't allocate future if result was already null if (result == null) { return CompletableFutures.completedNull(); } return CompletableFuture.completedFuture(result); } } catch (Throwable t) { return CompletableFutures.completedExceptionFuture(t); } }

Target:
I don't think this is needed on the originator: `keyDataConversion` and `valueDataConversion` are not private to the command, they're already wired, and even if `wireDependencies` is idempotent, it's not that cheap. `SingleRpcCommand` and `PrepareCommand` already init the sub-commands on the target nodes, you just need to add it in `BackupWriteCommand`.
Source:
public boolean hasZeroLockAcquisition() { if (modifications == null || modifications.length == 0) { return false; } boolean hasZeroLock = true; for (WriteCommand wc : modifications) { // If even a single command doesn't have the zero lock acquisition timeout flag, we can't use a zero timeout if (!wc.hasAnyFlag(FlagBitSets.ZERO_LOCK_ACQUISITION_TIMEOUT)) { hasZeroLock = false; break; } } return hasZeroLock; }

Target:
Could `return false` and avoid the variable.
Source:
AdvancedCache<K, V> cacheToUse(boolean isWrite) { // For non writes we don't have any lock wait time. This is to prevent deadlocks with a concurrent write and // also so that multiple gets, only one will win. // Pessimistic caches will already hold the lock for the read value and thus we have to skip locking // Optimistic will not hold the lock at this point and thus we always have to lock the entry return isWrite ? optimisticTransaction ? cache : cache.withFlags(Flag.SKIP_LOCKING) : cache.withFlags(Flag.ZERO_LOCK_ACQUISITION_TIMEOUT); }

Target:
Some parentheses to improve readability please
Source:
final CompletableFuture<Void> removeLifespanExpired(K key, V value, Long lifespan, long explicitFlags) { long flagBitSet = explicitFlags | FlagBitSets.SKIP_CACHE_LOAD | FlagBitSets.SKIP_SHARED_CACHE_STORE | FlagBitSets.SKIP_XSITE_BACKUP; RemoveExpiredCommand command = commandsFactory.buildRemoveExpiredCommand(key, value, keyPartitioner.getSegment(key), lifespan, flagBitSet); // Remove expired returns a boolean - just ignore it, the caller just needs to know that the expired // entry is removed when this completes CompletableFuture<Boolean> completableFuture = performRemoveExpiredCommand(command); return completableFuture.thenApply(b -> null); }

Target:
I don't think we can do this here. We need to set the flag on the cache in the reaper. Otherwise a get which removes the expired entry won't remove the entry from the shared store possibly.
Source:
public CommandResult exec(ContextAwareCommandInvocation invocation) { if (help) { invocation.println(invocation.getHelpInfo()); } CommandInputLine cmd = new CommandInputLine(Task.CMD) .arg(TYPE, Task.Exec.CMD) .arg(NAME, taskName) .arg(PARAMETERS, parameters != null ? parameters : Collections.emptyMap()); return invocation.execute(cmd); }

Target:
why not init the parameters to emptyMap ?
Source:
public String describe() throws IOException { return NAME;//TODO }

Target:
//TODO ?
Source:
public void cacheManagerStarting(GlobalComponentRegistry gcr, GlobalConfiguration globalConfiguration) { BasicComponentRegistry bcr = gcr.getComponent(BasicComponentRegistry.class); Interpreter interpreter = new Interpreter(); bcr.registerComponent(Interpreter.class, interpreter, true); if (globalConfiguration.statistics()) { try { CacheManagerJmxRegistration jmxRegistration = bcr.getComponent(CacheManagerJmxRegistration.class).running(); jmxRegistration.registerMBean(interpreter); } catch (Exception e) { log.jmxRegistrationFailed(); } } }

Target:
-1 since the interpreter is only used with JMX now.
Source:
public void verifyTopology(LocalizedCacheTopology localizedCacheTopology) { for (PrimitiveIterator.OfInt segmentIterator = segments.iterator(); segmentIterator.hasNext(); ) { int segment = segmentIterator.nextInt(); if (!localizedCacheTopology.isSegmentReadOwner(segment)) { if (trace) { log.tracef("Listener %s lost segment %d before invocation", this, segment); } segmentIterator.remove(); } } }

Target:
protected or package-private
Source:
public void clearTempDir() { Util.recursiveFileRemove(tmpDirectory); }

Target:
Need `@AfterClass(alwaysRun = true)` as well to run after failures Edit: Also `if (tmpDirectory != null)`
Source:
protected void adaptLONConfiguration(BackupConfigurationBuilder builder) { builder.stateTransfer().chunkSize(2).timeout(2000).maxRetries(2); }

Target:
Ouch, default MAX_RETRIES is 30??? To me even 2 is excessive in a test :)
Source:
public void validate() { if (connectionFactory != null) { connectionFactory.validate(); } // TODO: I don't think this is quite correct... if (attributes.attribute(MANAGE_CONNECTION_FACTORY).get() && (connectionFactory == null || connectionFactory.needsManaging())) { table.validate(); } super.validate(); }

Target:
Can't we do this without the need for the `needsManaging` interface. The following should be sufficient: ```java if (!attributes.attribute(MANAGE_CONNECTION_FACTORY).get()) table.validate() ``` If we add `builder.manageConnectionFactory(false);` to the `ManagedConnectionFactoryConfigurationBuilder` constructor.
Source:
public CommandResult exec(ContextAwareCommandInvocation invocation) { if (help) { invocation.println(invocation.getHelpInfo()); } CommandInputLine cmd = new CommandInputLine(Shutdown.CMD) .arg(TYPE, Shutdown.Cluster.CMD); return invocation.execute(Collections.singletonList(cmd)); }

Target:
why do we need a `Collections.singletonList(cmd)` here?
Source:
public Collection<String> getAvailableServers(String container) throws IOException { List<String> members = (List<String>) parseBody(fetch(() -> client.cacheManager(container).info()), Map.class).get("cluster_members"); return members; }

Target:
remove `members`?
Source:
public HashSet<V> toSet() { return new HashSet<>(values); }

Target:
Can we have this return `Set` :)
Source:
private void update(MarshallerType type, Consumer<MarshallerContext> consumer) { if (type == GLOBAL) { synchronized (global) { consumer.accept(global); } return; } synchronized (persistence) { consumer.accept(persistence); } }

Target:
I would personally have preferred an else block, but I am fine with how you have it.
Source:
public CommandInputLine option(String name, Integer value) { if (value != null) { this.options.put(name, Integer.valueOf(value)); } return this; }

Target:
Guessing you wanted the argument to be `int`? If not then the `valueOf` is unneeded.
Source:
public SpringRemoteCacheManagerFactoryBean springCacheManager() { SpringRemoteCacheManagerFactoryBean factoryBean = new SpringRemoteCacheManagerFactoryBean(); factoryBean.setServerList(Arrays.asList(new InetSocketAddress("localhost", SERVER_PORT))); factoryBean.setMarshaller(JavaSerializationMarshaller.class.getName()); factoryBean.setClassWhiteList(AbstractRemoteCacheManagerFactory.SPRING_JAVA_SERIAL_WHITELIST + ",java.util.*"); return factoryBean; }

Target:
this shouldn't be necessary at this point, am I wrong ?
Source:
protected String initDomain() { if (!globalJmxRegistration.isJMXEnabled()) { if (globalJmxRegistration.mBeanServer == null) { globalJmxRegistration.mBeanServer = mBeanServer; } globalJmxRegistration.initJMX(); } return globalJmxRegistration.jmxDomain; }

Target:
Why do we set the global jmx `mBeanServer` to the cache's mBeanServer if JMX is disabled globally?
Source:
protected void assertEventuallyStateTransferNotRunning() { eventually(() -> adminOperations().getRunningStateTransfer().isEmpty(), 30, TimeUnit.SECONDS); }

Target:
unneeded change
Source:
public ProtostreamTranscoder(SerializationContext ctx, ClassLoader classLoader) { super(APPLICATION_PROTOSTREAM, APPLICATION_OCTET_STREAM, TEXT_PLAIN, APPLICATION_OBJECT, APPLICATION_JSON, APPLICATION_UNKNOWN); this.ctx = ctx; this.marshaller = new ProtoStreamMarshaller(ctx); this.classLoader = classLoader; }

Target:
`ProtoStreamMarshaller` is also using the `SerializationContext`. Shouldn't be updated?
Source:
public GenericJBossMarshaller(ClassLoader classLoader, ClassWhiteList classWhiteList) { super(); this.classLoader = classLoader == null ? getClass().getClassLoader() : classLoader; baseCfg.setClassResolver(classWhiteList == null ? new DefaultContextClassResolver(classLoader) : new CheckedClassResolver(classWhiteList, classLoader) ); }

Target:
Not doing ```getClass().getClassLoader()``` and just leaving it null would default to TCCL. Not sure which one is best.
Source:
public ModulusOffsetCalculator(int numBlocks) { int blocksMinusOne = numBlocks - 1; // We need a positive offset count // And it has to be a power of 2 if (numBlocks <= 0 && (numBlocks & blocksMinusOne) == 0) { throw new IllegalArgumentException("maxOffset " + numBlocks + " must be greater than 0 and a power of 2"); } this.blocksMinusOne = blocksMinusOne; }

Target:
```suggestion if (numBlocks <= 0 || (numBlocks & blocksMinusOne) != 0) { ```
Source:
void free(long address) { if (trace) { Long prev = allocatedBlocks.remove(address); if (prev == null) { throw new IllegalArgumentException(); } } UNSAFE.freeMemory(address); }

Target:
Oops, good catch!
Source:
public synchronized void updateOnCommunicationFailure(long sendTimeMillis) { if (!recordingOfflineStatus) { if (trace) { log.trace("Start recording failures"); } recordingOfflineStatus = true; firstFailureTime = sendTimeMillis; } failureCount++; if (trace) { log.tracef("Failures count: %s", failureCount); } }

Target:
Is this really needed?
Source:
public CompletionStage<?> applyState(Address sender, int topologyId, boolean pushTransfer, Collection<StateChunk> stateChunks) { expectLatch.countDown(); try { assertTrue(blockLatch.await(10, TimeUnit.SECONDS)); } catch (InterruptedException e) { throw new RuntimeException(e); } super.applyState(sender, topologyId, pushTransfer, stateChunks); return null; }

Target:
Should this return the value of the previous line?
Source:
public CompletionStage<?> applyState(Address sender, int topologyId, boolean pushTransfer, Collection<StateChunk> stateChunks) { delegate.applyState(sender, topologyId, pushTransfer, stateChunks); return null; }

Target:
This should return the previous line as well.
Source:
static void addInternalClassesToWhiteList(ClassWhiteList list) { // Infinispan Enums with no Externalizer list.addClasses( BackupSender.BringSiteOnlineResponse.class, BackupSender.TakeSiteOfflineResponse.class, CacheMode.class, XSiteAdminCommand.AdminOperation.class, XSiteAdminCommand.Status.class ); list.addClasses(Enum.class, Number.class, Object.class, Object[].class, SerializedLambda.class); }

Target:
This would also allow removing Enum from this list. Object class isn't Serializable, why is this here?
Source:
public void scheduleTimeout(Channel channel) { assert timeoutFuture == null; this.timeoutFuture = channel.eventLoop().schedule(new TimeoutRunnable(channel), channelFactory.socketTimeout(), TimeUnit.MILLISECONDS); }

Target:
Meh, that means a new allocation in each operation :-/ I wonder how much mess would be storing the channel directly in the `HotRodOperation`.
Source:
public void handleCreatedEvent(ClientCacheEntryCreatedEvent e) { createdEvents.add(e); System.out.println("Created " + e); }

Target:
You'd probably rather use logging here?
Source:
MemcachedMetadata(long flags, long lifespan, EntryVersion version) { super(lifespan, version); this.flags = flags; }

Target:
This can be private as it was before.
Source:
public String toString() { return "EmbeddedMaxIdleExpirableMetadata{" + "version=" + version() + ", maxIdle=" + maxIdle + '}'; }

Target:
```version``` is protected. I don't think we need to access it via its accessor
Source:
public <K, V> CompletionStage<KeyValueStore<K, V>> getKeyValueStore(String name, KeyValueStoreConfig config) { return CompletableFuture.supplyAsync(() -> { addProtobufSchema(config); RemoteCache<K, V> cache = cacheManager.getCache(name, false); RemoteCache<K, V> cacheWithReturnValues = cacheManager.getCache(name, true); return new KeyValueStoreImpl(cache, cacheWithReturnValues); }, asyncExecutorService); }

Target:
`<>` missing
Source:
public ClientKeyValueStoreListener(EntryStatus[] types) { List<EntryStatus> eventTypes = Arrays.asList(types); listenCreated = eventTypes.contains(EntryStatus.CREATED) ? true : false; listenUpdated = eventTypes.contains(EntryStatus.UPDATED) ? true : false; listenDeleted = eventTypes.contains(EntryStatus.DELETED) ? true : false; }

Target:
`eventTypes.contains()` is enough xD
Source:
public void subscribe(Subscriber<? super KeyValueEntry<K, V>> subscriber) { subscribers.add(subscriber); createContinuousQueryFlowable(); flowable.subscribe(subscriber); flowable.doOnError(e -> { log.error(e); continuousQuery.removeContinuousQueryListener(continuousQueryListener); }).doOnCancel(() -> continuousQuery.removeContinuousQueryListener(continuousQueryListener)); }

Target:
do you need to add the error and cancel handles every time? can it be done when you create the `flowable`?
Source:
public void setBytes(byte[] bytes) { this.bytes = bytes; this.hash = Arrays.hashCode(bytes); }

Target:
I'd really really like `ByteString` objects to be immutable, because we use them in a lot of places.
Source:
Set<String> getFileNames() { readLock.lock(); try { return filenames; } finally { readLock.unlock(); } }

Target:
The caller is going to use the collection outside the lock and the field is final, so the lock doesn't do anything. I think this needs a custom MessageMarshaller.
Source:
public void startUp() { cacheManager = TestCacheManagerFactory.createCacheManager(hotRodCacheConfiguration()); assertEquals(cacheManager.getCache().size(), 0); TestingUtil.registerTranscoders(cacheManager, new ProtostreamBinaryTranscoder()); hotRodServer = HotRodTestingUtil.startHotRodServer(cacheManager, 19711); }

Target:
I'm surprised the server doesn't already do this.
Source:
public void testIterationStateReaperOnClosedConnections() throws InterruptedException { IterationManager iterationManager = server().getIterationManager(); for (int i = 0; i < 10; i++) { hotRodClient.iteratorStart(null, null, null, 10, false); } hotRodClient.stop().await(); assertEquals(0, iterationManager.activeIterations()); }

Target:
Thinking we should verify that there are actually 10 active iterations before stopping the client. Same with the reaper timeout below.
Source:
default Publisher<MarshalledEntry<K, V>> publishEntries(IntSet segments, Predicate<? super K> filter, boolean fetchValue, boolean fetchMetadata) { return null; }

Target:
Doesn't seem right
Source:
public SuccessfulResponse addResponse(Address sender, Response response) { if (response.isSuccessful()) { return (SuccessfulResponse) response; } if (response instanceof ExceptionResponse) { throw ResponseCollectors.wrapRemoteException(sender, ((ExceptionResponse) response).getException()); } if (response instanceof UnsureResponse) { hasUnsureResponse = true; return null; } else if (response instanceof CacheNotFoundResponse) { hasSuspectResponse = true; return null; } throw ResponseCollectors.unexpectedResponse(response); }

Target:
Looks like this field is never read.
Source:
public static String resolvePath(String path, String relativeTo) { if (new File(path).isAbsolute()) { return path; } else if (relativeTo != null) { return new File(new File(relativeTo), path).getAbsolutePath(); } else { return path; } }

Target:
This can be reduced to ```java if (!new File(path).isAbsolute() && relativeTo != null) { return new File(new File(relativeTo), path).getAbsolutePath(); } return path; ```
Source:
public ConfigurationBuilder getDefaultConfigurationBuilder() { return globalConfigurationBuilder.defaultCacheName().map(namedConfigurationBuilders::get).orElse(null); }

Target:
Technically this is another lambda and out of scope of this PR imo.
Source:
public CompletionStage<Void> setAvailabilityMode(AvailabilityMode availabilityMode) { if (availabilityMode != this.availabilityMode) { if (notifier.hasListener(PartitionStatusChanged.class)) { return notifier.notifyPartitionStatusChanged(availabilityMode, true) .thenCompose(ignore -> { updateAvailabilityMode(availabilityMode); return notifier.notifyPartitionStatusChanged(availabilityMode, false); }); } else { return updateAvailabilityMode(availabilityMode); } } else { return CompletableFutures.completedNull(); } }

Target:
This isn't really that performance-sensitive
Source:
public static void unregisterMBean(ObjectName objectName, MBeanServer mBeanServer) throws Exception { if (objectName != null && mBeanServer.isRegistered(objectName)) { SecurityActions.unregisterMBean(objectName, mBeanServer); log.tracef("Unregistered %s", objectName); } }

Target:
IMO the caller should do this check, in fact most callers already do.
Source:
public int getStatus() { return response.getStatus().code(); }

Target:
`response.status().code()`
Source:
private String getParameterValue(RestRequest restRequest, String name) { List<String> values = restRequest.parameters().get(name); if (values == null) return null; return values.iterator().next(); }

Target:
return `values == null ? null : values.iterator().next();`
Source:
public Class<? extends AtomicKeySetImpl> getJavaClass() { return AtomicKeySetImpl.class; }

Target:
getJavaClass() should declare the exact class. no need for wildcards. not just here, everywhere.
Source:
public void setServers(Collection<SocketAddress> servers) { this.servers = servers.toArray(new SocketAddress[servers.size()]); // keep the old index if possible so that we don't produce more requests for the first server if (index >= this.servers.length) { index = ThreadLocalRandom.current().nextInt(this.servers.length); } if (trace) { log.tracef("New server list is: " + Arrays.toString(this.servers)); } }

Target:
Shouldn't `index` be initialized to MAX_INT in order to trigger this on 1st call ?
Source:
public AssertsNearCache<K, V> expectNearPreemptiveRemove(K key, AssertsNearCache<K, V>... affected) { if (nearCacheMode.invalidated()) { // Preemptive remove MockRemoveEvent preemptiveRemove = pollEvent(events); assertEquals(key, preemptiveRemove.key); } expectNoNearEvents(); return this; }

Target:
Don't have eager near cache anymore...
Source:
public boolean isObjectStorage() { boolean storageHinted = status == NO_ERROR_STATUS_OBJ_STORAGE || status == SUCCESS_WITH_PREVIOUS_OBJ_STORAGE || status == NOT_EXECUTED_WITH_PREVIOUS_OBJ_STORAGE; boolean objectMediaType = keyMediaType != null && keyMediaType.match(MediaType.APPLICATION_OBJECT); return storageHinted || objectMediaType; }

Target:
I'm not sure I like these checks staying here. They should be moved to Codec28 so that these checks are only done if using HR protocol 2.8 (or whichever is the last HR protocol version that sent them). If you leave them here, you're going to carry checking even with protocol 2.9 which is wasteful since the server does not send them.
Source:
public void afterClass() { embeddedCacheManager.stop(); remoteCacheManager.stop(); hotrodServer.stop(); }

Target:
Why change the order? You normally stop in opposite order to creation. So, if you create embedded cache manager first and then the server, you normally stop server first, then the cache manager.
Source:
private static void assertXaException(ExceptionRunnable runnable, int errorCode) { try { runnable.run(); fail(); } catch (Exception e) { Exceptions.assertException(XAException.class, e); //noinspection ConstantConditions assertEquals(errorCode, ((XAException) e).errorCode); } }

Target:
`assertException` doesn't really help here, I'd rather do something like this: private static void assertXaException(ExceptionRunnable runnable, int errorCode) throws Exception { try { runnable.run(); fail(); } catch (XAException e) { assertEquals(errorCode, e.errorCode); } } I'd also move the helper methods after the tests.
Source:
public Builder<?> read(NearCacheConfiguration template) { mode = template.mode(); maxEntries = template.maxEntries(); Pattern pattern = template.cacheNamePattern(); cacheNamePattern = pattern; return this; }

Target:
Can be just `cacheNamePattern = template.cacheNamePattern();`
Source:
public IndependentClustersMergeTest() { this.numMembersInCluster = 2; this.mergePolicy = (preferredEntry, otherEntries) -> { CacheEntry entry = preferredEntry != null ? preferredEntry : (CacheEntry) otherEntries.get(0); entry.setValue(MERGE_RESULT); return entry; }; }

Target:
Unnecessary cast. Could also avoid the unchecked warning by declaring `entry` and `mergePolicy` with generic parameters `<String, String>`.
Source:
public static SmallIntSet of(int i1) { SmallIntSet set = new SmallIntSet(1); set.set(i1); return set; }

Target:
Maybe `i1 + 1`? Same in the other `of(...)` methods, the constructor parameter is the end of the range.
Source:
private static void closeIterator(Iterator<?> iter) { if (iter != null && iter instanceof CloseableIterator) { ((CloseableIterator) iter).close(); } }

Target:
unnecessary null check
Source:
private int getSegment(Object key) { if (cacheMode.needsStateTransfer()) { return keyPartitioner.getSegment(key); } // LOCAL and INVAL don't require segments, so just use 0 return 0; }

Target:
Maybe we should change `KeyPartitionerFactory` to return a `k -> 0` partitioner in local and invalidation caches instead
Source:
public V get(Object key) { assertKeyNotNull(key); checkCanRun(cache, componentRegistry); InternalCacheEntry<K, V> ice = getDataContainer().get(key); if (ice != null) { return ice.getValue(); } return null; }

Target:
`componentRegistry` can be removed (`cache.getName()`)
Source:
protected void writeCommandParameters(ObjectOutput output, ReplicableCommand command) throws IOException { command.writeTo(output); if (command instanceof TopologyAffectedCommand) { output.writeInt(((TopologyAffectedCommand) command).getTopologyId()); } if (command instanceof SegmentSpecificCommand) { UnsignedNumeric.writeUnsignedInt(output, ((SegmentSpecificCommand) command).getSegment()); } }

Target:
-1, IMO the commands should write/read the segment themselves
Source:
public ConfigurationBuilder() { this.classLoader = new WeakReference<>(Thread.currentThread().getContextClassLoader()); this.connectionPool = new ConnectionPoolConfigurationBuilder(this); this.asyncExecutorFactory = new ExecutorFactoryConfigurationBuilder(this); this.security = new SecurityConfigurationBuilder(this); this.nearCache = new NearCacheConfigurationBuilder(this); transaction = new TransactionConfigurationBuilder(this); }

Target:
for symmetry either qualify the field with this. or remove the others :smile:
Source:
public void stop() { if (trace) { log.tracef("Stopping LocalTopologyManager on %s", transport.getAddress()); } running = false; for (LocalCacheStatus cache : runningCaches.values()) { cache.getTopologyUpdatesExecutor().shutdownNow(); } withinThreadExecutor.shutdown(); persistentUUIDManager.removePersistentAddressMapping(persistentUUID); }

Target:
We should really have proper dependency graphs to avoid these "conjured" numbers