auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public static Properties defaultProperties() { final Properties properties = AzureManagementApiMetadata.defaultProperties(); properties.put(ComputeServiceProperties.POLL_INITIAL_PERIOD, 1000); properties.put(ComputeServiceProperties.POLL_MAX_PERIOD, 10000); properties.setProperty(OPERATION_TIMEOUT, "46000000"); properties.setProperty(OPERATION_POLL_INITIAL_PERIOD, "5"); properties.setProperty(OPERATION_POLL_MAX_PERIOD, "15"); properties.setProperty(TCP_RULE_FORMAT, "tcp_%s-%s"); properties.setProperty(TCP_RULE_REGEXP, "tcp_\\d{1,5}-\\d{1,5}"); properties.put(RESOURCE, "<LINK_0>"); properties.put(CREDENTIAL_TYPE, CLIENT_CREDENTIALS_SECRET.toString()); properties.put(RESOURCE_GROUP_NAME, "jcloudsgroup"); properties.put(IMAGE_PUBLISHERS, "Canonical"); properties.put(DEFAULT_VNET_ADDRESS_SPACE_PREFIX, "10.0.0.0/16"); properties.put(DEFAULT_SUBNET_ADDRESS_PREFIX, "10.0.0.0/24"); properties.put(IMAGE_PUBLISHERS, "Canonical,RedHat"); properties.put(DEFAULT_IMAGE_LOGIN, "jclouds:Password1!"); properties.put(TIMEOUT_NODE_TERMINATED, 60 * 10 * 1000); return properties; }

Target:
public static Properties defaultProperties() { final Properties properties = AzureManagementApiMetadata.defaultProperties(); properties.put(ComputeServiceProperties.POLL_INITIAL_PERIOD, 1000); properties.put(ComputeServiceProperties.POLL_MAX_PERIOD, 10000); properties.setProperty(OPERATION_TIMEOUT, "46000000"); properties.setProperty(OPERATION_POLL_INITIAL_PERIOD, "5"); properties.setProperty(OPERATION_POLL_MAX_PERIOD, "15"); properties.setProperty(TCP_RULE_FORMAT, "tcp_%s-%s"); properties.setProperty(TCP_RULE_REGEXP, "tcp_\\d{1,5}-\\d{1,5}"); properties.put(RESOURCE, "<LINK_0>"); properties.put(CREDENTIAL_TYPE, CLIENT_CREDENTIALS_SECRET.toString()); properties.put(RESOURCE_GROUP_NAME, "jcloudsgroup"); properties.put(DEFAULT_VNET_ADDRESS_SPACE_PREFIX, "10.0.0.0/16"); properties.put(DEFAULT_SUBNET_ADDRESS_PREFIX, "10.0.0.0/24"); properties.put(DEFAULT_DATADISKSIZE, "100"); properties.put(IMAGE_PUBLISHERS, "Canonical,RedHat"); properties.put(DEFAULT_IMAGE_LOGIN, "jclouds:Password1!"); properties.put(TIMEOUT_NODE_TERMINATED, 60 * 10 * 1000); return properties; }
Source:
public void testContinueSoundDoesNotStartFromBeginning() { secondScript.addBrick(new SceneTransitionBrick(firstSceneName)); runProject(lastBrickFirstScript); MediaPlayer mediaPlayer = getMediaplayer(); assertTrue(mediaPlayer.isPlaying()); assertTrue(mediaPlayer.getCurrentPosition() > 0); }

Target:
public void testContinueSoundDoesNotStartFromBeginning() { secondScript.addBrick(new SceneTransitionBrick(firstSceneName)); runProject(lastBrickFirstScript); MediaPlayer mediaPlayer = getMediaplayer(); assertTrue(mediaPlayer.isPlaying()); assertTrue(mediaPlayer.getCurrentPosition() > 50); }
Source:
public URI getLatestVersion(final URI uri, final @Nullable Pattern pattern) { try { final CloudObjectLocation coords = new CloudObjectLocation(S3Utils.checkURI(uri)); long mostRecent = Long.MIN_VALUE; URI latest = null; final Iterator<S3ObjectSummary> objectSummaryIterator = S3Utils.objectSummaryIterator( s3Client, uri, MAX_LISTING_KEYS ); while (objectSummaryIterator.hasNext()) { final S3ObjectSummary objectSummary = objectSummaryIterator.next(); String keyString = objectSummary.getKey().substring(coords.getPath().length()); if (keyString.startsWith("/")) { keyString = keyString.substring(1); } if (pattern != null && !pattern.matcher(keyString).matches()) { continue; } final long latestModified = objectSummary.getLastModified().getTime(); if (latestModified >= mostRecent) { mostRecent = latestModified; latest = new URI( StringUtils.format("s3://%s/%s", objectSummary.getBucketName(), objectSummary.getKey()) ); } } return latest; } catch (Exception e) { throw new RuntimeException(e); } }

Target:
public URI getLatestVersion(final URI uri, final @Nullable Pattern pattern) { try { final CloudObjectLocation coords = new CloudObjectLocation(S3Utils.checkURI(uri)); long mostRecent = Long.MIN_VALUE; URI latest = null; final Iterator<S3ObjectSummary> objectSummaryIterator = S3Utils.objectSummaryIterator( s3Client, uri, MAX_LISTING_KEYS ); while (objectSummaryIterator.hasNext()) { final S3ObjectSummary objectSummary = objectSummaryIterator.next(); final CloudObjectLocation objectLocation = S3Utils.summaryToCloudObjectLocation(objectSummary); String keyString = StringUtils.maybeRemoveLeadingSlash( objectLocation.getPath().substring(coords.getPath().length()) ); if (pattern != null && !pattern.matcher(keyString).matches()) { continue; } final long latestModified = objectSummary.getLastModified().getTime(); if (latestModified >= mostRecent) { mostRecent = latestModified; latest = objectLocation.toUri(S3StorageDruidModule.SCHEME); } } return latest; } catch (Exception e) { throw new RuntimeException(e); } }
Source:
protected final void writeByte(int val) throws IOException { assert(val >= 0x00 && val <= 0xFF); output.write(val); }

Target:
protected final void writeByte(int val) throws IOException { output.write(val & 0xFF); }
Source:
public static String getPostURL(){ try{ SharedPreferences prefs = CommCareApplication._().getCurrentApp().getAppPreferences(); return prefs.getString(HttpRequestGenerator.USER_DOMAIN_SUFFIX, "not found"); } catch(NullPointerException e){ return "PostURL not set."; } }

Target:
public static String getPostURL(){ try{ SharedPreferences prefs = CommCareApplication._().getCurrentApp().getAppPreferences(); return prefs.getString(HttpRequestGenerator.USER_DOMAIN_SUFFIX, "not found"); } catch(Exception e){ return "PostURL not set."; } }
Source:
public boolean writeInbound(Object... msgs) { ensureOpen(); if (msgs.length == 0) { return isNotEmpty(inboundMessages); } if (!config().isAutoRead()) { for (Object m : msgs) { tempInboundMessages().add(m); } return true; } ChannelPipeline p = pipeline(); for (Object m: msgs) { p.fireChannelRead(m); } flushInbound(false, voidPromise()); return isNotEmpty(inboundMessages); }

Target:
public boolean writeInbound(Object... msgs) { ensureOpen(); if (msgs.length == 0) { return isNotEmpty(inboundMessages); } if (!config().isAutoRead()) { Queue<AbstractMap.SimpleEntry<Object, ChannelPromise>> tempInboundMessages = tempInboundMessages(); for (Object msg : msgs) { tempInboundMessages.add(new AbstractMap.SimpleEntry<Object, ChannelPromise>(msg, null)); } return false; } ChannelPipeline p = pipeline(); for (Object m: msgs) { p.fireChannelRead(m); } flushInbound(false, voidPromise()); return isNotEmpty(inboundMessages); }
Source:
public MockStore(List<MessageInfo> messageInfo, List<ByteBuffer> buffers) { if (messageInfo.size() != buffers.size()) { throw new IllegalArgumentException("message info size and buffer size does not match"); } messageInfoList = messageInfo; log = new DummyLog(buffers); bytesWrittenSoFar = new Long(0); }

Target:
public MockStore(List<MessageInfo> messageInfo, List<ByteBuffer> buffers) { if (messageInfo.size() != buffers.size()) { throw new IllegalArgumentException("message info size and buffer size does not match"); } messageInfoList = messageInfo; log = new DummyLog(buffers); }
Source:
public WebViewPage(WebDriver driver) { super(driver); webViewDriver = (AppiumDriver) (((EventFiringWebDriver) getDriver()).getWrappedDriver()); Set contextNames = webViewDriver.getContextHandles(); contextNames.forEach(System.out::println); webViewContext = contextNames.toArray()[1].toString(); }

Target:
public WebViewPage(WebDriver driver) { super(driver); }
Source:
public T value(boolean forceRefresh) { if (forceRefresh) { m_value = null; return value(); } return value(); }

Target:
public T value(boolean forceRefresh) { if (forceRefresh) { m_value = null; } return value(); }
Source:
public String toString() { return domainType + "+" + connectorType + "+" + instanceId; }

Target:
public String toString() { return toFullID(); }
Source:
String send(byte[] body) { HttpURLConnection connection = null; try { URL url = new URL(this.requestUrl); connection = (HttpURLConnection) url.openConnection(); connection.setDoOutput(true); connection.setRequestMethod("POST"); connection.setRequestProperty("Content-Type", "application/json"); connection.setRequestProperty("Accept", "application/json"); connection.setRequestProperty("Content-Length", Integer.toString(body.length)); writeRequest(body, connection); return readResponse(connection); } catch (Exception e) { log.error(e.getMessage(), e); return null; } finally { if (connection != null) { connection.disconnect(); } } }

Target:
String send(byte[] body) { HttpURLConnection connection = null; try { URL url = new URL(this.requestUrl); connection = prepareConnection(url, body); writeRequest(body, connection); return readResponse(connection); } catch (Exception e) { log.error(e.getMessage(), e); return null; } finally { if (connection != null) { connection.disconnect(); } } }
Source:
protected void releaseConnection(LeasedSmtpConnection leasedSmtpConnection) { synchronized (m_poolLock) { Assertions.assertFalse(m_destroyed, "SmtpConnectionPool not available because it has already been destroyed."); SmtpConnectionPoolEntry candidate = null; for (Iterator<SmtpConnectionPoolEntry> it = m_leasedEntries.iterator(); it.hasNext();) { SmtpConnectionPoolEntry entry = it.next(); if (leasedSmtpConnection.getTransport() == entry.getTransport()) { candidate = entry; it.remove(); break; } } if (candidate != null && !candidate.getTransport().isConnected()) { LOG.debug("Releasing pooled SMTP connection {}; transport is already closed, not returning to idle pool.", candidate); candidate = null; } if (candidate != null) { IDateProvider dateProvider = BEANS.get(IDateProvider.class); if (dateProvider.currentMillis().getTime() - candidate.getCreateTime() < m_maxConnectionLifetime) { LOG.debug("Releasing pooled SMTP connection {}; returning to idle pool.", candidate); candidate.withIdleSince(dateProvider.currentMillis().getTime()); m_idleEntries.add(candidate); } else { LOG.debug("Releasing pooled SMTP connection {}; pooled connection reached max lifetime of {}s, not returning to idle pool.", candidate, m_maxConnectionLifetime / 1000d); } } m_poolLock.notifyAll(); } }

Target:
protected void releaseConnection(LeasedSmtpConnection leasedSmtpConnection) { synchronized (m_poolLock) { Assertions.assertFalse(m_destroyed, "SmtpConnectionPool not available because it has already been destroyed."); SmtpConnectionPoolEntry candidate = null; for (Iterator<SmtpConnectionPoolEntry> it = m_leasedEntries.iterator(); it.hasNext();) { SmtpConnectionPoolEntry entry = it.next(); if (leasedSmtpConnection.getTransport() == entry.getTransport()) { candidate = entry; it.remove(); break; } } if (candidate != null && !candidate.getTransport().isConnected()) { LOG.debug("Releasing pooled SMTP connection {}; transport is already closed, not returning to idle pool.", candidate); candidate = null; } if (candidate != null) { IDateProvider dateProvider = BEANS.get(IDateProvider.class); P_ReuseCheckResult reuseCheckResult = isReuseAllowed(candidate); if (reuseCheckResult.isReuseAllowed()) { LOG.debug("Releasing pooled SMTP connection {}; returning to idle pool.", candidate); candidate.withIdleSince(dateProvider.currentMillis().getTime()); m_idleEntries.add(candidate); } else { safeCloseTransport(candidate); LOG.debug("Releasing pooled SMTP connection {}; {}, not returning to idle pool.", candidate, reuseCheckResult.getReuseDeniedReason()); } } m_poolLock.notifyAll(); } }
Source:
public void testTableViewer_ReplacingSelectedItemSelectsNewItem() { TableViewer tableViewer = new TableViewer(getShell()); tableViewer.setComparator(new ViewerComparator()); tableViewer.setContentProvider(new ObservableListContentProvider()); tableViewer.setInput(elementsList); tableViewer.getTable().selectAll(); elementsList.set(0, "foo"); IStructuredSelection selection = (IStructuredSelection) tableViewer.getSelection(); Assert.assertEquals(elements.length, selection.size()); Assert.assertTrue(selection.toList().contains("foo")); }

Target:
public void testTableViewer_ReplacingSelectedItemSelectsNewItem() { TableViewer tableViewer = new TableViewer(getShell()); tableViewer.setComparator(new ViewerComparator()); tableViewer.setContentProvider(new ObservableListContentProvider()); tableViewer.setInput(elementsList); tableViewer.getTable().selectAll(); elementsList.set(0, "foo"); IStructuredSelection selection = tableViewer.getStructuredSelection(); Assert.assertEquals(elements.length, selection.size()); Assert.assertTrue(selection.toList().contains("foo")); }
Source:
public SuccessOrFailure isReady(DockerComposeRule rule) { return SuccessOrFailure.onResultOf(() -> { CassandraClusterOperations cassandraOperations = new CassandraClusterOperations(rule, CASSANDRA_VERSION, ImmutableList.of(CONTAINER_NAME), CLI_CONTAINER_NAME); if (!cassandraOperations.nodetoolShowsAllCassandraNodesUp()) { return false; } cassandraOperations.disableAutoCompaction(); return canCreateCassandraKeyValueService(); }); }

Target:
public SuccessOrFailure isReady(DockerComposeRule rule) { return SuccessOrFailure.onResultOf(() -> { CassandraClusterOperations cassandraOperations = new CassandraClusterOperations(rule, CASSANDRA_VERSION, ImmutableList.of(CONTAINER_NAME), CONTAINER_NAME); if (!cassandraOperations.nodetoolShowsAllCassandraNodesUp()) { return false; } cassandraOperations.disableAutoCompaction(); return canCreateCassandraKeyValueService(); }); }
Source:
public void testTimelineUpdateWaitsForActivePublish() throws InterruptedException, IOException, TimeoutException { final TimelineSync t1 = createTimeline(); final TimelineSync t2 = createTimeline(); final String eventType = UUID.randomUUID().toString(); final AtomicBoolean updated = new AtomicBoolean(false); final Closeable publishing = t1.workWithEventType(eventType, TimeUnit.SECONDS.toMillis(1)); try { new Thread(() -> { try { t2.startTimelineUpdate(eventType, TimeUnit.SECONDS.toMillis(30)); updated.set(true); } catch (final InterruptedException ex) { throw new RuntimeException(ex); } }, "timeline_update").start(); Thread.sleep(TimeUnit.SECONDS.toMillis(3)); Assert.assertEquals(false, updated.get()); } finally { publishing.close(); } int attemptsLeft = 5; while (attemptsLeft-- > 0) { Thread.sleep(300); if (updated.get()) { break; } } Assert.assertEquals(true, updated.get()); }

Target:
public void testTimelineUpdateWaitsForActivePublish() throws InterruptedException, IOException, TimeoutException { final TimelineSync t1 = createTimeline(); final TimelineSync t2 = createTimeline(); final String eventType = UUID.randomUUID().toString(); final AtomicBoolean updated = new AtomicBoolean(false); try (Closeable ignored = t1.workWithEventType(eventType, TimeUnit.SECONDS.toMillis(1))) { new Thread(() -> { try { t2.startTimelineUpdate(eventType, TimeUnit.SECONDS.toMillis(30)); updated.set(true); } catch (final InterruptedException ex) { throw new RuntimeException(ex); } }, "timeline_update").start(); Thread.sleep(TimeUnit.SECONDS.toMillis(3)); Assert.assertEquals(false, updated.get()); } TestUtils.waitFor(() -> Assert.assertTrue(updated.get())); }
Source:
public EntityStorageRecord read(I id, FieldMask fieldMask) { final EntityStorageRecord.Builder builder = EntityStorageRecord.newBuilder(read(id)); final Any state = builder.getState(); builder.setState(AnyPacker.pack(FieldMasks.applyIfValid(fieldMask, AnyPacker.unpack(state), TypeUrl.of(state.getTypeUrl())))); return builder.build(); }

Target:
public EntityStorageRecord read(I id, FieldMask fieldMask) { final EntityStorageRecord rawResult = read(id); final EntityStorageRecord.Builder builder = EntityStorageRecord.newBuilder(rawResult); final Any state = builder.getState(); final TypeUrl type = TypeUrl.of(state.getTypeUrl()); final Message stateAsMessage = AnyPacker.unpack(state); final Message maskedState = FieldMasks.applyMask(fieldMask, stateAsMessage, type); final Any packedState = AnyPacker.pack(maskedState); builder.setState(packedState); return builder.build(); }
Source:
public void testSetAttributeEnumMap() { configurationApplication.setAttributeEnumMap( Arrays.asList( "", "unrestrictedAttribute", "restrictedAttributeWithEmptyEnum=", "restrictedAttributeWithSpaces=list,of, possible ,values", "restrictedAttributeWithDuplicates=duplicate, duplicate, values, values")); Map<String, Set<String>> attributeEnumMap = configurationApplication.getAttributeEnumMap(); assertThat(configurationApplication.getEditorAttributes().size(), is(4)); assertThat(attributeEnumMap.size(), is(2)); assertThat(attributeEnumMap, not(hasKey("restrictedAttributeWithEmptyEnum"))); assertThat(attributeEnumMap.get("restrictedAttributeWithSpaces"), hasItem("possible")); assertThat(attributeEnumMap.get("restrictedAttributeWithDuplicates").size(), is(2)); }

Target:
public void testSetAttributeEnumMap() { configurationApplication.setAttributeEnumMap( Arrays.asList( "", "unrestrictedAttribute", "restrictedAttributeWithEmptyEnum=", "=blank,attribute,name", " restrictedAttributeWithSpaces = list,of, possible ,values", "restrictedAttributeWithDuplicates=duplicate, duplicate, values, values", "duplicateAttribute=value1", "duplicateAttribute=value2")); Map<String, Set<String>> attributeEnumMap = configurationApplication.getAttributeEnumMap(); assertThat(configurationApplication.getEditorAttributes().size(), is(5)); assertThat(attributeEnumMap.size(), is(3)); assertThat(attributeEnumMap, not(hasKey("restrictedAttributeWithEmptyEnum"))); assertThat(attributeEnumMap, not(hasKey(""))); assertThat(attributeEnumMap.get("restrictedAttributeWithSpaces"), hasItem("possible")); assertThat(attributeEnumMap.get("restrictedAttributeWithDuplicates").size(), is(2)); assertThat(attributeEnumMap.get("duplicateAttribute").size(), is(2)); }
Source:
public void setBoldStylerProvider(BoldStylerProvider boldStylerProvider) { fBoldStylerProvider= boldStylerProvider; }

Target:
void setBoldStylerProvider(BoldStylerProvider boldStylerProvider) { fBoldStylerProvider= boldStylerProvider; }
Source:
private static int findNonWhitespace(AppendableCharSequence sb, int offset, boolean validateOWS) { for (int result = offset; result < sb.length(); ++result) { char c = sb.charAtUnsafe(result); if (!Character.isWhitespace(c)) { return result; } else if (validateOWS && !isOWS(c)) { throw new IllegalArgumentException("Invalid separator, only OWS allowed"); } } return sb.length(); }

Target:
private static int findNonWhitespace(AppendableCharSequence sb, int offset, boolean validateOWS) { for (int result = offset; result < sb.length(); ++result) { char c = sb.charAtUnsafe(result); if (!Character.isWhitespace(c)) { return result; } else if (validateOWS && !isOWS(c)) { throw new IllegalArgumentException("Invalid separator, only a single space or horizontal tab allowed," + " but received a '" + c + "'"); } } return sb.length(); }
Source:
public void initialize() { setDiskVmElement(getDisk().getDiskVmElementForVm(getVm().getId())); super.initialize(); getIsReadOnly().setEntity(getDiskVmElement().isReadOnly()); getIsBootable().setEntity(getDiskVmElement().isBoot()); getPassDiscard().setEntity(getDiskVmElement().isPassDiscard()); switch (getDisk().getDiskStorageType()) { case IMAGE: DiskImage diskImage = (DiskImage) getDisk(); boolean isExtendImageSizeEnabled = getVm() != null && !diskImage.isDiskSnapshot() && ActionUtils.canExecute(Collections.singletonList(getVm()), VM.class, ActionType.ExtendImageSize); getSizeExtend().setIsChangeable(isExtendImageSizeEnabled); break; case LUN: getIsUsingScsiReservation().setEntity(getDiskVmElement().isUsingScsiReservation()); break; case CINDER: case MANAGED_BLOCK_STORAGE: break; } updateReadOnlyChangeability(); updatePassDiscardChangeability(); updateWipeAfterDeleteChangeability(); }

Target:
public void initialize() { super.initialize(); getIsReadOnly().setEntity(getDiskVmElement().isReadOnly()); getIsBootable().setEntity(getDiskVmElement().isBoot()); getPassDiscard().setEntity(getDiskVmElement().isPassDiscard()); if (getDisk().getDiskStorageType() == DiskStorageType.LUN) { getIsUsingScsiReservation().setEntity(getDiskVmElement().isUsingScsiReservation()); } updateReadOnlyChangeability(); updatePassDiscardChangeability(); updateWipeAfterDeleteChangeability(); }
Source:
public static EnterpriseArchive createDeployment() { final WebArchive war = ShrinkWrap.create(WebArchive.class, WEB_APP_CONTEXT + ".war"); war.addClasses(XalanUsageServlet.class); war.addAsResource(XalanUsageServlet.class.getPackage(), "dummy.xml", XalanUsageServlet.XML_RESOURCE_TO_TRANSFORM); war.addAsResource(XalanUsageServlet.class.getPackage(), "dummy.xsl", XalanUsageServlet.XSL_RESOURCE); final EnterpriseArchive ear = ShrinkWrap.create(EnterpriseArchive.class, "xalan-usage.ear"); ear.addAsModule(war); ear.addAsLibrary(XalanUsageTestCase.class.getResource("xalan-2.7.2.jar"), "xalan.jar"); ear.addAsLibrary(XalanUsageTestCase.class.getResource("xalan-serializer-2.7.2.jar"), "xalan-serializer.jar"); return ear; }

Target:
public static EnterpriseArchive createDeployment() throws Exception { final WebArchive war = ShrinkWrap.create(WebArchive.class, WEB_APP_CONTEXT + ".war"); war.addClasses(XalanUsageServlet.class); war.addAsResource(XalanUsageServlet.class.getPackage(), "dummy.xml", XalanUsageServlet.XML_RESOURCE_TO_TRANSFORM); war.addAsResource(XalanUsageServlet.class.getPackage(), "dummy.xsl", XalanUsageServlet.XSL_RESOURCE); final EnterpriseArchive ear = ShrinkWrap.create(EnterpriseArchive.class, "xalan-usage.ear"); ear.addAsModule(war); final List<URL> xalanJars = MavenUtil.create(false).createMavenGavRecursiveURLs("xalan:xalan:2.7.2"); if (xalanJars == null || xalanJars.isEmpty()) { throw new RuntimeException("Could not locate Xalan dependencies"); } for (final URL xalanDep : xalanJars) { ear.addAsLibrary(xalanDep, Paths.get(xalanDep.toURI()).getFileName().toString()); } return ear; }
Source:
void processMessage(Message message) { if (Command.CONNECTED.toString().equals(message.getCommand())) { this.connected.countDown(); } else if (Command.ACK.toString().equals(message.getCommand())) { String headerId = message.getHeaders().get(HEADER_ID); if (!isEmpty(headerId)) { this.subscribed.countDown(); } } else if (Command.ERROR.toString().equals(message.getCommand())) { String errorMessage = message.getHeaders().get(HEADER_MESSAGE); StringBuilder error = new StringBuilder(); if (!isEmpty(errorMessage)){ error.append(errorMessage); } if (!isEmpty(message.getContent())) { error.append(errorMessage); } LOG.error("Error Message recieved: " + error); } else if (Command.MESSAGE.toString().equals(message.getCommand())) { super.emitOnMessageReceived(message.getContent().getBytes(Charset.forName("UTF-8"))); } }

Target:
void processMessage(Message message) { if (Command.CONNECTED.toString().equals(message.getCommand())) { this.connected.countDown(); } else if (Command.ACK.toString().equals(message.getCommand())) { String headerId = message.getHeaders().get(HEADER_ID); if (!isEmpty(headerId)) { this.subscribed.countDown(); } } else if (Command.ERROR.toString().equals(message.getCommand())) { String errorMessage = message.getHeaders().get(HEADER_MESSAGE); StringBuilder error = new StringBuilder(); if (!isEmpty(errorMessage)){ error.append(errorMessage); } if (!isEmpty(message.getContent())) { error.append(errorMessage); } LOG.error("Error Message recieved: " + error); } else if (Command.MESSAGE.toString().equals(message.getCommand())) { super.emitOnMessageReceived(message.getContent().getBytes(UTF8)); } }
Source:
public void spoutMustIgnoreFailsForTuplesItIsNotAssignedAfterRebalance() throws Exception { ArgumentCaptor<ConsumerRebalanceListener> rebalanceListenerCapture = ArgumentCaptor.forClass(ConsumerRebalanceListener.class); Subscription subscriptionMock = mock(Subscription.class); doNothing() .when(subscriptionMock) .subscribe(any(KafkaConsumer.class), rebalanceListenerCapture.capture(), any(TopologyContext.class)); KafkaSpoutRetryService retryServiceMock = mock(KafkaSpoutRetryService.class); KafkaSpout<String, String> spout = new KafkaSpout<>(createKafkaSpoutConfigBuilder(subscriptionMock, -1) .setOffsetCommitPeriodMs(10) .setRetry(retryServiceMock) .build(), consumerFactoryMock); String topic = SingleTopicKafkaSpoutConfiguration.TOPIC; TopicPartition partitionThatWillBeRevoked = new TopicPartition(topic, 1); TopicPartition assignedPartition = new TopicPartition(topic, 2); when(retryServiceMock.getMessageId(Mockito.any(ConsumerRecord.class), contextMock)) .thenReturn(new KafkaSpoutMessageId(partitionThatWillBeRevoked, 0, contextMock)) .thenReturn(new KafkaSpoutMessageId(assignedPartition, 0, contextMock)); List<KafkaSpoutMessageId> emittedMessageIds = emitOneMessagePerPartitionThenRevokeOnePartition( spout, partitionThatWillBeRevoked, assignedPartition, rebalanceListenerCapture); verify(retryServiceMock, times(2)).getMessageId(Mockito.any(ConsumerRecord.class), contextMock); spout.fail(emittedMessageIds.get(0)); spout.fail(emittedMessageIds.get(1)); verify(retryServiceMock, never()).schedule(emittedMessageIds.get(0)); verify(retryServiceMock).schedule(emittedMessageIds.get(1)); }

Target:
public void spoutMustIgnoreFailsForTuplesItIsNotAssignedAfterRebalance() throws Exception { ArgumentCaptor<ConsumerRebalanceListener> rebalanceListenerCapture = ArgumentCaptor.forClass(ConsumerRebalanceListener.class); Subscription subscriptionMock = mock(Subscription.class); doNothing() .when(subscriptionMock) .subscribe(any(KafkaConsumer.class), rebalanceListenerCapture.capture(), any(TopologyContext.class)); KafkaSpoutRetryService retryServiceMock = mock(KafkaSpoutRetryService.class); KafkaSpout<String, String> spout = new KafkaSpout<>(createKafkaSpoutConfigBuilder(subscriptionMock, -1) .setOffsetCommitPeriodMs(10) .setRetry(retryServiceMock) .build(), consumerFactoryMock); String topic = SingleTopicKafkaSpoutConfiguration.TOPIC; TopicPartition partitionThatWillBeRevoked = new TopicPartition(topic, 1); TopicPartition assignedPartition = new TopicPartition(topic, 2); when(retryServiceMock.getMessageId(Mockito.any(ConsumerRecord.class))) .thenReturn(new KafkaSpoutMessageId(partitionThatWillBeRevoked, 0)) .thenReturn(new KafkaSpoutMessageId(assignedPartition, 0)); List<KafkaSpoutMessageId> emittedMessageIds = emitOneMessagePerPartitionThenRevokeOnePartition( spout, partitionThatWillBeRevoked, assignedPartition, rebalanceListenerCapture); verify(retryServiceMock, times(2)).getMessageId(Mockito.any(ConsumerRecord.class)); spout.fail(emittedMessageIds.get(0)); spout.fail(emittedMessageIds.get(1)); verify(retryServiceMock, never()).schedule(emittedMessageIds.get(0)); verify(retryServiceMock).schedule(emittedMessageIds.get(1)); }
Source:
public void removePost(Post postToRemove) { recalculateModificationDate(); posts.remove(postToRemove); }

Target:
public void removePost(Post postToRemove) { posts.remove(postToRemove); Topic topic = postToRemove.getTopic(); if (postToRemove.getCreationDate().withMillis(0).equals(topic.getModificationDate().withMillis(0))) { topic.recalculateModificationDate(); } }
Source:
public void createOverride(int groupId, String methodName, String className) { try { for (Method method : EditService.getInstance().getMethodsFromGroupId(groupId, null)) { if (method.getMethodName().equals(methodName) && method.getClassName().equals(className)) { return; } } } catch (Exception e) { } try (Connection sqlConnection = sqlService.getConnection()) { PreparedStatement statement = sqlConnection.prepareStatement( "INSERT INTO " + Constants.DB_TABLE_OVERRIDE + "(" + Constants.OVERRIDE_METHOD_NAME + "," + Constants.OVERRIDE_CLASS_NAME + "," + Constants.OVERRIDE_GROUP_ID + ")" + " VALUES (?, ?, ?)" ); statement.setString(1, methodName); statement.setString(2, className); statement.setInt(3, groupId); statement.executeUpdate(); } catch (SQLException e) { e.printStackTrace(); } }

Target:
public void createOverride(int groupId, String methodName, String className) throws Exception { for (Method method : EditService.getInstance().getMethodsFromGroupId(groupId, null)) { if (method.getMethodName().equals(methodName) && method.getClassName().equals(className)) { return; } } try (Connection sqlConnection = sqlService.getConnection()) { PreparedStatement statement = sqlConnection.prepareStatement( "INSERT INTO " + Constants.DB_TABLE_OVERRIDE + "(" + Constants.OVERRIDE_METHOD_NAME + "," + Constants.OVERRIDE_CLASS_NAME + "," + Constants.OVERRIDE_GROUP_ID + ")" + " VALUES (?, ?, ?)" ); statement.setString(1, methodName); statement.setString(2, className); statement.setInt(3, groupId); statement.executeUpdate(); } catch (SQLException e) { e.printStackTrace(); } }
Source:
private URI addCookieInterceptorIfRequired(URI uri) { String urlProtocol = uri.getScheme(); String urlHost = uri.getHost(); String urlPath = uri.getRawPath(); int urlPort = uri.getPort(); if (urlPort < 0) { if (urlProtocol.equals("http")) { urlPort = 80; } else if (urlProtocol.equals("https")) { urlPort = 443; } else { throw new RuntimeException("Unknown protocol: "+urlProtocol); } } if (uri.getUserInfo() != null) { String[] parts = uri.getUserInfo().split(":"); if (parts.length == 2) { CookieInterceptor ci = new CookieInterceptor(parts[0], parts[1]); requestInterceptors.add(ci); responseInterceptors.add(ci); } } try { URI redacted = new URI(urlProtocol + "://" + urlHost + ":" + urlPort + (urlPath != null ? urlPath : "")); return redacted; } catch (URISyntaxException e) { throw new RuntimeException(e); } }

Target:
private URI addCookieInterceptorIfRequired(URI uri) { String uriProtocol = uri.getScheme(); String uriHost = uri.getHost(); String uriPath = uri.getRawPath(); int uriPort = uri.getPort(); if (uriPort < 0) { if ("http".equals(uriProtocol)) { uriPort = 80; } else if ("https".equals(uriProtocol)) { uriPort = 443; } else { throw new RuntimeException("Unknown protocol: "+uriProtocol); } } if (uri.getUserInfo() != null) { String[] parts = uri.getUserInfo().split(":"); if (parts.length == 2) { CookieInterceptor ci = new CookieInterceptor(parts[0], parts[1]); requestInterceptors.add(ci); responseInterceptors.add(ci); } } try { URI redacted = new URI(uriProtocol + "://" + uriHost + ":" + uriPort + (uriPath != null ? uriPath : "")); return redacted; } catch (URISyntaxException e) { throw new RuntimeException(e); } }
Source:
private void openUrlWithCustomTab(String url) { TypedValue tvBackground = new TypedValue(); getTheme().resolveAttribute(R.attr.colorPrimary, tvBackground, true); CustomTabsIntent intent = new CustomTabsIntent.Builder() .setToolbarColor(tvBackground.data) .setStartAnimations(this, R.anim.slide_in_right, R.anim.slide_out_left) .setExitAnimations(this, R.anim.slide_in_left, R.anim.slide_out_right) .setShowTitle(true) .build(); try { intent.launchUrl(this, Uri.parse(url)); } catch (Exception e) { e.printStackTrace(); } }

Target:
private void openUrlWithCustomTab(String url) { TypedValue backgroundColor = new TypedValue(); getTheme().resolveAttribute(R.attr.colorPrimary, backgroundColor, true); CustomTabsIntent intent = new CustomTabsIntent.Builder() .setToolbarColor(backgroundColor.data) .setStartAnimations(this, R.anim.slide_in_right, R.anim.slide_out_left) .setExitAnimations(this, R.anim.slide_in_left, R.anim.slide_out_right) .setShowTitle(true) .build(); try { intent.launchUrl(this, Uri.parse(url)); } catch (Exception e) { e.printStackTrace(); } }
Source:
static boolean isValidAddress(InetAddress address) { if (address == null || address.isLoopbackAddress()) { return false; } String name = address.getHostAddress(); return (name != null && !Constants.ANYHOST_VALUE.equals(name) && !Constants.LOCALHOST_VALUE.equals(name) && IP_PATTERN.matcher(name).matches()); }

Target:
static boolean isValidAddress(InetAddress address) { if (address == null || address.isLoopbackAddress()) { return false; } String name = address.getHostAddress(); return (name != null && IP_PATTERN.matcher(name).matches() && !Constants.ANYHOST_VALUE.equals(name) && !Constants.LOCALHOST_VALUE.equals(name)); }
Source:
public CalculatorExpressionTokenizer(Context context) { mReplacementMap = new HashMap<>(); Locale locale = context.getResources().getConfiguration().locale; if (!"fa".equals(locale.getLanguage())) { locale = (new Locale.Builder()) .setLocale(locale) .setUnicodeLocaleKeyword("nu", "latn") .build(); } final NumberFormat nf = DecimalFormat.getInstance(locale); final DecimalFormatSymbols symbols = new DecimalFormatSymbols(locale); mReplacementMap.put(".", String.valueOf(symbols.getDecimalSeparator())); for (int i = 0; i <= 9; ++i) { mReplacementMap.put(String.valueOf(i), nf.format(i)); } mReplacementMap.put("/", context.getString(R.string.op_div)); mReplacementMap.put("*", context.getString(R.string.op_mul)); mReplacementMap.put("-", context.getString(R.string.op_sub)); mReplacementMap.put("cos", context.getString(R.string.fun_cos)); mReplacementMap.put("ln", context.getString(R.string.fun_ln)); mReplacementMap.put("log", context.getString(R.string.fun_log)); mReplacementMap.put("sin", context.getString(R.string.fun_sin)); mReplacementMap.put("tan", context.getString(R.string.fun_tan)); mReplacementMap.put("Infinity", context.getString(R.string.inf)); }

Target:
public CalculatorExpressionTokenizer(Context context) { mReplacementMap = new HashMap<>(); Locale locale = context.getResources().getConfiguration().locale; if (!context.getResources().getBoolean(R.bool.use_localized_digits)) { locale = new Locale.Builder() .setLocale(locale) .setUnicodeLocaleKeyword("nu", "latn") .build(); } final DecimalFormatSymbols symbols = new DecimalFormatSymbols(locale); final char zeroDigit = symbols.getZeroDigit(); mReplacementMap.put(".", String.valueOf(symbols.getDecimalSeparator())); for (int i = 0; i <= 9; ++i) { mReplacementMap.put(Integer.toString(i), String.valueOf((char) (i + zeroDigit))); } mReplacementMap.put("/", context.getString(R.string.op_div)); mReplacementMap.put("*", context.getString(R.string.op_mul)); mReplacementMap.put("-", context.getString(R.string.op_sub)); mReplacementMap.put("cos", context.getString(R.string.fun_cos)); mReplacementMap.put("ln", context.getString(R.string.fun_ln)); mReplacementMap.put("log", context.getString(R.string.fun_log)); mReplacementMap.put("sin", context.getString(R.string.fun_sin)); mReplacementMap.put("tan", context.getString(R.string.fun_tan)); mReplacementMap.put("Infinity", context.getString(R.string.inf)); }
Source:
public byte[] getProgram() { try { if (program != null) return Arrays.copyOf(program, program.length); ByteArrayOutputStream bos = new ByteArrayOutputStream(); for (ScriptChunk chunk : chunks) { bos.write(chunk.toByteArray()); } program = bos.toByteArray(); return program; } catch (IOException e) { throw new RuntimeException(e); } }

Target:
public byte[] getProgram() { try { if (program != null) return Arrays.copyOf(program, program.length); ByteArrayOutputStream bos = new ByteArrayOutputStream(); for (ScriptChunk chunk : chunks) { chunk.write(bos); } program = bos.toByteArray(); return program; } catch (IOException e) { throw new RuntimeException(e); } }
Source:
public boolean hasVisibleCompartment(View comment) { boolean empty = true; if (isStereotypeComment(comment)) { Iterator<?> childrenIterator = comment.getChildren().iterator(); while (childrenIterator.hasNext() && empty) { Object child = childrenIterator.next(); if (isStereotypeCompartment(child)) { empty = !((View) child).isVisible(); } } } return !empty; }

Target:
public boolean hasVisibleCompartment(View comment) { boolean empty = true; if (isStereotypeComment(comment)) { Iterator<?> childrenIterator = comment.getChildren().iterator(); while (empty && childrenIterator.hasNext()) { Object child = childrenIterator.next(); if (isStereotypeCompartment(child)) { empty = !((View) child).isVisible(); } } } return !empty; }
Source:
public DefaultTokenCacheStore(Context context) { mContext = context; if (context != null) { if (!StringExtensions.IsNullOrBlank(AuthenticationSettings.INSTANCE .getSharedPrefPackageName())) { try { mContext = context.createPackageContext( AuthenticationSettings.INSTANCE.getSharedPrefPackageName(), Context.MODE_PRIVATE); } catch (NameNotFoundException e) { throw new IllegalArgumentException("Package name:" + AuthenticationSettings.INSTANCE.getSharedPrefPackageName() + " is not found"); } } mPrefs = mContext.getSharedPreferences(SHARED_PREFERENCE_NAME, Activity.MODE_PRIVATE); if (mPrefs == null) { throw new IllegalStateException(ADALError.DEVICE_SHARED_PREF_IS_NOT_AVAILABLE.getDescription()); } } else { throw new IllegalArgumentException("Context is null"); } try { getStorageHelper().loadSecretKeyForAPI(mContext); } catch (IOException | GeneralSecurityException e) { throw new IllegalStateException("Failed to get private key from AndroidKeyStore", e); } }

Target:
public DefaultTokenCacheStore(Context context) { if (context == null) { throw new IllegalArgumentException("Context is null"); } mContext = context; if (!StringExtensions.IsNullOrBlank(AuthenticationSettings.INSTANCE .getSharedPrefPackageName())) { try { mContext = context.createPackageContext( AuthenticationSettings.INSTANCE.getSharedPrefPackageName(), Context.MODE_PRIVATE); } catch (NameNotFoundException e) { throw new IllegalArgumentException("Package name:" + AuthenticationSettings.INSTANCE.getSharedPrefPackageName() + " is not found"); } } mPrefs = mContext.getSharedPreferences(SHARED_PREFERENCE_NAME, Activity.MODE_PRIVATE); if (mPrefs == null) { throw new IllegalStateException(ADALError.DEVICE_SHARED_PREF_IS_NOT_AVAILABLE.getDescription()); } try { getStorageHelper().loadSecretKeyForAPI(); } catch (IOException | GeneralSecurityException e) { throw new IllegalStateException("Failed to get private key from AndroidKeyStore", e); } }
Source:
private boolean restoreVolumeToSnapshot(Guid upServerId, GlusterVolumeEntity volume, String snapshotName) { if (volume != null) { try (EngineLock lock = acquireEngineLock(volume.getClusterId(), LockingGroup.GLUSTER)) { VDSReturnValue retVal = runVdsCommand(VDSCommandType.RestoreGlusterVolumeSnapshot, new GlusterVolumeSnapshotActionVDSParameters(upServerId, volume.getName(), snapshotName)); if (!retVal.getSucceeded()) { handleVdsError(AuditLogType.GLUSTER_VOLUME_SNAPSHOT_RESTORE_FAILED, retVal.getVdsError() .getMessage()); setSucceeded(false); return false; } else { getGlusterVolumeSnapshotDao().removeByName(volume.getId(), snapshotName); List<GlusterBrickEntity> oldBricks = volume.getBricks(); getGlusterBrickDao().removeAllInBatch(oldBricks); VDS upServer = getClusterUtils().getRandomUpServer(volume.getClusterId()); VDSReturnValue volDetailsRetVal = runVdsCommand(VDSCommandType.GetGlusterVolumeInfo, new GlusterVolumeInfoVDSParameters(upServer.getId(), volume.getClusterId(), volume.getName())); GlusterVolumeEntity fetchedVolume = ((Map<Guid, GlusterVolumeEntity>) volDetailsRetVal.getReturnValue()).get(volume.getId()); List<GlusterBrickEntity> fetchedBricks = fetchedVolume.getBricks(); if (fetchedBricks != null) { for (GlusterBrickEntity fetchdBrick : fetchedVolume.getBricks()) { if (fetchdBrick.getServerId() != null) { fetchdBrick.setStatus(GlusterStatus.UP); getGlusterBrickDao().save(fetchdBrick); } } } } } } return true; }

Target:
private boolean restoreVolumeToSnapshot(Guid upServerId, GlusterVolumeEntity volume, String snapshotName) { if (volume != null) { try (EngineLock lock = acquireEngineLock(volume.getId(), LockingGroup.GLUSTER)) { VDSReturnValue retVal = runVdsCommand(VDSCommandType.RestoreGlusterVolumeSnapshot, new GlusterVolumeSnapshotActionVDSParameters(upServerId, volume.getName(), snapshotName)); if (!retVal.getSucceeded()) { handleVdsError(AuditLogType.GLUSTER_VOLUME_SNAPSHOT_RESTORE_FAILED, retVal.getVdsError() .getMessage()); setSucceeded(false); return false; } else { getGlusterVolumeSnapshotDao().removeByName(volume.getId(), snapshotName); VDS upServer = getClusterUtils().getRandomUpServer(volume.getClusterId()); VDSReturnValue volDetailsRetVal = runVdsCommand(VDSCommandType.GetGlusterVolumeInfo, new GlusterVolumeInfoVDSParameters(upServer.getId(), volume.getClusterId(), volume.getName())); GlusterVolumeEntity fetchedVolume = ((Map<Guid, GlusterVolumeEntity>) volDetailsRetVal.getReturnValue()).get(volume.getId()); List<GlusterBrickEntity> fetchedBricks = fetchedVolume.getBricks(); if (fetchedBricks != null) { getGlusterBrickDao().removeAllInBatch(volume.getBricks()); for (GlusterBrickEntity fetchdBrick : fetchedVolume.getBricks()) { if (fetchdBrick.getServerId() != null) { fetchdBrick.setStatus(GlusterStatus.UP); getGlusterBrickDao().save(fetchdBrick); } } } } } } return true; }
Source:
public List<Integer> addGermplasm(final List<Pair<Germplasm, Name>> germplasms) { final List<Integer> isGermplasmsSaved = new ArrayList<>(); try { final GermplasmDAO dao = this.getGermplasmDao(); final NameDAO nameDao = this.getNameDao(); for (final Pair<Germplasm, Name> pair : germplasms) { final Germplasm germplasm = pair.getLeft(); final Name name = pair.getRight(); name.setNstat(Integer.valueOf(1)); final Germplasm germplasmSaved = dao.saveOrUpdate(germplasm); isGermplasmsSaved.add(germplasmSaved.getGid()); name.setGermplasmId(germplasmSaved.getGid()); nameDao.saveOrUpdate(name); } } catch (final Exception e) { throw new MiddlewareQueryException("Error encountered while saving Germplasm: GermplasmDataManager.addGermplasm(): " + e.getMessage(), e); } return isGermplasmsSaved; }

Target:
public List<Integer> addGermplasm(final List<Pair<Germplasm, Name>> germplasms) { final List<Integer> isGermplasmsSaved = new ArrayList<>(); try { final GermplasmDAO dao = this.getGermplasmDao(); final NameDAO nameDao = this.getNameDao(); for (final Pair<Germplasm, Name> pair : germplasms) { final Germplasm germplasm = pair.getLeft(); final Name name = pair.getRight(); name.setNstat(Integer.valueOf(1)); final Germplasm germplasmSaved = dao.save(germplasm); isGermplasmsSaved.add(germplasmSaved.getGid()); name.setGermplasmId(germplasmSaved.getGid()); nameDao.save(name); } } catch (final Exception e) { throw new MiddlewareQueryException("Error encountered while saving Germplasm: GermplasmDataManager.addGermplasm(): " + e.getMessage(), e); } return isGermplasmsSaved; }
Source:
public void execute(IAtsWorkItem workItem, IAtsServices atsServices, IAtsChangeSet changes, RunRuleResults ruleResults) { if (workItem.isTeamWorkflow()) { boolean createTask = true; for (IAtsTask task : atsServices.getWorkItemService().getTasks((IAtsTeamWorkflow) workItem)) { if (task.getName().equals(this.name)) { createTask = false; break; } } if (createTask) { List<String> titles = new ArrayList<>(); titles.add(this.getTitle()); Collection<IAtsTask> createdTasks = atsServices.getTaskService().createTasks((IAtsTeamWorkflow) workItem, titles, assignees, new Date(), atsServices.getUserService().getCurrentUser(), this.relatedState, changes); ruleResults.addChange(workItem.getUuid(), RuleResultsEnum.CREATE_TASK); for (IAtsTask task : createdTasks) { ruleResults.addChange(task.getUuid(), RuleResultsEnum.NEW_TASK); } } } }

Target:
public void execute(IAtsWorkItem workItem, IAtsServices atsServices, IAtsChangeSet changes, RunRuleResults ruleResults) { if (workItem.isTeamWorkflow()) { boolean createTask = true; for (IAtsTask task : atsServices.getWorkItemService().getTasks((IAtsTeamWorkflow) workItem)) { if (task.getName().equals(this.name)) { createTask = false; break; } } if (createTask) { Map<String, List<String>> attributes = new HashMap<>(); List<String> desc = new ArrayList<>(); desc.add(this.description); attributes.put("ats.Description", desc); List<String> titles = new ArrayList<>(); titles.add(this.getTitle()); Collection<IAtsTask> createdTasks = atsServices.getTaskService().createTasks((IAtsTeamWorkflow) workItem, titles, this.assignees, new Date(), atsServices.getUserService().getCurrentUser(), this.relatedState, this.taskWorkDef, attributes, "No Comment"); ruleResults.addChange(workItem.getUuid(), RuleResultsEnum.CREATE_TASK); for (IAtsTask task : createdTasks) { ruleResults.addChange(task.getUuid(), RuleResultsEnum.NEW_TASK); } } } }
Source:
public BoundState bindToCluster() throws Throwable { if ( dbNameStorage.exists() ) { String storedName = dbNameStorage.readState().name(); if ( !dbName.equals( storedName ) ) { throw new IllegalStateException( format("Your configured database name may have changed. Found %s, expected %s", dbName, storedName ) ); } } else { dbNameStorage.writeState( new DatabaseName( dbName ) ); } if ( clusterIdStorage.exists() ) { clusterId = clusterIdStorage.readState(); publishClusterId( clusterId ); log.info( "Already bound to cluster: " + clusterId ); return new BoundState( clusterId ); } CoreSnapshot snapshot = null; CoreTopology topology; long endTime = clock.millis() + timeoutMillis; do { topology = topologyService.localCoreServers(); if ( topology.clusterId() != null ) { clusterId = topology.clusterId(); log.info( "Bound to cluster: " + clusterId ); } else if ( hostShouldBootstrapCluster( topology ) ) { clusterId = new ClusterId( UUID.randomUUID() ); snapshot = coreBootstrapper.bootstrap( topology.members().keySet() ); log.info( format( "Bootstrapped with snapshot: %s and clusterId: %s", snapshot, clusterId ) ); publishClusterId( clusterId ); } else { retryWaiter.apply(); } } while ( clusterId == null && clock.millis() < endTime ); if ( clusterId == null ) { throw new TimeoutException( format( "Failed to join a cluster with members %s. Another member should have published " + "a clusterId but none was detected. Please restart the cluster.", topology ) ); } clusterIdStorage.writeState( clusterId ); return new BoundState( clusterId, snapshot ); }

Target:
public BoundState bindToCluster() throws Throwable { DatabaseName newName = new DatabaseName( dbName ); dbNameStorage.writeOrVerify( newName, existing -> { if ( !newName.equals( existing ) ) { throw new IllegalStateException( format("Your configured database name has changed. Found %s but expected %s in %s.", dbName, existing.name(), CausalClusteringSettings.database.name() ) ); } } ); if ( clusterIdStorage.exists() ) { clusterId = clusterIdStorage.readState(); publishClusterId( clusterId ); log.info( "Already bound to cluster: " + clusterId ); return new BoundState( clusterId ); } CoreSnapshot snapshot = null; CoreTopology topology; long endTime = clock.millis() + timeoutMillis; do { topology = topologyService.localCoreServers(); if ( topology.clusterId() != null ) { clusterId = topology.clusterId(); log.info( "Bound to cluster: " + clusterId ); } else if ( hostShouldBootstrapCluster( topology ) ) { clusterId = new ClusterId( UUID.randomUUID() ); snapshot = coreBootstrapper.bootstrap( topology.members().keySet() ); log.info( format( "Bootstrapped with snapshot: %s and clusterId: %s", snapshot, clusterId ) ); publishClusterId( clusterId ); } else { retryWaiter.apply(); } } while ( clusterId == null && clock.millis() < endTime ); if ( clusterId == null ) { throw new TimeoutException( format( "Failed to join a cluster with members %s. Another member should have published " + "a clusterId but none was detected. Please restart the cluster.", topology ) ); } clusterIdStorage.writeState( clusterId ); return new BoundState( clusterId, snapshot ); }
Source:
public void pushExportBuffer( final long uso, final ByteBuffer buffer, final boolean sync, final boolean endOfStream) { try { m_bufferPushPermits.acquire(); } catch (InterruptedException e) { Throwables.propagate(e); } ListeningExecutorService es = getExecutorService(); if (es==null) { throw new RuntimeException("This generation must be active by the time pushExportBuffer is called"); } if (es.isShutdown()) { m_bufferPushPermits.release(); return; } try { es.execute((new Runnable() { @Override public void run() { try { if (!es.isShutdown()) { pushExportBufferImpl(uso, buffer, sync, endOfStream); } } catch (Throwable t) { VoltDB.crashLocalVoltDB("Error pushing export buffer", true, t); } finally { m_bufferPushPermits.release(); } } })); } catch (RejectedExecutionException rej) { m_bufferPushPermits.release(); exportLog.info("Error pushing export buffer: ", rej); } }

Target:
public void pushExportBuffer( final long uso, final ByteBuffer buffer, final boolean sync, final boolean endOfStream) { try { m_bufferPushPermits.acquire(); } catch (InterruptedException e) { Throwables.propagate(e); } ListeningExecutorService es = getExecutorService(); assert(es!=null); if (es==null) { exportLog.error( "Push export buffer called before the generation is active. This push will be ignored"); return; } if (es.isShutdown()) { m_bufferPushPermits.release(); return; } try { es.execute((new Runnable() { @Override public void run() { try { if (!es.isShutdown()) { pushExportBufferImpl(uso, buffer, sync, endOfStream); } } catch (Throwable t) { VoltDB.crashLocalVoltDB("Error pushing export buffer", true, t); } finally { m_bufferPushPermits.release(); } } })); } catch (RejectedExecutionException rej) { m_bufferPushPermits.release(); exportLog.info("Error pushing export buffer: ", rej); } }