auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public boolean referenceSetExists(String referenceSetName, String version) throws EamDbException{ Connection conn = connect(); PreparedStatement preparedStatement1 = null; ResultSet resultSet = null; String sql1 = "SELECT * FROM reference_sets WHERE set_name=? AND version=?"; try { preparedStatement1 = conn.prepareStatement(sql1); preparedStatement1.setString(1, referenceSetName); preparedStatement1.setString(2, version); resultSet = preparedStatement1.executeQuery(); return (resultSet.next()); } catch (SQLException ex) { <START> throw new EamDbException("Error getting reference instances by type and value.", ex); END> } finally { EamDbUtil.closePreparedStatement(preparedStatement1); EamDbUtil.closeResultSet(resultSet); EamDbUtil.closeConnection(conn); } }</code><technical_language>I this is wrong error message. Also, above, I debugging if include some identification of reference set experienced error condition in error message</technical_language>

Target:
public boolean referenceSetExists(String referenceSetName, String version) throws EamDbException{ Connection conn = connect(); PreparedStatement preparedStatement1 = null; ResultSet resultSet = null; String sql1 = "SELECT * FROM reference_sets WHERE set_name=? AND version=?"; try { preparedStatement1 = conn.prepareStatement(sql1); preparedStatement1.setString(1, referenceSetName); preparedStatement1.setString(2, version); resultSet = preparedStatement1.executeQuery(); return (resultSet.next()); } catch (SQLException ex) { throw new EamDbException("Error testing whether reference set exists (name: " + referenceSetName + " version: " + version, ex); } finally { EamDbUtil.closePreparedStatement(preparedStatement1); EamDbUtil.closeResultSet(resultSet); EamDbUtil.closeConnection(conn); } }
Source:
<code>public void addInput(Page page) { requireNonNull(page, "page is null"); checkState(!isFinished(), "Operator is already finished"); Block sourceBlock = page.getBlock(setChannel); Page sourcePage = hashChannel.isPresent() ? new Page(sourceBlock, page.getBlock(hashChannel.get())) : new Page(sourceBlock); unfinishedWork = channelSetBuilder.addPage(sourcePage); processUnfinishedWork(); <START> channelSetBuilder.updateMemoryReservation(); <END> }</code><technical_language>times page OperatorContext#setMemoryReservation is called now</technical_language>

Target:
public void addInput(Page page) { requireNonNull(page, "page is null"); checkState(!isFinished(), "Operator is already finished"); Block sourceBlock = page.getBlock(setChannel); Page sourcePage = hashChannel.isPresent() ? new Page(sourceBlock, page.getBlock(hashChannel.get())) : new Page(sourceBlock); unfinishedWork = channelSetBuilder.addPage(sourcePage); processUnfinishedWork(); }
Source:
<code>public void commitJob(JobContext jobContext) throws IOException { View<E> targetView = load(jobContext); if(targetView instanceof ReadiableView) { <START> ((ReadiableView)targetView).signalReady(); <END> } }</code><technical_language>is reasoning automatically signalling output is ready? I want accumulate a lot of unused files in signal directory. sense add a configuration option signal output is completed</technical_language>

Target:
public void commitJob(JobContext jobContext) throws IOException { View<E> targetView = load(jobContext); if (targetView instanceof Signalable) { ((Signalable)targetView).signalReady(); } }
Source:
<code>public void visitClass(ClassTree tree) { boolean generatesEquals = usesAnnotation(tree, GENERATES_EQUALS); markIssues(tree, UnusedPrivateFieldCheck.class, IssueState.shouldBeRefused(generatesEquals || usesAnnotation(tree, GENERATE_UNUESED_FIELD_RELATED_METHODS))); markIssues(tree, EqualsNotOverriddenInSubclassCheck.class, IssueState.shouldBeRefused(generatesEquals)); <START> markIssues(tree, EqualsNotOverriddenInSubclassCheck.class, IssueState.shouldBeRefused(generatesEquals)); <END> markIssues(tree, UtilityClassWithPublicConstructorCheck.class, IssueState.shouldBeRefused(usesAnnotation(tree, GENERATE_PRIVATE_CONSTRUCTOR))); super.visitClass(tree); }</code><technical_language>duplicate line</technical_language>

Target:
public void visitClass(ClassTree tree) { boolean generatesEquals = usesAnnotation(tree, GENERATE_EQUALS); if (generatesEquals || usesAnnotation(tree, GENERATE_UNUSED_FIELD_RELATED_METHODS)) { excludeLines(tree, UnusedPrivateFieldCheck.class); } else { acceptLines(tree, UnusedPrivateFieldCheck.class); } if (generatesEquals) { excludeLines(tree, EqualsNotOverriddenInSubclassCheck.class); excludeLines(tree, EqualsNotOverridenWithCompareToCheck.class); } else { acceptLines(tree, EqualsNotOverriddenInSubclassCheck.class); acceptLines(tree, EqualsNotOverridenWithCompareToCheck.class); } if (usesAnnotation(tree, GENERATE_PRIVATE_CONSTRUCTOR)) { excludeLines(tree, UtilityClassWithPublicConstructorCheck.class); } else { acceptLines(tree, UtilityClassWithPublicConstructorCheck.class); } super.visitClass(tree); }
Source:
<code>public void handleData(ITmfEvent data) { super.handleData(data); long index = getIndex() + getNbRead() - 1; if (data == null) { for (ITmfEventRequest request : fRequests) { request.handleData(null); } return; } <START> Iterable<ITmfEventRequest> requests = fRequestingATrace.get(data.getTrace()); <END> for (ITmfEventRequest request : requests) { long start = request.getIndex(); if (!request.isCompleted() && index >= start && request.getNbRead() < request.getNbRequested()) { ITmfTimestamp ts = data.getTimestamp(); if (request.getRange().contains(ts)) { if (request.getDataType().isInstance(data)) { request.handleData(data); } } } } }</code><technical_language>need check if (!frequestingATrace.contains(data.getTrace() )){ populate for type }</technical_language>

Target:
public void handleData(ITmfEvent data) { super.handleData(data); long index = getIndex() + getNbRead() - 1; if (data == null) { for (ITmfEventRequest request : fRequests) { request.handleData(null); } return; } ITmfTrace trace = data.getTrace(); if (!fRequestingATrace.containsKey(trace)) { fRequestingATrace.put(trace, new HashSet<ITmfEventRequest>()); ITmfEventProvider eventProvider = getEventProvider(); if (eventProvider != null) { Set<ITmfEventRequest> populatedList = populateTraceList(((TmfCompositeComponent) eventProvider).getAncestors()); fRequestingATrace.get(trace).addAll(populatedList); } } Iterable<ITmfEventRequest> requests = fRequestingATrace.get(trace); for (ITmfEventRequest request : requests) { long start = request.getIndex(); if (!request.isCompleted() && index >= start && request.getNbRead() < request.getNbRequested()) { ITmfTimestamp ts = data.getTimestamp(); if (request.getRange().contains(ts)) { if (request.getDataType().isInstance(data)) { request.handleData(data); } } } } }
Source:
<code>protected void openConnection() { for (IpNode receiverNode : receiverNodes.keySet()) { Socket socket = receiverNodes.get(receiverNode); if (socket == null) { try { socket = new Socket(receiverNode.getAddressString(), receiverNode.getPort()); } catch (IOException e) { logger.warn("Could not connect to in {}: {}", receiverNode, this.thing.getUID(), e); <START> return; <END> } } if (socket.isConnected()) { receiverNodes.put(receiverNode, socket); } else { receiverNodes.put(receiverNode, null); return; } } isConnected = true; }</code><technical_language>isConnected set false here</technical_language>

Target:
protected void openConnection() { if (!this.thing.getStatus().equals(ThingStatus.ONLINE)) { for (IpNode receiverNode : receiverNodes.keySet()) { Socket socket = receiverNodes.get(receiverNode); if (socket == null) { try { socket = new Socket(receiverNode.getAddressString(), receiverNode.getPort()); } catch (IOException e) { logger.debug("Could not connect to in {}: {}", receiverNode, this.thing.getUID(), e); updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR, "could not connect to " + receiverNode.toString()); return; } } if (socket.isConnected()) { receiverNodes.put(receiverNode, socket); } else { updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR); receiverNodes.put(receiverNode, null); return; } } updateStatus(ThingStatus.ONLINE); } }
Source:
<code>public void onReceive(Context context, Intent intent) { FilterableNotification filterableNotification = intent.getParcelableExtra("notification"); <START> if (intent.getParcelableExtra("notification") == null || SwrveHelper.isNullOrEmpty(filterableNotification.getData())) { <END> Log.e(LOG_TAG, "LocationCampaignEngageReceiver. Payload data is null or empty or missing."); } else { String locationMessageId = filterableNotification.getData(); SwrveSDKBase.event("Swrve.Location.Location-" + locationMessageId + ".engaged"); } launchApp(context, intent.getExtras()); }</code><technical_language>filterableNotification</technical_language>

Target:
public void onReceive(Context context, Intent intent) { FilterableNotification filterableNotification = intent.getParcelableExtra("notification"); if (filterableNotification == null || SwrveHelper.isNullOrEmpty(filterableNotification.getData())) { Log.e(LOG_TAG, "LocationCampaignEngageReceiver. Payload data is null or empty or missing."); } else { String locationMessageId = filterableNotification.getData(); SwrveSDKBase.event("Swrve.Location.Location-" + locationMessageId + ".engaged"); } launchApp(context, intent.getExtras()); }
Source:
<code>public void failQuery(QueryId queryId, Throwable cause) { requireNonNull(queryId, "queryId is null"); requireNonNull(cause, "cause is null"); <START> log.warn(cause, "Fail query %s", queryId); <END> QueryExecution query = queries.get(queryId); if (query != null) { query.fail(cause); } }</code><technical_language>Query %s failed. Also, pretty log failures somewhere? if don't, a good reason for that</technical_language>

Target:
public void failQuery(QueryId queryId, Throwable cause) { requireNonNull(queryId, "queryId is null"); requireNonNull(cause, "cause is null"); QueryExecution query = queries.get(queryId); if (query != null) { query.fail(cause); } }
Source:
<code>public Response getAllMetadataStoreRealms(@QueryParam("sharding-key") String shardingKey) { try { if (shardingKey == null) { Collection<String> realms = _metadataStoreDirectory.getAllMetadataStoreRealms(_namespace); Map<String, Collection<String>> responseMap = ImmutableMap.of(MetadataStoreRoutingConstants.METADATA_STORE_REALMS, realms); return JSONRepresentation(responseMap); <START> } else { <END> String realm = _metadataStoreDirectory.getMetadataStoreRealm(_namespace, shardingKey); return JSONRepresentation(new MetadataStoreShardingKey(shardingKey, realm)); } } catch (NoSuchElementException ex) { return notFound(ex.getMessage()); } }</code><technical_language>Remove else clause</technical_language>

Target:
public Response getAllMetadataStoreRealms(@QueryParam("sharding-key") String shardingKey) { try { if (shardingKey == null) { Collection<String> realms = _metadataStoreDirectory.getAllMetadataStoreRealms(_namespace); Map<String, Collection<String>> responseMap = ImmutableMap.of(MetadataStoreRoutingConstants.METADATA_STORE_REALMS, realms); return JSONRepresentation(responseMap); } String realm = _metadataStoreDirectory.getMetadataStoreRealm(_namespace, shardingKey); return JSONRepresentation(new MetadataStoreShardingKey(shardingKey, realm)); } catch (NoSuchElementException ex) { return notFound(ex.getMessage()); } }
Source:
<code><START> public PollingResult compareRemoteRevisionWith(@Nonnull Job<?,?> project, @Nullable Launcher launcher, @Nonnull TaskListener listener, @Nonnull SCMRevisionState baseline) throws IOException, InterruptedException { <END> if (requiresWorkspaceForPolling()) return PollingResult.SIGNIFICANT; else return compareRemoteRevisionWith(project, launcher, null, listener, baseline); }</code><technical_language>NIT: Nullable => CheckForNull</technical_language>

Target:
public PollingResult compareRemoteRevisionWith(@Nonnull Job<?,?> project, @Nullable Launcher launcher, @Nonnull TaskListener listener, @Nonnull SCMRevisionState baseline) throws IOException, InterruptedException { if (requiresWorkspaceForPolling()) return PollingResult.UNCERTAIN; else return compareRemoteRevisionWith(project, launcher, null, listener, baseline); }
Source:
<code>private static void reset() throws MalformedURLException { for (Enumeration<Logger> logger = LogManager.getCurrentLoggers(); logger.hasMoreElements();) { logger.nextElement().setLevel(null); } if <START> (Strings.isNullOrEmpty(System.getProperty(JAVA_OPTIONS_LOG_CONFIG))) <END> { PropertyConfigurator.configure(Loader.getResource(LOG_CONFIGURATION)); } else { PropertyConfigurator.configure( new URL(System.getProperty(JAVA_OPTIONS_LOG_CONFIG))); } }</code><technical_language>Optional: extract this a var, retrieve twice: line 90</technical_language>

Target:
private static void reset() throws MalformedURLException { for (Enumeration<Logger> logger = LogManager.getCurrentLoggers(); logger.hasMoreElements();) { logger.nextElement().setLevel(null); } String path = System.getProperty(JAVA_OPTIONS_LOG_CONFIG); if (Strings.isNullOrEmpty(path)) { PropertyConfigurator.configure(Loader.getResource(LOG_CONFIGURATION)); } else { PropertyConfigurator.configure(new URL(path)); } }
Source:
<code>public void containersChanged(Set<TaskContainerDelta> containers) { for (TaskContainerDelta delta : containers) { <START> ITask updatedTask = (ITask) delta.getElement(); <END> if (updatedTask != null && isTaskAssosciatedWithReviewConnector(updatedTask)) { SynchronizationState taskState = updatedTask.getSynchronizationState(); if (taskState == SynchronizationState.INCOMING || taskState == SynchronizationState.INCOMING_NEW) { for (ITask assosciatedTask : getTasksAssosciatedWithReviewTask(updatedTask)) { updateTaskWithIncomingReviewState(assosciatedTask, true); } } else { forceFullRefreshFor(updatedTask); } } } }</code><technical_language>clearer call this updatedReview</technical_language>

Target:
public void containersChanged(Set<TaskContainerDelta> containers) { for (TaskContainerDelta delta : containers) { ITask updatedReview = (ITask) delta.getElement(); if (updatedReview != null && isTaskAssosciatedWithReviewConnector(updatedReview)) { SynchronizationState taskState = updatedReview.getSynchronizationState(); if (taskState.isIncoming()) { ITask assosciatedTask = getTasksAssosciatedWithReviewTask(updatedReview); if (assosciatedTask != null) { updateTaskWithIncomingReviewState(assosciatedTask, true); } } else { forceFullRefreshFor(updatedReview); } } } }
Source:
<code>public void testDownloadUnknownPackage() throws Exception { <START> assertPkgs(NON_EXISTENT, "unknown-package"); <END> boolean isSuccessful = connectBroker.downloadPackages(Arrays.asList("unknown-package")); assertThat(isSuccessful).isFalse(); assertPkgs(NON_EXISTENT, "unknown-package"); connectBroker.getCommandSet().log(); String expectedLogs = "Downloading [unknown-package]...\n" + "\tDownload failed (not found)."; assertThat(logOf(logCaptureResult)).isEqualTo(expectedLogs); }</code><technical_language>overkill assertNull(PackagePersistence.getState("unknown-package"))</technical_language>

Target:
public void testDownloadUnknownPackage() throws Exception { checkPackagesState(null, "unknown-package"); boolean isSuccessful = connectBroker.downloadPackages(Arrays.asList("unknown-package")); assertThat(isSuccessful).isFalse(); checkPackagesState(null, "unknown-package"); connectBroker.getCommandSet().log(); String expectedLogs = "Downloading [unknown-package]...\n" + "\tDownload failed (not found)."; assertThat(logOf(logCaptureResult)).isEqualTo(expectedLogs); }
Source:
<code>public void reload() { if (pluginDirectory == null || !pluginDirectory.isDirectory() || !pluginDirectory.canRead()) { LOGGER.log(Level.WARNING, "Plugin directory not found or not readable: {0}. " + "All requests allowed.", pluginDirectory); return; } if (stack == null) { LOGGER.log(Level.WARNING, "Plugin stack not found in configuration: null. All requests allowed."); return; } LOGGER.log(Level.INFO, "Plugins are being reloaded from {0}", pluginDirectory.getAbsolutePath()); loader = (AuthorizationPluginClassLoader) AccessController.doPrivileged(new PrivilegedAction() { @Override public Object run() { return new AuthorizationPluginClassLoader(pluginDirectory); } }); <START> AuthorizationStack newStack = getStack().clone(); <END> if (getLoadClasses()) { loadClassFiles(newStack, IOUtils.listFilesRec(pluginDirectory, ".class")); } if (getLoadJars()) { loadJarFiles(newStack, IOUtils.listFiles(pluginDirectory, ".jar")); } loadAllPlugins(newStack); AuthorizationStack oldStack; lock.writeLock().lock(); try { oldStack = stack; stack = newStack; increasePluginVersion(); } finally { lock.writeLock().unlock(); } Statistics stats = RuntimeEnvironment.getInstance().getStatistics(); stats.addRequest("authorization_stack_reload"); removeAll(oldStack); oldStack = null; }</code><technical_language>is I overlooked new stack comming configuration change</technical_language>

Target:
public void reload() { if (pluginDirectory == null || !pluginDirectory.isDirectory() || !pluginDirectory.canRead()) { LOGGER.log(Level.WARNING, "Plugin directory not found or not readable: {0}. " + "All requests allowed.", pluginDirectory); return; } if (stack == null) { LOGGER.log(Level.WARNING, "Plugin stack not found in configuration: null. All requests allowed."); return; } LOGGER.log(Level.INFO, "Plugins are being reloaded from {0}", pluginDirectory.getAbsolutePath()); loader = (AuthorizationPluginClassLoader) AccessController.doPrivileged(new PrivilegedAction() { @Override public Object run() { return new AuthorizationPluginClassLoader(pluginDirectory); } }); AuthorizationStack newLocalStack; if (this.newStack == null) { newLocalStack = getStack().clone(); } else { newLocalStack = this.newStack.clone(); } if (isLoadClassesEnabled()) { loadClassFiles(newLocalStack, IOUtils.listFilesRec(pluginDirectory, ".class")); } if (isLoadJarsEnabled()) { loadJarFiles(newLocalStack, IOUtils.listFiles(pluginDirectory, ".jar")); } loadAllPlugins(newLocalStack); AuthorizationStack oldStack; lock.writeLock().lock(); try { oldStack = stack; stack = newLocalStack; increasePluginVersion(); } finally { lock.writeLock().unlock(); } Statistics stats = RuntimeEnvironment.getInstance().getStatistics(); stats.addRequest("authorization_stack_reload"); removeAll(oldStack); oldStack = null; }
Source:
<code>private List<DatasetField> sortDatasetFields (List<DatasetField> dsfList) { <START> Collections.sort(dsfList, (DatasetField d1, DatasetField d2) -> { <END> int a = d1.getDatasetFieldType().getDisplayOrder(); int b = d2.getDatasetFieldType().getDisplayOrder(); return Integer.valueOf(a).compareTo(b); }); return dsfList; }</code><technical_language>This Comparator a duplicate of above. new function is :)</technical_language>

Target:
private List<DatasetField> sortDatasetFields (List<DatasetField> dsfList) { Collections.sort(dsfList, new Comparator<DatasetField>() { public int compare(DatasetField d1, DatasetField d2) { int a = d1.getDatasetFieldType().getDisplayOrder(); int b = d2.getDatasetFieldType().getDisplayOrder(); return Integer.valueOf(a).compareTo(Integer.valueOf(b)); } }); return dsfList; }
Source:
<code>private void update() { if (boshURL == null || StringUtils.isNullOrEmpty(domain)) { return; } boshURL = boshURL.replace("{host}", domain); String subdomain = ""; if (roomName != null && roomName.contains("@")) { String mucAddress = roomName.substring(roomName.indexOf("@") + 1); String mucAddressPrefix = this.mucAddressPrefix != null ? this.mucAddressPrefix : "conference"; if (mucAddress.startsWith(mucAddressPrefix) && mucAddress.endsWith(domain)) { if (mucAddressPrefix.length() + domain.length() + 2 < mucAddress.length()) { subdomain = mucAddress.substring( mucAddressPrefix.length() + 1, mucAddress.length() - domain.length() - 1); this.subDomain = subdomain; subdomain = "/" + subdomain; } } boshURL = boshURL.replace("{subdomain}", subdomain); } if (this.authToken != null) { String tokenParam = "&token=" + this.authToken; <START> if (!boshURL.endsWith(tokenParam)) <END> { boshURL = boshURL + tokenParam; } } }</code><technical_language>change contains &token= minimize string comparison</technical_language>

Target:
private void update() { if (boshURL == null || StringUtils.isNullOrEmpty(domain)) { return; } boshURL = boshURL.replace("{host}", domain); String subdomain = ""; if (roomName != null && roomName.contains("@")) { String mucAddress = roomName.substring(roomName.indexOf("@") + 1); String mucAddressPrefix = this.mucAddressPrefix != null ? this.mucAddressPrefix : "conference"; if (mucAddress.startsWith(mucAddressPrefix) && mucAddress.endsWith(domain)) { if (mucAddressPrefix.length() + domain.length() + 2 < mucAddress.length()) { subdomain = mucAddress.substring( mucAddressPrefix.length() + 1, mucAddress.length() - domain.length() - 1); this.subDomain = subdomain; subdomain = "/" + subdomain; } } boshURL = boshURL.replace("{subdomain}", subdomain); } if (this.authToken != null) { if (!boshURL.contains("&token=")) { boshURL = boshURL + "&token=" + this.authToken; } } }
Source:
<code><START> public void integerValue(DistinctQueryType queryType) { <END> String resource = String.format("{ " + "\"id\": %d + \"}", 5); DistinctMap distinctMap = DistinctMap.create(queryType, null); Utils.ValueHolder<String> outHash = new Utils.ValueHolder<>(); boolean add = distinctMap.add(resource, outHash); System.out.println("outHash5 = " + outHash.v); assertThat(add).as("Value should be added first time").isTrue(); boolean add2 = distinctMap.add(resource, outHash); assertThat(add2).as("same value should not be added again").isFalse(); resource = String.format("{ " + "\"id\": %d + \"}", 3); boolean add3 = distinctMap.add(resource, outHash); assertThat(add3).as("different value should be added again").isTrue(); }</code><technical_language>need a test for 1.0 1</technical_language>

Target:
public void integerValue(DistinctQueryType queryType) { String doc = String.format("{ " + "\"id\": \"%s\", \"prop\": %d }", UUID.randomUUID().toString(), 5); Document resource = new Document(doc); DistinctMap distinctMap = DistinctMap.create(queryType, null); Utils.ValueHolder<String> outHash = new Utils.ValueHolder<>(); boolean add = distinctMap.add(resource, outHash); assertThat(add).as("Value should be added first time").isTrue(); boolean add2 = distinctMap.add(resource, outHash); assertThat(add2).as("same value should not be added again").isFalse(); resource = new Document(String.format("{ " + "\"id\": \"%s\", \"prop\": %d }", UUID.randomUUID().toString(), 3)); boolean add3 = distinctMap.add(resource, outHash); assertThat(add3).as("different value should be added again").isTrue(); }
Source:
<code>public void leaseExpiry() throws Exception { URI connectionURI = getProxyURI(); CacheManagerBuilder<PersistentCacheManager> clusteredCacheManagerBuilder = CacheManagerBuilder.newCacheManagerBuilder() .with(ClusteringServiceConfigurationBuilder.cluster(connectionURI.resolve("/crud-cm")) .timeouts(TimeoutsBuilder.timeouts() .connection(Duration.ofSeconds(20))) .autoCreate() .defaultServerResource("primary-server-resource")); PersistentCacheManager cacheManager = clusteredCacheManagerBuilder.build(false); cacheManager.init(); CacheConfiguration<Long, String> config = CacheConfigurationBuilder.newCacheConfigurationBuilder(Long.class, String.class, resourcePoolsBuilder).build(); Cache<Long, String> cache = cacheManager.createCache("clustered-cache", config); cache.put(1L, "The one"); cache.put(2L, "The two"); cache.put(3L, "The three"); assertThat(cache.get(1L), equalTo("The one")); assertThat(cache.get(2L), equalTo("The two")); assertThat(cache.get(3L), equalTo("The three")); <START> setDelay(6000); <END> Thread.sleep(6000); setDelay(0L); assertThat(cache.get(1L), is(nullValue())); assertThat(cache.get(2L), is(nullValue())); assertThat(cache.get(3L), is(nullValue())); }</code><technical_language>6 seconds is long wait in a test. lease expiring faster? (or rely a time source)</technical_language>

Target:
public void leaseExpiry() throws Exception { URI connectionURI = getProxyURI(); CacheManagerBuilder<PersistentCacheManager> clusteredCacheManagerBuilder = CacheManagerBuilder.newCacheManagerBuilder() .with(ClusteringServiceConfigurationBuilder.cluster(connectionURI.resolve("/crud-cm")) .timeouts(TimeoutsBuilder.timeouts() .connection(Duration.ofSeconds(20))) .autoCreate() .defaultServerResource("primary-server-resource")); PersistentCacheManager cacheManager = clusteredCacheManagerBuilder.build(false); cacheManager.init(); CacheConfiguration<Long, String> config = CacheConfigurationBuilder.newCacheConfigurationBuilder(Long.class, String.class, resourcePoolsBuilder).build(); Cache<Long, String> cache = cacheManager.createCache("clustered-cache", config); cache.put(1L, "The one"); cache.put(2L, "The two"); cache.put(3L, "The three"); assertThat(cache.get(1L), equalTo("The one")); assertThat(cache.get(2L), equalTo("The two")); assertThat(cache.get(3L), equalTo("The three")); setDelay(2000); Thread.sleep(2000); setDelay(0L); assertThat(cache.get(1L), is(nullValue())); assertThat(cache.get(2L), is(nullValue())); assertThat(cache.get(3L), is(nullValue())); }
Source:
<code>public void focusLost(FocusEvent e) { if (this.handleFocusChanges) { if (!e.widget.isDisposed() && !commit(MoveDirectionEnum.NONE, true)) { if (e.widget instanceof Control <START> && !e.widget.isDisposed()) { <END> ((Control) e.widget).forceFocus(); } } else { if (!AbstractCellEditor.this.parent.isDisposed()) AbstractCellEditor.this.parent.forceFocus(); } } }</code><technical_language>minor ... check is necessary anymore</technical_language>

Target:
public void focusLost(FocusEvent e) { if (this.handleFocusChanges) { if (!e.widget.isDisposed() && !commit(MoveDirectionEnum.NONE, true)) { if (e.widget instanceof Control) { ((Control) e.widget).forceFocus(); } } else { if (!AbstractCellEditor.this.parent.isDisposed()) AbstractCellEditor.this.parent.forceFocus(); } } }
Source:
<code>public void setUpTest() { String username = UUID.randomUUID().toString(); <START> RealmLog.error("Username %s", username); <END> SyncCredentials credentials = SyncCredentials.usernamePassword(username, "password", true); user = SyncUser.login(credentials, Constants.AUTH_URL); looperThread.runAfterTest(new Runnable() { @Override public void run() { user.logout(); } }); SystemClock.sleep(5000); }</code><technical_language>error? info debug</technical_language>

Target:
public void setUpTest() { user = UserFactory.createUniqueUser(Constants.AUTH_URL); looperThread.runAfterTest(new Runnable() { @Override public void run() { user.logout(); } }); }
Source:
<code>public void eventOccured(String message) { if (message.contains("(CRC wrong after decryption)")) { logger.debug("BaseStation eventOccured: CRC wrong after decryption"); return; } if (message.contains("Base Station")) { StringTokenizer strTok = new StringTokenizer(message, "\n"); String data = null; versionInfo = new String[strTok.countTokens()]; <START> logger.debug("BaseStation eventOccured - initial message ( " + strTok.countTokens() + " )"); <END> int i = 0; while (strTok.hasMoreTokens()) { versionInfo[i] = strTok.nextToken(); logger.debug("<BaseStation>[" + i + "]: " + versionInfo[i]); i++; } } else { String logResult = message.replaceAll("\n", "\\\\n").replaceAll("\r", "\\\\r").substring(0, 40); logger.debug("BaseStation eventOccured - giving to Binding " + logResult); if (bindingEventWorker != null) { bindingEventWorker.eventOccured(message); } } }</code><technical_language>Please parametrized logging of slf4j instead of string concatenation</technical_language>

Target:
public void eventOccured(String message) { if (message.contains("(CRC wrong after decryption)")) { logger.debug("BaseStation eventOccured: CRC wrong after decryption"); return; } if (message.contains("Base Station")) { StringTokenizer strTok = new StringTokenizer(message, "\n"); String data = null; versionInfo = new String[strTok.countTokens()]; logger.debug("BaseStation eventOccured - initial message ( )", strTok.countTokens()); int i = 0; while (strTok.hasMoreTokens()) { versionInfo[i] = strTok.nextToken(); logger.debug("<BaseStation>[ ]: {}", i, versionInfo[i]); i++; } } else { String logResult = message.replaceAll("\n", "\\\\n").replaceAll("\r", "\\\\r").substring(0, 40); logger.debug("BaseStation eventOccured - giving to Binding {}", logResult); if (bindingEventWorker != null) { bindingEventWorker.eventOccured(message); } } }
Source:
<code>protected void updateNetworks(Collection<Network> networks) { VnicProfile profile = getProfile(); <START> if (profile != null) { <END> Network selected = networks.stream() .filter(net -> Objects.equals(profile.getNetworkId(), net.getId())) .findFirst().get(); getNetwork().setSelectedItem(selected); getNetwork().setIsChangeable(false); } }</code><technical_language>I change 'if (profile != null && profile.getNetworkId() != null)'. is more explicit</technical_language>

Target:
protected void updateNetworks(Collection<Network> networks) { VnicProfile profile = getProfile(); if (profile != null && profile.getNetworkId() != null) { Network selected = networks.stream() .filter(net -> Objects.equals(profile.getNetworkId(), net.getId())) .findFirst().get(); getNetwork().setSelectedItem(selected); getNetwork().setIsChangeable(false); } }
Source:
<code>public void testRecorderCamera() throws Exception { int width; int height; if (!hasCamera()) { return; } try { Camera camera = Camera.open(); width = camera.getParameters().getSupportedPreviewSizes().get(0).width; height = camera.getParameters().getSupportedPreviewSizes().get(0).height; camera.release(); } catch (Exception e) { <START> width = <END> VIDEO_WIDTH; height = VIDEO_HEIGHT; } mMediaRecorder.setVideoSource(MediaRecorder.VideoSource.CAMERA); mMediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.DEFAULT); mMediaRecorder.setVideoEncoder(MediaRecorder.VideoEncoder.DEFAULT); mMediaRecorder.setVideoSize(width, height); mMediaRecorder.setVideoEncodingBitRate(VIDEO_BIT_RATE_IN_BPS); mMediaRecorder.setPreviewDisplay(mActivity.getSurfaceHolder().getSurface()); mMediaRecorder.prepare(); mMediaRecorder.start(); Thread.sleep(RECORD_TIME_MS); mMediaRecorder.stop(); checkOutputExist(); }</code><technical_language>camera released if is Exception</technical_language>

Target:
public void testRecorderCamera() throws Exception { int width; int height; Camera camera = null; if (!hasCamera()) { return; } try { camera = Camera.open(); width = camera.getParameters().getSupportedPreviewSizes().get(0).width; height = camera.getParameters().getSupportedPreviewSizes().get(0).height; } catch (Exception e) { width = VIDEO_WIDTH; height = VIDEO_HEIGHT; } if (camera != null) { camera.release(); } mMediaRecorder.setVideoSource(MediaRecorder.VideoSource.CAMERA); mMediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.DEFAULT); mMediaRecorder.setVideoEncoder(MediaRecorder.VideoEncoder.DEFAULT); mMediaRecorder.setVideoSize(width, height); mMediaRecorder.setVideoEncodingBitRate(VIDEO_BIT_RATE_IN_BPS); mMediaRecorder.setPreviewDisplay(mActivity.getSurfaceHolder().getSurface()); mMediaRecorder.prepare(); mMediaRecorder.start(); Thread.sleep(RECORD_TIME_MS); mMediaRecorder.stop(); checkOutputExist(); }
Source:
<code>@VisibleForTesting Call<MwQueryResponse<Nearby>> request(@NonNull Service service, double latitude, double longitude, double radius, @NonNull final Callback cb) { String latLng = String.format(Locale.ROOT, "%f|%f", latitude, longitude); Call<MwQueryResponse<Nearby>> call = service.request(latLng, radius, Constants.PREFERRED_THUMB_SIZE); call.enqueue(new retrofit2.Callback<MwQueryResponse<Nearby>>() { @Override public void onResponse(Call<MwQueryResponse<Nearby>> call, Response<MwQueryResponse<Nearby>> response) { if (response.isSuccessful()) { if (response.body().success()) { cb.success(call, new NearbyResult(response.body().query().list())); } else if (response.body().hasError()) { cb.failure(call, new MwApiErrorException(response.body().getError())); <START> } <END> } else { cb.failure(call, RetrofitException.httpError(response, cachedService.retrofit())); } } @Override public void onFailure(Call<MwQueryResponse<Nearby>> call, Throwable t) { cb.failure(call, t); } }); return call; }</code><technical_language>Consider a else case avoid a scenario callback is invoked</technical_language>

Target:
@VisibleForTesting Call<MwQueryResponse<Nearby>> request(@NonNull Service service, double latitude, double longitude, double radius, @NonNull final Callback cb) { String latLng = String.format(Locale.ROOT, "%f|%f", latitude, longitude); Call<MwQueryResponse<Nearby>> call = service.request(latLng, radius, Constants.PREFERRED_THUMB_SIZE); call.enqueue(new retrofit2.Callback<MwQueryResponse<Nearby>>() { @Override public void onResponse(Call<MwQueryResponse<Nearby>> call, Response<MwQueryResponse<Nearby>> response) { if (response.isSuccessful()) { if (response.body().success()) { cb.success(call, new NearbyResult(response.body().query().list())); } else if (response.body().hasError()) { cb.failure(call, new MwApiException(response.body().getError())); } else { cb.success(call, new NearbyResult(new ArrayList<NearbyPage>())); } } else { cb.failure(call, RetrofitException.httpError(response, cachedService.retrofit())); } } @Override public void onFailure(Call<MwQueryResponse<Nearby>> call, Throwable t) { cb.failure(call, t); } }); return call; }
Source:
<code>public List<JournalEntry> getEntriesSince(long offset, boolean inclusive) { try { if (offset < journal.firstKey() || offset > journal.lastKey() || !journal.containsKey(offset)) { return null; } } catch (NoSuchElementException e) { return null; } ConcurrentNavigableMap<Long, StoreKey> subsetMap = journal.tailMap(offset, true); int entriesToReturn = Math.min(subsetMap.size(), maxEntriesToReturn); List<JournalEntry> journalEntries = new ArrayList<JournalEntry>(entriesToReturn); int entriesAdded = 0; for (Map.Entry<Long, StoreKey> entry : subsetMap.entrySet()) { if (inclusive || entry.getKey() != offset) { journalEntries.add(new JournalEntry(entry.getKey(), entry.getValue())); entriesAdded++; if (entriesAdded == entriesToReturn) { break; } } } try { if (offset < journal.firstKey()) { <START> return null; <END> } } catch (NoSuchElementException e) { return null; } logger.trace("Journal : " + dataDir + " entries returned " + journalEntries.size()); return journalEntries; }</code><technical_language>check for journalEntries journal</technical_language>

Target:
public List<JournalEntry> getEntriesSince(long offset, boolean inclusive) { Map.Entry<Long, StoreKey> first = journal.firstEntry(); Map.Entry<Long, StoreKey> last = journal.lastEntry(); if (first == null || offset < first.getKey() || last == null || offset > last.getKey() || !journal.containsKey(offset)) { return null; } ConcurrentNavigableMap<Long, StoreKey> subsetMap = journal.tailMap(offset, true); int entriesToReturn = Math.min(subsetMap.size(), maxEntriesToReturn); List<JournalEntry> journalEntries = new ArrayList<JournalEntry>(entriesToReturn); int entriesAdded = 0; for (Map.Entry<Long, StoreKey> entry : subsetMap.entrySet()) { if (inclusive || entry.getKey() != offset) { journalEntries.add(new JournalEntry(entry.getKey(), entry.getValue())); entriesAdded++; if (entriesAdded == entriesToReturn) { break; } } } first = journal.firstEntry(); if (first == null || offset < first.getKey()) { return null; } logger.trace("Journal : " + dataDir + " entries returned " + journalEntries.size()); return journalEntries; }
Source:
<code>public AggregatorFactory getMergingFactory(AggregatorFactory other) throws AggregatorFactoryNotMergeableException { if (other.getName().equals(this.getName()) && other instanceof DoublesSketchAggregatorFactory) { <START> return new DoublesSketchMergeAggregatorFactory(name, k); <END> } else { throw new AggregatorFactoryNotMergeableException(this, other); } }</code><technical_language>I if this.k other.k different</technical_language>

Target:
public AggregatorFactory getMergingFactory(AggregatorFactory other) throws AggregatorFactoryNotMergeableException { if (other.getName().equals(this.getName()) && other instanceof DoublesSketchAggregatorFactory) { return new DoublesSketchMergeAggregatorFactory(name, Math.max(k, ((DoublesSketchAggregatorFactory) other).k)); } else { throw new AggregatorFactoryNotMergeableException(this, other); } }
Source:
<code>public static void main(String[] args) throws SmackException, IOException, XMPPException, InterruptedException { ModularXmppClientToServerConnectionConfiguration.Builder builder = ModularXmppClientToServerConnectionConfiguration.builder(); <START> builder.removeModule(XmppTcpTransportModuleDescriptor.class); <END> builder.setXmppAddressAndPassword(args[0], args[1]); ModularXmppClientToServerConnectionConfiguration config = builder.build(); ModularXmppClientToServerConnection connection = new ModularXmppClientToServerConnection(config); connection.connect(); connection.login(); }</code><technical_language>approach is fragile. If add another module later, this active here. want do instead is removeAllModules() add module want</technical_language>

Target:
public static void main(String[] args) throws SmackException, IOException, XMPPException, InterruptedException, URISyntaxException { ModularXmppClientToServerConnectionConfiguration.Builder builder = ModularXmppClientToServerConnectionConfiguration.builder(); builder.removeAllModules(); builder.setXmppAddressAndPassword(args[0], args[1]); XmppWebsocketTransportModuleDescriptor.Builder websocketBuilder = XmppWebsocketTransportModuleDescriptor.getBuilder(builder); websocketBuilder.explicitlySetWebsocketEndpointAndDiscovery(new URI(args[2]), false); builder.addModule(websocketBuilder.build()); ModularXmppClientToServerConnectionConfiguration config = builder.build(); ModularXmppClientToServerConnection connection = new ModularXmppClientToServerConnection(config); connection.connect(); connection.login(); connection.disconnect(); }
Source:
<code>private void assertConstraints(TaskAssigningSolution solution) { <START> int[] totalTasks = {0}; <END> solution.getUserList().forEach(user -> { List<Task> taskList = extractTaskList(user); totalTasks[0] += taskList.size(); taskList.forEach(task -> assertAssignment(user, task, solution.getUserList())); }); assertEquals(solution.getTaskList().size(), totalTasks[0]); }</code><technical_language>If access 0 index of array, do need array all</technical_language>

Target:
private void assertConstraints(TaskAssigningSolution solution) { int totalTasks = 0; for (User user : solution.getUserList()) { List<Task> taskList = extractTaskList(user); totalTasks += taskList.size(); taskList.forEach(task -> assertAssignment(user, task, solution.getUserList())); } assertEquals(solution.getTaskList().size(), totalTasks); }
Source:
<code><START> public void bind(PropertyBindingContext context) { <END> context.getDependencies() .useRootOnly(); IndexSchemaElement schemaElement = context.getIndexSchemaElement(); IndexSchemaObjectField userMetadataField = schemaElement.objectField( "userMetadata" ); userMetadataField.fieldTemplate( "userMetadataValueTemplate", f -> f.asString().analyzer( "english" ) ); context.setBridge( new Bridge( userMetadataField.toReference() ) ); }</code><technical_language>include class statement in code sample</technical_language>

Target:
public void bind(PropertyBindingContext context) { context.getDependencies() .useRootOnly(); IndexSchemaElement schemaElement = context.getIndexSchemaElement(); IndexSchemaObjectField userMetadataField = schemaElement.objectField( "userMetadata" ); userMetadataField.fieldTemplate( "userMetadataValueTemplate", f -> f.asString().analyzer( "english" ) ); context.setBridge( new UserMetadataBridge( userMetadataField.toReference() ) ); }
Source:
<code><START> protected void addCanDoActionMessages(VdcBllMessages... messages) { <END> for (VdcBllMessages msg : messages) { addCanDoActionMessage(msg); } }</code><technical_language>final method</technical_language>

Target:
protected final void addCanDoActionMessages(VdcBllMessages... messages) { for (VdcBllMessages msg : messages) { addCanDoActionMessage(msg); } }
Source:
<code>public void shouldRunAllTests() { <START> final Result result = runJUnit( <END> DummyTestClass.class.getName(), DummyTestClass0.class.getName(), DummyTestClass1.class.getName(), DummyTestClass01.class.getName(), DummyTestClass0TestMethod1.class.getName()); assertFinished(DummyTestClass.class); assertFinished(DummyTestClass0.class); assertFinished(DummyTestClass1.class); assertFinished(DummyTestClass01.class); assertFinished(DummyTestClass0TestMethod1.class); assertThat("runCount does not match", result.getRunCount(), is(5)); assertThat("failureCount does not match", result.getFailureCount(), is(0)); }</code><technical_language>nit: remove final (here in this file)</technical_language>

Target:
public void shouldRunAllTests() { Result result = runJUnit( DummyTestClass.class.getName(), DummyTestClass0.class.getName(), DummyTestClass1.class.getName(), DummyTestClass01.class.getName(), DummyTestClass0TestMethod1.class.getName()); assertWasRun(DummyTestClass.class); assertWasRun(DummyTestClass0.class); assertWasRun(DummyTestClass1.class); assertWasRun(DummyTestClass01.class); assertWasRun(DummyTestClass0TestMethod1.class); assertThat("runCount does not match", result.getRunCount(), is(5)); assertThat("failureCount does not match", result.getFailureCount(), is(0)); }
Source:
<code>private void toggleMute() { mLogger.d("toggleMute"); mMute = !mMute; <START> updateMicrophoneVolume(mMute ? getResources().getInteger(R.integer.mute_microphone_volume_value) : getResources().getInteger(R.integer.unmute_microphone_volume_value)); <END> updateUi(); }</code><technical_language>Get integer resources previous line do once. e.g. int volume = getResources().getInteger(mMute ?........); updateMicrophoneVolume(volume);</technical_language>

Target:
private void toggleMute() { mLogger.d("toggleMute"); mMute = !mMute; int volume = getResources().getInteger(mMute ? R.integer.mute_microphone_volume_value : R.integer.unmute_microphone_volume_value); updateMicrophoneVolume(volume); updateUi(); }
Source:
<code>@Override public RelNode convert(RelNode rel) { LogicalTableSpool spool = (LogicalTableSpool) rel; <START> return new EnumerableTableSpool( <END> spool.getCluster(), spool.getTraitSet().replace(EnumerableConvention.INSTANCE), convert(spool.getInput(), spool.getInput().getTraitSet().replace(EnumerableConvention.INSTANCE)), spool.getReadType(), spool.getWriteType(), spool.getTableName()); }</code><technical_language>Static factory instead</technical_language>

Target:
@Override public RelNode convert(RelNode rel) { LogicalTableSpool spool = (LogicalTableSpool) rel; return EnumerableTableSpool.create( convert(spool.getInput(), spool.getInput().getTraitSet().replace(EnumerableConvention.INSTANCE)), spool.readType, spool.writeType, spool.getTableName()); }
Source:
<code>@Override public void initCubicWorld() { ICubicChunksWorldType type = (ICubicChunksWorldType) this.getWorldType(); this.maxHeight = type.getDefaultMaxHeight(); <START> this.minHeight = type.getDefaultMinHeight(); <END> if (CubicChunks.Config.getWorldHeightLowerBound() >= type.getDefaultMinHeight()) { this.minHeight = CubicChunks.Config.getWorldHeightLowerBound(); } if (CubicChunks.Config.getWorldHeightUpperBound() <= this.maxHeight) { this.maxHeight = CubicChunks.Config.getWorldHeightUpperBound(); } }</code><technical_language>If absolute height bounds - rename methods match. I proposed names I in mind actual defaults (I thoiught obvious)</technical_language>

Target:
@Override public void initCubicWorld() { ICubicChunksWorldType type = (ICubicChunksWorldType) this.getWorldType(); this.maxHeight = type.getMaximumPossibleHeight(); this.minHeight = type.getMinimumPossibleHeight(); if (CubicChunks.Config.getWorldHeightLowerBound() >= type.getMinimumPossibleHeight()) { this.minHeight = CubicChunks.Config.getWorldHeightLowerBound(); } if (CubicChunks.Config.getWorldHeightUpperBound() <= this.maxHeight) { this.maxHeight = CubicChunks.Config.getWorldHeightUpperBound(); } }
Source:
<code>public Optional<TYPE> last() { Optional result = Optional.empty(); <START> List<TYPE> list = last(1).asList(); <END> if(!list.isEmpty()) { result = Optional.of(list.get(0)); } return result; }</code><technical_language>Similar change first(count)</technical_language>

Target:
public Optional<TYPE> last() { Iterator<TYPE> resultIterator = last(1).iterator(); return resultIterator.hasNext() ? Optional.of(resultIterator.next()) : Optional.empty(); }
Source:
<code>public SocatContainer() { <START> this(DockerImageName.parse("alpine/socat:latest")); <END> }</code><technical_language>related this PR, is a good time pin socat? :D re-publish testcontainers automated build alpine/socat:latest pin it</technical_language>

Target:
public SocatContainer() { this(DockerImageName.parse("alpine/socat:1.7.3.4-r0")); }
Source:
<code>public void testValidationWithoutSettings() throws ValidationException { CloudWatchWriter writer = createCloudWatchWriter(); Query query = Query.builder() .setObj("test") .build(); Server server = Server.builder().setHost("localhost").setPort("123").build(); writer.validateSetup(server, query); <START> System.out.println("I got here"); <END> }</code><technical_language>Remove this. =)</technical_language>

Target:
public void testValidationWithoutSettings() throws ValidationException { CloudWatchWriter writer = createCloudWatchWriter(); Query query = Query.builder() .setObj("test") .build(); Server server = Server.builder().setHost("localhost").setPort("123").build(); writer.validateSetup(server, query); }
Source:
<code>public ClassLoader connectorLoader(String connectorClassOrAlias) { log.debug("Getting plugin class loader for connector: '{}'", connectorClassOrAlias); String fullName = aliases.containsKey(connectorClassOrAlias) ? aliases.get(connectorClassOrAlias) : connectorClassOrAlias; PluginClassLoader classLoader = pluginClassLoader(fullName); if (classLoader == null) { <START> log.trace( <END> "Plugin class loader for connector: '{}' was not found. Returning: {}", connectorClassOrAlias, this ); return this; } return classLoader; }</code><technical_language>I agree this error. debug reasonable "Getting plugin class loader" message above</technical_language>

Target:
public ClassLoader connectorLoader(String connectorClassOrAlias) { String fullName = aliases.containsKey(connectorClassOrAlias) ? aliases.get(connectorClassOrAlias) : connectorClassOrAlias; ClassLoader classLoader = pluginClassLoader(fullName); if (classLoader == null) classLoader = this; log.debug( "Getting plugin class loader: '{}' for connector: {}", classLoader, connectorClassOrAlias ); return classLoader; }
Source:
<code>void sendEvent(byte[] key, byte[] value, long dataVersion, CacheEntryEvent event) { Events.Event remoteEvent = createRemoteEvent(key, value, dataVersion, event); if (isTrace) log.tracef("Queue event %s, before queuing event queue size is %d", remoteEvent, eventQueue.size()); EventLoop loop = ch.eventLoop(); if (loop.inEventLoop()) { <START> boolean offered = eventQueue.offer(remoteEvent); <END> while (!offered) { writeEventsIfPossible(); try { offered = eventQueue.offer(remoteEvent, 1, TimeUnit.MILLISECONDS); } catch (InterruptedException e) { throw new CacheException(e); } } if (ch.isWritable()) { loop.submit(writeEventsIfPossible); } } else { try { eventQueue.put(remoteEvent); } catch (InterruptedException e) { throw new CacheException(e); } if (ch.isWritable()) { loop.submit(writeEventsIfPossible); } } }</code><technical_language>IMO throw exception instead of complicating code</technical_language>

Target:
void sendEvent(byte[] key, byte[] value, long dataVersion, CacheEntryEvent event) { Events.Event remoteEvent = createRemoteEvent(key, value, dataVersion, event); if (isTrace) log.tracef("Queue event %s, before queuing event queue size is %d", remoteEvent, eventQueue.size()); EventLoop loop = ch.eventLoop(); if (loop.inEventLoop()) { boolean offered = eventQueue.offer(remoteEvent); while (!offered) { writeEventsIfPossible(); try { offered = eventQueue.offer(remoteEvent, 1, TimeUnit.MILLISECONDS); } catch (InterruptedException e) { throw new CacheException(e); } } } else { try { if (!eventQueue.offer(remoteEvent, 30, TimeUnit.SECONDS)) { throw new TimeoutException("Timed out attempting to offer remote event into queue"); } } catch (InterruptedException e) { throw new CacheException(e); } } if (ch.isWritable()) { loop.submit(writeEventsIfPossible); } }