auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public static Slice canonicalizePhoneNumber( @SqlType(StandardTypes.VARCHAR) Slice phoneNumber, @SqlNullable @SqlType(StandardTypes.VARCHAR) Slice country, @SqlType(StandardTypes.VARCHAR) Slice format) { PhoneNumberFormat numberFormat; if (format == null) { numberFormat = PhoneNumberFormat.RFC3966; } else { String formatString = format.toStringUtf8(); try { numberFormat = PhoneNumberFormat.valueOf(formatString); } catch (IllegalArgumentException ex) { throw new PrestoException(StandardErrorCode.INVALID_FUNCTION_ARGUMENT, "Invalid format provided: " + formatString + ". Allowed values: " + Arrays.toString(PhoneNumberFormat.values())); } } PhoneNumber number; try { number = PHONE_NUMBER_UTIL.parse(phoneNumber.toStringUtf8(), country != null ? country.toStringUtf8() : null); } catch (NumberParseException ex) { throw new PrestoException(StandardErrorCode.INVALID_FUNCTION_ARGUMENT, "Unable to parse phone number: " + phoneNumber.toStringUtf8(), ex); } return Slices.utf8Slice(PHONE_NUMBER_UTIL.format(number, numberFormat)); }

Target:
public static Slice canonicalizePhoneNumber( @SqlType(StandardTypes.VARCHAR) Slice phoneNumber, @SqlNullable @SqlType(StandardTypes.VARCHAR) Slice country, @SqlType(StandardTypes.VARCHAR) Slice format) { PhoneNumberFormat numberFormat; if (format == null) { numberFormat = RFC3966; } else { String formatString = format.toStringUtf8().toUpperCase(); try { numberFormat = PhoneNumberFormat.valueOf(formatString); } catch (IllegalArgumentException ex) { throw new PrestoException(INVALID_FUNCTION_ARGUMENT, "Invalid format provided: " + formatString + ". Allowed values: " + Arrays.toString(PhoneNumberFormat.values())); } } PhoneNumber number; try { number = PHONE_NUMBER_UTIL.parse(phoneNumber.toStringUtf8(), country != null ? country.toStringUtf8().toUpperCase() : null); } catch (NumberParseException ex) { throw new PrestoException(INVALID_FUNCTION_ARGUMENT, "Unable to parse phone number: " + phoneNumber.toStringUtf8(), ex); } return Slices.utf8Slice(PHONE_NUMBER_UTIL.format(number, numberFormat)); }
Source:
void single( long reference, Read read ) { if ( getId() != NO_ID ) { reset(); } if ( pageCursor == null ) { pageCursor = read.nodePage( reference ); } this.next = reference; this.highMark = NO_ID; this.lastStoreReference = -2; this.read = read; this.hasChanges = HasChanges.MAYBE; this.addedNodes = emptySet(); }

Target:
void single( long reference, Read read ) { if ( getId() != NO_ID ) { reset(); } if ( pageCursor == null ) { pageCursor = read.nodePage( reference ); } this.next = reference; this.highMark = NO_ID; this.nextStoreReference = NO_ID; this.read = read; this.hasChanges = HasChanges.MAYBE; this.addedNodes = LongSets.immutable.empty(); }
Source:
public void removeUnusedModels(Set<String> reposInUse) { Set<String> openRepos = models.toModels().stream().map(Model::getRepoId).collect(Collectors.toSet()); openRepos.removeAll(reposInUse); for (String unusedRepoId : openRepos) { removeRepoModel(unusedRepoId); } }

Target:
public void removeUnusedModels(Set<String> reposInUse) { models.toModels().stream().map(Model::getRepoId). filter(repoId -> !reposInUse.contains(repoId)). forEach(repoIdNotInUse -> models.removeRepoModelById(repoIdNotInUse)); }
Source:
public Server findServerAvatica(String connectionId) { Server chosenServer = avaticaConnectionBalancer.balance(getAllServers(), connectionId); if (chosenServer == null) { log.makeAlert( "Catastrophic failure! No servers found at all! Failing request!" ).emit(); throw new ISE("No server found for Avatica request with connectionId[%s]", connectionId); } log.info( "Balancer class [%s] sending request with connectionId[%s] to server: %s", avaticaConnectionBalancer.getClass(), connectionId, chosenServer.getHost() ); return chosenServer; }

Target:
public Server findServerAvatica(String connectionId) { Server chosenServer = avaticaConnectionBalancer.pickServer(getAllServers(), connectionId); if (chosenServer == null) { log.makeAlert( "Catastrophic failure! No servers found at all! Failing request!" ).emit(); throw new ISE("No server found for Avatica request with connectionId[%s]", connectionId); } log.debug( "Balancer class [%s] sending request with connectionId[%s] to server: %s", avaticaConnectionBalancer.getClass(), connectionId, chosenServer.getHost() ); return chosenServer; }
Source:
private void checkEndOfBattle(final StepUnits units) { final Collection<Unit> attackingUnits = units.getAliveOrWaitingToDieFriendly(); final Collection<Unit> defendingUnits = units.getAliveOrWaitingToDieEnemy(); final GamePlayer attacker = units.getPlayer(); final Territory battleSite = parameters.getLocation(); final Collection<TerritoryEffect> territoryEffects = parameters.getTerritoryEffects(); if (CollectionUtils.getMatches(attackingUnits, Matches.unitIsNotInfrastructure()).size() == 0) { if (!Properties.getTransportCasualtiesRestricted(parameters.getData())) { loseProbability = 1; hasResult = true; } else { final Predicate<Unit> matchAllied = Matches.unitIsTransport() .and(Matches.unitIsNotCombatTransport()) .and(Matches.isUnitAllied(attacker, parameters.getData())); final List<Unit> alliedTransports = CollectionUtils.getMatches(battleSite.getUnits(), matchAllied); if (alliedTransports.isEmpty()) { loseProbability = 1; hasResult = true; } else if (round <= 1) { } else { loseProbability = 1; hasResult = true; } } } else if (CollectionUtils.getMatches(defendingUnits, Matches.unitIsNotInfrastructure()) .size() == 0) { if (Properties.getTransportCasualtiesRestricted(parameters.getData())) { checkUndefendedTransports(units.getEnemy(), units); } checkForUnitsThatCanRollLeft(false, units); winProbability = 1; hasResult = true; } else if (MAX_ROUNDS > 0 && MAX_ROUNDS <= round) { tieProbability = 1; hasResult = true; } if (hasResult && units.noMoreEnemies() && units.noMoreFriendlies()) { loseProbability = 0; winProbability = 0; badProbability = 0; tieProbability = 1; } }

Target:
private void checkEndOfBattle(final StepUnits units) { final Collection<Unit> attackingUnits = units.getAliveOrWaitingToDieFriendly(); final Collection<Unit> defendingUnits = units.getAliveOrWaitingToDieEnemy(); final GamePlayer attacker = units.getPlayer(); final Territory battleSite = parameters.getLocation(); if (CollectionUtils.getMatches(attackingUnits, Matches.unitIsNotInfrastructure()).isEmpty()) { if (!Properties.getTransportCasualtiesRestricted(parameters.getData())) { loseProbability = 1; hasResult = true; } else { final Predicate<Unit> matchAllied = Matches.unitIsTransport() .and(Matches.unitIsNotCombatTransport()) .and(Matches.isUnitAllied(attacker, parameters.getData())); final List<Unit> alliedTransports = CollectionUtils.getMatches(battleSite.getUnits(), matchAllied); if (alliedTransports.isEmpty()) { loseProbability = 1; hasResult = true; } else if (round <= 1) { } else { loseProbability = 1; hasResult = true; } } } else if (CollectionUtils.getMatches(defendingUnits, Matches.unitIsNotInfrastructure()).size() == 0) { if (Properties.getTransportCasualtiesRestricted(parameters.getData())) { checkUndefendedTransports(units.getEnemy(), units); } checkForUnitsThatCanRollLeft(false, units); winProbability = 1; hasResult = true; } else if (MAX_ROUNDS > 0 && MAX_ROUNDS <= round) { tieProbability = 1; hasResult = true; } if (hasResult && units.noMoreEnemies() && units.noMoreFriendlies()) { loseProbability = 0; winProbability = 0; badProbability = 0; tieProbability = 1; } }
Source:
public String getLastOpenBoard() { return lastOpenBoard.get(); }

Target:
public Optional<String> getLastOpenBoard() { return lastOpenBoard; }
Source:
public String getText() { return StringUtil.escapeXml(myText); }

Target:
public String getText() { return myText; }
Source:
public void testListGatewaysWithOneDispatcherThread() { String command = "create gateway-sender --id=ln_Serial --remote-distributed-system-id=2 --dispatcher-threads=1"; int lnPort = locatorSite1.getPort(); server1 = clusterStartupRule.startServerVM(3, lnPort); server2 = clusterStartupRule.startServerVM(4, lnPort); server3 = clusterStartupRule.startServerVM(5, lnPort); gfsh.executeAndAssertThat(command).statusIsSuccess(); gfsh.executeAndAssertThat("list gateways").statusIsSuccess() .hasTableSection("gatewaySenders") .hasRowSize(3).hasColumn("Status").contains("Running, not Connected"); gfsh.executeAndAssertThat("list gateways --senders-only").statusIsSuccess() .hasNoSection("gatewayReceivers") .hasTableSection("gatewaySenders") .hasRowSize(3).hasColumn("Status").contains("Running, not Connected"); }

Target:
public void testListGatewaysWithOneDispatcherThread() { String command = new CommandStringBuilder(CliStrings.CREATE_GATEWAYSENDER) .addOption(CliStrings.CREATE_GATEWAYSENDER__ID, "ln_Serial") .addOption(CliStrings.CREATE_GATEWAYSENDER__REMOTEDISTRIBUTEDSYSTEMID, "2") .addOption(CliStrings.CREATE_GATEWAYSENDER__DISPATCHERTHREADS, "1") .getCommandString(); int lnPort = locatorSite1.getPort(); server1 = clusterStartupRule.startServerVM(3, lnPort); server2 = clusterStartupRule.startServerVM(4, lnPort); server3 = clusterStartupRule.startServerVM(5, lnPort); gfsh.executeAndAssertThat(command).statusIsSuccess(); gfsh.executeAndAssertThat(CliStrings.LIST_GATEWAY).statusIsSuccess() .hasTableSection("gatewaySenders") .hasRowSize(3).hasColumn("Status").contains("Running, not Connected"); gfsh.executeAndAssertThat( CliStrings.LIST_GATEWAY + " --" + CliStrings.LIST_GATEWAY__SHOW_SENDERS_ONLY) .statusIsSuccess() .hasNoSection("gatewayReceivers") .hasTableSection("gatewaySenders") .hasRowSize(3).hasColumn("Status").contains("Running, not Connected"); }
Source:
public void after() throws IOException { EasyMock.verify(_mocks.toArray()); folder.delete(); }

Target:
public void after() throws IOException { folder.delete(); }
Source:
private boolean shouldBeIncluded(IResource res, GitSynchronizeDataSet dataSet) { final IProject project = res.getProject(); if (project == null) return false; final GitSynchronizeData syncData = dataSet.getData(project); if (syncData == null) return false; final Set<? extends IResource> includedPaths = syncData .getIncludedPaths(); if (includedPaths == null) return true; IPath path = res.getLocation(); for (IResource resource : includedPaths) if (resource.getLocation().isPrefixOf(path)) return true; return false; }

Target:
private boolean shouldBeIncluded(IResource res, GitSynchronizeDataSet dataSet) { final IProject project = res.getProject(); if (project == null) return false; final GitSynchronizeData syncData = dataSet.getData(project); if (syncData == null) return false; final Set<? extends IResource> includedPaths = syncData .getIncludedPaths(); if (includedPaths == null) return true; IPath path = res.getLocation(); if (path != null) { for (IResource resource : includedPaths) { IPath inclResourceLocation = resource.getLocation(); if (inclResourceLocation != null && inclResourceLocation.isPrefixOf(path)) return true; } } return false; }
Source:
private void setCowVirtualSizeAndQcowCompat(DiskImage diskImage, Image glanceImage) { byte[] imgContent = new byte[72]; ImageDownload downloadImage = getClient().images().download(glanceImage.getId()).execute(); try (InputStream inputStream = downloadImage.getInputStream()) { int bytesRead = inputStream.read(imgContent, 0, imgContent.length); if (bytesRead != imgContent.length) { throw new OpenStackImageException( OpenStackImageException.ErrorType.UNABLE_TO_DOWNLOAD_IMAGE, "Unable to read image header: " + bytesRead); } } catch (IOException e) { throw new OpenStackImageException( OpenStackImageException.ErrorType.UNABLE_TO_DOWNLOAD_IMAGE, "Unable to download image"); } ByteBuffer b = ByteBuffer.wrap(imgContent); int qcow2Signature = b.getInt(); int qcow2Version = b.getInt(); QcowCompat qcowCompat = QcowCompat.forQcowHeaderVersion(qcow2Version); if (qcow2Signature == QCOW2_SIGNATURE && (qcowCompat != null || qcowCompat != QcowCompat.Undefined)) { b.position(QCOW2_SIZE_OFFSET); diskImage.setSize(b.getLong()); diskImage.setQcowCompat(qcowCompat); } else { throw new OpenStackImageException( OpenStackImageException.ErrorType.UNRECOGNIZED_IMAGE_FORMAT, "Unable to recognize QCOW2 format"); } }

Target:
private void setCowVirtualSizeAndQcowCompat(DiskImage diskImage, Image glanceImage) { byte[] imgContent = new byte[72]; ImageDownload downloadImage = getClient().images().download(glanceImage.getId()).execute(); try (InputStream inputStream = downloadImage.getInputStream()) { int bytesRead = inputStream.read(imgContent, 0, imgContent.length); if (bytesRead != imgContent.length) { throw new OpenStackImageException( OpenStackImageException.ErrorType.UNABLE_TO_DOWNLOAD_IMAGE, "Unable to read image header: " + bytesRead); } } catch (IOException e) { throw new OpenStackImageException( OpenStackImageException.ErrorType.UNABLE_TO_DOWNLOAD_IMAGE, "Unable to download image"); } ByteBuffer b = ByteBuffer.wrap(imgContent); int qcow2Signature = b.getInt(); int qcow2Version = b.getInt(); QcowCompat qcowCompat = QcowCompat.forQcowHeaderVersion(qcow2Version); if (qcow2Signature == QCOW2_SIGNATURE && qcowCompat != null && qcowCompat != QcowCompat.Undefined) { b.position(QCOW2_SIZE_OFFSET); diskImage.setSize(b.getLong()); diskImage.setQcowCompat(qcowCompat); } else { throw new OpenStackImageException( OpenStackImageException.ErrorType.UNRECOGNIZED_IMAGE_FORMAT, "Unable to recognize QCOW2 format"); } }
Source:
Mono<Response<DirectoryInfo>> createWithResponse(FileSmbProperties smbProperties, String filePermission, Map<String, String> metadata, Context context) { FileSmbProperties properties = smbProperties == null ? new FileSmbProperties() : smbProperties; FileExtensions.filePermissionAndKeyHelper(filePermission, properties.filePermissionKey()); filePermission = properties.filePermission(filePermission, FileConstants.FILE_PERMISSION_INHERIT); String filePermissionKey = properties.filePermissionKey(); String fileAttributes = properties.ntfsFileAttributes(FileConstants.FILE_ATTRIBUTES_NONE); String fileCreationTime = properties.fileCreationTime(FileConstants.FILE_TIME_NOW); String fileLastWriteTime = properties.fileLastWriteTime(FileConstants.FILE_TIME_NOW); return postProcessResponse(azureFileStorageClient.directorys().createWithRestResponseAsync(shareName, directoryPath, fileAttributes, fileCreationTime, fileLastWriteTime, null, metadata, filePermission, filePermissionKey, context)) .map(this::createWithRestResponse); }

Target:
Mono<Response<DirectoryInfo>> createWithResponse(FileSmbProperties smbProperties, String filePermission, Map<String, String> metadata, Context context) { FileSmbProperties properties = smbProperties == null ? new FileSmbProperties() : smbProperties; filePermissionAndKeyHelper(filePermission, properties.filePermissionKey()); filePermission = properties.filePermission(filePermission, FileConstants.FILE_PERMISSION_INHERIT); String filePermissionKey = properties.filePermissionKey(); String fileAttributes = properties.ntfsFileAttributes(FileConstants.FILE_ATTRIBUTES_NONE); String fileCreationTime = properties.fileCreationTime(FileConstants.FILE_TIME_NOW); String fileLastWriteTime = properties.fileLastWriteTime(FileConstants.FILE_TIME_NOW); return postProcessResponse(azureFileStorageClient.directorys().createWithRestResponseAsync(shareName, directoryPath, fileAttributes, fileCreationTime, fileLastWriteTime, null, metadata, filePermission, filePermissionKey, context)) .map(this::createWithRestResponse); }
Source:
public SpecialAdminDashboardPageObject(WebDriver driver) { super(driver); PageFactory.initElements(driver, this); }

Target:
public SpecialAdminDashboardPageObject(WebDriver driver) { super(driver); }
Source:
protected <T> T getEntity(Class<T> clz, SearchType searchType, String constraint) { try { VdcQueryReturnValue result = runQuery(VdcQueryType.Search, new SearchParameters(constraint, searchType)); if (!result.getSucceeded()) { throw new BackendFailureException(localize(result.getExceptionString()), ErrorMessageHelper.getErrorStatus(result.getExceptionString())); } T entity; if (List.class.isAssignableFrom(clz) && result.getReturnValue() instanceof List) { entity = clz.cast(result.getReturnValue()); } else { List<T> list = asCollection(clz, result.getReturnValue()); if (list == null || list.isEmpty()) { throw new EntityNotFoundException(constraint); } entity = clz.cast(list.get(0)); } return entity; } catch (Exception e) { return handleError(clz, e, false); } }

Target:
protected <T> T getEntity(Class<T> clz, SearchType searchType, String constraint) { try { VdcQueryReturnValue result = runQuery(VdcQueryType.Search, new SearchParameters(constraint, searchType)); if (!result.getSucceeded()) { backendFailure(result.getExceptionString()); } T entity; if (List.class.isAssignableFrom(clz) && result.getReturnValue() instanceof List) { entity = clz.cast(result.getReturnValue()); } else { List<T> list = asCollection(clz, result.getReturnValue()); if (list == null || list.isEmpty()) { throw new EntityNotFoundException(constraint); } entity = clz.cast(list.get(0)); } return entity; } catch (Exception e) { return handleError(clz, e, false); } }
Source:
public void testPoNHyperparameterInitialization() { LoggingUtils.setLoggingLevel(Log.LogLevel.INFO); final AllelicPanelOfNormals allelicPoN = new AllelicPanelOfNormals(new AllelicCountCollection(ALLELIC_PON_NORMAL_COUNTS_FILE)); final SimpleInterval firstSite = new SimpleInterval("1", 1, 1); final SimpleInterval siteNotInPON = new SimpleInterval("2", 1, 1); final double alphaAtFirstSite = allelicPoN.getAlpha(firstSite); final double betaAtFirstSite = allelicPoN.getBeta(firstSite); Assert.assertEquals(alphaAtFirstSite, ALPHA_EXPECTED_AT_FIRST_SITE, DELTA); Assert.assertEquals(betaAtFirstSite, BETA_EXPECTED_AT_FIRST_SITE, DELTA); final double alphaNotInPON = allelicPoN.getAlpha(siteNotInPON); final double betaNotInPON = allelicPoN.getBeta(siteNotInPON); final double meanBias = allelicPoN.getGlobalMeanBias(); final double biasVariance = allelicPoN.getGlobalBiasVariance(); Assert.assertEquals(alphaNotInPON, MLE_ALPHA_EXPECTED, DELTA); Assert.assertEquals(betaNotInPON, MLE_BETA_EXPECTED, DELTA); Assert.assertEquals(meanBias, MLE_MEAN_BIAS_EXPECTED, DELTA); Assert.assertEquals(biasVariance, MLE_BIAS_VARIANCE_EXPECTED, DELTA); }

Target:
public void testPoNHyperparameterInitialization() { LoggingUtils.setLoggingLevel(Log.LogLevel.INFO); final AllelicPanelOfNormals allelicPoN = new AllelicPanelOfNormals(new AllelicCountCollection(ALLELIC_PON_NORMAL_COUNTS_FILE)); final SimpleInterval firstSite = new SimpleInterval("1", 1, 1); final SimpleInterval siteNotInPoN = new SimpleInterval("2", 1, 1); final double alphaAtFirstSite = allelicPoN.getAlpha(firstSite); final double betaAtFirstSite = allelicPoN.getBeta(firstSite); Assert.assertEquals(alphaAtFirstSite, ALPHA_EXPECTED_AT_FIRST_SITE, DELTA); Assert.assertEquals(betaAtFirstSite, BETA_EXPECTED_AT_FIRST_SITE, DELTA); final double alphaNotInPoN = allelicPoN.getAlpha(siteNotInPoN); final double betaNotInPoN = allelicPoN.getBeta(siteNotInPoN); final double meanBias = allelicPoN.getGlobalMeanBias(); final double biasVariance = allelicPoN.getGlobalBiasVariance(); Assert.assertEquals(alphaNotInPoN, MLE_ALPHA_EXPECTED, DELTA); Assert.assertEquals(betaNotInPoN, MLE_BETA_EXPECTED, DELTA); Assert.assertEquals(meanBias, MLE_MEAN_BIAS_EXPECTED, DELTA); Assert.assertEquals(biasVariance, MLE_BIAS_VARIANCE_EXPECTED, DELTA); }
Source:
public void onImportUserFromLDAP(LDAPObject ldapUser, UserModel user, RealmModel realm, boolean isCreate) { String userModelAttrName = getUserModelAttribute(); String attributeValue = getAttributeValue(); Property<Object> userModelProperty = userModelProperties.get(userModelAttrName.toLowerCase()); if (userModelProperty != null) { checkDuplicateEmail(userModelAttrName, attributeValue, realm, ldapProvider.getSession(), user); setPropertyOnUserModel(userModelProperty, user, attributeValue); } else { user.setAttribute(userModelAttrName, Arrays.asList(attributeValue)); } }

Target:
public void onImportUserFromLDAP(LDAPObject ldapUser, UserModel user, RealmModel realm, boolean isCreate) { String userModelAttrName = getUserModelAttribute(); String attributeValue = getAttributeValue(); Property<Object> userModelProperty = userModelProperties.get(userModelAttrName.toLowerCase()); if (userModelProperty != null) { setPropertyOnUserModel(userModelProperty, user, attributeValue); } else { user.setAttribute(userModelAttrName, Arrays.asList(attributeValue)); } }
Source:
public String toString() { if (m_map.isEmpty()) { return "Empty Map"; } StringBuilder sb = new StringBuilder(); sb.append("lastSpUniqueId ").append(UniqueIdGenerator.toShortString(m_lastSpUniqueId)).append(" "); sb.append("lastMpUniqueId ").append(UniqueIdGenerator.toShortString(m_lastMpUniqueId)).append(" "); for (Range<Long> entry : m_map.asRanges()) { sb.append("[").append(start(entry)).append("(").append(DRLogSegmentId.getSequenceNumberFromDRId(start(entry))).append("), ") .append(end(entry)).append("(").append(DRLogSegmentId.getSequenceNumberFromDRId(end(entry))).append(")] "); } return sb.toString(); }

Target:
public String toString() { if (m_map.isEmpty()) { return "Empty Map"; } StringBuilder sb = new StringBuilder(); sb.append("lastSpUniqueId ").append(UniqueIdGenerator.toShortString(m_lastSpUniqueId)).append(" "); sb.append("lastMpUniqueId ").append(UniqueIdGenerator.toShortString(m_lastMpUniqueId)).append(" "); for (Range<Long> entry : m_map.asRanges()) { sb.append("[").append(DRLogSegmentId.getDebugStringFromDRId(start(entry))).append(", ") .append(DRLogSegmentId.getDebugStringFromDRId(end(entry))).append("] "); } return sb.toString(); }
Source:
public InMemoryMessageIdProvider(final NetworkConfig config) { if (config == null) { throw new NullPointerException("Config must not be null"); } String textualMode = null; TrackerMode mode = TrackerMode.GROUPED; try { textualMode = config.getString(NetworkConfig.Keys.MID_TRACKER); mode = TrackerMode.valueOf(textualMode); } catch (Throwable t) { if (null == textualMode) { throw new IllegalArgumentException("Tracker mode unknown!"); } else { throw new IllegalArgumentException("Tracker mode '" + textualMode + "' not supported!"); } } this.mode = mode; this.exchangeLifetimeMillis = config.getLong(NetworkConfig.Keys.EXCHANGE_LIFETIME); this.midGroups = config.getInt(NetworkConfig.Keys.MID_TRACKER_GROUPS); if (config.getBoolean(NetworkConfig.Keys.USE_RANDOM_MID_START)) { random = new Random(System.currentTimeMillis()); } else { random = null; } trackers = new LeastRecentlyUsedCache<>(config.getInt(NetworkConfig.Keys.MAX_ACTIVE_PEERS, 150000), config.getLong(NetworkConfig.Keys.MAX_PEER_INACTIVITY_PERIOD, 10 * 60)); }

Target:
public InMemoryMessageIdProvider(final NetworkConfig config) { if (config == null) { throw new NullPointerException("Config must not be null"); } String textualMode = null; TrackerMode mode = TrackerMode.GROUPED; try { textualMode = config.getString(NetworkConfig.Keys.MID_TRACKER); mode = TrackerMode.valueOf(textualMode); } catch (IllegalArgumentException e) { throw new IllegalArgumentException("Tracker mode '" + textualMode + "' not supported!"); } catch (NullPointerException e) { throw new IllegalArgumentException("Tracker mode not provided/configured!"); } this.config = config; this.mode = mode; if (config.getBoolean(NetworkConfig.Keys.USE_RANDOM_MID_START)) { random = new Random(System.currentTimeMillis()); } else { random = null; } trackers = new LeastRecentlyUsedCache<>(config.getInt(NetworkConfig.Keys.MAX_ACTIVE_PEERS, 150000), config.getLong(NetworkConfig.Keys.MAX_PEER_INACTIVITY_PERIOD, 10 * 60)); }
Source:
public static PythonVersion fromString(String propertyValue) { String[] intervals = propertyValue.split(","); if (intervals.length > 2) { LOG.warn(String.format("Error while parsing value of parameter '%s' (%s). Only two intervals are supported (e.g. >= 3.6, < 3.8).", PYTHON_VERSION_KEY, propertyValue)); return PythonVersion.allVersions(); } PythonVersion pythonVersion = new PythonVersion(); for (String interval : intervals) { Matcher matcher = PATTERN.matcher(interval); if (!matcher.find()) { LOG.warn( String.format( Locale.ROOT, "Error while parsing value of parameter '%s' (%s). Versions must be between %.1f and %.1f.", PYTHON_VERSION_KEY, propertyValue, MIN_VERSION, MAX_VERSION)); return PythonVersion.allVersions(); } String operator = matcher.group(1); Double version = getVersion(matcher.group(2)); if (version != null) { pythonVersion.setMinAndMaxVersion(operator, version); } else { return PythonVersion.allVersions(); } } return pythonVersion; }

Target:
public static PythonVersion fromString(String propertyValue) { String[] intervals = propertyValue.split(","); if (intervals.length > 2) { LOG.warn(String.format("Error while parsing value of parameter '%s' (%s). Only two intervals are supported (e.g. >= 3.6, < 3.8).", PYTHON_VERSION_KEY, propertyValue)); return PythonVersion.allVersions(); } PythonVersion pythonVersion = new PythonVersion(); pythonVersion.minVersion = MIN_VALUE; pythonVersion.maxVersion = MAX_VALUE; for (String interval : intervals) { Matcher matcher = PATTERN.matcher(interval); if (!matcher.find()) { LOG.warn(String.format(Locale.ROOT, parseErrorMessage(propertyValue.trim()), PYTHON_VERSION_KEY, propertyValue, MIN_VERSION, MAX_VERSION)); return PythonVersion.allVersions(); } String operator = matcher.group(1); pythonVersion.setMinAndMaxVersion(operator, Double.parseDouble(matcher.group(2))); } if (pythonVersion.minVersion != MIN_VALUE && (pythonVersion.minVersion < MIN_VERSION || pythonVersion.minVersion > MAX_VERSION)) { LOG.warn(String.format(Locale.ROOT, "Python version range '%s' is not supported. Versions must be between %.1f and %.1f.", propertyValue, MIN_VERSION, MAX_VERSION)); return PythonVersion.allVersions(); } if (pythonVersion.maxVersion != MAX_VALUE && (pythonVersion.maxVersion > MAX_VERSION || pythonVersion.maxVersion < MIN_VERSION)) { LOG.warn(String.format(Locale.ROOT, "Python version range '%s' is not supported. Versions must be between %.1f and %.1f.", propertyValue, MIN_VERSION, MAX_VERSION)); return PythonVersion.allVersions(); } if (pythonVersion.minVersion > pythonVersion.maxVersion) { return PythonVersion.allVersions(); } pythonVersion.minVersion = max(pythonVersion.minVersion, MIN_VERSION); pythonVersion.maxVersion = min(pythonVersion.maxVersion, MAX_VERSION); return pythonVersion; }
Source:
public PhysicalOperation visitDistinctLimit(DistinctLimitNode node, LocalExecutionPlanContext context) { PhysicalOperation source = node.getSource().accept(this, context); Optional<Integer> hashChannel = node.getHashSymbol().map(channelGetter(source)); List<Integer> distinctChannels = getChannelsForSymbols(node.getDistinctSymbols(), source.getLayout()); OperatorFactory operatorFactory = new DistinctLimitOperatorFactory( context.getNextOperatorId(), node.getId(), source.getTypes(), distinctChannels, node.getLimit(), hashChannel, joinCompiler); return new PhysicalOperation(operatorFactory, makeLayout(node), source); }

Target:
public PhysicalOperation visitDistinctLimit(DistinctLimitNode node, LocalExecutionPlanContext context) { PhysicalOperation source = node.getSource().accept(this, context); Optional<Integer> hashChannel = node.getHashSymbol().map(channelGetter(source)); List<Integer> distinctChannels = getChannelsForSymbols(node.getDistinctSymbols(), source.getLayout()); OperatorFactory operatorFactory = new DistinctLimitOperatorFactory( context.getNextOperatorId(), node.getId(), source.getTypes(), distinctChannels, node.getLimit(), hashChannel, joinCompiler); return new PhysicalOperation(operatorFactory, makeLayout(node), context, source); }
Source:
public static FindDialog getDialog(Window parent, boolean modal) { if (getParentsList().containsKey(parent)) { FindDialog activeDialog = getParentsList().get(parent); activeDialog.getTxtFind().requestFocusInWindow(); return activeDialog; } return new FindDialog(parent, modal); }

Target:
public static FindDialog getDialog(Window parent, boolean modal) { FindDialog activeDialog = getParentsMap().get(parent); if (activeDialog != null) { activeDialog.getTxtFind().requestFocus(); return activeDialog; } FindDialog newDialog = new FindDialog(parent, modal); getParentsMap().put(parent, newDialog); newDialog.addWindowListener(new WindowAdapter() { @Override public void windowClosed(WindowEvent e) { getParentsMap().remove(parent); } }); return newDialog; }
Source:
public int size() { int waitingSplits = 0; for (PriorityQueue<PrioritizedSplitRunner> level : levelWaitingSplits) { waitingSplits += level.size(); } return waitingSplits; }

Target:
public int size() { lock.lock(); try { int total = 0; for (PriorityQueue<PrioritizedSplitRunner> level : levelWaitingSplits) { total += level.size(); } return total; } finally { lock.unlock(); } }
Source:
private void assertOutput(String path) throws IOException { File expectedOutput = copyFromResource(path, expectedSources); File actual = new File(outputSources, path); assertTrue("file does not exist. files: " + Arrays.toString(outputSources.listFiles()), actual.exists()); try { Truth.ASSERT.about(JAVA_SOURCE).that(expectedOutput) .isEquivalentTo(actual); } catch (AssertionError e) { throw new ComparisonFailure("", Files.toString(expectedOutput, UTF_8), Files.toString(actual, UTF_8)); } catch (RuntimeException e) { throw new ComparisonFailure("", Files.toString(expectedOutput, UTF_8), Files.toString(actual, UTF_8)); } }

Target:
private void assertOutput(String path) throws IOException { File expectedOutput = copyFromResource(path, expectedSources); File actual = new File(outputSources, path); assertTrue("file does not exist. files: " + Arrays.toString(outputSources.listFiles()), actual.exists()); try { ASSERT.about(JAVA_SOURCE).that(expectedOutput) .isEquivalentTo(actual); } catch (AssertionError e) { throw new ComparisonFailure("", Files.toString(expectedOutput, UTF_8), Files.toString(actual, UTF_8)); } catch (RuntimeException e) { throw new ComparisonFailure("", Files.toString(expectedOutput, UTF_8), Files.toString(actual, UTF_8)); } }
Source:
private Records<?> getFollowupsMissedClinicVisitsReport(GridSettings settings) { try { settings = DtoLookupHelper.changeLookupAndOrderForFollowupsMissedClinicVisitsReport(settings); if(settings == null) { return new Records<Object>(null); } Order order = null; if (StringUtils.isNotBlank(settings.getSortColumn())) { order = new Order(settings.getSortColumn(), settings.getSortDirection()); } QueryParams queryParams = new QueryParams(settings.getPage(), settings.getRows(), order); return lookupService.getEntities(MissedVisitsReportDto.class, Visit.class, settings.getLookup(), settings.getFields(), queryParams); } catch (IOException e) { LOGGER.error(e.getMessage(), e); return new Records<Object>(null); } }

Target:
private Records<?> getFollowupsMissedClinicVisitsReport(GridSettings settings) { try { settings = DtoLookupHelper.changeLookupAndOrderForFollowupsMissedClinicVisitsReport(settings); if(settings == null) { return new Records<Object>(null); } Order order = null; if (StringUtils.isNotBlank(settings.getSortColumn())) { order = new Order(settings.getSortColumn(), settings.getSortDirection()); } QueryParams queryParams = new QueryParams(settings.getPage(), settings.getRows(), order); return lookupService.getEntities(MissedVisitsReportDto.class, Visit.class, settings.getLookup(), settings.getFields(), queryParams); } catch (IOException | EbodacLookupException e) { LOGGER.error(e.getMessage(), e); return new Records<Object>(null); } }
Source:
public ConversationSendResponse sendMessage(ConversationSendRequest request) throws UnauthorizedException, GeneralException { String url = String.format("%s%s", this.conversationsBaseUrl, CONVERSATION_SEND_PATH); return messageBirdService.sendPayLoad(url, request, ConversationSendResponse.class); }

Target:
public ConversationSendResponse sendMessage(ConversationSendRequest request) throws UnauthorizedException, GeneralException { String url = String.format("%s%s", CONVERSATIONS_BASE_URL, CONVERSATION_SEND_PATH); return messageBirdService.sendPayLoad(url, request, ConversationSendResponse.class); }
Source:
private static HyperLogLogPlus decodeBytes(DataInput oi, int version) throws IOException { int p = Varint.readUnsignedVarInt(oi); int sp = Varint.readUnsignedVarInt(oi); int formatType = Varint.readUnsignedVarInt(oi); if (formatType == 0) { int storageType = 1; if (version < -2) storageType = Varint.readUnsignedVarInt(oi); int size = Varint.readUnsignedVarInt(oi); byte[] longArrayBytes = new byte[size]; oi.readFully(longArrayBytes); HyperLogLogPlus hyperLogLogPlus = new HyperLogLogPlus(p, sp, new RegisterSet(1 << p, Bits.getBits(longArrayBytes), RegisterSetStorage.Type.fromInt(storageType))); hyperLogLogPlus.format = Format.NORMAL; return hyperLogLogPlus; } else { int[] rehydratedSparseSet = new int[Varint.readUnsignedVarInt(oi)]; int prevDeltaRead = 0; for (int i = 0; i < rehydratedSparseSet.length; i++) { int nextVal = Varint.readUnsignedVarInt(oi) + prevDeltaRead; rehydratedSparseSet[i] = nextVal; prevDeltaRead = nextVal; } HyperLogLogPlus hyperLogLogPlus = new HyperLogLogPlus(p, sp, rehydratedSparseSet); hyperLogLogPlus.format = Format.SPARSE; return hyperLogLogPlus; } }

Target:
private static HyperLogLogPlus decodeBytes(DataInput oi, int version) throws IOException { int p = Varint.readUnsignedVarInt(oi); int sp = Varint.readUnsignedVarInt(oi); int formatType = Varint.readUnsignedVarInt(oi); if (formatType == 0) { boolean useDirect = false; if (version < -2) { useDirect = oi.readBoolean(); } int size = Varint.readUnsignedVarInt(oi); byte[] longArrayBytes = new byte[size]; oi.readFully(longArrayBytes); HyperLogLogPlus hyperLogLogPlus = new HyperLogLogPlus(p, sp, new RegisterSet(1 << p, Bits.getBits(longArrayBytes), useDirect)); hyperLogLogPlus.format = Format.NORMAL; return hyperLogLogPlus; } else { int[] rehydratedSparseSet = new int[Varint.readUnsignedVarInt(oi)]; int prevDeltaRead = 0; for (int i = 0; i < rehydratedSparseSet.length; i++) { int nextVal = Varint.readUnsignedVarInt(oi) + prevDeltaRead; rehydratedSparseSet[i] = nextVal; prevDeltaRead = nextVal; } HyperLogLogPlus hyperLogLogPlus = new HyperLogLogPlus(p, sp, rehydratedSparseSet); hyperLogLogPlus.format = Format.SPARSE; return hyperLogLogPlus; } }
Source:
public int getSlaveConnectTimeout() { return slaveConnectTimeout; }

Target:
public int getSlaveConnectTimeout() { if (slaveConnectTimeout == 0) return DEFAULT_SLAVE_JENKINS_CONNECTION_TIMEOUT; return slaveConnectTimeout; }
Source:
public ArrayList<SectionItemInterface> getRecentDownloadedVideosList() { ArrayList<SectionItemInterface> recentVideolist = new ArrayList<>(); ArrayList<EnrolledCoursesResponse> courseList = null; String username = getUsername(); if (username != null) { courseList = (ArrayList) api.getUserEnrolledCourses(username, true); } if (courseList != null || courseList.size() == 0) { for (final EnrolledCoursesResponse course : courseList) { List<VideoModel> videos = db.getSortedDownloadsByDownloadedDateForCourseId( course.getCourse().getId(), null); if (videos != null && videos.size() > 0) { recentVideolist.add(course); for (VideoModel videoModel : videos) { recentVideolist.add((SectionItemInterface) videoModel); } } } } return recentVideolist; }

Target:
public ArrayList<SectionItemInterface> getRecentDownloadedVideosList() { ArrayList<SectionItemInterface> recentVideolist = new ArrayList<>(); ArrayList<EnrolledCoursesResponse> courseList = null; String username = getUsername(); if (username != null) { courseList = (ArrayList) api.getUserEnrolledCourses(username, true); } if (courseList != null && !courseList.isEmpty()) { for (final EnrolledCoursesResponse course : courseList) { List<VideoModel> videos = db.getSortedDownloadsByDownloadedDateForCourseId( course.getCourse().getId(), null); if (videos != null && videos.size() > 0) { recentVideolist.add(course); for (VideoModel videoModel : videos) { recentVideolist.add((SectionItemInterface) videoModel); } } } } return recentVideolist; }
Source:
public String getContinuationToken() { return this.nextLink; }

Target:
public String getContinuationToken() { return this.continuationToken; }
Source:
public String getPath(String rootPath) { if (path == null) { return null; } boolean trailingSeparator = path.endsWith(File.separator); Path absolutePath = Paths.get(path); if (!absolutePath.isAbsolute()) { if (StringUtils.isNotBlank(rootPath)) { absolutePath = Paths.get(rootPath, path); } else { LOGGER.warn("Root path is blank. ", path, absolutePath.toAbsolutePath()); } } String absolutePathStr = absolutePath.toAbsolutePath().toString(); return trailingSeparator ? absolutePathStr + File.separator : absolutePathStr; }

Target:
public String getPath(String rootPath) { if (path == null) { return null; } boolean trailingSeparator = path.endsWith(File.separator); Path absolutePath = Paths.get(path); if (!absolutePath.isAbsolute()) { if (StringUtils.isNotBlank(rootPath)) { absolutePath = Paths.get(rootPath, path); } else { LOGGER.debug( "Root path is blank. Resolving relative path to: {}", path, absolutePath.toAbsolutePath()); } } String absolutePathStr = absolutePath.toAbsolutePath().toString(); return trailingSeparator ? absolutePathStr + File.separator : absolutePathStr; }
Source:
protected String getKeyForInstructor(String courseId, String instructorEmail) { return StringHelper.encrypt(getInstructor(courseId, instructorEmail).getKey()); }

Target:
protected String getKeyForInstructor(String courseId, String instructorEmail) { return getInstructor(courseId, instructorEmail).getKey(); }
Source:
public void checkPermission(AuthorizationConfiguration configuration, AuthorizationPermission perm) { if (globalConfiguration.authorization().enabled()) { if (Security.isPrivileged()) { Security.checkPermission(perm.getSecurityPermission()); } else { Subject subject = Security.getSubject(); try { if (subject != null) { int subjectMask = computeSubjectRoleMask(subject, configuration); if ((subjectMask & perm.getMask()) != perm.getMask()) { checkSecurityManagerPermission(perm); } else { if (audit != null) { audit.audit(subject, context, name, perm, AuditResponse.ALLOW); } } } else { checkSecurityManagerPermission(perm); } } catch (SecurityException e) { if (audit != null) { audit.audit(subject, context, name, perm, AuditResponse.DENY); } throw log.unauthorizedAccess(String.valueOf(subject), perm.toString()); } } } }

Target:
public void checkPermission(AuthorizationConfiguration configuration, AuthorizationPermission perm) { if (globalConfiguration.authorization().enabled()) { if (Security.isPrivileged()) { Security.checkPermission(perm.getSecurityPermission()); } else { Subject subject = Security.getSubject(); try { if (subject != null) { int subjectMask = computeSubjectRoleMask(subject, configuration); if ((subjectMask & perm.getMask()) != perm.getMask()) { checkSecurityManagerPermission(perm); } else { audit.audit(subject, context, name, perm, AuditResponse.ALLOW); } } else { checkSecurityManagerPermission(perm); } } catch (SecurityException e) { audit.audit(subject, context, name, perm, AuditResponse.DENY); throw log.unauthorizedAccess(String.valueOf(subject), perm.toString()); } } } }
Source:
public void onConfigurationChange(Configuration conf) { float originSlop = slop; float originOverallSlop = overallSlop; super.setConf(conf); LOG.info("Update configuration of SimpleLoadBalancer, previous slop is " + originSlop + ", current slop is " + slop + "previous overallSlop is" + originOverallSlop + ", current overallSlop is " + overallSlop); }

Target:
public void onConfigurationChange(Configuration conf) { float originSlop = slop; float originOverallSlop = overallSlop; super.setConf(conf); LOG.info("Update configuration of SimpleLoadBalancer, previous slop is {}," + " current slop is {}, previous overallSlop is {}, current overallSlop is {}", originSlop, slop, originOverallSlop, overallSlop); }
Source:
public synchronized void serviceStart() throws Exception { try { if (!getConfig().getBoolean( JHAdminConfig.MR_HISTORY_MINICLUSTER_FIXED_PORTS, JHAdminConfig.DEFAULT_MR_HISTORY_MINICLUSTER_FIXED_PORTS)) { String hostname = MiniYARNCluster.getHostname(); getConfig().set(JHAdminConfig.MR_HISTORY_ADDRESS, hostname + ":0"); MRWebAppUtil.setJHSWebappURLWithoutScheme(getConfig(), hostname + ":0"); getConfig().set(JHAdminConfig.JHS_ADMIN_ADDRESS, hostname + ":0"); } historyServer = new JobHistoryServer(); historyServer.init(getConfig()); new Thread() { public void run() { historyServer.start(); jhsStarted = true; }; }.start(); final int launchTimeout = getConfig().getInt( JHAdminConfig.MR_HISTORY_MINICLUSTER_LAUNCH_TIMEOUT_MS, JHAdminConfig.DEFAULT_MR_HISTORY_MINICLUSTER_LAUNCH_TIMEOUT_MS); GenericTestUtils.waitFor(() -> jhsStarted, 1500, launchTimeout); if (historyServer.getServiceState() != STATE.STARTED) { throw new IOException("HistoryServer failed to start"); } super.serviceStart(); } catch (Throwable t) { throw new YarnRuntimeException(t); } }

Target:
public synchronized void serviceStart() throws Exception { try { if (!getConfig().getBoolean( JHAdminConfig.MR_HISTORY_MINICLUSTER_FIXED_PORTS, JHAdminConfig.DEFAULT_MR_HISTORY_MINICLUSTER_FIXED_PORTS)) { String hostname = MiniYARNCluster.getHostname(); getConfig().set(JHAdminConfig.MR_HISTORY_ADDRESS, hostname + ":0"); MRWebAppUtil.setJHSWebappURLWithoutScheme(getConfig(), hostname + ":0"); getConfig().set(JHAdminConfig.JHS_ADMIN_ADDRESS, hostname + ":0"); } historyServer = new JobHistoryServer(); historyServer.init(getConfig()); new Thread() { public void run() { historyServer.start(); }; }.start(); final int launchTimeout = getConfig().getInt( MR_HISTORY_MINICLUSTER_LAUNCH_TIMEOUT_MS, 60_000); GenericTestUtils.waitFor( () -> historyServer.getServiceState() == STATE.STARTED || historyServer.getServiceState() == STATE.STOPPED, 100, launchTimeout); if (historyServer.getServiceState() != STATE.STARTED) { throw new IOException("HistoryServer failed to start"); } super.serviceStart(); } catch (Throwable t) { throw new YarnRuntimeException(t); } }
Source:
private String normalizeQName(QName qName) { return qName.toString().substring(1) .replace("}", "__") .replace("/", "") .replace(':', '_'); }

Target:
private String normalizeQName(QName qName) { return qName.toString() .replace("}", "") .replace("}", "__") .replace("/", "") .replace(':', '_'); }
Source:
public static double stXMax(@SqlType(GEOMETRY_TYPE_NAME) Slice input) { Envelope envelope = deserializeEnvelope(input); if (envelope == null) { return 0.0; } return envelope.getXMax(); }

Target:
public static Double stXMax(@SqlType(GEOMETRY_TYPE_NAME) Slice input) { Envelope envelope = deserializeEnvelope(input); if (envelope == null) { return null; } return envelope.getXMax(); }
Source:
public static void updateDocumentBy(Document doc, Patient patient) { doc.setPatientId(patient.getPatientIdentifierIso()); doc.setSourcePatientId(patient.getPatientIdentifierIso()); Personname personname = HelperUtil.lastItem(patient.getPersonnames()); if (personname != null) { doc.setPid5(MessageFormat.format("{0}^{1}^^^", personname.getLastName(), personname.getFirstName())); } Timestamp dateOfBirth = patient.getDateOfBirth(); { doc.setPid7(new SimpleDateFormat("yyyyMMdd").format(dateOfBirth)); } doc.setPid8(patient.getGender()); Address address = HelperUtil.lastItem(patient.getAddresses()); if (address != null) { doc.setPid11(MessageFormat.format("{0}^^{1}^{2}^{3}^", address.getStreet1(), address.getCity(), address.getState(), address.getPostal())); } if (HelperUtil.isId(patient.getPatientId())) { doc.setPatientRecordId(patient.getPatientId()); } }

Target:
public static void updateDocumentBy(Document doc, Patient patient) { doc.setPatientId(patient.getPatientIdentifierIso()); doc.setSourcePatientId(patient.getPatientIdentifierIso()); SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd"); Personname personname = HelperUtil.lastItem(patient.getPersonnames()); if (personname != null) { doc.setPid5(MessageFormat.format("{0}^{1}^^^", personname.getLastName(), personname.getFirstName())); } Timestamp dateOfBirth = patient.getDateOfBirth(); if (dateOfBirth != null) { doc.setPid7(sdf.format(dateOfBirth)); } doc.setPid8(patient.getGender()); Address address = HelperUtil.lastItem(patient.getAddresses()); if (address != null) { doc.setPid11(MessageFormat.format("{0}^^{1}^{2}^{3}^", address.getStreet1(), address.getCity(), address.getState(), address.getPostal())); } if (HelperUtil.isId(patient.getPatientId())) { doc.setPatientRecordId(patient.getPatientId()); } }
Source:
public void run() { started = true; if(!prepared) { logger.error("The StageRunner was not prepared prior to being started. Aborting!"); return; } if(stageGroup.getSize() < 1) { logger.info("Stage group "+stageGroup.getName() + " has no stages, and can not be started."); return; } do { logger.info("Starting stage group " + stageGroup.getName() + ". Times started so far: " + timesStarted); timesStarted++; boolean cleanShutdown = runGroup(); if (cleanShutdown) { return; } if (!hasQueried()) { logger.error("The stage group " + stageGroup.getName() + " did not start. It will not be restarted until configuration changes."); return; } } while (timesToRetry == -1 || timesToRetry >= timesStarted); logger.error("Stage group " + stageGroup.getName() + " has failed and cannot be restarted. "); }

Target:
public void run() { started = true; if (!prepared) { logger.error("The StageRunner was not prepared prior to being started. Aborting!"); return; } if (stageGroup.isEmpty()) { logger.info("Stage group " + stageGroup.getName() + " has no stages, and can not be started."); return; } do { logger.info("Starting stage group " + stageGroup.getName() + ". Times started so far: " + timesStarted); timesStarted++; boolean cleanShutdown = runGroup(); if (cleanShutdown) { return; } if (!hasQueried()) { logger.error("The stage group " + stageGroup.getName() + " did not start. It will not be restarted until configuration changes."); return; } } while (timesToRetry == -1 || timesToRetry >= timesStarted); logger.error("Stage group " + stageGroup.getName() + " has failed and cannot be restarted. "); }
Source:
public void handlesPersistentConnection() throws Exception { final int port = 8080; final String uri = String.format("http://localhost:%d", port); final int count = 1; final CountDownLatch completed = new CountDownLatch(count); final Take take = new Take() { @Override public Response act(final Request req) throws IOException { return new TkEmpty().act(req); } }; new Thread( new Runnable() { @Override public void run() { try { new FtBasic( new BkBasic(take), port ).start( new Exit() { @Override public boolean ready() { return completed.getCount() == 0; } } ); } catch (final IOException ex) { throw new IllegalStateException(ex); } } } ).start(); final HttpURLConnection conn = HttpURLConnection.class.cast( new URL(uri).openConnection() ); final String connection = "Connection"; final String keepAlive = "Keep-Alive"; conn.setRequestMethod("GET"); conn.setUseCaches(false); conn.setInstanceFollowRedirects(false); conn.addRequestProperty("Host", "localhost"); conn.addRequestProperty(connection, keepAlive); MatcherAssert.assertThat( conn.getHeaderFields(), Matchers.hasKey(connection) ); MatcherAssert.assertThat( conn.getHeaderFields().get(connection), Matchers.hasItem(keepAlive) ); completed.countDown(); completed.await(1L, TimeUnit.MILLISECONDS); MatcherAssert.assertThat(completed.getCount(), Matchers.equalTo(0L)); }

Target:
public void handlesPersistentConnection() throws Exception { final int port = 8080; final String uri = String.format("http://localhost:%d", port); final Take take = new Take() { @Override public Response act(final Request req) throws IOException { return new TkEmpty().act(req); } }; final Thread app = new Thread( new Runnable() { @Override public void run() { try { new FtBasic( new BkBasic(take), port ).start( Exit.NEVER ); } catch (final IOException ex) { throw new IllegalStateException(ex); } } } ); app.start(); Thread.sleep(BkBasicTest.WAIT_APP); final HttpURLConnection httpURLConnection = HttpURLConnection .class.cast( new URL(uri).openConnection() ); final String connection = "Connection"; final String keepAlive = "Keep-Alive"; httpURLConnection.setRequestMethod("GET"); httpURLConnection.setUseCaches(false); httpURLConnection.setInstanceFollowRedirects(false); httpURLConnection.addRequestProperty("Host", "localhost"); httpURLConnection.addRequestProperty(connection, keepAlive); MatcherAssert.assertThat( httpURLConnection.getHeaderFields().get(connection), Matchers.hasItem(keepAlive) ); app.interrupt(); }