auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
private String getTimestamp() { SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss", Locale.US); dateFormat.setTimeZone(TimeZone.getTimeZone("GMT")); try { return URLEncoder.encode(dateFormat.format(new Date()), CHARSET_UTF8); } catch (UnsupportedEncodingException e) { Timber.e(e.getMessage()); return null; } }

Target:
private String getTimestamp() { SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss", Locale.US); dateFormat.setTimeZone(TimeZone.getTimeZone("GMT")); return encodeParam(dateFormat.format(new Date())); }
Source:
protected void populateHiddenFields(EntityInfo ei, Metadata md, String version, Map<String, String> fieldMap, QueryExpression query) throws IOException { LOGGER.info("Starting population of hidden fields due to new or modified indexes."); MongoDataStore ds = (MongoDataStore) ei.getDataStore(); DB entityDB = dbResolver.get(ds); DBCollection coll = entityDB.getCollection(ds.getCollectionName()); DBCursor cursor = null; if (query != null){ MetadataResolver mdResolver = new MetadataResolver() { @Override public EntityMetadata getEntityMetadata(String entityName) { String v = version == null ? ei.getDefaultVersion() : version; return md.getEntityMetadata(entityName, v); } }; Translator trans = new Translator(mdResolver, JsonNodeFactory.instance); DBObject mongoQuery = trans.translate(mdResolver.getEntityMetadata(ei.getName()), query); cursor = coll.find(mongoQuery); } else { cursor = coll.find(); } while (cursor.hasNext()) { DBObject doc = cursor.next(); DBObject original = (DBObject) ((BasicDBObject) doc).copy(); Translator.populateDocHiddenFields(doc, fieldMap); if (!doc.equals(original)) { try { coll.save(doc); } catch (Exception e) { LOGGER.error(e.getMessage()); LOGGER.debug("Original doc:\n{}", original); LOGGER.debug("Error saving doc:\n{}", doc); } } } cursor.close(); LOGGER.info("Finished population of hidden fields."); }

Target:
protected void populateHiddenFields(EntityInfo ei, Metadata md, String version, Map<String, String> fieldMap, QueryExpression query) throws IOException { LOGGER.info("Starting population of hidden fields due to new or modified indexes."); MongoDataStore ds = (MongoDataStore) ei.getDataStore(); DB entityDB = dbResolver.get(ds); DBCollection coll = entityDB.getCollection(ds.getCollectionName()); DBCursor cursor = null; if (query != null) { MetadataResolver mdResolver = new MetadataResolver() { @Override public EntityMetadata getEntityMetadata(String entityName) { String v = version == null ? ei.getDefaultVersion() : version; return md.getEntityMetadata(entityName, v); } }; Translator trans = new Translator(mdResolver, JsonNodeFactory.instance); DBObject mongoQuery = trans.translate(mdResolver.getEntityMetadata(ei.getName()), query); cursor = coll.find(mongoQuery); } else { cursor = coll.find(); } try { while (cursor.hasNext()) { DBObject doc = cursor.next(); DBObject original = (DBObject) ((BasicDBObject) doc).copy(); try { Translator.populateDocHiddenFields(doc, fieldMap); if (!doc.equals(original)) { coll.save(doc); } } catch (Exception e) { LOGGER.error(e.getMessage()); LOGGER.debug("Original doc:\n{}", original); LOGGER.debug("Error saving doc:\n{}", doc); } } } catch (Exception e) { LOGGER.error("Error during reindexing"); LOGGER.error(e.getMessage()); throw new RuntimeException(e); } finally { cursor.close(); } LOGGER.info("Finished population of hidden fields."); }
Source:
public Future<UpdateCenterJob> deploy(boolean dynamicLoad, @CheckForNull UUID correlationId) { Jenkins.getInstance().checkPermission(Jenkins.ADMINISTER); UpdateCenter uc = Jenkins.getInstance().getUpdateCenter(); for (Plugin dep : getNeededDependencies()) { UpdateCenter.InstallationJob job = uc.getJob(dep); if (job == null || job.status instanceof UpdateCenter.DownloadJob.Failure) { LOGGER.log(Level.WARNING, "Adding dependent install of " + dep.name + " for plugin " + name); dep.deploy(dynamicLoad); } else { LOGGER.log(Level.WARNING, "Dependent install of " + dep.name + " for plugin " + name + " already added, skipping"); } } PluginWrapper pw = getInstalled(); if(pw != null) { Future<UpdateCenterJob> enableJob = null; if(!pw.isEnabled()) { UpdateCenter.EnableJob job = uc.new EnableJob(UpdateSite.this, this); job.setCorrelationId(correlationId); enableJob = uc.addJob(job); } if(pw.getVersionNumber().equals(new VersionNumber(version))) { return enableJob != null ? enableJob : uc.addJob(uc.new NoOpJob(UpdateSite.this, this)); } } UpdateCenter.InstallationJob job = uc.new InstallationJob(this, UpdateSite.this, Jenkins.getAuthentication(), dynamicLoad); job.setCorrelationId(correlationId); return uc.addJob(job); }

Target:
public Future<UpdateCenterJob> deploy(boolean dynamicLoad, @CheckForNull UUID correlationId) { Jenkins.getInstance().checkPermission(Jenkins.ADMINISTER); UpdateCenter uc = Jenkins.getInstance().getUpdateCenter(); for (Plugin dep : getNeededDependencies()) { UpdateCenter.InstallationJob job = uc.getJob(dep); if (job == null || job.status instanceof UpdateCenter.DownloadJob.Failure) { LOGGER.log(Level.WARNING, "Adding dependent install of " + dep.name + " for plugin " + name); dep.deploy(dynamicLoad); } else { LOGGER.log(Level.WARNING, "Dependent install of " + dep.name + " for plugin " + name + " already added, skipping"); } } PluginWrapper pw = getInstalled(); if(pw != null) { Future<UpdateCenterJob> enableJob = null; if(!pw.isEnabled()) { UpdateCenter.EnableJob job = uc.new EnableJob(UpdateSite.this, null, this, dynamicLoad); job.setCorrelationId(correlationId); enableJob = uc.addJob(job); } if(pw.getVersionNumber().equals(new VersionNumber(version))) { return enableJob != null ? enableJob : uc.addJob(uc.new NoOpJob(UpdateSite.this, null, this)); } } UpdateCenter.InstallationJob job = uc.new InstallationJob(this, UpdateSite.this, Jenkins.getAuthentication(), dynamicLoad); job.setCorrelationId(correlationId); return uc.addJob(job); }
Source:
private void getFavFromPoint(RotatedTileBox tb, List<? super FavouritePoint> res, int r, int ex, int ey, FavouritePoint n) { if (n.isVisible()) { int x = (int) tb.getPixXFromLatLon(n.getLatitude(), n.getLongitude()); int y = (int) tb.getPixYFromLatLon(n.getLatitude(), n.getLongitude()); if (calculateBelongs(ex, ey, x, y, r)) { if (!n.getName().equals(FavouritePoint.PointType.PARKING.getName())) { res.add(n); } } } }

Target:
private void getFavFromPoint(RotatedTileBox tb, List<? super FavouritePoint> res, int r, int ex, int ey, FavouritePoint n) { if (n.isVisible()) { int x = (int) tb.getPixXFromLatLon(n.getLatitude(), n.getLongitude()); int y = (int) tb.getPixYFromLatLon(n.getLatitude(), n.getLongitude()); if (calculateBelongs(ex, ey, x, y, r)) { res.add(n); } } }
Source:
public void exceptionsWithRetryAfterBacksOffAfterQueryingAllNodesInTheCluster() { for (int i = 0; i < CLUSTER_SIZE; i++) { simulateRequest(spiedTarget); spiedTarget.continueOrPropagate(EXCEPTION_WITH_RETRY_AFTER); } long bottom = FailoverFeignTarget.BACKOFF_BEFORE_ROUND_ROBIN_RETRY_MILLIS / 2; long cap = (FailoverFeignTarget.BACKOFF_BEFORE_ROUND_ROBIN_RETRY_MILLIS * 3) / 2; verify(spiedTarget, times(1)).pauseForBackoff(any(), longThat(is(both(greaterThanOrEqualTo(bottom)).and(lessThan(cap))))); }

Target:
public void exceptionsWithRetryAfterBacksOffAfterQueryingAllNodesInTheCluster() { for (int i = 0; i < CLUSTER_SIZE; i++) { simulateRequest(spiedTarget); spiedTarget.continueOrPropagate(EXCEPTION_WITH_RETRY_AFTER); } verify(spiedTarget, times(1)).pauseForBackoff(any(), longThat(is(both(greaterThanOrEqualTo(LOWER_BACKOFF_BOUND)).and(lessThan(UPPER_BACKOFF_BOUND))))); }
Source:
private static boolean isAffinityAvailable() { try { boolean jnaAvailable = Affinity.isJNAAvailable(); if (!jnaAvailable) { System.err.println("jna is not available"); } return jnaAvailable; } catch (NoClassDefFoundError e) { e.printStackTrace(); System.err.println("Affinity jar isn't available"); return false; } }

Target:
private static boolean isAffinityAvailable() { try { boolean jnaAvailable = Affinity.isJNAAvailable(); if (!jnaAvailable) { Logger.getLogger(ThreadAffinity.class).warning("jna is not available"); } return jnaAvailable; } catch (NoClassDefFoundError e) { Logger.getLogger(ThreadAffinity.class).warning("Affinity jar isn't available: " + e.getMessage()); return false; } }
Source:
public void test() throws Exception { ExternalBuildReport report = new ExternalBuildReport("<LINK_0>"); assertEquals("View External Report", report.getDisplayName()); assertEquals("graph.gif", report.getIconFileName()); assertEquals("graph.gif", report.getIconFileName()); assertEquals("<LINK_0>", report.getUrlName()); assertEquals(null, report.getTarget()); }

Target:
public void test() throws Exception { ExternalBuildReport report = new ExternalBuildReport("<LINK_0>"); assertEquals("View External Report", report.getDisplayName()); assertEquals("graph.gif", report.getIconFileName()); assertEquals("<LINK_0>", report.getUrlName()); assertEquals(null, report.getTarget()); }
Source:
public void spec113_mustProduceTheSameElementsInTheSameSequenceToAllOfItsSubscribersWhenRequestingManyUpfront() throws Throwable { activePublisherTest(3, new PublisherTestRun<T>() { @Override public void run(Publisher<T> pub) throws Throwable { ManualSubscriber<T> sub1 = env.newManualSubscriber(pub); ManualSubscriber<T> sub2 = env.newManualSubscriber(pub); ManualSubscriber<T> sub3 = env.newManualSubscriber(pub); List<T> received1 = new ArrayList<T>(); List<T> received2 = new ArrayList<T>(); List<T> received3 = new ArrayList<T>(); sub1.request(3); sub2.request(3); sub3.request(3); received1.addAll(sub1.nextElements(3)); received2.addAll(sub2.nextElements(3)); received3.addAll(sub3.nextElements(3)); sub1.nextElementOrEndOfStream(); sub2.nextElementOrEndOfStream(); sub3.nextElementOrEndOfStream(); assertEquals(received1, received2, String.format("Expected elements to be signaled in the same sequence to both subscribers")); assertEquals(received2, received3, String.format("Expected elements to be signaled in the same sequence to both subscribers")); } }); }

Target:
public void spec113_mustProduceTheSameElementsInTheSameSequenceToAllOfItsSubscribersWhenRequestingManyUpfront() throws Throwable { optionalActivePublisherTest(3, new PublisherTestRun<T>() { @Override public void run(Publisher<T> pub) throws Throwable { ManualSubscriber<T> sub1 = env.newManualSubscriber(pub); ManualSubscriber<T> sub2 = env.newManualSubscriber(pub); ManualSubscriber<T> sub3 = env.newManualSubscriber(pub); List<T> received1 = new ArrayList<T>(); List<T> received2 = new ArrayList<T>(); List<T> received3 = new ArrayList<T>(); sub1.request(4); sub2.request(4); sub3.request(4); received1.addAll(sub1.nextElements(3)); received2.addAll(sub2.nextElements(3)); received3.addAll(sub3.nextElements(3)); sub1.expectCompletion(); sub2.expectCompletion(); sub3.expectCompletion(); assertEquals(received1, received2, String.format("Expected elements to be signaled in the same sequence to 1st and 2nd subscribers")); assertEquals(received2, received3, String.format("Expected elements to be signaled in the same sequence to 2nd and 3rd subscribers")); } }); }
Source:
public static String getHeaderField(final URL url, final String name) { URLConnection conn = null; try { conn = openConnection(url); if(conn instanceof HttpURLConnection) { final HttpURLConnection httpConn = HttpURLConnection.class.cast(conn); httpConn.setRequestMethod("HEAD"); } return conn.getHeaderField(name); } catch (final IOException e) { e.printStackTrace(); return null; } finally { if (conn != null && conn instanceof HttpURLConnection) { ((HttpURLConnection) conn).disconnect(); } } }

Target:
public static String getHeaderField(final URL url, final String name) { URLConnection conn = null; try { conn = openConnection(url); if (conn instanceof HttpURLConnection) { ((HttpURLConnection) conn).setRequestMethod("HEAD"); } return conn.getHeaderField(name); } catch (final IOException e) { e.printStackTrace(); return null; } finally { if (conn != null && conn instanceof HttpURLConnection) { ((HttpURLConnection) conn).disconnect(); } } }
Source:
public void verifyTappingOnImageEdge (PerformTouchAction touchAction, String edge) { String currentImageSrc = getCurrentImagePath(); String nextImageSrc; int pointX = 25; int duration = 500; int waitAfter = 5000; if (edge == "right") { pointX = 75; } else { edge = "left"; } touchAction.tapOnPointXY(pointX, 50, duration, waitAfter); nextImageSrc = getCurrentImagePath(); if (!nextImageSrc.contains(currentImageSrc)) { PageObjectLogging.log("verifyTappingOnImageEdge", "Tapping on " + edge + " edge works", true); } else { PageObjectLogging.log("verifyTappingOnImageEdge", "Tapping on " + edge + " edge doesn't work", false); } }

Target:
public void verifyTappingOnImageEdge (PerformTouchAction touchAction, String edge) { String currentImageSrc = getCurrentImagePath(); String nextImageSrc; int pointX = 25; int duration = 500; int waitAfter = 5000; if ("right".equals(edge)) { pointX = 75; } else { edge = "left"; } touchAction.tapOnPointXY(pointX, 50, duration, waitAfter); nextImageSrc = getCurrentImagePath(); if (!nextImageSrc.contains(currentImageSrc)) { PageObjectLogging.log("verifyTappingOnImageEdge", "Tapping on " + edge + " edge works", true); } else { PageObjectLogging.log("verifyTappingOnImageEdge", "Tapping on " + edge + " edge doesn't work", false); } }
Source:
public Builder reset() { return rgb(0, 0, 0); }

Target:
public Builder reset() { this.red = -1; this.green = -1; this.blue = -1; return this; }
Source:
public void testSendPojoReceivePojoKryoWithStreamListener() throws Exception { StreamListenerMessageHandler handler = this.buildStreamListener( AbstractBinderTests.class, "echoStation", Station.class); Binder binder = getBinder(); PP producerProperties = createProducerProperties(); BindingProperties producerBindingProperties = createProducerBindingProperties(producerProperties); DirectChannel moduleOutputChannel = createBindableChannel("output", producerBindingProperties); DirectChannel moduleInputChannel = createBindableChannel("input", producerBindingProperties); Binding<MessageChannel> producerBinding = binder.bindProducer(String.format("bad%s0b", getDestinationNameDelimiter()), moduleOutputChannel, producerProperties); Binding<MessageChannel> consumerBinding = binder.bindConsumer(String.format("bad%s0b", getDestinationNameDelimiter()), "test-2", moduleInputChannel, createConsumerProperties()); Station station = new Station(); Message<?> message = MessageBuilder.withPayload(station).setHeader( MessageHeaders.CONTENT_TYPE, MessageConverterUtils.X_JAVA_OBJECT).build(); moduleInputChannel.subscribe(handler); moduleOutputChannel.send(message); QueueChannel replyChannel = (QueueChannel) handler.getOutputChannel(); Message<?> replyMessage = replyChannel.receive(5000); assertTrue(replyMessage.getPayload() instanceof Station); producerBinding.unbind(); consumerBinding.unbind(); }

Target:
public void testSendPojoReceivePojoKryoWithStreamListener() throws Exception { StreamListenerMessageHandler handler = this.buildStreamListener( AbstractBinderTests.class, "echoStation", Station.class); Binder binder = getBinder(); BindingProperties producerBindingProperties = createProducerBindingProperties(createProducerProperties()); DirectChannel moduleOutputChannel = createBindableChannel("output", producerBindingProperties); BindingProperties consumerBindingProperties = createConsumerBindingProperties(createConsumerProperties()); DirectChannel moduleInputChannel = createBindableChannel("input", consumerBindingProperties); Binding<MessageChannel> producerBinding = binder.bindProducer(String.format("bad%s0b", getDestinationNameDelimiter()), moduleOutputChannel, producerBindingProperties.getProducer()); Binding<MessageChannel> consumerBinding = binder.bindConsumer(String.format("bad%s0b", getDestinationNameDelimiter()), "test-2", moduleInputChannel, consumerBindingProperties.getConsumer()); Station station = new Station(); Message<?> message = MessageBuilder.withPayload(station).setHeader( MessageHeaders.CONTENT_TYPE, MessageConverterUtils.X_JAVA_OBJECT).build(); moduleInputChannel.subscribe(handler); moduleOutputChannel.send(message); QueueChannel replyChannel = (QueueChannel) handler.getOutputChannel(); Message<?> replyMessage = replyChannel.receive(5000); assertTrue(replyMessage.getPayload() instanceof Station); producerBinding.unbind(); consumerBinding.unbind(); }
Source:
void shutdown() { log.info( "Shutting down as there is no ping response on port {}", port ); shutdown.run(); }

Target:
void shutdown() { log.warn( "Shutting down as there is no ping response from on port {}", talker.getHost(), talker.getPort() ); shutdown.run(); }
Source:
public void checkExecutorHealthQuietly() { try { checkExecutorHealth(); } catch (Throwable t) { logger.error("Unexepected error during executor healthcheck. Cause: " + ExceptionUtils.getStackTrace(t)); } }

Target:
public void checkExecutorHealthQuietly() { try { checkExecutorHealth(); } catch (final RuntimeException e) { logger.error("Unexepected error during executor healthcheck. Cause: " + ExceptionUtils.getStackTrace(e)); } }
Source:
String calculateCommitMessage(Collection<String> paths) { if (commitMessage != null) { return commitMessage; } if (amending) return previousCommitMessage; StringBuilder calculatedCommitMessage = new StringBuilder(); Set<IResource> resources = new HashSet<>(); for (String path : paths) { IFile file = findFile(path); if (file != null) resources.add(file.getProject()); } if (resources.size() == 0 && repository != null) { resources .addAll(Arrays.asList(ProjectUtil.getProjects(repository))); } try { List<ICommitMessageProvider> messageProviders = getCommitMessageProviders(); IResource[] resourcesArray = resources .toArray(new IResource[0]); String providedMessageSeparator = "\n\n"; for (ICommitMessageProvider messageProvider : messageProviders) { String message = null; try { message = messageProvider.getMessage(resourcesArray); } catch (RuntimeException e) { Activator.logError(e.getMessage(), e); } if (message != null && !"".equals(message.trim())) { if (calculatedCommitMessage.length() > 0) { calculatedCommitMessage .append(providedMessageSeparator); } calculatedCommitMessage.append((message.trim())); } } } catch (CoreException coreException) { Activator.logError(coreException.getLocalizedMessage(), coreException); } return calculatedCommitMessage.toString(); }

Target:
String calculateCommitMessage(Collection<String> paths) { if (commitMessage != null) { return commitMessage; } if (amending) return previousCommitMessage; StringBuilder calculatedCommitMessage = new StringBuilder(); Set<IResource> resources = new HashSet<>(); for (String path : paths) { IFile file = findFile(path); if (file != null) resources.add(file.getProject()); } if (resources.size() == 0 && repository != null) { resources .addAll(Arrays.asList(ProjectUtil.getProjects(repository))); } List<ICommitMessageProvider> messageProviders = getCommitMessageProviders(); IResource[] resourcesArray = resources.toArray(new IResource[0]); String providedMessageSeparator = "\n\n"; for (ICommitMessageProvider messageProvider : messageProviders) { String message = null; try { message = messageProvider.getMessage(resourcesArray); } catch (RuntimeException e) { Activator.logError(e.getMessage(), e); } if (message != null && !message.trim().isEmpty()) { if (calculatedCommitMessage.length() > 0) { calculatedCommitMessage.append(providedMessageSeparator); } calculatedCommitMessage.append((message.trim())); } } return calculatedCommitMessage.toString(); }
Source:
void deleteChecked() { final StringBuilder message = new StringBuilder(); message.append("<b>").append(Gerrit.C.branchDeletionConfirmationMessage()).append("</b>"); message.append("<p>"); final HashSet<Branch.NameKey> ids = new HashSet<Branch.NameKey>(); for (int row = 1; row < table.getRowCount(); row++) { final Branch k = getRowItem(row); if (k != null && table.getWidget(row, 1) instanceof CheckBox && ((CheckBox) table.getWidget(row, 1)).getValue()) { if (!ids.isEmpty()) { message.append(", <br>"); } final String escapedBranchName = new SafeHtmlBuilder().append(k.getName()).asString(); message.append(escapedBranchName); ids.add(k.getNameKey()); } } message.append("</p>"); if (ids.isEmpty()) { return; } ConfirmationDialog confirmationDialog = new ConfirmationDialog(Gerrit.C.branchDeletionDialogTitle(), new HTML(message.toString()), new ConfirmationCallback() { @Override public void onOk() { Util.PROJECT_SVC.deleteBranch(getProjectKey(), ids, new GerritCallback<Set<Branch.NameKey>>() { public void onSuccess(final Set<Branch.NameKey> deleted) { for (int row = 1; row < table.getRowCount();) { final Branch k = getRowItem(row); if (k != null && deleted.contains(k.getNameKey())) { table.removeRow(row); } else { row++; } } } }); } }); confirmationDialog.center(); }

Target:
void deleteChecked() { final SafeHtmlBuilder b = new SafeHtmlBuilder(); b.openElement("b"); b.append(Gerrit.C.branchDeletionConfirmationMessage()); b.closeElement("b"); b.openElement("p"); final HashSet<Branch.NameKey> ids = new HashSet<Branch.NameKey>(); for (int row = 1; row < table.getRowCount(); row++) { final Branch k = getRowItem(row); if (k != null && table.getWidget(row, 1) instanceof CheckBox && ((CheckBox) table.getWidget(row, 1)).getValue()) { if (!ids.isEmpty()) { b.append(",").br(); } b.append(k.getName()); ids.add(k.getNameKey()); } } b.closeElement("p"); if (ids.isEmpty()) { return; } ConfirmationDialog confirmationDialog = new ConfirmationDialog(Gerrit.C.branchDeletionDialogTitle(), b.toSafeHtml(), new ConfirmationCallback() { @Override public void onOk() { Util.PROJECT_SVC.deleteBranch(getProjectKey(), ids, new GerritCallback<Set<Branch.NameKey>>() { public void onSuccess(final Set<Branch.NameKey> deleted) { for (int row = 1; row < table.getRowCount();) { final Branch k = getRowItem(row); if (k != null && deleted.contains(k.getNameKey())) { table.removeRow(row); } else { row++; } } } }); } }); confirmationDialog.center(); }
Source:
public void staffUserShouldSeeReviewModule() { SpecialJsPage wikiaJs = new SpecialJsPage().open("Wikia"); Assertion.assertTrue(wikiaJs.getReviewModule().isModuleVisible()); }

Target:
public void staffUserShouldSeeReviewModule() { SpecialJsPage wikiaJs = new SpecialJsPage().open("wikia"); Assertion.assertTrue(wikiaJs.getReviewModule().isModuleVisible()); }
Source:
private BrowserWebDriverContainer startBrowser(TestConfiguration testConfiguration, ExtensionContext extensionContext) { LOGGER.info("(*) Starting browser [{}]...", testConfiguration.getBrowser()); BrowserWebDriverContainer webDriverContainer = new BrowserWebDriverContainer<>() .withDesiredCapabilities(testConfiguration.getBrowser().getCapabilities()) .withNetwork(Network.SHARED) .withNetworkAliases("vnchost") .withRecordingMode(BrowserWebDriverContainer.VncRecordingMode.SKIP, null) .withFileSystemBind(TEST_RESOURCES_HOST_PATH, testConfiguration.getTestResourcesPath()); if (testConfiguration.isVerbose()) { LOGGER.info(String.format("Docker image used: [%s]", BrowserWebDriverContainer.getImageForCapabilities(testConfiguration.getBrowser().getCapabilities()))); webDriverContainer.withLogConsumer(new Slf4jLogConsumer(LoggerFactory.getLogger(this.getClass()))); } webDriverContainer.start(); if (testConfiguration.vnc()) { LOGGER.info("VNC server address = " + webDriverContainer.getVncAddress()); } saveBrowserWebDriverContainer(extensionContext, webDriverContainer); XWikiWebDriver xwikiWebDriver = new XWikiWebDriver(webDriverContainer.getWebDriver()); saveXWikiWebDriver(extensionContext, xwikiWebDriver); LOGGER.info("(*) Initialize Test Context..."); PersistentTestContext testContext = initializePersistentTestContext(xwikiWebDriver); savePersistentTestContext(extensionContext, testContext); testContext.getUtil().setURLPrefix(computeXWikiURLPrefix( testConfiguration.getServletEngine().getInternalIP(), testConfiguration.getServletEngine().getInternalPort())); testContext.getUtil().rest().setURLPrefix(loadXWikiURL(extensionContext)); DockerTestUtils.followOutput(webDriverContainer, getClass()); testContext.getUtil().recacheSecretToken(); return webDriverContainer; }

Target:
private BrowserWebDriverContainer startBrowser(TestConfiguration testConfiguration, ExtensionContext extensionContext) { BrowserContainerExecutor browserContainerExecutor = new BrowserContainerExecutor(); BrowserWebDriverContainer webDriverContainer = browserContainerExecutor.start(testConfiguration); saveBrowserWebDriverContainer(extensionContext, webDriverContainer); XWikiWebDriver xwikiWebDriver = new XWikiWebDriver(webDriverContainer.getWebDriver()); saveXWikiWebDriver(extensionContext, xwikiWebDriver); LOGGER.info("(*) Initialize Test Context..."); PersistentTestContext testContext = initializePersistentTestContext(xwikiWebDriver); savePersistentTestContext(extensionContext, testContext); testContext.getUtil().setURLPrefix(computeXWikiURLPrefix( testConfiguration.getServletEngine().getInternalIP(), testConfiguration.getServletEngine().getInternalPort())); testContext.getUtil().rest().setURLPrefix(loadXWikiURL(extensionContext)); DockerTestUtils.followOutput(webDriverContainer, getClass()); testContext.getUtil().recacheSecretToken(); return webDriverContainer; }
Source:
public Value toAbsolutePath( Value request ) throws FaultException { Value response = Value.create(); String fileName = request.strValue(); String absolutePath = Paths.get( fileName ).toAbsolutePath().normalize().toString(); if ( absolutePath == null ) { throw new FaultException( "Not a valid path", new IOException() ); } response.setValue( absolutePath ); return response; }

Target:
public Value toAbsolutePath( Value request ) throws FaultException { Value response = Value.create(); String fileName = request.strValue(); Path absolutePath = null; try { absolutePath = Paths.get( fileName ).toAbsolutePath().normalize(); } catch ( InvalidPathException invalidPathException ) { throw new FaultException( invalidPathException ); } response.setValue( absolutePath.toString() ); return response; }
Source:
public void onActivityResult(int requestCode, int resultCode, Intent data) { IntentResult scanResult = IntentIntegrator.parseActivityResult(requestCode, resultCode, data); NightscoutPreferences prefs = new AndroidPreferences( this, mainPreferenceFragment.getPreferenceManager().getSharedPreferences()); if (scanResult != null && scanResult.getContents() != null) { NSBarcodeConfig barcode = new NSBarcodeConfig(scanResult.getContents()); if (barcode.hasMongoConfig()) { prefs.setMongoUploadEnabled(true); if (barcode.getMongoUri().isPresent()) { prefs.setMongoClientUri(barcode.getMongoUri().get()); prefs.setMongoCollection(barcode.getMongoCollection().orNull()); prefs.setMongoDeviceStatusCollection( barcode.getMongoDeviceStatusCollection().orNull()); } } else { prefs.setMongoUploadEnabled(false); } if (barcode.hasApiConfig()) { prefs.setRestApiEnabled(true); prefs.setRestApiBaseUris(barcode.getApiUris()); } else { prefs.setRestApiEnabled(false); } refreshFragments(); } }

Target:
public void onActivityResult(int requestCode, int resultCode, Intent data) { IntentResult scanResult = IntentIntegrator.parseActivityResult(requestCode, resultCode, data); NightscoutPreferences prefs = new AndroidPreferences(this); if (scanResult != null && scanResult.getContents() != null) { NSBarcodeConfig barcode = new NSBarcodeConfig(scanResult.getContents()); if (barcode.hasMongoConfig()) { prefs.setMongoUploadEnabled(true); if (barcode.getMongoUri().isPresent()) { prefs.setMongoClientUri(barcode.getMongoUri().get()); prefs.setMongoCollection(barcode.getMongoCollection().orNull()); prefs.setMongoDeviceStatusCollection( barcode.getMongoDeviceStatusCollection().orNull()); } } else { prefs.setMongoUploadEnabled(false); } if (barcode.hasApiConfig()) { prefs.setRestApiEnabled(true); prefs.setRestApiBaseUris(barcode.getApiUris()); } else { prefs.setRestApiEnabled(false); } refreshFragments(); } }
Source:
private List<URL> addPythonDependency(List<URL> dependencies) { List<URL> newDependencies = new ArrayList<>(dependencies); try { URL location = Class.forName( "org.apache.flink.python.PythonFunctionRunner", false, Thread.currentThread().getContextClassLoader()) .getProtectionDomain().getCodeSource().getLocation(); if (Paths.get(location.toURI()).toFile().isFile()) { newDependencies.add(location); } else { throw new FlinkException("flink-python module detected but is not a jar file: " + location + "."); } } catch (URISyntaxException | ClassNotFoundException | FlinkException e) { LOG.warn("Python UDF detected but flink-python jar not found. " + "If you starts SQL-Client via `sql-client.sh`, " + "please add the flink-python jar via `-j` command option manually.", e); } return newDependencies; }

Target:
private List<URL> addPythonDependency(List<URL> dependencies) { List<URL> newDependencies = new ArrayList<>(dependencies); try { URL location = Class.forName( "org.apache.flink.python.PythonFunctionRunner", false, Thread.currentThread().getContextClassLoader()) .getProtectionDomain().getCodeSource().getLocation(); if (Paths.get(location.toURI()).toFile().isFile()) { newDependencies.add(location); } } catch (URISyntaxException | ClassNotFoundException e) { throw new SqlExecutionException("Python UDF detected but flink-python jar not found. " + "If you starts SQL-Client via `sql-client.sh`, please add the flink-python jar " + "via `-j` command option manually.", e); } return newDependencies; }
Source:
static Map<String, DiscoveryGroupConfiguration> addDiscoveryGroupConfigs(final OperationContext context, final ModelNode model) throws OperationFailedException { Map<String, DiscoveryGroupConfiguration> configs = new HashMap<>(); if (model.hasDefined(CommonAttributes.JGROUP_DISCOVERY_GROUP)) { for (Property prop : model.get(CommonAttributes.JGROUP_DISCOVERY_GROUP).asPropertyList()) { configs.put(prop.getName(), createDiscoveryGroupConfiguration(context, prop.getName(), prop.getValue())); } } if (model.hasDefined(CommonAttributes.SOCKET_DISCOVERY_GROUP)) { for (Property prop : model.get(CommonAttributes.SOCKET_DISCOVERY_GROUP).asPropertyList()) { configs.put(prop.getName(), createDiscoveryGroupConfiguration(context, prop.getName(), prop.getValue())); } } return configs; }

Target:
static Map<String, DiscoveryGroupConfiguration> addDiscoveryGroupConfigs(final OperationContext context, final ModelNode model) throws OperationFailedException { Map<String, DiscoveryGroupConfiguration> configs = new HashMap<>(); if (model.hasDefined(CommonAttributes.JGROUPS_DISCOVERY_GROUP)) { for (Property prop : model.get(CommonAttributes.JGROUPS_DISCOVERY_GROUP).asPropertyList()) { configs.put(prop.getName(), createDiscoveryGroupConfiguration(context, prop.getName(), prop.getValue())); } } if (model.hasDefined(CommonAttributes.SOCKET_DISCOVERY_GROUP)) { for (Property prop : model.get(CommonAttributes.SOCKET_DISCOVERY_GROUP).asPropertyList()) { configs.put(prop.getName(), createDiscoveryGroupConfiguration(context, prop.getName(), prop.getValue())); } } return configs; }
Source:
public void testAllOnlineConfigChange() throws IOException { LOG.debug("Starting the test " + name.getMethodName()); Admin admin = TEST_UTIL.getAdmin(); admin.updateConfiguration(); }

Target:
public void testAllOnlineConfigChange() throws IOException { LOG.debug("Starting the test ", name.getMethodName()); Admin admin = TEST_UTIL.getAdmin(); admin.updateConfiguration(); }
Source:
public static MultiCurrencyAmountArray of(Map<Currency, DoubleArray> values) { values.values().stream().reduce((a1, a2) -> checkSize(a1, a2)); return new MultiCurrencyAmountArray(values.size(), values); }

Target:
public static MultiCurrencyAmountArray of(Map<Currency, DoubleArray> values) { values.values().stream().reduce((a1, a2) -> checkSize(a1, a2)); int size = values.isEmpty() ? 0 : values.values().iterator().next().size(); return new MultiCurrencyAmountArray(size, values); }
Source:
public Response deleteToken() { User u; try { u = findUserOrDie(); } catch (WrappedResponse ex) { return ex.getResponse(); } AuthenticatedUser au; try{ au = (AuthenticatedUser) u; } catch (ClassCastException e){ return notFound("Token for " + u.getIdentifier() + " not found."); } if (au == null) { return notFound("Token for " + u.getIdentifier() + " not found."); } authSvc.removeApiToken(au); return ok("Token for " + au.getUserIdentifier() + " deleted."); }

Target:
public Response deleteToken() { User u; try { u = findUserOrDie(); } catch (WrappedResponse ex) { return ex.getResponse(); } AuthenticatedUser au; try{ au = (AuthenticatedUser) u; } catch (ClassCastException e){ return notFound("Token for " + u.getIdentifier() + " not eligible for deletion."); } authSvc.removeApiToken(au); return ok("Token for " + au.getUserIdentifier() + " deleted."); }
Source:
public void applyOrderEdit() { OrderEditFixtures.withUpdateableOrderEdit(client(), orderEdit -> { final Address address = Address.of(CountryCode.DE); final SetBillingAddress setBillingAddress = SetBillingAddress.of(address); final OrderEditUpdateCommand orderEditUpdateCommand = OrderEditUpdateCommand.of(orderEdit, AddStagedAction.of(setBillingAddress)) .withExpansionPaths(OrderEditExpansionModel::resource); final OrderEdit updatedOrderEdit = client().executeBlocking(orderEditUpdateCommand); Assertions.assertThat(updatedOrderEdit).isNotNull(); final OrderEditApplyCommand orderEditApplyCommand = OrderEditApplyCommand.of(updatedOrderEdit.getId(), updatedOrderEdit.getResource().getObj().getVersion(), updatedOrderEdit.getVersion()); final OrderEdit appliedOrderEdit = client().executeBlocking(orderEditApplyCommand); Assertions.assertThat(appliedOrderEdit).isNotNull(); final OrderByIdGet orderByIdGet = OrderByIdGet.of(updatedOrderEdit.getResource().getObj().getId()); final Order order = client().executeBlocking(orderByIdGet); Assertions.assertThat(order).isNotNull(); Assertions.assertThat(order.getBillingAddress().getCountry()).isEqualTo(CountryCode.DE); return appliedOrderEdit; }); }

Target:
public void applyOrderEdit() { final Function<OrderEdit, OrderEditApplyCommand> function = (OrderEdit orderEdit) -> OrderEditApplyCommand.of(orderEdit.getId(), orderEdit.getVersion(), orderEdit.getResource().getObj().getVersion()); apply(function); }
Source:
void shutdown() { try { removeTemporaryWs(); } catch (ServerException | ConflictException e) { LOG.warn("Unable to cleanup temporary workspaces on shutdown: " + e.getLocalizedMessage(), e); } }

Target:
void shutdown() { try { removeTemporaryWs(); } catch (ServerException e) { LOG.warn("Unable to cleanup temporary workspaces on shutdown: " + e.getLocalizedMessage(), e); } }
Source:
public StubTypes(AnnotatedTypeFactory factory) { this.factory = factory; this.typesFromStubFiles = new HashMap<>(); this.declAnnosFromStubFiles = new HashMap<>(); this.parsing = false; String release = PluginUtil.releaseValue(factory.getProcessingEnv()); this.annotatedJdkVersion = release != null ? release : String.valueOf(PluginUtil.getJreVersion()); this.shouldParseJdk = !factory.getContext().getChecker().hasOption("ignorejdkastub") && PluginUtil.getJreVersion() != 8 && annotatedJdkVersion.equals("11"); }

Target:
public StubTypes(AnnotatedTypeFactory factory) { this.factory = factory; this.typesFromStubFiles = new HashMap<>(); this.declAnnosFromStubFiles = new HashMap<>(); this.parsing = false; String release = PluginUtil.getReleaseValue(factory.getProcessingEnv()); this.annotatedJdkVersion = release != null ? release : String.valueOf(PluginUtil.getJreVersion()); this.shouldParseJdk = !factory.getContext().getChecker().hasOption("ignorejdkastub") && PluginUtil.getJreVersion() != 8 && annotatedJdkVersion.equals("11"); }
Source:
private String rewrittenRedirectUri(String originalUri) { String rewrittenRedirectUri = originalUri; try { URL url = new URL(originalUri); Map<String, String> rewriteRules = deployment.getRedirectRewriteRules(); if(rewriteRules != null && !rewriteRules.isEmpty()) { Map.Entry<String, String> rule = rewriteRules.entrySet().iterator().next(); StringBuilder redirectUriBuilder = new StringBuilder(url.getProtocol()); redirectUriBuilder.append("://"+ url.getAuthority()); redirectUriBuilder.append(url.getPath().replaceFirst(rule.getKey(), rule.getValue())); return redirectUriBuilder.toString(); } } catch (MalformedURLException ex) { log.error("Not a valid request url"); } return rewrittenRedirectUri; }

Target:
private String rewrittenRedirectUri(String originalUri) { Map<String, String> rewriteRules = deployment.getRedirectRewriteRules(); if(rewriteRules != null && !rewriteRules.isEmpty()) { try { URL url = new URL(originalUri); Map.Entry<String, String> rule = rewriteRules.entrySet().iterator().next(); StringBuilder redirectUriBuilder = new StringBuilder(url.getProtocol()); redirectUriBuilder.append("://"+ url.getAuthority()); redirectUriBuilder.append(url.getPath().replaceFirst(rule.getKey(), rule.getValue())); return redirectUriBuilder.toString(); } catch (MalformedURLException ex) { log.error("Not a valid request url"); throw new RuntimeException(ex); } } return originalUri; }
Source:
public String getFirstName() { return (firstName == null) ? getPlaceHolderString("message.alternative.first.name") : firstName; }

Target:
public String getFirstName() { return (firstName == null) ? getTranslation("message.alternative.first.name", getSenderNickname()) : firstName; }
Source:
public AvailabilityType getAvailability() { boolean trace = log.isTraceEnabled(); EmsBean bean = getEmsBean(); try { if (bean != null) { bean.refreshAttributes(); if (bean.getAttribute("CacheStatus").getValue().equals("RUNNING")) { if (trace) log.trace("Cache " + cacheName + " within " + cacheManagerName + " cache manager is running, so it's up."); return AvailabilityType.UP; } } if (trace) log.trace("Cache status for " + cacheName + " within " + cacheManagerName + " cache manager is anything other than running, so it's down."); return AvailabilityType.DOWN; } catch (Exception e) { if (trace) log.trace("There was an exception checking availability, so cache status is down.", e); return AvailabilityType.DOWN; } }

Target:
public AvailabilityType getAvailability() { boolean trace = log.isTraceEnabled(); EmsBean bean = getEmsBean(); try { if (bean != null) { bean.refreshAttributes(AVAILABILITY_ATTRIBUTE); if ("RUNNING".equals(bean.getAttribute(STATUS_ATTRIBUTE_NAME).getValue())) { if (trace) log.trace("Cache " + cacheName + " within " + cacheManagerName + " cache manager is running, so it's up."); return AvailabilityType.UP; } } if (trace) log.trace("Cache status for " + cacheName + " within " + cacheManagerName + " cache manager is anything other than running, so it's down."); return AvailabilityType.DOWN; } catch (Exception e) { if (trace) log.trace("There was an exception checking availability, so cache status is down.", e); return AvailabilityType.DOWN; } }
Source:
public void depositLots(final Integer userId, final Set<Integer> lotIds, final List<LotDepositDto> lotDepositDtoList, final TransactionStatus transactionStatus) { final LotsSearchDto lotsSearchDto = new LotsSearchDto(); lotsSearchDto.setLotIds(new ArrayList<>(lotIds)); final List<ExtendedLotDto> lots = this.daoFactory.getLotDao().searchLots(lotsSearchDto, null); final Map<String, List<LotDepositDto>> lotDepositDtoMap = lotDepositDtoList.stream().collect(Collectors.groupingBy(LotDepositDto::getLotUID)); for (final ExtendedLotDto extendedLotDto : lots) { final List<LotDepositDto> lotDepositDtos = lotDepositDtoMap.get(extendedLotDto.getLotUUID()); for (final LotDepositDto lotDepositDto : lotDepositDtos) { final Transaction transaction = new Transaction(TransactionType.DEPOSIT, transactionStatus, userId, lotDepositDto.getNotes(), extendedLotDto.getLotId(), lotDepositDto.getAmount()); this.daoFactory.getTransactionDAO().save(transaction); } } }

Target:
public void depositLots(final Integer userId, final Set<Integer> lotIds, final List<LotDepositDto> lotDepositDtoList, final TransactionStatus transactionStatus) { final LotsSearchDto lotsSearchDto = new LotsSearchDto(); lotsSearchDto.setLotIds(new ArrayList<>(lotIds)); final List<ExtendedLotDto> lots = this.daoFactory.getLotDao().searchLots(lotsSearchDto, null); final Map<String, ExtendedLotDto> extendedLotDtoMap = lots.stream().collect(Collectors.toMap(ExtendedLotDto::getLotUUID, extendedLotDto -> extendedLotDto)); for (final LotDepositDto lotDepositDto : lotDepositDtoList) { final ExtendedLotDto extendedLotDto = extendedLotDtoMap.get(lotDepositDto.getLotUID()); final Transaction transaction = new Transaction(TransactionType.DEPOSIT, transactionStatus, userId, lotDepositDto.getNotes(), extendedLotDto.getLotId(), lotDepositDto.getAmount()); this.daoFactory.getTransactionDAO().save(transaction); } }
Source:
private String runtimeClassPath() throws UnsupportedEncodingException { StringBuilder runtimeClassPath = new StringBuilder(); for (URL url : ((URLClassLoader) LocalScriptTestDriveService.class.getClassLoader()).getURLs()) { if (url.getPath().contains("ngrinder-runtime") || url.getPath().contains("ngrinder-groovy")) { runtimeClassPath.append(URLDecoder.decode(url.getFile(), "UTF-8")).append(File.pathSeparator); } } return runtimeClassPath.toString(); }

Target:
private String runtimeClassPath() { StringBuilder runtimeClassPath = new StringBuilder(); for (URL url : ((URLClassLoader) LocalScriptTestDriveService.class.getClassLoader()).getURLs()) { if (url.getPath().contains("ngrinder-runtime") || url.getPath().contains("ngrinder-groovy")) { runtimeClassPath.append(decodePathWithUTF8(url.getFile())).append(File.pathSeparator); } } return runtimeClassPath.toString(); }
Source:
public void trackTagLoaded(ReaderTag tag) { AnalyticsTracker.Stat stat = null; if (tag.isFreshlyPressed()) { stat = AnalyticsTracker.Stat.READER_FRESHLY_PRESSED_LOADED; } else if (tag.isTagTopic()) { stat = AnalyticsTracker.Stat.READER_TAG_LOADED; } else if (tag.isListTopic()) { stat = AnalyticsTracker.Stat.READER_LIST_LOADED; } if (stat == null) return; Map<String, String> properties = new HashMap<>(); properties.put("tag", tag.getTagName()); AnalyticsTracker.track(stat, properties); }

Target:
private void trackTagLoaded(ReaderTag tag) { AnalyticsTracker.Stat stat = null; if (tag.isFreshlyPressed()) { stat = AnalyticsTracker.Stat.READER_FRESHLY_PRESSED_LOADED; } else if (tag.isTagTopic()) { stat = AnalyticsTracker.Stat.READER_TAG_LOADED; } else if (tag.isListTopic()) { stat = AnalyticsTracker.Stat.READER_LIST_LOADED; } if (stat == null) return; Map<String, String> properties = new HashMap<>(); properties.put("tag", tag.getTagName()); AnalyticsTracker.track(stat, properties); }
Source:
public void prefixKeyWithSalt(final byte[] row_key, final int bucket) { if (salt_width == 1) { row_key[0] = (byte) bucket; return; } int shift = 0; for (int i = 0; i <= salt_width; i++) { row_key[salt_width - i] = 0; row_key[salt_width - i] = (byte) (bucket >>> shift); shift += 8; } }

Target:
public void prefixKeyWithSalt(final byte[] row_key, final int bucket) { if (salt_width == 1) { row_key[0] = (byte) bucket; return; } int shift = 0; for (int i = 0; i < salt_width; i++) { row_key[salt_width - i - 1] = 0; row_key[salt_width - i - 1] = (byte) (bucket >>> shift); shift += 8; } }
Source:
public void testUpdateProject() throws SQLException{ ProjectInfo projectInfo = new ProjectInfo(); projectInfo.name = "TEST_PROJECT_NAME"; projectInfo.displayName = "TEST_PROJECT_DISPLAYNAME"; projectInfo.common = "TEST_PROJECT_COMMON"; projectInfo.manager = "TEST_PROJECT_MANAGER"; projectInfo.attachFileSize = 2048L; long projectId = mProjectMapper.createProject(projectInfo.name, projectInfo); assertTrue(projectId > 0); projectInfo.displayName = "TEST_PROJECT_DISPLAYNAME_NEW"; projectInfo.common = "TEST_PROJECT_COMMON_NEW"; projectInfo.manager = "TEST_PROJECT_MANAGER_NEW"; projectInfo.attachFileSize = 1024L; mProjectMapper.updateProject(projectId, projectInfo); IQueryValueSet valueSet = new MySQLQuerySet(); valueSet.addTableName(ProjectEnum.TABLE_NAME); valueSet.addEqualCondition(ProjectEnum.ID, projectId); String query = valueSet.getSelectQuery(); ResultSet resultSet = mControl.executeQuery(query); if (resultSet.next()) { ProjectObject project = ProjectDAO.getInstance().convertProject(resultSet); assertEquals(projectInfo.displayName, project.getDisplayName()); assertEquals(projectInfo.common, project.getComment()); assertEquals(projectInfo.manager, project.getManager()); assertEquals(projectInfo.attachFileSize, project.getAttachFileSize()); } }

Target:
public void testUpdateProject() throws SQLException{ ProjectInfo newProjectInfo = new ProjectInfo(); newProjectInfo.displayName = "TEST_PROJECT_DISPLAYNAME_NEW"; newProjectInfo.common = "TEST_PROJECT_COMMON_NEW"; newProjectInfo.manager = "TEST_PROJECT_MANAGER_NEW"; newProjectInfo.attachFileSize = 1024L; mProjectMapper.updateProject(mProjectId, newProjectInfo); IQueryValueSet valueSet = new MySQLQuerySet(); valueSet.addTableName(ProjectEnum.TABLE_NAME); valueSet.addEqualCondition(ProjectEnum.ID, mProjectId); String query = valueSet.getSelectQuery(); ResultSet resultSet = mControl.executeQuery(query); if (resultSet.next()) { ProjectObject project = ProjectDAO.getInstance().convertProject(resultSet); assertEquals(newProjectInfo.displayName, project.getDisplayName()); assertEquals(newProjectInfo.common, project.getComment()); assertEquals(newProjectInfo.manager, project.getManager()); assertEquals(newProjectInfo.attachFileSize, project.getAttachFileSize()); } }
Source:
public boolean hostileTakeover() { LeadershipState leadershipState = determineLeadershipState(); StillLeadingStatus status = leadershipState.status(); switch (status) { case LEADING: return true; case NOT_LEADING: try { proposer.propose(getNextSequenceNumber(leadershipState.greatestLearnedValue()), null); StillLeadingStatus newStatus = determineLeadershipState().status(); if (newStatus == StillLeadingStatus.LEADING) { log.info("Successfully took over", SafeArg.of("newStatus", newStatus)); return true; } else { log.info("Failed to take over", SafeArg.of("newStatus", newStatus)); return false; } } catch (PaxosRoundFailureException e) { log.info("Couldn't takeover leadership because a quorum could not be obtained.", SafeArg.of("lastObservedState", leadershipState)); return false; } case NO_QUORUM: log.info("Couldn't takeover leadership because a quorum could not be obtained: NO_QUORUM"); return false; default: throw new IllegalStateException("Unexpected value: " + status); } }

Target:
public boolean hostileTakeover() { LeadershipState leadershipState = determineLeadershipState(); StillLeadingStatus status = leadershipState.status(); switch (status) { case LEADING: return true; case NOT_LEADING: try { proposer.propose( getNextSequenceNumber(leadershipState.greatestLearnedValue()), LEADERSHIP_PROPOSAL_VALUE); StillLeadingStatus newStatus = determineLeadershipState().status(); if (newStatus == StillLeadingStatus.LEADING) { log.info("Successfully took over", SafeArg.of("newStatus", newStatus)); return true; } else { log.info("Failed to take over", SafeArg.of("newStatus", newStatus)); return false; } } catch (PaxosRoundFailureException e) { log.info("Couldn't takeover leadership because a quorum could not be obtained.", SafeArg.of("lastObservedState", leadershipState)); return false; } case NO_QUORUM: log.info("Couldn't takeover leadership because a quorum could not be obtained: NO_QUORUM"); return false; default: throw new IllegalStateException("Unexpected value: " + status); } }