auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
private boolean isSource(Block block) { if (isLiquid(block.getType())) { BlockData data = block.getBlockData(); if (data instanceof Levelled) { Levelled levelled = (Levelled) data; return levelled.getLevel() == 0; } } return false; }

Target:
private boolean isSource(Block block) { if (block.isLiquid()) { BlockData data = block.getBlockData(); if (data instanceof Levelled) { Levelled levelled = (Levelled) data; return levelled.getLevel() == 0; } } return false; }
Source:
public void setup() { createDirectoryForLeaderForEachClientUseCase(NAMESPACE_1); createDirectoryTimestampUseCase(NAMESPACE_2); createDirectoryTimestampUseCase(PaxosTimeLockConstants.LEADER_PAXOS_NAMESPACE); diskNamespaceLoader = new DiskNamespaceLoader(tempFolder.getRoot().toPath()); }

Target:
public void setup() { diskNamespaceLoader = new DiskNamespaceLoader(tempFolder.getRoot().toPath()); createDirectoryForLeaderForEachClientUseCase(NAMESPACE_1); createDirectoryInRootDataDirectory(NAMESPACE_2); }
Source:
public SetFacesToCull(int mode) { if (!modeNameMap.containsKey(mode)) { throw new IllegalArgumentException("Mode must be GL_BACK, GL_FRONT or GL_FRONT_AND_BACK."); } this.mode = mode; }

Target:
public SetFacesToCull(int mode) { if (mode == GL_BACK || mode == GL_FRONT || mode == GL_FRONT_AND_BACK) { this.mode = mode; } else { throw new IllegalArgumentException("Mode must be GL_BACK, GL_FRONT or GL_FRONT_AND_BACK."); } }
Source:
public static final int headerEnd(final byte[] b, int ptr) { final int sz = b.length; while (ptr < sz) { final byte c = b[ptr++]; if (c == '\n' && (ptr == sz || b[ptr] != ' ')) return ptr - 1; } return ptr - 1; }

Target:
public static final int headerEnd(final byte[] b, int ptr) { final int sz = b.length; while (ptr < sz) { final byte c = b[ptr++]; if (c == '\n' && (ptr == sz || b[ptr] != ' ')) { return ptr - 1; } } return ptr - 1; }
Source:
public Object downloadFile(@PathVariable("candidateId") Long candidateId, RedirectAttributes redirectAttrs) throws Exception { String cvFilename = candidateService.getCvFilenameById(candidateId); if (cvFilename != null && !cvFilename.isEmpty()) { try { File file = new File(uploadLocation + File.separator + cvFilename); InputStream inputStream = new BufferedInputStream(new FileInputStream(file)); InputStreamResource inputStreamResource = new InputStreamResource(inputStream); HttpHeaders responseHeaders = new HttpHeaders(); responseHeaders.set(CONTENT_DISPOSITION, String.format(INLINE_FORMAT + cvFilename + "\"")); responseHeaders.setContentType(MediaType.APPLICATION_OCTET_STREAM); responseHeaders.setContentLength(file.length()); return new ResponseEntity<>(inputStreamResource, responseHeaders, HttpStatus.OK); } catch (IOException e) { redirectAttrs.addFlashAttribute(FILE_ERROR_MESSAGE, FILE_ERROR_MESSAGE_KEY); } } else { redirectAttrs.addFlashAttribute(FILE_ERROR_MESSAGE, FILE_ERROR_MESSAGE_KEY); } return new ModelAndView(REDIRECT_CANDIDATE_PAGE + "/" + candidateId); }

Target:
public Object downloadFile(@PathVariable("candidateId") Long candidateId, RedirectAttributes redirectAttrs) throws Exception { CandidateDTO candidateDTO = candidateService.getCandidate(candidateId); String candidateCVFilename = candidateDTO.getCvFilename(); if (StringUtils.isNotBlank(candidateCVFilename)) { try { File file = candidateCVFileHandler .createCVFileFromFolderLocationAndCandidateDtoAndCVFilename(uploadLocation, candidateId, candidateCVFilename); if (!file.exists()) { throw new IOException(); } InputStream inputStream = new BufferedInputStream(new FileInputStream(file)); InputStreamResource inputStreamResource = new InputStreamResource(inputStream); HttpHeaders responseHeaders = new HttpHeaders(); responseHeaders.set(CONTENT_DISPOSITION, String.format(INLINE_FORMAT + candidateCVFilename)); responseHeaders.setContentType(MediaType.APPLICATION_OCTET_STREAM); responseHeaders.setContentLength(file.length()); return new ResponseEntity<>(inputStreamResource, responseHeaders, HttpStatus.OK); } catch (IOException e) { redirectAttrs.addFlashAttribute(FILE_ERROR_MESSAGE, FILE_ERROR_MESSAGE_KEY); } } else { redirectAttrs.addFlashAttribute(FILE_ERROR_MESSAGE, FILE_ERROR_MESSAGE_KEY); } return new ModelAndView(REDIRECT_CANDIDATE_PAGE + "/" + candidateId); }
Source:
public void testCorrectHeaderFormatWithoutInstanceId() { UserAgent baseUserAgent = UserAgent.of("service", "1.0.0"); assertThat(UserAgents.format(baseUserAgent)).isEqualTo("service (1.0.0)"); UserAgent derivedAgent = UserAgents.merge(baseUserAgent, UserAgent.of("remoting", "2.0.0")); assertThat(UserAgents.format(derivedAgent)).isEqualTo("service (1.0.0), remoting (2.0.0)"); }

Target:
public void testCorrectHeaderFormatWithoutInstanceId() { UserAgent baseUserAgent = UserAgent.of(UserAgent.Agent.of("service", "1.0.0")); assertThat(UserAgents.format(baseUserAgent)).isEqualTo("service (1.0.0)"); UserAgent derivedAgent = baseUserAgent.addAgent(UserAgent.Agent.of("remoting", "2.0.0")); assertThat(UserAgents.format(derivedAgent)).isEqualTo("service (1.0.0), remoting (2.0.0)"); }
Source:
public void return_default_values_map() { final NullToleranceTest.Builder builder = NullToleranceTest.newBuilder(); int expectedSize = 0; int actualSize = builder.getDefaultValues() .size(); assertEquals(expectedSize, actualSize); builder.addDefaultValue(0); builder.addDefaultValue('\u000f'); expectedSize = 2; actualSize = builder.getDefaultValues() .size(); assertEquals(expectedSize, actualSize); final Map<? super Class, ? super Object> expectedMap = newHashMap(); expectedMap.put(Integer.class, 0); expectedMap.put(Character.class, '\u000f'); assertEquals(expectedMap, builder.getDefaultValues()); }

Target:
public void return_default_values_map() { final NullToleranceTest.Builder builder = NullToleranceTest.newBuilder(); final int integerDefaultValue = 0; builder.addDefaultValue(integerDefaultValue); final int actualSize = builder.getDefaultValues() .size(); assertEquals(1, actualSize); final Map<? super Class, ? super Object> expectedMap = newHashMap(); expectedMap.put(Integer.class, integerDefaultValue); assertEquals(expectedMap, builder.getDefaultValues()); }
Source:
public void testCtfTmfTimestamp() { long timestamp = 1L; CtfTmfTimestamp result = new CtfTmfTimestamp(timestamp); assertNotNull(result); assertEquals("19:00:00.000 000 001", result.toString()); assertEquals(0, result.getPrecision()); assertEquals(-9, result.getScale()); assertEquals(1L, result.getValue()); }

Target:
public void testCtfTmfTimestamp() { long timestamp = 1L; DateFormat df = new SimpleDateFormat("HH:mm:ss.SSS"); Date d = new Date(timestamp / 1000000); CtfTmfTimestamp result = new CtfTmfTimestamp(timestamp); assertNotNull(result); assertEquals(df.format(d) + " 000 001", result.toString()); assertEquals(0, result.getPrecision()); assertEquals(-9, result.getScale()); assertEquals(1L, result.getValue()); }
Source:
public void testOkWithResource() throws Exception { assertEquals("No warnings.", lintProject(xml("AndroidManifest.xml", "" + "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n" + "<manifest xmlns:android=\"<LINK_0>\"\n" + " package=\"com.example.helloworld\" >\n" + "\n" + " <application\n" + " android:allowBackup=\"true\"\n" + " android:icon=\"@mipmap/ic_launcher\"\n" + " android:label=\"@string/app_name\"\n" + " android:theme=\"@style/AppTheme\" >\n" + " <activity\n" + " android:name=\".FullscreenActivity\"\n" + " android:configChanges=\"orientation|keyboardHidden|screenSize\"\n" + " android:label=\"@string/title_activity_fullscreen\"\n" + " android:theme=\"@style/FullscreenTheme\" >\n" + " <intent-filter android:label=\"@string/title_activity_fullscreen\">\n" + " <action android:name=\"android.intent.action.VIEW\" />\n" + " <data android:scheme=\"http\"\n" + " android:host=\"example.com\"\n" + " android:pathPrefix=\"@string/path_prefix\"\n" + " android:port=\"@string/port\"/>\n" + " <category android:name=\"android.intent.category.DEFAULT\" />\n" + " <category android:name=\"android.intent.category.BROWSABLE\" />\n" + " </intent-filter>\n" + " </activity>\n" + " </application>\n" + "\n" + "</manifest>\n"), xml("res/values/strings.xml", "" + "<resources>\n" + " <string name=\"path_prefix\">/gizmos</string>\n" + " <string name=\"port\">8080</string>\n" + "</resources>\n"))); }

Target:
public void testOkWithResource() throws Exception { assertEquals("No warnings.", lintProjectIncrementally( "AndroidManifest.xml", "appindexing_manifest.xml=>AndroidManifest.xml", "res/values/appindexing_strings.xml")); }
Source:
public WrappingFileHandle( File file, File baseDirectory, FileSystemAbstraction fs ) { this.file = file; this.baseDirectory = baseDirectory; this.fs = fs; }

Target:
WrappingFileHandle( File file, File baseDirectory, FileSystemAbstraction fs ) { this.file = file; this.baseDirectory = baseDirectory; this.fs = fs; }
Source:
private void rollbackTest(boolean killTransactor) throws Exception { Transactor t1 = new Transactor(config); TestTransaction tx = new TestTransaction(config); tx.mutate().row("bob").col(balanceCol).set("10"); tx.mutate().row("joe").col(balanceCol).set("20"); tx.mutate().row("jill").col(balanceCol).set("60"); tx.commit(); TestTransaction tx2 = new TestTransaction(config, t1); int bal1 = Integer.parseInt(tx2.get().row("bob").col(balanceCol).toString()); int bal2 = Integer.parseInt(tx2.get().row("joe").col(balanceCol).toString()); tx2.mutate().row("bob").col(balanceCol).set("" + (bal1 - 7)); tx2.mutate().row("joe").col(balanceCol).set("" + (bal2 + 7)); CommitData cd = tx2.createCommitData(); Assert.assertTrue(tx2.preCommit(cd)); if (killTransactor) { t1.close(); } TransactionImpl tx3 = new TransactionImpl(config); Assert.assertEquals(0, tx3.getStats().getDeadRollbacks()); Assert.assertEquals(0, tx3.getStats().getTimeoutRollbacks()); int bobFinal = Integer.parseInt(tx3.get(new ArrayByteSequence("bob"), balanceCol).toString()); Assert.assertEquals(10, bobFinal); if (killTransactor) { Assert.assertEquals(1, tx3.getStats().getDeadRollbacks()); Assert.assertEquals(0, tx3.getStats().getTimeoutRollbacks()); } else { Assert.assertEquals(0, tx3.getStats().getDeadRollbacks()); Assert.assertEquals(1, tx3.getStats().getTimeoutRollbacks()); } if (!killTransactor) { t1.close(); } }

Target:
private void rollbackTest(boolean killTransactor) throws Exception { TransactorID t1 = new TransactorID(config); TestTransaction tx = new TestTransaction(config); tx.mutate().row("bob").col(balanceCol).set("10"); tx.mutate().row("joe").col(balanceCol).set("20"); tx.mutate().row("jill").col(balanceCol).set("60"); tx.commit(); TestTransaction tx2 = new TestTransaction(config, t1); int bal1 = tx2.get().row("bob").col(balanceCol).toInteger(); int bal2 = tx2.get().row("joe").col(balanceCol).toInteger(); tx2.mutate().row("bob").col(balanceCol).set(bal1 - 7); tx2.mutate().row("joe").col(balanceCol).set(bal2 + 7); CommitData cd = tx2.createCommitData(); Assert.assertTrue(tx2.preCommit(cd)); if (killTransactor) { t1.close(); } TransactionImpl tx3 = new TransactionImpl(config); Assert.assertEquals(0, tx3.getStats().getDeadLocks()); Assert.assertEquals(0, tx3.getStats().getTimedOutLocks()); int bobFinal = Integer.parseInt(tx3.get(new ArrayByteSequence("bob"), balanceCol).toString()); Assert.assertEquals(10, bobFinal); if (killTransactor) { Assert.assertEquals(1, tx3.getStats().getDeadLocks()); Assert.assertEquals(0, tx3.getStats().getTimedOutLocks()); } else { Assert.assertEquals(0, tx3.getStats().getDeadLocks()); Assert.assertEquals(1, tx3.getStats().getTimedOutLocks()); } long commitTs = OracleClient.getInstance(config).getTimestamp(); if (killTransactor) { exception.expect(IllegalStateException.class); tx2.commitPrimaryColumn(cd, commitTs); } else { Assert.assertFalse(tx2.commitPrimaryColumn(cd, commitTs)); t1.close(); } }
Source:
public void upgrade() { final VDS host = getSelectedItem(); Model model; if (host.getVdsType() == VDSType.oVirtNode) { model = new UpgradeModel(host); } else { model = new UpgradeConfirmationModel(host); } setWindow(model); model.initialize(); model.getCommands().add(UICommand.createCancelUiCommand("Cancel", this)); }

Target:
public void upgrade() { final VDS host = getSelectedItem(); Model model = createUpgradeModel(host); setWindow(model); model.initialize(); model.getCommands().add(UICommand.createCancelUiCommand("Cancel", this)); }
Source:
OneMeasurement constructOneMeasurement(String name) { switch (_measurementType) { case HISTOGRAM: return new OneMeasurementHistogram(name, _props); case HDRHISTOGRAM: return new OneMeasurementHdrHistogram(name, _props); case HDRHISTOGRAM_AND_HISTOGRAM: return new TwoInOneMeasurement(name, new OneMeasurementHdrHistogram("Hdr"+name, _props), new OneMeasurementHistogram("Bucket"+name, _props)); case HDRHISTOGRAM_AND_RAW: return new TwoInOneMeasurement(name, new OneMeasurementHdrHistogram("Hdr"+name, _props), new OneMeasurementHistogram("Raw"+name, _props)); case HDRHISTOGRAM_AND_PERIODICHISTOGRAM: return new TwoInOneMeasurement(name, new OneMeasurementHdrHistogram("Hdr"+name, _props), new PeriodicHistogram(name, _props)); case PERIODICHISTOGRAM: return new PeriodicHistogram(name, _props); case TIMESERIES: return new OneMeasurementTimeSeries(name, _props); case RAW: return new OneMeasurementRaw(name, _props); default: throw new AssertionError("Impossible to be here. Dead code reached. Bugs?"); } }

Target:
OneMeasurement constructOneMeasurement(String name) { switch (_measurementType) { case HISTOGRAM: return new OneMeasurementHistogram(name, _props); case HDRHISTOGRAM: return new OneMeasurementHdrHistogram(name, _props); case HDRHISTOGRAM_AND_HISTOGRAM: return new TwoInOneMeasurement(name, new OneMeasurementHdrHistogram("Hdr"+name, _props), new OneMeasurementHistogram("Bucket"+name, _props)); case HDRHISTOGRAM_AND_RAW: return new TwoInOneMeasurement(name, new OneMeasurementHdrHistogram("Hdr"+name, _props), new OneMeasurementRaw("Raw"+name, _props)); case HDRHISTOGRAM_AND_PERIODICHISTOGRAM: return new TwoInOneMeasurement(name, new OneMeasurementHdrHistogram("Hdr"+name, _props), new PeriodicHistogram(name, _props)); case PERIODICHISTOGRAM: return new PeriodicHistogram(name, _props); case TIMESERIES: return new OneMeasurementTimeSeries(name, _props); case RAW: return new OneMeasurementRaw(name, _props); default: throw new AssertionError("Impossible to be here. Dead code reached. Bugs?"); } }
Source:
protected void failWithCustomSubject(String verb, Object expected, Object actual) { StringBuilder message = new StringBuilder("Not true that "); message.append((actual == null) ? "null reference" : actual).append(" ").append(verb); failureStrategy.fail(message.toString()); }

Target:
protected void failWithCustomSubject(String verb, Object expected, Object actual) { String message = String.format("Not true that <%s> %s <%s>", ((actual == null) ? "null reference" : actual), verb, expected); failureStrategy.fail(message); }
Source:
private void redirectToAuthorization(DeviceAuthorizationCacheControl cacheData) { try { log.info("Redirecting to authorization code flow to process device authorization, data: {}", cacheData); String authorizationEndpoint = appConfiguration.getAuthorizationEndpoint(); String clientId = cacheData.getClient().getClientId(); String responseType = "code"; String scope = Util.listAsString(cacheData.getScopes()); String state = UUID.randomUUID().toString(); String nonce = UUID.randomUUID().toString(); RedirectUri authRequest = new RedirectUri(authorizationEndpoint); authRequest.addResponseParameter(CLIENT_ID, clientId); authRequest.addResponseParameter(RESPONSE_TYPE, responseType); authRequest.addResponseParameter(SCOPE, scope); authRequest.addResponseParameter(STATE, state); authRequest.addResponseParameter(NONCE, nonce); authRequest.addResponseParameter(USER_CODE, cacheData.getUserCode()); FacesContext.getCurrentInstance().getExternalContext().redirect(authRequest.toString()); } catch (IOException e) { log.error("Problems trying to redirect to authorization page from device authorization action", e); String message = languageBean.getMessage("error.errorEncountered"); facesMessages.add(FacesMessage.SEVERITY_WARN, message); } catch (Exception e) { log.error("Exception processing redirection", e); String message = languageBean.getMessage("error.errorEncountered"); facesMessages.add(FacesMessage.SEVERITY_WARN, message); } }

Target:
private void redirectToAuthorization(DeviceAuthorizationCacheControl cacheData) { try { log.info("Redirecting to authorization code flow to process device authorization, data: {}", cacheData); String authorizationEndpoint = appConfiguration.getAuthorizationEndpoint(); String clientId = cacheData.getClient().getClientId(); String responseType = appConfiguration.getDeviceAuthzResponseTypeToProcessAuthz(); String scope = Util.listAsString(cacheData.getScopes()); String state = UUID.randomUUID().toString(); String nonce = UUID.randomUUID().toString(); RedirectUri authRequest = new RedirectUri(authorizationEndpoint); authRequest.addResponseParameter(CLIENT_ID, clientId); authRequest.addResponseParameter(RESPONSE_TYPE, responseType); authRequest.addResponseParameter(SCOPE, scope); authRequest.addResponseParameter(STATE, state); authRequest.addResponseParameter(NONCE, nonce); FacesContext.getCurrentInstance().getExternalContext().redirect(authRequest.toString()); } catch (IOException e) { log.error("Problems trying to redirect to authorization page from device authorization action", e); String message = languageBean.getMessage("error.errorEncountered"); facesMessages.add(FacesMessage.SEVERITY_WARN, message); } catch (Exception e) { log.error("Exception processing redirection", e); String message = languageBean.getMessage("error.errorEncountered"); facesMessages.add(FacesMessage.SEVERITY_WARN, message); } }
Source:
public void doCreateAccount(@NonNull String token) { progressDialog.show(); String email = null; if (emailEdit.getText().length() != 0) { email = emailEdit.getText().toString(); } String password = passwordEdit.getText().toString(); String repeat = passwordInput.isPasswordVisible() ? password : passwordRepeatEdit.getText().toString(); createAccountClient.request(wiki, usernameEdit.getText().toString(), password, repeat, token, email, captchaHandler.isActive() ? captchaHandler.captchaId() : "null", captchaHandler.isActive() ? captchaHandler.captchaWord() : "null", new CreateAccountClient.Callback() { @Override public void success(@NonNull Call<CreateAccountResponse> call, @NonNull final CreateAccountSuccessResult result) { if (!progressDialog.isShowing()) { return; } getUserId(new UserIdCallback() { @Override public void success(@NonNull Call<MwQueryResponse<UserIdClient.QueryUserInfo>> call, int userId) { finishWithUserResult(result, userId); } @Override public void failure(@NonNull Call<MwQueryResponse<UserIdClient.QueryUserInfo>> call, @NonNull Throwable caught) { finishWithUserResult(result, 0); L.e("Failed to obtain new user ID", caught); } }); } @Override public void failure(@NonNull Call<CreateAccountResponse> call, @NonNull Throwable caught) { L.e(caught.toString()); if (!progressDialog.isShowing()) { return; } progressDialog.dismiss(); FeedbackUtil.showError(CreateAccountActivity.this, caught); } }); }

Target:
public void doCreateAccount(@NonNull String token) { progressDialog.show(); String email = null; if (emailEdit.getText().length() != 0) { email = emailEdit.getText().toString(); } String password = passwordEdit.getText().toString(); String repeat = passwordInput.isPasswordVisible() ? password : passwordRepeatEdit.getText().toString(); createAccountClient.request(wiki, usernameEdit.getText().toString(), password, repeat, token, email, captchaHandler.isActive() ? captchaHandler.captchaId() : "null", captchaHandler.isActive() ? captchaHandler.captchaWord() : "null", new CreateAccountClient.Callback() { @Override public void success(@NonNull Call<CreateAccountResponse> call, @NonNull final CreateAccountSuccessResult result) { if (!progressDialog.isShowing()) { return; } finishWithUserResult(result); } @Override public void failure(@NonNull Call<CreateAccountResponse> call, @NonNull Throwable caught) { L.e(caught.toString()); if (!progressDialog.isShowing()) { return; } progressDialog.dismiss(); FeedbackUtil.showError(CreateAccountActivity.this, caught); } }); }
Source:
private String getRefererHeaderUrl() { if (backStack.size() > 0) { PageBackStackItem item = backStack.get(backStack.size() - 1); if (item.getHistoryEntry().getSource() == HistoryEntry.SOURCE_INTERNAL_LINK && fragment.isRefererHeaderUrlEnabled()) { fragment.setRefererHeaderUrlEnabled(false); return item.getHistoryEntry().getTitle().getCanonicalUri(); } } return null; }

Target:
private String getRefererHeaderUrl() { if (backStack.size() > 0) { if (fragment.isRefererHeaderUrlAvailable(model.getTitle()) && backStack.get(backStack.size() - 1).getHistoryEntry().getSource() == HistoryEntry.SOURCE_INTERNAL_LINK) { return fragment.getRefererHeaderPage(model.getTitle()).getCanonicalUri(); } } return null; }
Source:
public void testBoolFromFunction() throws ParseException { JSONObject object = MapboxTestUtils.object("{'expr': { 'base': 1, 'stops': [ [ 0, true ], [ 10, true ], [ 22, true ] ] }}"); Expression expression = parser.string(object, "expr", "name"); assertTrue("Parse result must be a function", Function.class.isAssignableFrom(expression.getClass())); }

Target:
public void testBoolFromFunction() throws ParseException { JSONObject object = MapboxTestUtils.object("{'expr': { 'base': 1, 'stops': [ [ 0, true ], [ 10, true ], [ 22, true ] ] }}"); Expression expression = parser.bool(object, "expr", true); assertTrue("Parse result must be a function", Function.class.isAssignableFrom(expression.getClass())); }
Source:
protected void startInner() throws VoldemortException { JNAUtils.tryMlockall(); logger.info("Starting " + basicServices.size() + " services."); long start = System.currentTimeMillis(); boolean goOnline; if (getMetadataStore().getServerStateUnlocked() == MetadataStore.VoldemortState.NORMAL_SERVER) goOnline = true; else if (getMetadataStore().getServerStateUnlocked() == MetadataStore.VoldemortState.OFFLINE_SERVER) goOnline = false; else throw new VoldemortException("Invalid Server state. Neither online nor offline found"); for(VoldemortService service: basicServices) { try { service.start(); } catch (DisabledStoreException e) { logger.error("Got a DisabledStoreException from " + service.getType().getDisplayName(), e); goOnline = false; } } if (goOnline) { startOnlineServices(); } else { goOffline(); } long end = System.currentTimeMillis(); logger.info("Startup completed in " + (end - start) + " ms."); }

Target:
protected void startInner() throws VoldemortException { JNAUtils.tryMlockall(); logger.info("Starting " + basicServices.size() + " services."); long start = System.currentTimeMillis(); boolean goOnline; if (getMetadataStore().getServerStateUnlocked() == MetadataStore.VoldemortState.OFFLINE_SERVER) goOnline = false; else goOnline = true; for(VoldemortService service: basicServices) { try { service.start(); } catch (DisabledStoreException e) { logger.error("Got a DisabledStoreException from " + service.getType().getDisplayName(), e); goOnline = false; } } if (goOnline) { startOnlineServices(); } else { goOffline(); } long end = System.currentTimeMillis(); logger.info("Startup completed in " + (end - start) + " ms."); }
Source:
protected void doStart() { try { server.start().await(); } catch(InterruptedException e) { Thread.currentThread().interrupt(); } }

Target:
protected void doStart() { try { Assert.notNull(server.start().await(), "Server did not start properly"); } catch(InterruptedException e) { Thread.currentThread().interrupt(); } }
Source:
private MultiServerRetryInterceptor(List<String> uris) { this.uris = uris; }

Target:
private MultiServerRetryInterceptor(List<String> uris) { this.uris = ImmutableList.copyOf(uris); }
Source:
public static OSGIUtil getInstance() { if (instance == null) { instance = new OSGIUtil(Config.CONTEXT); } return instance; }

Target:
public static OSGIUtil getInstance() { return OSGIUtilHolder.instance; }
Source:
public void createTable(HTableDescriptor desc) throws IOException { CreateTableRequest.Builder builder = CreateTableRequest.newBuilder(); clusterMetadataSetter.setMetadata(builder); builder.setTableId(desc.getTableName().getQualifierAsString()); builder.setTable(tableAdapter.adapt(desc)); try { bigtableAdminClient.createTable(builder.build()); } catch (Throwable throwable) { throwable.printStackTrace(); throw new IOException( String.format( "Failed to create table '%s'", desc.getTableName().getNameAsString()), throwable); } }

Target:
public void createTable(HTableDescriptor desc) throws IOException { CreateTableRequest.Builder builder = CreateTableRequest.newBuilder(); clusterMetadataSetter.setMetadata(builder); builder.setTableId(desc.getTableName().getQualifierAsString()); builder.setTable(tableAdapter.adapt(desc)); try { bigtableAdminClient.createTable(builder.build()); } catch (Throwable throwable) { throw new IOException( String.format( "Failed to create table '%s'", desc.getTableName().getNameAsString()), throwable); } }
Source:
public JAXBModule() { this.jaxbContextFactory = defaultJAXBContextFactory(); }

Target:
public JAXBModule() { this.jaxbContextFactory = new JAXBContextFactory.Builder().build(); }
Source:
private static Optional<Path> findWebInfParentDirectory(FileSystem fs) { FilePredicates predicates = fs.predicates(); ArrayList<InputFile> inputFiles = new ArrayList<>(); fs.inputFiles(predicates.matchesPathPattern("**/WEB-INF/**")).forEach(inputFiles::add); if (!inputFiles.isEmpty()) { Path path = Paths.get(inputFiles.get(0).absolutePath()); Path parent = path.getParent(); while (parent != null) { if (parent.endsWith("WEB-INF")) { return Optional.ofNullable(parent.getParent()); } parent = parent.getParent(); } } LOG.debug("WEB-INF directory not found, will use basedir as context root"); return Optional.empty(); }

Target:
private static Optional<Path> findWebInfParentDirectory(FileSystem fs) { FilePredicates predicates = fs.predicates(); List<InputFile> inputFiles = new ArrayList<>(); fs.inputFiles(predicates.matchesPathPattern("**/WEB-INF/**")).forEach(inputFiles::add); if (!inputFiles.isEmpty()) { Path path = Paths.get(inputFiles.get(0).absolutePath()); Path parent = path.getParent(); while (parent != null) { if (parent.endsWith("WEB-INF")) { return Optional.ofNullable(parent.getParent()); } parent = parent.getParent(); } } LOG.debug("WEB-INF directory not found, will use basedir as context root"); return Optional.empty(); }
Source:
private final boolean isValidFile(LocatedFileStatus fileStatus) { if (fileStatus.isFile()) { if (whitelistRegexp!=null) { return Pattern.matches(whitelistRegexp, fileStatus.getPath().getName()); } else { return true; } } return false; }

Target:
private final boolean isValidFile(LocatedFileStatus fileStatus) { if (fileStatus.isFile()) { return WHITELIST_REGEXP.matcher(fileStatus.getPath().getName()).matches(); } else { return false; } }
Source:
private String externalChildSensorName(final String threadId, final String operationName, final String entityName) { return "external" + SENSOR_PREFIX_DELIMITER + threadId + SENSOR_PREFIX_DELIMITER + "entity" + SENSOR_PREFIX_DELIMITER + entityName + SENSOR_NAME_DELIMITER + operationName; }

Target:
private String externalChildSensorName(final String threadId, final String operationName, final String entityName) { return SENSOR_EXTERNAL_LABEL + SENSOR_PREFIX_DELIMITER + threadId + SENSOR_PREFIX_DELIMITER + SENSOR_ENTITY_LABEL + SENSOR_PREFIX_DELIMITER + entityName + SENSOR_NAME_DELIMITER + operationName; }
Source:
public JolieServiceLoader( String code, Expression channelDest, Interpreter currInterpreter ) throws IOException { super( channelDest ); InterpreterParameters interpreterParameters = new InterpreterParameters( currInterpreter.optionArgs(), currInterpreter.getInterpreterParameters().includePaths(), currInterpreter.getInterpreterParameters().libUrls(), new File( "#native_code" ), currInterpreter.getClassLoader(), new ByteArrayInputStream( code.getBytes() ) ); interpreter = new Interpreter( currInterpreter.getClassLoader(), interpreterParameters, currInterpreter.programDirectory() ); }

Target:
public JolieServiceLoader( String code, Expression channelDest, Interpreter currInterpreter ) throws IOException { super( channelDest ); InterpreterParameters interpreterParameters = new InterpreterParameters( currInterpreter.optionArgs(), currInterpreter.getInterpreterParameters().includePaths(), currInterpreter.getInterpreterParameters().libUrls(), new File( "#native_code_" + serviceLoaderCounter.getAndIncrement() ), currInterpreter.getClassLoader(), new ByteArrayInputStream( code.getBytes() ) ); interpreter = new Interpreter( currInterpreter.getClassLoader(), interpreterParameters, currInterpreter.programDirectory() ); }
Source:
public SetInputTextureFromFbo(int textureSlot, SimpleUri fboUri, FboTexturesTypes textureType, BaseFBOsManager fboManager, ResourceUrn materialUrn, String shaderParameterName) { this.textureSlot = textureSlot; this.textureType = textureType; this.fbo = fboManager.get(fboUri); this.materialUrn = materialUrn; this.shaderParameterName = shaderParameterName; this.material = getMaterial(materialUrn); propertyChange(null); fboManager.subscribe(this); }

Target:
public SetInputTextureFromFbo(int textureSlot, SimpleUri fboUri, FboTexturesTypes textureType, BaseFBOsManager fboManager, ResourceUrn materialUrn, String shaderParameterName) { this(textureSlot, fboManager.get(fboUri), textureType, fboManager, materialUrn, shaderParameterName); }
Source:
public boolean entityInteract(GlowPlayer player, InteractEntityMessage message) { if (!super.entityInteract(player, message) && message.getAction() == InteractEntityMessage.Action.INTERACT.ordinal()) { ItemStack item = InventoryUtil .itemOrEmpty(player.getInventory().getItem(message.getHandSlot())); int growthAmount = computeGrowthAmount(item.getType()); if (item.getType() == Material.MONSTER_EGG && item.hasItemMeta()) { GlowMetaSpawn meta = (GlowMetaSpawn) item.getItemMeta(); if (meta.hasSpawnedType() && meta.getSpawnedType() == this.getType()) { this.createBaby(); if (player.getGameMode() == GameMode.SURVIVAL || player.getGameMode() == GameMode.ADVENTURE) { player.getInventory().consumeItemInMainHand(); } return true; } } else if (growthAmount > 0) { grow(growthAmount); player.getInventory().consumeItemInMainHand(); return true; } } return false; }

Target:
public boolean entityInteract(GlowPlayer player, InteractEntityMessage message) { if (!super.entityInteract(player, message) && message.getAction() == InteractEntityMessage.Action.INTERACT.ordinal()) { ItemStack item = InventoryUtil .itemOrEmpty(player.getInventory().getItem(message.getHandSlot())); int growthAmount = computeGrowthAmount(item.getType()); if (item.getType() == Material.MONSTER_EGG && item.hasItemMeta()) { GlowMetaSpawn meta = (GlowMetaSpawn) item.getItemMeta(); if (meta.hasSpawnedType() && meta.getSpawnedType() == this.getType()) { this.createBaby(); if (player.getGameMode() == GameMode.SURVIVAL || player.getGameMode() == GameMode.ADVENTURE) { player.getInventory().consumeItem(message.getHand()); } return true; } } else if (growthAmount > 0) { grow(growthAmount); player.getInventory().consumeItem(message.getHand()); return true; } } return false; }
Source:
private void shutdown() { try { LOG.info("Starting to close KafkaConsumer."); kafkaConsumer.close(); LOG.info("Successfully closed KafkaConsumer."); } catch (Exception e) { LOG.error("An error occurred while closing KafkaConsumer!", e); } finally { shutdownLatch.countDown(); } }

Target:
private void shutdown() { try { LOG.debug("Starting to close KafkaConsumer."); kafkaConsumer.close(); LOG.debug("Successfully closed KafkaConsumer."); } catch (RuntimeException e) { LOG.error("An error occurred while closing KafkaConsumer.", e); } finally { shutdownLatch.countDown(); } }
Source:
public T get() { try { T value = delegate.get(); manager.addInstance(value); return value; } catch (Exception e) { throw new ProvisionException("While adding to lifecycle manager", e); } }

Target:
public T get() { checkState(delegate != null, "delegate is null"); T value = delegate.get(); try { lifeCycleManager.addInstance(value); } catch (Exception e) { throw new ProvisionException("While adding to lifecycle manager", e); } return value; }
Source:
protected MistDataEvent generateEvent(final I input) { if (extractTimestampFunc == null) { return new MistDataEvent(input, getCurrentTimestamp()); } else { Tuple<V, Long> extractionResult = extractTimestampFunc.apply(input); if (extractionResult.getValue() > latestWatermarkTimestamp) { if (extractionResult.getKey() == null || extractionResult.getValue() == null) { throw new IllegalArgumentException("Timestamp extraction from input data is failed. Data is " + extractionResult.getKey().toString() + ", timestamp is " + extractionResult.getValue().toString()); } return new MistDataEvent(extractionResult.getKey(), extractionResult.getValue()); } else { LOG.log(Level.INFO, "Late data: The data timestamp was later than the latest watermark timestamp."); return null; } } }

Target:
protected MistDataEvent generateEvent(final I input) { if (extractTimestampFunc == null) { long currentTimestamp = getCurrentTimestamp(); if (currentTimestamp > latestWatermarkTimestamp) { return new MistDataEvent(input, currentTimestamp); } else { return null; } } else { Tuple<V, Long> extractionResult = extractTimestampFunc.apply(input); if (extractionResult.getValue() > latestWatermarkTimestamp) { if (extractionResult.getKey() == null || extractionResult.getValue() == null) { throw new IllegalArgumentException("Timestamp extraction from input data is failed. Data is " + extractionResult.getKey().toString() + ", timestamp is " + extractionResult.getValue().toString()); } return new MistDataEvent(extractionResult.getKey(), extractionResult.getValue()); } else { LOG.log(Level.INFO, "Late data: The data timestamp was later than the latest watermark timestamp."); return null; } } }
Source:
public int getNumStages() { return mNumStages; }

Target:
public int getNumStages() { return mFunnel.length; }
Source:
public Collection<Proposal> getProposals(TypeDefinition type, AbstractNode node, String prefix) { return Lists.newArrayList( new Proposal("array", "array", null, "enum"), new Proposal("boolean", "boolean", null, "enum"), new Proposal("integer", "integer", null, "enum"), new Proposal("null", "null", null, "enum"), new Proposal("number", "number", null, "enum"), new Proposal("object", "object", null, "enum"), new Proposal("string", "string", null, "enum")); }

Target:
public Collection<Proposal> getProposals(TypeDefinition type, AbstractNode node, String prefix) { return Lists.newArrayList( new Proposal("array", "array", null, "enum"), new Proposal("boolean", "boolean", null, "enum"), new Proposal("integer", "integer", null, "enum"), new Proposal("\"null\"", "null", null, "enum"), new Proposal("number", "number", null, "enum"), new Proposal("object", "object", null, "enum"), new Proposal("string", "string", null, "enum")); }
Source:
public void testDoesNotAllowOuterJoin() { PlanBuilder p = planBuilder(); Symbol a1 = p.symbol("A1"); Symbol b1 = p.symbol("B1"); JoinNode outerJoin = p.join( JoinNode.Type.FULL, p.values(a1), p.values(b1), ImmutableList.of(equiJoinClause(a1, b1)), ImmutableList.of(a1, b1), Optional.empty()); toMultiJoinNode(outerJoin, noLookup(), DEFAULT_JOIN_LIMIT); }

Target:
public void testDoesNotAllowOuterJoin() { PlanBuilder p = planBuilder(); Symbol a1 = p.symbol("A1"); Symbol b1 = p.symbol("B1"); JoinNode outerJoin = p.join( FULL, p.values(a1), p.values(b1), ImmutableList.of(equiJoinClause(a1, b1)), ImmutableList.of(a1, b1), Optional.empty()); toMultiJoinNode(outerJoin, noLookup(), DEFAULT_JOIN_LIMIT); }
Source:
protected Schema generateSchema() { if (getChild() == null) { return null; } Schema inputSchema = getChild().getSchema(); Schema schema = inputSchema.getSubSchema(gfields); for (int i = 0; i < factories.length; ++i) { schema = Schema.merge(schema, factories[i].generateSchema(inputSchema)); } return schema; }

Target:
protected Schema generateSchema() { if (getChild() == null) { return null; } Schema inputSchema = getChild().getSchema(); Schema aggSchema = Schema.EMPTY_SCHEMA; for (int i = 0; i < factories.length; ++i) { aggSchema = Schema.merge(aggSchema, factories[i].generateSchema(inputSchema)); } return Schema.merge(inputSchema.getSubSchema(gfields), aggSchema); }
Source:
public IStructuredSelection convertToResources( IStructuredSelection originalSelection) { List result = new ArrayList(); Iterator elements = originalSelection.iterator(); while (elements.hasNext()) { Object currentElement = elements.next(); IResource resource = ResourceUtil.getResource(currentElement); if (resource == null) { ResourceMapping mapping = ResourceUtil .getResourceMapping(currentElement); if (mapping == null) continue; ResourceTraversal[] traversals = null; try { traversals = mapping.getTraversals( ResourceMappingContext.LOCAL_CONTEXT, new NullProgressMonitor()); } catch (CoreException e) { StatusManager.getManager().handle(e, IDEWorkbenchPlugin.IDE_WORKBENCH); } if (traversals != null) { IResource[] resources = null; for (ResourceTraversal traversal : traversals) { resources = traversal.getResources(); if (resources != null) { for (IResource resource2 : resources) { result.add(resource2); } } } } } else result.add(resource); } if (result.isEmpty()) { return StructuredSelection.EMPTY; } return new StructuredSelection(result.toArray()); }

Target:
public IStructuredSelection convertToResources( IStructuredSelection originalSelection) { List result = new ArrayList(); Iterator elements = originalSelection.iterator(); while (elements.hasNext()) { Object currentElement = elements.next(); IResource resource = ResourceUtil.getResource(currentElement); if (resource == null) { ResourceMapping mapping = ResourceUtil .getResourceMapping(currentElement); if (mapping == null) continue; ResourceTraversal[] traversals = null; try { traversals = mapping.getTraversals( ResourceMappingContext.LOCAL_CONTEXT, new NullProgressMonitor()); } catch (CoreException e) { StatusManager.getManager().handle(e, IDEWorkbenchPlugin.IDE_WORKBENCH); } if (traversals != null) { IResource[] resources = null; for (ResourceTraversal traversal : traversals) { resources = traversal.getResources(); if (resources != null) { for (IResource traversalResource : resources) { result.add(traversalResource); } } } } } else result.add(resource); } if (result.isEmpty()) { return StructuredSelection.EMPTY; } return new StructuredSelection(result.toArray()); }
Source:
private void init() { inflate(getContext(), R.layout.item_page_list_entry, this); ButterKnife.bind(this); setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT)); setClickable(true); FeedbackUtil.setToolbarButtonLongPressToast(actionView); actionView.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { if (callback != null) { callback.onActionClick(item); } } }); }

Target:
private void init() { inflate(getContext(), R.layout.item_page_list_entry, this); ButterKnife.bind(this); setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT)); FeedbackUtil.setToolbarButtonLongPressToast(actionView); }
Source:
public void run() { String threadName = Thread.currentThread().getName(); for (String threadToIgnore : this.threadsToIgnore) { if (threadName.matches(threadToIgnore)) { if (log.isTraceEnabled()) { log.trace(String.format( "Thread with name [%s] matches the regex [%s]. A span will not be created for this Thread.", threadName, threadToIgnore)); } this.actual.run(); return; } } Span span = this.parent; boolean created = false; if (span != null) { span = this.tracer.joinSpan(this.parent.context()); } else { span = this.tracer.nextSpan().name(RXJAVA_COMPONENT).start(); span.tag( this.traceKeys.getAsync().getPrefix() + this.traceKeys.getAsync().getThreadNameKey(), Thread.currentThread().getName()); created = true; } try (Tracer.SpanInScope ws = this.tracer.withSpanInScope(span)) { this.actual.run(); } finally { if (created) { span.finish(); } } }

Target:
public void run() { String threadName = Thread.currentThread().getName(); for (String threadToIgnore : this.threadsToIgnore) { if (threadName.matches(threadToIgnore)) { if (log.isTraceEnabled()) { log.trace(String.format( "Thread with name [%s] matches the regex [%s]. A span will not be created for this Thread.", threadName, threadToIgnore)); } this.actual.run(); return; } } Span span = this.parent; boolean created = false; if (span == null) { span = this.tracer.nextSpan().name(RXJAVA_COMPONENT).start(); span.tag( this.traceKeys.getAsync().getPrefix() + this.traceKeys.getAsync().getThreadNameKey(), Thread.currentThread().getName()); created = true; } try (Tracer.SpanInScope ws = this.tracer.withSpanInScope(span)) { this.actual.run(); } finally { if (created) { span.finish(); } } }
Source:
protected HandlerRegistration addTimerChangeListener() { if (timerChangeHandler == null) { timerChangeHandler = timer.addValueChangeHandler(new ValueChangeHandler<String>() { @Override public void onValueChange(ValueChangeEvent<String> event) { int newInterval; try { newInterval = Integer.valueOf(event.getValue()); } catch (NumberFormatException nfe) { newInterval = timer.getRefreshRate(); } if (timer.isActive()) { if (newInterval != timer.getRefreshRate()) { timer.stop(); timer.setRefreshRate(newInterval); timer.start(); } } else { timer.setRefreshRate(newInterval); } } }); } else { removeTimerChangeHandler(); addTimerChangeListener(); } return timerChangeHandler; }

Target:
private void addTimerChangeListener() { timerChangeHandler = timer.addValueChangeHandler(new ValueChangeHandler<Integer>() { @Override public void onValueChange(ValueChangeEvent<Integer> event) { int newInterval = event.getValue(); if (timer.isActive()) { if (newInterval != timer.getRefreshRate()) { timer.stop(); timer.setRefreshRate(newInterval); timer.start(); } } else { timer.setRefreshRate(newInterval); } } }); }
Source:
public synchronized void stop() { if (acceptor != null) { try { acceptor.dispose(); log.info("Stopped Gerrit SSHD"); } finally { acceptor = null; } } }

Target:
public synchronized void stop() { if (acceptor != null) { try { close(true).await(); } catch (InterruptedException e) { log.warn("Exception caught while closing", e); } finally { acceptor = null; } } }
Source:
protected void onMethodInvocationFound(MethodInvocationTree mit) { if (GET_INSTANCE_METHOD.equals(mit.symbol().name())) { ExpressionTree argument = mit.arguments().get(0); if (argument.is(Tree.Kind.STRING_LITERAL)) { String algorithm = LiteralUtils.trimQuotes(((LiteralTree) argument).value()); if (algorithmKeySizeMap.containsKey(algorithm)) { storeAlgorithmKeySize(algorithm); storeSymbolOfAssignedInstance(mit); } } } else { if (isValidKeyGenSymbolOfInitializeMethod(mit)) { checkAlgorithmParameterToReport(mit.arguments().get(0)).ifPresent(reportString -> reportIssue(mit, reportString)); } } }

Target:
protected void onMethodInvocationFound(MethodInvocationTree mit) { MethodTree methodTree = findEnclosingMethod(mit); String getInstanceArg = ConstantUtils.resolveAsStringConstant(mit.arguments().get(0)); if (methodTree != null && getInstanceArg != null) { MethodVisitor methodVisitor = new MethodVisitor(getInstanceArg); methodTree.accept(methodVisitor); } }
Source:
public FullTextQuery createFullTextQuery(Query luceneQuery, Class<?>... entities) { if (entities.length > 1) { throw new APIException("Can't create FullTextQuery for multiple persistent classes"); } if (log.isDebugEnabled()) { log.debug("Creating new FullTextQuery instance"); } Class<?> entityClass = entities[0]; FullTextQuery query = delegate.createFullTextQuery(luceneQuery, entityClass); if (log.isDebugEnabled()) { log.debug("Notifying FullTextQueryCreated listeners..."); } FullTextQueryAndEntityClass queryAndClass = new FullTextQueryAndEntityClass(query, entityClass); eventPublisher.publishEvent(new FullTextQueryCreatedEvent(queryAndClass)); return query; }

Target:
public FullTextQuery createFullTextQuery(Query luceneQuery, Class<?>... entities) { if (entities.length > 1) { throw new DAOException("Can't create FullTextQuery for multiple persistent classes"); } if (log.isDebugEnabled()) { log.debug("Creating new FullTextQuery instance"); } Class<?> entityClass = entities[0]; FullTextQuery query = delegate.createFullTextQuery(luceneQuery, entityClass); if (log.isDebugEnabled()) { log.debug("Notifying FullTextQueryCreated listeners..."); } FullTextQueryAndEntityClass queryAndClass = new FullTextQueryAndEntityClass(query, entityClass); eventPublisher.publishEvent(new FullTextQueryCreatedEvent(queryAndClass)); return query; }
Source:
public ActualProperties visitTopNRowNumber(TopNRowNumberNode node, List<ActualProperties> inputProperties) { ActualProperties properties = Iterables.getOnlyElement(inputProperties); ImmutableList.Builder<LocalProperty<Symbol>> localProperties = ImmutableList.builder(); localProperties.add(new GroupingProperty<>(node.getPartitionBy())); for (Symbol column : node.getOrderingScheme().getOrderBy()) { localProperties.add(new SortingProperty<>(column, node.getOrderingScheme().getOrderings().get(column))); } return ActualProperties.builderFrom(properties) .local(localProperties.build()) .build(); }

Target:
public ActualProperties visitTopNRowNumber(TopNRowNumberNode node, List<ActualProperties> inputProperties) { ActualProperties properties = Iterables.getOnlyElement(inputProperties); ImmutableList.Builder<LocalProperty<Symbol>> localProperties = ImmutableList.builder(); localProperties.add(new GroupingProperty<>(node.getPartitionBy())); for (Symbol column : node.getOrderingScheme().getOrderBy()) { localProperties.add(new SortingProperty<>(column, node.getOrderingScheme().getOrdering(column))); } return ActualProperties.builderFrom(properties) .local(localProperties.build()) .build(); }
Source:
public void setAgentProtocols(Set<String> protocols) { Set<String> disabled = new TreeSet<>(); Set<String> enabled = new TreeSet<>(); for (AgentProtocol p : AgentProtocol.all()) { String name = p.getName(); if (name != null && !p.isRequired()) { if (p.isOptIn()) { if (protocols.contains(name)) { enabled.add(name); } } else { if (!protocols.contains(name)) { disabled.add(name); } } } } disabledAgentProtocols = fixEmpty(StringUtils.join(disabled, ", ")); enabledAgentProtocols = fixEmpty(StringUtils.join(enabled, ", ")); agentProtocols = null; }

Target:
public void setAgentProtocols(Set<String> protocols) { Set<String> disabled = new TreeSet<>(); Set<String> enabled = new TreeSet<>(); for (AgentProtocol p : AgentProtocol.all()) { String name = p.getName(); if (name != null && !p.isRequired()) { if (p.isOptIn()) { if (protocols.contains(name)) { enabled.add(name); } } else { if (!protocols.contains(name)) { disabled.add(name); } } } } disabledAgentProtocols = disabled.isEmpty() ? null : new ArrayList<>(disabled); enabledAgentProtocols = enabled.isEmpty() ? null : new ArrayList<>(enabled); agentProtocols = null; }
Source:
public Set<Application> getApplications() { File[] appDefinitions = APPLICATION_DEFINITIONS_FOLDER.toFile().listFiles(); if (appDefinitions == null) { LOGGER.warn("No application-definitions configuration files found."); return Collections.emptySet(); } List<Application> apps = new ArrayList<>(); for (File appDef : appDefinitions) { try { Application app = Boon.fromJson(IOUtils.toString(appDef.toURI()), ApplicationImpl.class); apps.add(app); } catch (IOException e) { LOGGER.warn("Unable to parse application from file ", appDef.getPath()); } } return new TreeSet<>(apps); }

Target:
public Set<Application> getApplications() { File[] appDefinitions = APPLICATION_DEFINITIONS_FOLDER.toFile().listFiles(); if (appDefinitions == null) { LOGGER.warn("No application-definitions configuration files found."); return Collections.emptySet(); } Set<Application> apps = new HashSet<>(); for (File appDef : appDefinitions) { try { Application app = Boon.fromJson(IOUtils.toString(appDef.toURI()), ApplicationImpl.class); if (isPermittedToViewFeature(app.getName())) { apps.add(app); } } catch (IOException e) { LOGGER.warn("Unable to parse application from file ", appDef.getPath()); } } return apps; }