auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
private void onNext() { if (mClientCertificateCheckBox.isChecked()) { // Auto-setup doesn't support client certificates. onManualSetup(); return; } String email = mEmailView.getText().toString(); ConnectionSettings connectionSettings = providersXmlDiscovery.discover(email); if (connectionSettings == null) { connectionSettings = srvServiceDiscovery.discover(email); } if (connectionSettings != null) { finishAutoSetup(connectionSettings); } else { // We don't have default settings for this account, start the manual setup process. onManualSetup(); } }

Target:
private void onNext() { if (mClientCertificateCheckBox.isChecked()) { // Auto-setup doesn't support client certificates. onManualSetup(); return; } String email = mEmailView.getText().toString(); ConnectionSettings connectionSettings = providersXmlDiscovery.discover(email); if (connectionSettings != null) { finishAutoSetup(connectionSettings); } else { // We don't have default settings for this account, start the manual setup process. onManualSetup(); } }
Source:
private String getSpecialFoldersList() { String builder = "<?xml version=\"1.0\" encoding=\"utf-8\" standalone=\"no\"?>" + "<propfind xmlns=\"DAV:\">" + "<prop>" + "<" + WebDavConstants.DAV_MAIL_INBOX_FOLDER + " xmlns=\"urn:schemas:httpmail:\"/>" + "<" + WebDavConstants.DAV_MAIL_DRAFTS_FOLDER + " xmlns=\"urn:schemas:httpmail:\"/>" + "<" + WebDavConstants.DAV_MAIL_OUTBOX_FOLDER + " xmlns=\"urn:schemas:httpmail:\"/>" + "<" + WebDavConstants.DAV_MAIL_SENT_FOLDER + " xmlns=\"urn:schemas:httpmail:\"/>" + "<" + WebDavConstants.DAV_MAIL_TRASH_FOLDER + " xmlns=\"urn:schemas:httpmail:\"/>" + "<" + WebDavConstants.DAV_MAIL_SPAM_FOLDER + " xmlns=\"urn:schemas:httpmail:\"/>" + "</prop>" + "</propfind>"; // This should always be ##DavMailSubmissionURI## for which we already have a constant // buffer.append("<sendmsg xmlns=\"urn:schemas:httpmail:\"/>"); return builder; }

Target:
private String getSpecialFoldersList() { return "<?xml version=\"1.0\" encoding=\"utf-8\" standalone=\"no\"?>" + "<propfind xmlns=\"DAV:\">" + "<prop>" + "<" + WebDavConstants.DAV_MAIL_INBOX_FOLDER + " xmlns=\"urn:schemas:httpmail:\"/>" + "<" + WebDavConstants.DAV_MAIL_DRAFTS_FOLDER + " xmlns=\"urn:schemas:httpmail:\"/>" + "<" + WebDavConstants.DAV_MAIL_OUTBOX_FOLDER + " xmlns=\"urn:schemas:httpmail:\"/>" + "<" + WebDavConstants.DAV_MAIL_SENT_FOLDER + " xmlns=\"urn:schemas:httpmail:\"/>" + "<" + WebDavConstants.DAV_MAIL_TRASH_FOLDER + " xmlns=\"urn:schemas:httpmail:\"/>" + "<" + WebDavConstants.DAV_MAIL_SPAM_FOLDER + " xmlns=\"urn:schemas:httpmail:\"/>" + // This should always be ##DavMailSubmissionURI## for which we already have a constant // "<sendmsg xmlns=\"urn:schemas:httpmail:\"/>" + "</prop>" + "</propfind>"; }
Source:
public static void clearTemporaryAttachmentsCache(Context context){ File cacheDir = context.getCacheDir(); File tempAttachmentsDirectory = new File(cacheDir.getPath() + RESIZED_ATTACHMENTS_TEMPORARY_DIRECTORY); if(tempAttachmentsDirectory.exists()){ try { FileUtils.cleanDirectory(tempAttachmentsDirectory); } catch (IOException e) { Timber.e("Error occurred while cleaning temporary directory for resized attachments"); e.printStackTrace(); } } }

Target:
public static void clearTemporaryAttachmentsCache(Context context) { File cacheDir = context.getCacheDir(); File tempAttachmentsDirectory = new File(cacheDir.getPath() + RESIZED_ATTACHMENTS_TEMPORARY_DIRECTORY); if (tempAttachmentsDirectory.exists()) { try { FileUtils.cleanDirectory(tempAttachmentsDirectory); } catch (IOException e) { Timber.e(e, "Error occurred while cleaning temporary directory for resized attachments"); } } }
Source:
public void delete_notImplemented() throws MessagingException { ImapFolder folder = createFolder("Folder"); try { folder.delete(false); fail("Error expected"); } catch (Error e) { } }

Target:
public void delete_notImplemented() throws MessagingException { ImapFolder folder = createFolder("Folder"); folder.delete(false); }
Source:
public void areMoreMessagesAvailable_withIndexOf1_shouldReturnFalseWithoutPerformingSearch() throws Exception { ImapFolder folder = createFolder("Folder"); prepareImapFolderForOpen(OPEN_MODE_RW); folder.open(OPEN_MODE_RW); boolean result = folder.areMoreMessagesAvailable(1, null); //SELECT during OPEN verify(imapConnection, times(1)).executeSimpleCommand(anyString()); assertFalse(result); }

Target:
public void areMoreMessagesAvailable_withIndexOf1_shouldReturnFalseWithoutPerformingSearch() throws Exception { ImapFolder folder = createFolder("Folder"); prepareImapFolderForOpen(OPEN_MODE_RW); folder.open(OPEN_MODE_RW); assertFalse(folder.areMoreMessagesAvailable(1, null)); //SELECT during OPEN and no more verify(imapConnection, times(1)).executeSimpleCommand(anyString()); }
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:
MimeBodyPart multipart(String type, BodyPart... subParts) throws MessagingException { MimeMultipart multiPart = new MimeMultipart(); multiPart.setSubType(type); for (BodyPart subPart : subParts) { multiPart.addBodyPart(subPart); } return new MimeBodyPart(multiPart); }
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:
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; }
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:
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()]), ' '); }
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:
public <X> WeldInstance<X> select(Type subtype, Annotation... qualifiers) { // verify if this was invoked on WeldInstance<Object> if (!this.getType().equals(Object.class)) { 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); }
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:
public void vetoedAlternativesShouldBeRejected() throws Exception { // should throw deployment exception }
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:
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.error("Delegate content index returned publisher that was not asked for." + " Requested publishers: {}", currentPublisher, publisherPrecedence); return false; }
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:
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); //close the streams outputStream.close(); rdfInput.close(); }
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:
public void addItem(Object key, Object value, CompletableFuture<?> future) { // This is what HS5 currently does, but introduce chunking could be a good idea. lastFuture = future.whenComplete((result, exception) -> { if (exception != null) { notifier.notifyEntityIndexingFailure(value.getClass(), key, exception); } else { notifier.notifyDocumentsAdded(1); } }).thenCombine(lastFuture, (ignored1, ignored2) -> null); }
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:
public <T, U> InternalRemoteCache<T, U> withDataFormat(DataFormat dataFormat) { InternalRemoteCache<T, U> newCache = delegate.withDataFormat(dataFormat); if (newCache != delegate) { return newDelegatingCache(newCache); } //noinspection unchecked return (InternalRemoteCache<T, U>) this; }
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:
public CompletableFuture<Object> invokeAsync(InvocationContext ctx, VisitableCommand command) { try { 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); } }
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:
public boolean hasZeroLockAcquisition() { if (modifications == null || modifications.length == 0) { return false; } 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)) { return false; } } return true; }
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:
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 with concurrent 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); }
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:
final CompletableFuture<Void> removeLifespanExpired(K key, V value, Long lifespan, long explicitFlags) { RemoveExpiredCommand command = commandsFactory.buildRemoveExpiredCommand(key, value, keyPartitioner.getSegment(key), lifespan, explicitFlags | FlagBitSets.SKIP_CACHE_LOAD | FlagBitSets.SKIP_XSITE_BACKUP); // 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); }
Source:
public String describe() throws IOException { return NAME;//TODO }

Target:
public String describe() { return NAME; }
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:
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(); } } }
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:
public void validate() { table.validate(); super.validate(); }
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:
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; }
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:
static void addInternalClassesToWhiteList(ClassWhiteList list) { list.addClasses(Number.class, Object.class, Object[].class, SerializedLambda.class); }
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:
public void setServers(Collection<SocketAddress> servers) { this.servers = servers.toArray(new SocketAddress[servers.size()]); // Always start with a random server after a topology update index = ThreadLocalRandom.current().nextInt(this.servers.length); if (trace) { log.tracef("New server list is: " + Arrays.toString(this.servers)); } }
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:
public AssertsNearCache<K, V> expectNearPreemptiveRemove(K key, AssertsNearCache<K, V>... affected) { // Preemptive remove MockRemoveEvent preemptiveRemove = pollEvent(events); assertEquals(key, preemptiveRemove.key); expectNoNearEvents(); return this; }
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:
private static void assertXaException(ExceptionRunnable runnable, int errorCode) throws Exception { try { runnable.run(); fail(); } catch (XAException e) { assertEquals(errorCode, e.errorCode); } }
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:
private int getSegment(Object key) { return keyPartitioner.getSegment(key); }
Source:
public boolean isReadable(int size) { return buffer.isReadable(); // see readableBytes(); }

Target:
public boolean isReadable(int size) { return buffer.isReadable(size); // see readableBytes(); }
Source:
static Configuration getCacheConfiguration(final AdvancedCache<?, ?> cache) { GetCacheConfigurationAction action = new GetCacheConfigurationAction(cache); return doPrivileged(action); }

Target:
static Configuration getCacheConfiguration(final AdvancedCache<?, ?> cache) { return doPrivileged(cache::getCacheConfiguration); }
Source:
public void stop(StopContext context) { // remove and destroy the counter instance EmbeddedCacheManager container = this.dependencies.getCacheContainer(); CounterManager counterManager = EmbeddedCounterManagerFactory.asCounterManager(container); counterManager.remove(counterConfigurationName); }

Target:
public void stop(StopContext context) { // intentionally empty as we don't do anything on service stop }
Source:
public BoundedOffHeapDataContainer(int desiredSize, long maxSize, EvictionType type) { super(desiredSize); this.maxSize = maxSize; if (type == EvictionType.COUNT) { sizeCalculator = i -> 1; } else { // Use size of entry plus 16 for our LRU pointers sizeCalculator = i -> offHeapEntryFactory.getSize(i) + OffHeapLruNode.getSize(); } this.lruLock = new ReentrantLock(); firstAddress = 0; }

Target:
public BoundedOffHeapDataContainer(int desiredSize, long maxSize, EvictionType type) { super(desiredSize); this.maxSize = maxSize; if (type == EvictionType.COUNT) { sizeCalculator = i -> 1; } else { // Use size of entry plus 16 for our LRU pointers sizeCalculator = i -> offHeapEntryFactory.getSize(i); } this.lruLock = new ReentrantLock(); firstAddress = 0; }
Source:
protected void entryReplaced(long newAddress, long oldAddress) { long oldSize = sizeCalculator.applyAsLong(oldAddress); long newSize = sizeCalculator.applyAsLong(newAddress); lruLock.lock(); try { if (trace) { log.tracef("Replacing LRU node: OldValue: 0x%016x NewValue: 0x%016x", oldAddress, newAddress); } removeNode(oldAddress); addEntryAddressToEnd(newAddress); currentSize += newSize; currentSize -= oldSize; // Must only remove entry while holding lru lock now super.entryReplaced(newAddress, oldAddress); } finally { lruLock.unlock(); } }

Target:
protected void entryReplaced(long newAddress, long oldAddress) { long oldSize = sizeCalculator.applyAsLong(oldAddress); long newSize = sizeCalculator.applyAsLong(newAddress); lruLock.lock(); try { removeNode(oldAddress); addEntryAddressToEnd(newAddress); currentSize += newSize; currentSize -= oldSize; // Must only remove entry while holding lru lock now super.entryReplaced(newAddress, oldAddress); } finally { lruLock.unlock(); } }
Source:
public <C> void addListener(Object listener, CacheEventFilter<? super K, ? super V> filter, CacheEventConverter<? super K, ? super V, C> converter, ClassLoader classLoader) { //TODO: add contracts for cache.getEncoder and cache.getWrapper addListenerInternal(listener, null, null, filter, converter, classLoader); }

Target:
public <C> void addListener(Object listener, CacheEventFilter<? super K, ? super V> filter, CacheEventConverter<? super K, ? super V, C> converter, ClassLoader classLoader) { addListenerInternal(listener, null, null, null, null, filter, converter, classLoader); }
Source:
public DecoratedCache(AdvancedCache<K, V> delegate, Object lockOwner, Flag... flags) { super(delegate); if (flags == null) throw new IllegalArgumentException("There is no point in using a DecoratedCache if Flags are set."); if (flags.length == 0) this.flags = EnumUtil.EMPTY_BIT_SET; else { this.flags = EnumUtil.bitSetOf(flags); } this.lockOwner = lockOwner; // Yuk cacheImplementation = (CacheImpl<K, V>) delegate; }

Target:
public DecoratedCache(AdvancedCache<K, V> delegate, Object lockOwner, Flag... flags) { super(delegate); if (flags.length == 0) this.flags = EnumUtil.EMPTY_BIT_SET; else { this.flags = EnumUtil.bitSetOf(flags); } this.lockOwner = lockOwner; // Yuk cacheImplementation = (CacheImpl<K, V>) delegate; }
Source:
public void accept(Object rv, Throwable throwable) { // We started with a CompletableFuture, which is now complete. if (trace) log.tracef("Resuming invocation of command %s with %d handlers", command, queueSize()); Stages.pushInvocationIdNDC(command, trace); try { invokeQueuedHandlers(rv, throwable); } finally { Stages.popInvocationIdNDC(command, trace); } }

Target:
public void accept(Object rv, Throwable throwable) { // We started with a CompletableFuture, which is now complete. invokeQueuedHandlers(rv, throwable); }
Source:
protected static CacheException handleMissingSuccessfulResponse(Map<Address, Response> responses) { if (responses.values().stream().anyMatch(UnsureResponse.class::isInstance)) { // We got only unsure responses, as all nodes that were read-owners at the time when we've sent // the request have progressed to newer topology. However we are guaranteed to have progressed // to a topology at most one older, and can immediately retry. return OutdatedTopologyException.getCachedInstance(); } else { // Another instance when we don't get any successful response is when all owners are lost. We'll handle // this later in StateTransferInterceptor, as we have to signal this to PartitionHandlingInterceptor // if that's present. return AllOwnersLostException.INSTANCE; } }

Target:
protected static CacheException handleMissingSuccessfulResponse(Map<Address, Response> responses) { // The response map does not contain any ExceptionResponses; these are rethrown as exceptions if (responses.values().stream().anyMatch(UnsureResponse.class::isInstance)) { // We got only unsure responses, as all nodes that were read-owners at the time when we've sent // the request have progressed to newer topology. However we are guaranteed to have progressed // to a topology at most one older, and can immediately retry. return OutdatedTopologyException.INSTANCE; } else { // Another instance when we don't get any successful response is when all owners are lost. We'll handle // this later in StateTransferInterceptor, as we have to signal this to PartitionHandlingInterceptor // if that's present. return AllOwnersLostException.INSTANCE; } }
Source:
public void onStateReceived(int segmentId, boolean isLastChunk) { if (!isCancelled && isLastChunk) { boolean isCompleted = false; synchronized (segments) { if (segments.contains(segmentId)) { finishedSegments.add((Integer) segmentId); if (finishedSegments.size() == segments.size()) { log.debugf("Finished receiving state for segments %s", segments); isCompleted = true; } } } if (isCompleted) { notifyCompletion(true); } } }

Target:
public void onStateReceived(int segmentId, boolean isLastChunk) { if (!isCancelled && isLastChunk) { boolean isCompleted = false; synchronized (segments) { if (segments.contains(segmentId)) { finishedSegments.add(segmentId); if (finishedSegments.size() == segments.size()) { log.debugf("Finished receiving state for segments %s", segments); isCompleted = true; } } } if (isCompleted) { notifyCompletion(true); } } }
Source:
protected final Object handleMissingEntryOnRead(TopologyAffectedCommand command) { // If we have the entry in context it means that we are read owners, so we don't have to check the topology CacheTopology cacheTopology = stateTransferManager.getCacheTopology(); int currentTopologyId = cacheTopology.getTopologyId(); int cmdTopology = command.getTopologyId(); if (cmdTopology < currentTopologyId) { return (Object) UnsuccessfulResponse.INSTANCE; } else { // If cmdTopology > currentTopologyId: the topology of this node is outdated // TODO: This situation won't happen as soon as we'll implement 4-phase topology change in ISPN-5021 // (then, Tx.readCH and T(x+1).readCH will always have common subset of nodes so we'll be safe here // to return UnsuccessfulResponse // If cmdTopology == currentTopologyId: between STI and BDI this node had different topology, therefore // the entry was not loaded into context. Retry again locally. throw new OutdatedTopologyException(cmdTopology); } }

Target:
protected final Object handleMissingEntryOnRead(TopologyAffectedCommand command) { // If we have the entry in context it means that we are read owners, so we don't have to check the topology CacheTopology cacheTopology = stateTransferManager.getCacheTopology(); int currentTopologyId = cacheTopology.getTopologyId(); int cmdTopology = command.getTopologyId(); if (cmdTopology < currentTopologyId) { return UnsuccessfulResponse.INSTANCE; } else { // If cmdTopology > currentTopologyId: the topology of this node is outdated // TODO: This situation won't happen as soon as we'll implement 4-phase topology change in ISPN-5021 // (then, Tx.readCH and T(x+1).readCH will always have common subset of nodes so we'll be safe here // to return UnsuccessfulResponse // If cmdTopology == currentTopologyId: between STI and BDI this node had different topology, therefore // the entry was not loaded into context. Retry again locally. throw new OutdatedTopologyException(cmdTopology); } }
Source:
public void testThrowingNullPointerExceptionOnNullGetWithClass() throws Exception { //when cache.get(null, (Class<Object>) null); }

Target:
public void testThrowingNullPointerExceptionOnNullGetWithClass() throws Exception { //when cache.get(null, (Class<?>) null); }
Source:
String readString() { byte mark = readByte(); switch(mark) { case 0: return ""; // empty string case 1: // small ascii int size = readByte(); String str = new String(bytes, 0, pos, size); pos += size; return str; case 2: // large string return readUTF(); case 3: default: throw new RuntimeException("Unknown marker(String). mark=" + mark); } }

Target:
String readString() { byte mark = readByte(); switch(mark) { case 0: return ""; // empty string case 1: // small ascii int size = readByte(); String str = new String(bytes, 0, pos, size); pos += size; return str; case 2: // large string return readUTF(); default: throw new RuntimeException("Unknown marker(String). mark=" + mark); } }
Source:
private Stream<Map<Address, CacheEntry<K, V>>> getConflicts(LocalizedCacheTopology topology) { if (stateConsumer.isStateTransferInProgress()) throw log.getConflictsStateTransferInProgress(cacheName); if (!streamInProgress.compareAndSet(false, true)) throw log.getConflictsAlreadyInProgress(); try { return StreamSupport .stream(new ReplicaSpliterator(topology), false) .filter(filterConsistentEntries()); } finally { streamInProgress.compareAndSet(true, false); } }

Target:
private Stream<Map<Address, CacheEntry<K, V>>> getConflicts(LocalizedCacheTopology topology) { if (stateConsumer.isStateTransferInProgress()) throw log.getConflictsStateTransferInProgress(cacheName); if (!streamInProgress.compareAndSet(false, true)) throw log.getConflictsAlreadyInProgress(); return StreamSupport .stream(new ReplicaSpliterator(topology), false) .filter(filterConsistentEntries()); }
Source:
public InputStream lookupFileStrict(URI uri, ClassLoader cl) throws FileNotFoundException { //in case we have not only file schema, but jar:file schema too, we have to get rid off all schemas int startIndex = uri.toString().lastIndexOf(':'); String fileName = uri.toString().substring(startIndex + 1); InputStream in = cl.getResourceAsStream(fileName); if(in != null){ return in; } else { return null; } }

Target:
public InputStream lookupFileStrict(URI uri, ClassLoader cl) throws FileNotFoundException { //in case we don't have only file schema, but jar:file schema too, we have to get rid of all schemas int startIndex = uri.toString().lastIndexOf(':'); String fileName = uri.toString().substring(startIndex + 1); return cl.getResourceAsStream(fileName); }
Source:
public SaslConfigurationBuilder forCredentials(String login, String password) { this.security().authentication().callbackHandler(new SimpleLoginHandler(login, password, Constants.DEFAULT_TEST_REALM)); return this; }

Target:
public SaslConfigurationBuilder forCredentials(String login, String password) { this.security().authentication().callbackHandler(new SimpleLoginHandler(login, password, DEFAULT_TEST_REALM)); return this; }
Source:
public void testWeldStandaloneInitialisation() throws Exception { //given WeldContainer weld = new Weld().initialize(); CDITestingBean testedBean = weld.instance().select(CDITestingBean.class).get(); //when testedBean.putValueInCache("test", "abcd"); String retrievedValue = testedBean.getValueFromCache("test"); //then assertEquals(retrievedValue, "abcd"); //cleanup weld.shutdown(); }

Target:
public void testWeldStandaloneInitialisation() throws Exception { WeldContainer weld = null; try { //given weld = new Weld().initialize(); CDITestingBean testedBean = weld.instance().select(CDITestingBean.class).get(); //when testedBean.putValueInCache("test", "abcd"); String retrievedValue = testedBean.getValueFromCache("test"); //then assertEquals(retrievedValue, "abcd"); } finally { if(weld != null) { //cleanup weld.shutdown(); } } }
Source:
protected boolean interceptorMatches(AsyncInterceptor interceptor, Class<? extends AsyncInterceptor> clazz) { Class<? extends AsyncInterceptor> interceptorType = interceptor.getClass(); return clazz == interceptorType; }

Target:
private boolean interceptorMatches(AsyncInterceptor interceptor, Class<? extends AsyncInterceptor> clazz) { Class<? extends AsyncInterceptor> interceptorType = interceptor.getClass(); return clazz == interceptorType; }
Source:
public void serialize(XMLExtendedStreamWriter writer, RemoteStoreConfiguration configuration) throws XMLStreamException { AttributeSet attributes = configuration.attributes(); writer.writeStartElement(Element.REMOTE_STORE); writeCommonStoreSubAttributes(writer, configuration); writeAsyncExecutor(writer, configuration.asyncExecutorFactory()); writeConnectionPool(writer, configuration.connectionPool()); writeServers(writer, configuration.servers()); writeCommonStoreElements(writer, configuration); writer.writeEndElement(); }

Target:
public void serialize(XMLExtendedStreamWriter writer, RemoteStoreConfiguration configuration) throws XMLStreamException { writer.writeStartElement(Element.REMOTE_STORE); configuration.attributes().write(writer); writeCommonStoreSubAttributes(writer, configuration); writeAsyncExecutor(writer, configuration.asyncExecutorFactory()); writeConnectionPool(writer, configuration.connectionPool()); writeServers(writer, configuration.servers()); writeCommonStoreElements(writer, configuration); writer.writeEndElement(); }
Source:
public void serialize(XMLExtendedStreamWriter writer, JdbcStringBasedStoreConfiguration configuration) throws XMLStreamException { writer.writeStartElement(Element.STRING_KEYED_JDBC_STORE); writeJdbcStoreAttributes(writer, configuration); configuration.attributes().write(writer, JdbcStringBasedStoreConfiguration.KEY2STRING_MAPPER, Attribute.KEY_TO_STRING_MAPPER); writeCommonStoreSubAttributes(writer, configuration); writeJDBCStoreTable(writer, Element.STRING_KEYED_TABLE, configuration.table()); writeJDBCStoreConnection(writer, configuration); writeCommonStoreElements(writer, configuration); writer.writeEndElement(); }

Target:
public void serialize(XMLExtendedStreamWriter writer, JdbcStringBasedStoreConfiguration configuration) throws XMLStreamException { writer.writeStartElement(Element.STRING_KEYED_JDBC_STORE); writeJdbcStoreAttributes(writer, configuration); writeCommonStoreSubAttributes(writer, configuration); writeJDBCStoreTable(writer, Element.STRING_KEYED_TABLE, configuration.table()); writeJDBCStoreConnection(writer, configuration); writeCommonStoreElements(writer, configuration); writer.writeEndElement(); }
Source:
public void writeObject(ObjectOutput output, ScriptMetadata object) throws IOException { output.writeUTF(object.name); output.writeUTF(object.extension); output.writeUTF(object.mode.name()); writeSet(output, object.parameters); output.writeObject(object.language); output.writeObject( object.role); output.writeObject(object.reducer); output.writeObject(object.collator); output.writeObject(object.combiner); }

Target:
public void writeObject(ObjectOutput output, ScriptMetadata object) throws IOException { output.writeUTF(object.name); output.writeUTF(object.extension); output.writeUTF(object.mode.name()); output.writeObject(object.parameters); output.writeObject(object.language); output.writeObject(object.role); output.writeObject(object.reducer); output.writeObject(object.collator); output.writeObject(object.combiner); }
Source:
public static void attemptObtain(ObtainableLock lock) throws IOException { int attempts = 0; while (lock.obtain()==false) { //we could fail immediately, but being Infinispan a bit latency sensitive we give a bit of grace here if (attempts++>MAX_LOCK_ACQUIRE_MILLISECONDS) failLockAcquire(); if (Thread.currentThread().isInterrupted()) failLockAcquire(); try { Thread.sleep(1); } catch (InterruptedException e) { Thread.currentThread().interrupt(); failLockAcquire(); } } }

Target:
public static void attemptObtain(ObtainableLock lock) throws IOException { int attempts = 0; while (!lock.obtain()) { //we could fail immediately, but being Infinispan a bit latency sensitive we give a bit of grace here if (attempts++ > MAX_LOCK_ACQUIRE_MILLISECONDS) failLockAcquire(); if (Thread.currentThread().isInterrupted()) failLockAcquire(); try { Thread.sleep(1); } catch (InterruptedException e) { Thread.currentThread().interrupt(); failLockAcquire(); } } }
Source:
public void setParameters(int commandId, Object[] args) { // TODO: Check duplicated in all commands? A better solution is needed. if (commandId != COMMAND_ID) throw new IllegalStateException("Unsupported command id:" + commandId); int i = 0; globalTx = (GlobalTransaction) args[i++]; unlock = (Boolean) args[i++]; keys = (List<Object>) args[i++]; flags = (EnumSet<Flag>) args[i]; }

Target:
public void setParameters(int commandId, Object[] args) { // TODO: Check duplicated in all commands? A better solution is needed. if (commandId != COMMAND_ID) throw new IllegalStateException("Unsupported command id:" + commandId); int i = 0; globalTx = (GlobalTransaction) args[i++]; unlock = (Boolean) args[i++]; keys = (List<Object>) args[i++]; flags = (Set<Flag>) args[i]; }
Source:
public void update(Object[] srcRow, Object[] destRow) { Number value = (Number) srcRow[pos]; if (value != null) { Number sum = (Number) destRow[pos]; if (sum == null) { destRow[pos] = value; } else { destRow[pos] = sum.intValue() + value.intValue(); //todo [anistor] this handles integers only! } } }

Target:
public void update(Object[] srcRow, Object[] destRow) { Number value = (Number) srcRow[pos]; if (value != null) { Number sum = (Number) destRow[pos]; if (sum == null) { destRow[pos] = value; } else { destRow[pos] = add(value, sum); } } }
Source:
protected boolean beforeInvoke() throws Exception { if (0 <= commandTopologyId && commandTopologyId < handler.stateTransferManager.getFirstTopologyAsMember()) { if (handler.isTraceEnabled()) { handler.getLog().tracef("Ignoring command sent before the local node was a member " + "(command topology id is %d)", commandTopologyId); } response = CacheNotFoundResponse.INSTANCE; return false; //skip invocation } return true; }

Target:
protected Response beforeInvoke() throws Exception { if (0 <= commandTopologyId && commandTopologyId < handler.stateTransferManager.getFirstTopologyAsMember()) { if (handler.isTraceEnabled()) { handler.getLog().tracef("Ignoring command sent before the local node was a member " + "(command topology id is %d)", commandTopologyId); } // Skip invocation return CacheNotFoundResponse.INSTANCE; } return null; }
Source:
private boolean updateCacheTopology(String cacheName, CacheTopology cacheTopology, Address sender, LocalCacheStatus cacheStatus) { // Block if there is a status request in progress // The caller should have already acquired the cacheStatus monitor synchronized (runningCaches) { if (!sender.equals(transport.getCoordinator())) { log.debugf("Ignoring topology %d from old coordinator %s", cacheTopology.getTopologyId(), sender); return false; } else { log.debugf("Updating local topology for cache %s: %s", cacheName, cacheTopology); cacheStatus.setCurrentTopology(cacheTopology); } } return true; }

Target:
private boolean updateCacheTopology(String cacheName, CacheTopology cacheTopology, Address sender, LocalCacheStatus cacheStatus) { // Block if there is a status request in progress // The caller should have already acquired the cacheStatus monitor synchronized (runningCaches) { if (!sender.equals(transport.getCoordinator())) { log.debugf("Ignoring topology %d from old coordinator %s", cacheTopology.getTopologyId(), sender); return false; } } log.debugf("Updating local topology for cache %s: %s", cacheName, cacheTopology); cacheStatus.setCurrentTopology(cacheTopology); return true; }
Source:
public Object visitPutKeyValueCommand(InvocationContext ctx, PutKeyValueCommand command) throws Throwable { if (command.hasFlag(Flag.PUT_FOR_EXTERNAL_READ)) { return handleNonTxWriteCommand(ctx, command); } try { return handleTxWriteCommand(ctx, command, new SingleKeyRecipientGenerator(command.getKey()), command.hasFlag(Flag.PUT_FOR_STATE_TRANSFER)); } finally { if (ctx.isOriginLocal()) { // If the state transfer interceptor has to retry the command, it should ignore the previous value. command.setValueMatcher(command.isSuccessful() ? ValueMatcher.MATCH_ALWAYS : ValueMatcher.MATCH_NEVER); } } }

Target:
public Object visitPutKeyValueCommand(InvocationContext ctx, PutKeyValueCommand command) throws Throwable { if (command.hasFlag(Flag.PUT_FOR_EXTERNAL_READ)) { return handleNonTxWriteCommand(ctx, command); } try { return handleTxWriteCommand(ctx, command, command.getKey(), command.hasFlag(Flag.PUT_FOR_STATE_TRANSFER)); } finally { if (ctx.isOriginLocal()) { // If the state transfer interceptor has to retry the command, it should ignore the previous value. command.setValueMatcher(command.isSuccessful() ? ValueMatcher.MATCH_ALWAYS : ValueMatcher.MATCH_NEVER); } } }
Source:
public void putAndActivate(final InternalCacheEntry newEntry) { ((ConcurrentHashMapV8<Object, InternalCacheEntry>) entries) .compute(newEntry.getKey(), new ConcurrentHashMapV8.BiFun<Object, InternalCacheEntry, InternalCacheEntry>() { @Override public InternalCacheEntry apply(Object key, InternalCacheEntry entry) { if (entry == null && activator != null) { //entry does not exists before. we need to activate it. activator.activate(key); } return newEntry; } }); }

Target:
public void putAndActivate(final InternalCacheEntry newEntry) { ((ConcurrentHashMapV8<Object, InternalCacheEntry>) entries) .compute(newEntry.getKey(), new ConcurrentHashMapV8.BiFun<Object, InternalCacheEntry, InternalCacheEntry>() { @Override public InternalCacheEntry apply(Object key, InternalCacheEntry entry) { if (entry == null) { //entry does not exists before. we need to activate it. activator.activate(key); } return newEntry; } }); }
Source:
public Object visitClearCommand(InvocationContext ctx, ClearCommand command) throws Throwable { // lock .errors key VisitableCommand cmd = commandsFactory.buildLockControlCommand(ERRORS_KEY_SUFFIX, null, null); invoker.invoke(ctx, cmd); SerializationContext serializationContext = protobufMetadataManager.getSerializationContext(); for (String fileName : serializationContext.getFileDescriptors().keySet()) { serializationContext.unregisterProtoFile(fileName); } return invokeNextInterceptor(ctx, command); }

Target:
public Object visitClearCommand(InvocationContext ctx, ClearCommand command) throws Throwable { // lock .errors key VisitableCommand cmd = commandsFactory.buildLockControlCommand(ERRORS_KEY_SUFFIX, null, null); invoker.invoke(ctx, cmd); for (String fileName : serializationContext.getFileDescriptors().keySet()) { serializationContext.unregisterProtoFile(fileName); } return invokeNextInterceptor(ctx, command); }
Source:
public void removeClientListener(byte[] listenerId) { EventDispatcher dispatcher = clientListeners.get(listenerId); dispatcher.transport.release(); // force shutting it clientListeners.remove(listenerId); if (log.isTraceEnabled()) log.tracef("Remove client listener with id %s", Util.printArray(listenerId)); }

Target:
public void removeClientListener(byte[] listenerId) { EventDispatcher dispatcher = clientListeners.remove(listenerId); dispatcher.transport.release(); // force shutting it if (log.isTraceEnabled()) log.tracef("Remove client listener with id %s", Util.printArray(listenerId)); }
Source:
private void writeNamedFactory(Transport transport, String factoryName, byte[][] params) { if (factoryName.isEmpty()) { transport.writeByte((short) 0); } else { transport.writeString(factoryName); if (params != null) { transport.writeByte((short) params.length); for (byte[] param : params) transport.writeArray(param); } else { transport.writeByte((short) 0); } } }

Target:
private void writeNamedFactory(Transport transport, String factoryName, byte[][] params) { transport.writeString(factoryName); if (!factoryName.isEmpty()) { // A named factory was written, how many parameters? if (params != null) { transport.writeByte((short) params.length); for (byte[] param : params) transport.writeArray(param); } else { transport.writeByte((short) 0); } } }
Source:
public static ClassLoader[] getClassLoaders(ClassLoader appClassLoader) { return new ClassLoader[] { appClassLoader, // User defined classes new OsgiClassLoader(), Util.class.getClassLoader(), // Infinispan classes (not always on TCCL [modular env]) ClassLoader.getSystemClassLoader() // Used when load time instrumentation is in effect }; }

Target:
public static ClassLoader[] getClassLoaders(ClassLoader appClassLoader) { return new ClassLoader[] { appClassLoader, // User defined classes OsgiClassLoader.getInstance(), // OSGi bundle context needs to be on top of TCCL, system CL, etc. Util.class.getClassLoader(), // Infinispan classes (not always on TCCL [modular env]) ClassLoader.getSystemClassLoader() // Used when load time instrumentation is in effect }; }
Source:
public InternalCacheEntry<K, V> remove(Object k) { InternalCacheEntry e = entries.remove(k); return e == null || (e.canExpire() && e.isExpired(timeService.wallClockTime())) ? null : e; }

Target:
public InternalCacheEntry<K, V> remove(Object k) { InternalCacheEntry<K, V> e = entries.remove(k); return e == null || (e.canExpire() && e.isExpired(timeService.wallClockTime())) ? null : e; }
Source:
public int compareTo(FileEntry fe) { int diff = size - fe.size; return (diff != 0) ? diff : (int) (offset - fe.offset); }

Target:
public int compareTo(FileEntry fe) { // We compare the size first, as the entries in the free list must be sorted by size int diff = size - fe.size; if (diff != 0) return diff; return (offset < fe.offset) ? -1 : ((offset == fe.offset) ? 0 : 1); }
Source:
public BackupReceiverImpl(Cache cache) { this.cache = cache; //TODO can we have a local cache? this.local = cache.getCacheConfiguration().clustering().cacheMode() == CacheMode.LOCAL; siteUpdater = new BackupCacheUpdater(cache, remote2localTx); }

Target:
public BackupReceiverImpl(Cache cache) { this.cache = cache; siteUpdater = new BackupCacheUpdater(cache, remote2localTx); }
Source:
private void free(FileEntry fe) throws IOException { if (fe != null) { // Entry could still be in use (in _load). So, wait till it releases it. fe.waitUnlocked(); // Invalidate entry on disk (by setting keyLen field to 0) // No need to wait for readers to unlock here, the FileEntry instance is not modified, // and allocate() won't return an entry as long as it has a reader. channel.write(ByteBuffer.wrap(ZERO_INT), fe.offset + KEYLEN_POS); if (!freeList.add(fe)) { throw new IllegalStateException(String.format("Trying to free an entry that was not allocated: %s", fe)); } if (trace) log.tracef("Deleted entry at %d:%d, there are now %d free entries", fe.offset, fe.size, freeList.size()); } }

Target:
private void free(FileEntry fe) throws IOException { if (fe != null) { // Invalidate entry on disk (by setting keyLen field to 0) // No need to wait for readers to unlock here, the FileEntry instance is not modified, // and allocate() won't return an entry as long as it has a reader. channel.write(ByteBuffer.wrap(ZERO_INT), fe.offset + KEYLEN_POS); if (!freeList.add(fe)) { throw new IllegalStateException(String.format("Trying to free an entry that was not allocated: %s", fe)); } if (trace) log.tracef("Deleted entry at %d:%d, there are now %d free entries", fe.offset, fe.size, freeList.size()); } }