auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>private List<String> getPackageFileList(String downloadedTestProject1PackageName) throws IOException { IOException lastException = null; for (int i = 0; i < MAX_ATTEMPTS; i++) { try { return downloadedFileUtil .getPackageFileList(seleniumWebDriver, downloadedTestProject1PackageName) .stream() <START> .filter(s -> !s.contains("target")) <END> .collect(Collectors.toList()); } catch (IOException e) { lastException = e; sleepQuietly(TestTimeoutsConstants.MINIMUM_SEC); } } throw lastException; }</code><technical_language>this "startsWith("/target") for more robustness</technical_language>

Target:
private List<String> getPackageFileList(String downloadedTestProject1PackageName) throws IOException { IOException lastException = null; for (int i = 0; i < MAX_ATTEMPTS; i++) { try { return downloadedFileUtil .getPackageFileList(seleniumWebDriver, downloadedTestProject1PackageName) .stream() .filter(s -> !s.contains("target/") && !s.startsWith(".che")) .collect(Collectors.toList()); } catch (IOException e) { lastException = e; sleepQuietly(TestTimeoutsConstants.MINIMUM_SEC); } } throw lastException; }
Source:
<code>public void testIsDefaultCallScreeningAppFailure() throws Exception { boolean exceptionThrown = false; <START> ComponentName componentName = new ComponentName("com.android.unknown", "com.android.unknown.callscreeningserviceimpl"); try { mTSIBinder.isDefaultCallScreeningApp(componentName); } catch (SecurityException e) { exceptionThrown = true; } assertTrue(exceptionThrown); <END> }</code><technical_language>please test default call screening app match condition</technical_language>

Target:
public void testIsDefaultCallScreeningAppFailure() throws Exception { boolean exceptionThrown = false; ComponentName unknownComponentName = new ComponentName("com.android.unknown", "com.android.unknown.callscreeningserviceimpl"); Settings.Secure.putStringForUser(mContentResolver, Settings.Secure .ALL_SCREENING_DEFAULT_APPLICATION, mThirdPartyCallScreening.flattenToString(), 0); try { mTSIBinder.isDefaultCallScreeningApp(unknownComponentName); } catch (SecurityException e) { exceptionThrown = true; } assertTrue(exceptionThrown); }
Source:
<code>public MethodOutcome updatePatientConditional( @ResourceParam Person thePerson, @IdParam IdDt theId) { MethodOutcome retVal = new MethodOutcome(); <START> retVal.setId(new IdDt(FHIRConstants.PERSON, thePerson.getId().getIdPart())); <END> OperationOutcome outcome = new OperationOutcome(); try{ Person person=personResource.updateFHIRPerson(thePerson,theId.getIdPart()); }catch(Exception e){ outcome.addIssue().setDetails("No Person is associated with the given UUID to update. Please" + " make sure you have set at lease one non-delete name to create a new Person with the given UUID"); retVal.setOperationOutcome(outcome); return retVal; } outcome.addIssue().setDetails("Person is successfully updated"); retVal.setOperationOutcome(outcome); return retVal; }</code><technical_language>need set this stage right. If client put contains id part</technical_language>

Target:
public MethodOutcome updatePatientConditional(@ResourceParam Person thePerson, @IdParam IdDt theId) { MethodOutcome retVal = new MethodOutcome(); OperationOutcome outcome = new OperationOutcome(); try { Person person = personResource.updateFHIRPerson(thePerson, theId.getIdPart()); } catch (Exception e) { outcome.addIssue() .setDetails( "No Person is associated with the given UUID to update. Please" + " make sure you have set at lease one non-delete name, Gender and Birthdate to create a new Person with the given UUID"); retVal.setOperationOutcome(outcome); return retVal; } outcome.addIssue().setDetails("Person is successfully updated"); retVal.setOperationOutcome(outcome); return retVal; }
Source:
<code>public void onStopProfiler() { enableStoppedCommands(); ProfileOperationRequest request = ProfileOperationRequest .create(response_.getFileName()); server_.stopProfiling(request, new ServerRequestCallback<ProfileOperationResponse>() { @Override public void onResponseReceived(ProfileOperationResponse response) { if (response.getErrorMessage() != null) { globalDisplay_.showErrorMessage("Profiler Error", response.getErrorMessage()); return; } } @Override public void onError(ServerError error) { <START> globalDisplay_.showErrorMessage("Failed to Stop Profiler", <END> error.getMessage()); } }); }</code><technical_language>(same stopped commands)</technical_language>

Target:
public void onStopProfiler() { ProfileOperationRequest request = ProfileOperationRequest .create(response_ != null ? response_.getFileName() : null); response_ = null; server_.stopProfiling(request, new ServerRequestCallback<ProfileOperationResponse>() { @Override public void onResponseReceived(ProfileOperationResponse response) { if (response.getErrorMessage() != null) { globalDisplay_.showErrorMessage("Profiler Error", response.getErrorMessage()); return; } } @Override public void onError(ServerError error) { globalDisplay_.showErrorMessage("Failed to Stop Profiler", error.getMessage()); } }); }
Source:
<code>public static ChangeKind getChangeKind(MergeUtil.Factory mergeUtilFactory, ProjectState project, Repository git, RevCommit prior, RevCommit next) { <START> if (next.getTree() == prior.getTree() && isSameParents(prior, next)) { return ChangeKind.NO_CODE_CHANGE; } <END> if (prior.getParentCount() != 1 || next.getParentCount() != 1) { return ChangeKind.REWORK; } if (next.getTree() == prior.getTree() && isSameParents(prior, next)) { return ChangeKind.TRIVIAL_REBASE; } try { MergeUtil mergeUtil = mergeUtilFactory.create(project); ThreeWayMerger merger = mergeUtil.newThreeWayMerger(git, mergeUtil.createDryRunInserter()); merger.setBase(prior.getParent(0)); if (merger.merge(next.getParent(0), prior) && merger.getResultTreeId().equals(next.getTree())) { return ChangeKind.TRIVIAL_REBASE; } else { return ChangeKind.REWORK; } } catch (IOException err) { log.warn("Cannot check trivial rebase of new patch set " + next.name() + " in " + project.getProject().getName(), err); return ChangeKind.REWORK; } }</code><technical_language>In thought, combination of condition: if (next.getTree() == prior.getTree() && isSameParents(prior, next)) { if (next.getFullMessage().equals(prior.getFullMessage())) { return ChangeKind.TRIVIAL_REBASE; } else { return ChangeKind.NO_CODE_CHANGE; } } condition line 390 removed</technical_language>

Target:
public static ChangeKind getChangeKind(MergeUtil.Factory mergeUtilFactory, ProjectState project, Repository git, RevCommit prior, RevCommit next) { if (next.getTree() == prior.getTree() && isSameParents(prior, next)) { return ChangeKind.NO_CODE_CHANGE; } if (prior.getParentCount() != 1 || next.getParentCount() != 1) { return ChangeKind.REWORK; } try { MergeUtil mergeUtil = mergeUtilFactory.create(project); ThreeWayMerger merger = mergeUtil.newThreeWayMerger(git, mergeUtil.createDryRunInserter()); merger.setBase(prior.getParent(0)); if (merger.merge(next.getParent(0), prior) && merger.getResultTreeId().equals(next.getTree())) { return ChangeKind.TRIVIAL_REBASE; } else { return ChangeKind.REWORK; } } catch (IOException err) { log.warn("Cannot check trivial rebase of new patch set " + next.name() + " in " + project.getProject().getName(), err); return ChangeKind.REWORK; } }
Source:
<code>private MaterialRevisions fanInOn(MaterialRevisions originalMaterialRevisions, CruiseConfig cruiseConfig, CaseInsensitiveString targetPipelineName) { <START> LOGGER.debug("[Revision Resolution] Fan-In Resolution is active for pipeline " + pipelineName); <END> return pipelineService.getRevisionsBasedOnDependencies(originalMaterialRevisions, cruiseConfig, targetPipelineName); }</code><technical_language>change</technical_language>

Target:
private MaterialRevisions fanInOn(MaterialRevisions originalMaterialRevisions, CruiseConfig cruiseConfig, CaseInsensitiveString targetPipelineName) { LOGGER.debug("[Revision Resolution] Fan-In Resolution is active for pipeline {}", pipelineName); return pipelineService.getRevisionsBasedOnDependencies(originalMaterialRevisions, cruiseConfig, targetPipelineName); }
Source:
<code>public Map<String, String> getGenericInformation() { <START> return this.genericInformation; <END> }</code><technical_language>shallow copy case before</technical_language>

Target:
public Map<String, String> getGenericInformation() { Set<Entry<String, String>> entries = this.genericInformation.entrySet(); Map<String, String> result = new HashMap<>(entries.size()); for (Entry<String, String> entry : entries) { result.put(entry.getKey(), entry.getValue()); } return result; }
Source:
<code>public static final HttpClient createHttpClient() { SocketConfig socketConfig = SocketConfig.copy(SocketConfig.DEFAULT).setSoTimeout(SERVER_CONNECTION_TIMEOUT).build(); List<String> targetPreferredAuthSchemes = new ArrayList<String>(); targetPreferredAuthSchemes.add(AuthSchemes.DIGEST); targetPreferredAuthSchemes.add(AuthSchemes.BASIC); RequestConfig requestConfig = RequestConfig.copy(RequestConfig.DEFAULT) .setConnectTimeout(SERVER_CONNECTION_TIMEOUT) .setAuthenticationEnabled(true) .setRedirectsEnabled(true) .setMaxRedirects(1) .setCircularRedirectsAllowed(true) .setTargetPreferredAuthSchemes(targetPreferredAuthSchemes) .build(); HttpClientBuilder clientBuilder = HttpClientBuilder.create() .setConnectionManager(connectionManager) .setConnectionManagerShared(true) .setDefaultSocketConfig(socketConfig) .setDefaultRequestConfig(requestConfig); HttpHost proxy = BriefcasePreferences.getBriefCaseProxyConnection(); if (proxy != null) { <START> clientBuilder.setRoutePlanner(new DefaultProxyRoutePlanner(proxy)).build(); <END> } return clientBuilder.build(); }</code><technical_language>I this call build is redundant. matters</technical_language>

Target:
public static final HttpClient createHttpClient() { SocketConfig socketConfig = SocketConfig.copy(SocketConfig.DEFAULT).setSoTimeout(SERVER_CONNECTION_TIMEOUT).build(); List<String> targetPreferredAuthSchemes = new ArrayList<String>(); targetPreferredAuthSchemes.add(AuthSchemes.DIGEST); targetPreferredAuthSchemes.add(AuthSchemes.BASIC); RequestConfig requestConfig = RequestConfig.copy(RequestConfig.DEFAULT) .setConnectTimeout(SERVER_CONNECTION_TIMEOUT) .setAuthenticationEnabled(true) .setRedirectsEnabled(true) .setMaxRedirects(1) .setCircularRedirectsAllowed(true) .setTargetPreferredAuthSchemes(targetPreferredAuthSchemes) .build(); HttpClientBuilder clientBuilder = HttpClientBuilder.create() .setConnectionManager(connectionManager) .setConnectionManagerShared(true) .setDefaultSocketConfig(socketConfig) .setDefaultRequestConfig(requestConfig); HttpHost proxy = BriefcasePreferences.getBriefCaseProxyConnection(); if (proxy != null) { clientBuilder.setRoutePlanner(new DefaultProxyRoutePlanner(proxy)); } return clientBuilder.build(); }
Source:
<code>private URIish createURI(byte[] keyFingerprint) { URIish uri = new URIish(); <START> uri = uri.setPath(MessageFormat.format(JGitText.get().gpgKeyUrish, <END> Hex.toHexString(keyFingerprint))); return uri; }</code><technical_language>misusing URI instead of adding CredentialsItem.InformationalMessage. If want show a URI this URI of keybox secring file key is loaded</technical_language>

Target:
private URIish createURI(byte[] keyFingerprint) { return new URIish().setScheme("gpgkey") .setPath(Hex.toHexString(keyFingerprint)); }
Source:
<code>public static void viewAccountSettings(Activity activity) { <START> AccountHelper.getDefaultAccount().fetchAccountSettings(); <END> Intent intent = new Intent(activity, SettingsActivity.class); AnalyticsUtils.trackWithCurrentBlogDetails(AnalyticsTracker.Stat.OPENED_ACCOUNT_SETTINGS); slideInFromRightForResult(activity, intent, RequestCodes.ACCOUNT_SETTINGS); }</code><technical_language>Hey @oguzkocer, Account settings update calls feel strange initiated here. I helper methods in ActivityLauncher.java launch activities business logic. I suggest moving update calls closer caller in Activities themselves? Cheers</technical_language>

Target:
public static void viewAccountSettings(Activity activity) { Intent intent = new Intent(activity, AccountSettingsActivity.class); AnalyticsUtils.trackWithCurrentBlogDetails(AnalyticsTracker.Stat.OPENED_ACCOUNT_SETTINGS); slideInFromRightForResult(activity, intent, RequestCodes.ACCOUNT_SETTINGS); }
Source:
<code>GetBlobInfoOperation(RouterConfig routerConfig, NonBlockingRouterMetrics routerMetrics, ClusterMap clusterMap, ResponseHandler responseHandler, String blobIdStr, GetBlobOptionsInternal options, Callback<GetBlobResultInternal> callback, Time time) throws RouterException { super(routerConfig, routerMetrics, clusterMap, responseHandler, blobIdStr, options, callback, time); operationTracker = new AdaptiveOperationTracker(routerConfig.routerDatacenterName, blobId.getPartition(), routerConfig.routerGetCrossDcEnabled, routerConfig.routerGetSuccessTarget, routerConfig.routerGetRequestParallelism, time, routerMetrics.getBlobInfoLocalColoLatency, <START> routerMetrics.getBlobInfoCrossColoLatency, routerConfig.routerLatencyToleranceQuantile); <END> }</code><technical_language>Do histograms account for values startup moving histograms</technical_language>

Target:
GetBlobInfoOperation(RouterConfig routerConfig, NonBlockingRouterMetrics routerMetrics, ClusterMap clusterMap, ResponseHandler responseHandler, String blobIdStr, GetBlobOptionsInternal options, Callback<GetBlobResultInternal> callback, Time time) throws RouterException { super(routerConfig, routerMetrics, clusterMap, responseHandler, blobIdStr, options, callback, time); operationTracker = new AdaptiveOperationTracker(routerConfig.routerDatacenterName, blobId.getPartition(), routerConfig.routerGetCrossDcEnabled, routerConfig.routerGetSuccessTarget, routerConfig.routerGetRequestParallelism, time, routerMetrics.getBlobInfoLocalColoLatencyMs, routerMetrics.getBlobInfoCrossColoLatencyMs, routerMetrics.getBlobInfoPastDueCount, routerConfig.routerLatencyToleranceQuantile); }
Source:
<code>public boolean perform(AbstractBuild<?, ?> build, Launcher launcher, BuildListener listener) throws InterruptedException, IOException { BuildData buildData = build.getAction(BuildData.class); if (buildData == null) { throw new IOException(Messages.GitHubCommitNotifier_NoBuildDataError()); } final Revision lastBuildRevision = buildData.getLastBuiltRevision(); final ObjectId sha1 = lastBuildRevision != null ? lastBuildRevision.getSha1() : null; if (sha1 == null) { throw new IOException(Messages.GitHubCommitNotifier_NoLastRevisionError()); <START> } <END> for (GitHubRepositoryName name : GitHubRepositoryNameContributor.parseAssociatedNames(build.getProject())) { for (GHRepository repository : name.resolve()) { GHCommitState state; String msg; final String duration = Util.getTimeSpanString(System.currentTimeMillis() - build.getTimeInMillis()); Result result = build.getResult(); if (result.isBetterOrEqualTo(SUCCESS)) { state = GHCommitState.SUCCESS; msg = Messages.CommitNotifier_Success(build.getDisplayName(), duration); } else if (result.isBetterOrEqualTo(UNSTABLE)) { state = GHCommitState.FAILURE; msg = Messages.CommitNotifier_Unstable(build.getDisplayName(), duration); } else { state = GHCommitState.ERROR; msg = Messages.CommitNotifier_Failed(build.getDisplayName(), duration); } listener.getLogger().println(Messages.GitHubCommitNotifier_SettingCommitStatus(repository.getUrl() + "/commit/" + sha1)); repository.createCommitStatus(ObjectId.toString(sha1), state, build.getAbsoluteUrl(), msg); } } return true; }</code><technical_language>Java fu is weak understanding of Jenkins internals is weaker, this throw exception if "last build revision" is available? Is fix exception is thrown, execution is halted build fail</technical_language>

Target:
public boolean perform(AbstractBuild<?, ?> build, Launcher launcher, BuildListener listener) throws InterruptedException, IOException { try { updateCommitStatus(build, listener); return true; } catch (IOException error) { final Result buildResult = getEffectiveResultOnFailure(); if (buildResult.equals(Result.FAILURE)) { throw error; } else { listener.error("[GitHub Commit Notifier] - " + error.getMessage()); if (buildResult.isWorseThan(build.getResult())) { listener.getLogger().println("[GitHub Commit Notifier] - Build result will be set to " + buildResult); build.setResult(buildResult); } } } return true; }
Source:
<code>public void before() throws Exception { MockitoAnnotations.initMocks(this); when(masterServices.skipRegionManagementAction(any())).thenReturn(false); testingUtility = new HBaseCommonTestingUtility(); queue = new RegionNormalizerWorkQueue<>(); workerThreadThrowable.set(null); final String threadNameFmt = TestRegionNormalizerWorker.class.getSimpleName() + "-" + testName.getMethodName() + "-%d"; final ThreadFactory threadFactory = new ThreadFactoryBuilder() .setNameFormat(threadNameFmt) .setDaemon(true) .setUncaughtExceptionHandler((t, e) -> workerThreadThrowable.set(e)) .build(); <START> workerPool = Executors.newFixedThreadPool(1, threadFactory); <END> }</code><technical_language>nit: newSingleThreadExecutor(factory) similar worker pool in source code</technical_language>

Target:
public void before() throws Exception { MockitoAnnotations.initMocks(this); when(masterServices.skipRegionManagementAction(any())).thenReturn(false); testingUtility = new HBaseCommonTestingUtility(); queue = new RegionNormalizerWorkQueue<>(); workerThreadThrowable.set(null); final String threadNameFmt = TestRegionNormalizerWorker.class.getSimpleName() + "-" + testName.getMethodName() + "-%d"; final ThreadFactory threadFactory = new ThreadFactoryBuilder() .setNameFormat(threadNameFmt) .setDaemon(true) .setUncaughtExceptionHandler((t, e) -> workerThreadThrowable.set(e)) .build(); workerPool = Executors.newSingleThreadExecutor(threadFactory); }
Source:
<code>public void testExecuteAndPostProcess() { ______TS("case: view instructor account details"); InstructorAttributes instructor1OfCourse1 = dataBundle.instructors.get("instructor1OfCourse1"); String[] submissionParams = new String[] { Const.ParamsNames.INSTRUCTOR_ID, instructor1OfCourse1.googleId }; final String adminUserId = "admin.user"; gaeSimulation.loginAsAdmin(adminUserId); AdminAccountDetailsPageAction action = getAction(submissionParams); ShowPageResult result = getShowPageResult(action); assertEquals("", result.getStatusMessage()); <START> assertEquals(getPageResultDestination("/jsp/adminAccountDetails.jsp", false, "admin.user"), <END> result.getDestinationWithParams()); assertFalse(result.isError); AdminAccountDetailsPageData data = (AdminAccountDetailsPageData) result.data; assertEquals(instructor1OfCourse1.googleId, data.getAccountInformation().googleId); }</code><technical_language>Similarly, adminUserId instead of "admin.user", Const.ViewURIs.ADMIN_ACCOUNT_MANAGEMENT instead of "/jsp/adminAccountDetails.jsp"</technical_language>

Target:
public void testExecuteAndPostProcess() { ______TS("case: view instructor account details"); InstructorAttributes instructor1OfCourse1 = dataBundle.instructors.get("instructor1OfCourse1"); String[] submissionParams = new String[] { Const.ParamsNames.INSTRUCTOR_ID, instructor1OfCourse1.googleId }; final String adminUserId = "admin.user"; gaeSimulation.loginAsAdmin(adminUserId); AdminAccountDetailsPageAction action = getAction(submissionParams); ShowPageResult result = getShowPageResult(action); assertEquals("", result.getStatusMessage()); assertEquals( getPageResultDestination(Const.ViewURIs.ADMIN_ACCOUNT_DETAILS, false, adminUserId), result.getDestinationWithParams()); assertFalse(result.isError); AdminAccountDetailsPageData data = (AdminAccountDetailsPageData) result.data; assertEquals(instructor1OfCourse1.googleId, data.getAccountInformation().googleId); }
Source:
<code>public void testStatsForValuesNodeWithJustNulls() { PlanNodeStatsEstimate nullAStats = PlanNodeStatsEstimate.builder() .setOutputRowCount(1) .addSymbolStatistics(new Symbol("a"), SymbolStatsEstimate.builder() .setDistinctValuesCount(0) <START> .setNullsFraction(NaN) <END> .setAverageRowSize(NaN) .setHighValue(NaN) .setLowValue(NaN) .build()) .build(); tester().assertStatsFor(pb -> pb .values(ImmutableList.of(pb.symbol("a", BIGINT)), ImmutableList.of( ImmutableList.of(expression("3 + null"))))) .check(outputStats -> outputStats.equalTo(nullAStats)); tester().assertStatsFor(pb -> pb .values(ImmutableList.of(pb.symbol("a", BIGINT)), ImmutableList.of( ImmutableList.of(expression("null"))))) .check(outputStats -> outputStats.equalTo(nullAStats)); tester().assertStatsFor(pb -> pb .values(ImmutableList.of(pb.symbol("a", UNKNOWN)), ImmutableList.of( ImmutableList.of(expression("null"))))) .check(outputStats -> outputStats.equalTo(nullAStats)); }</code><technical_language>setting nulls 1 work well? / not</technical_language>

Target:
public void testStatsForValuesNodeWithJustNulls() { PlanNodeStatsEstimate nullAStats = PlanNodeStatsEstimate.builder() .setOutputRowCount(1) .addSymbolStatistics(new Symbol("a"), SymbolStatsEstimate.zero()) .build(); tester().assertStatsFor(pb -> pb .values(ImmutableList.of(pb.symbol("a", BIGINT)), ImmutableList.of( ImmutableList.of(expression("3 + null"))))) .check(outputStats -> outputStats.equalTo(nullAStats)); tester().assertStatsFor(pb -> pb .values(ImmutableList.of(pb.symbol("a", BIGINT)), ImmutableList.of( ImmutableList.of(expression("null"))))) .check(outputStats -> outputStats.equalTo(nullAStats)); tester().assertStatsFor(pb -> pb .values(ImmutableList.of(pb.symbol("a", UNKNOWN)), ImmutableList.of( ImmutableList.of(expression("null"))))) .check(outputStats -> outputStats.equalTo(nullAStats)); }
Source:
<code>boolean includeClosed(CompositeT left, CompositeT to, List<CompositeT> res) { for (CompositeT next = left.nextSibling(); next != null; next = next.nextSibling()) { if (includeOpen(next, to, res)) { return true; } } <START> if (left.getParent() == null) { <END> throw new IllegalArgumentException("Right bound not found in left's bound hierarchy. to=" + to); } return includeClosed(left.getParent(), to, res); }</code><technical_language>First, is assert in beginning method. Second, left root in call of this method , I think</technical_language>

Target:
void includeClosed(CompositeT left, CompositeT to, List<CompositeT> res) { for (CompositeT next = left.nextSibling(); next != null; next = next.nextSibling()) { if (includeOpen(next, to, res)) { return; } } if (left.getParent() == null) { throw new IllegalArgumentException("Right bound not found in left's bound hierarchy. to=" + to); } includeClosed(left.getParent(), to, res); }
Source:
<code>public void visit(LwM2mResourceInstance instance) { <START> throw new UnsupportedOperationException("not yet implemented"); <END> }</code><technical_language>@sbernard31 , suppose add implementation ? rht</technical_language>

Target:
public void visit(LwM2mResourceInstance instance) { LOG.trace("Encoding resource instance into JSON", instance); if (!requestPath.isResourceInstance()) { throw new CodecException("Invalid request path %s for JSON resource instance encoding", requestPath); } baseName = requestPath.toString(); ResourceModel rSpec = model.getResourceModel(objectId, instance.getId()); Type expectedType = rSpec != null ? rSpec.type : instance.getType(); JsonArrayEntry jsonArrayEntry = createJsonArrayEntry(null, timestamp, instance.getType(), expectedType, instance.getValue()); resourceList = new ArrayList<>(); resourceList.add(jsonArrayEntry); }
Source:
<code>public synchronized void save() throws IOException { if(BulkChange.contains(this)) return; synchronized (saving) { saving.add(this); } try { <START> getConfigFile().write(this); <END> } finally { synchronized (saving) { saving.remove(this); } } SaveableListener.fireOnChange(this, getConfigFile()); }</code><technical_language>code dup. move private saveInternal()</technical_language>

Target:
public synchronized void save() throws IOException { if(BulkChange.contains(this)) return; getConfigFile().write(this); SaveableListener.fireOnChange(this, getConfigFile()); }
Source:
<code>private void updateEnablement() { boolean upEnabled = false; boolean newFolderEnabled = false; <START> boolean connectionOpen = fConnection.isOpen(); <END> if (connectionOpen) { if (fResources.size() == 1) { IFileStore store = fResources.get(0); if (store.fetchInfo().isDirectory()) { newFolderEnabled = true; } if (store.getParent() != null) { upEnabled = true; } } } if (fUpButton != null) { fUpButton.setEnabled(upEnabled); } if (fNewFolderButton != null) { fNewFolderButton.setEnabled(newFolderEnabled); } if (fRemotePathText != null) { fRemotePathText.setEnabled(connectionOpen); } if (fTreeViewer != null) { fTreeViewer.getTree().setEnabled(connectionOpen); } if (fShowHiddenButton != null) { fShowHiddenButton.setEnabled(connectionOpen); } }</code><technical_language>a NPE a result of this change</technical_language>

Target:
private void updateEnablement() { boolean upEnabled = false; boolean newFolderEnabled = false; boolean connectionOpen = fConnection != null && fConnection.isOpen(); if (connectionOpen) { if (fResources.size() == 1) { IFileStore store = fResources.get(0); if (store.fetchInfo().isDirectory()) { newFolderEnabled = true; } if (store.getParent() != null) { upEnabled = true; } } } if (fUpButton != null) { fUpButton.setEnabled(upEnabled); } if (fNewFolderButton != null) { fNewFolderButton.setEnabled(newFolderEnabled); } if (fRemotePathText != null) { fRemotePathText.setEnabled(connectionOpen); } if (fTreeViewer != null) { fTreeViewer.getTree().setEnabled(connectionOpen); } if (fShowHiddenButton != null) { fShowHiddenButton.setEnabled(connectionOpen); } }
Source:
<code>protected void doSensorStateChanged(@Nullable HueBridge bridge, @NonNull FullSensor sensor, Configuration config) { Object tmp = sensor.getState().get("temperature"); BigDecimal value = new BigDecimal(String.valueOf(tmp)); <START> DecimalType temperature = new DecimalType(value.divide(new BigDecimal(100))); <END> updateState(HueBindingConstants.CHANNEL_TEMPERATURE, temperature); }</code><technical_language>If I remember correctly declared temperature Channel Number:Temperature. do a DecimalType update state instead of a QuantityType</technical_language>

Target:
protected void doSensorStateChanged(@Nullable HueBridge bridge, @NonNull FullSensor sensor, Configuration config) { Object tmp = sensor.getState().get("temperature"); BigDecimal value = new BigDecimal(String.valueOf(tmp)); QuantityType<Temperature> temperature = new QuantityType<>(value.divide(new BigDecimal(100)), SIUnits.CELSIUS); updateState(HueBindingConstants.CHANNEL_TEMPERATURE, temperature); }
Source:
<code>public void shouldGenerateDevfileForFactoryWithNoDevfileOrJson() throws Exception { String githubUrl = "<LINK_0>"; FactoryDto computedFactory = generateDevfileFactory(); when(urlFactoryBuilder.buildDefaultDevfile(any())).thenReturn(computedFactory.getDevfile()); when(urlFactoryBuilder.createFactoryFromJson(any(RemoteFactoryUrl.class))) .thenReturn(Optional.empty()); when(urlFactoryBuilder.createFactoryFromDevfile(any(RemoteFactoryUrl.class), any(), anyMap())) .thenReturn(Optional.empty()); Map<String, String> params = new HashMap<>(); <START> params.put(URL_PARAMETER_NAME, githubUrl); <END> FactoryDto factory = githubFactoryParametersResolver.createFactory(params); verify(urlFactoryBuilder).buildDefaultDevfile(eq("che")); assertEquals(factory, computedFactory); }</code><technical_language>ImmutableMap.of(</technical_language>

Target:
public void shouldGenerateDevfileForFactoryWithNoDevfileOrJson() throws Exception { String githubUrl = "<LINK_0>"; FactoryDto computedFactory = generateDevfileFactory(); when(urlFactoryBuilder.buildDefaultDevfile(any())).thenReturn(computedFactory.getDevfile()); when(urlFactoryBuilder.createFactoryFromJson(any(RemoteFactoryUrl.class))) .thenReturn(Optional.empty()); when(urlFactoryBuilder.createFactoryFromDevfile(any(RemoteFactoryUrl.class), any(), anyMap())) .thenReturn(Optional.empty()); Map<String, String> params = ImmutableMap.of(URL_PARAMETER_NAME, githubUrl); FactoryDto factory = githubFactoryParametersResolver.createFactory(params); verify(urlFactoryBuilder).buildDefaultDevfile(eq("che")); assertEquals(factory, computedFactory); }
Source:
<code>public void setup() { Robolectric.getBackgroundThreadScheduler().pause(); formController = mock(FormController.class); logger = mock(AuditEventLogger.class); formSaver = mock(FormSaver.class); mediaUtils = mock(MediaUtils.class); Analytics analytics = mock(Analytics.class); when(formController.getAuditEventLogger()).thenReturn(logger); when(logger.isChangeReasonRequired()).thenReturn(false); <START> Map<String, String> originalFiles = new HashMap<>(); <END> Map<String, String> recentFiles = new HashMap<>(); originalFiles.put("questionIndex", "blah"); recentFiles.put("questionIndex", "blah"); viewModel = new FormSaveViewModel(savedStateHandle, () -> CURRENT_TIME, formSaver, mediaUtils, analytics); viewModel.formLoaded(formController); }</code><technical_language>need 4 lines for anything</technical_language>

Target:
public void setup() { Robolectric.getBackgroundThreadScheduler().pause(); formController = mock(FormController.class); logger = mock(AuditEventLogger.class); mediaUtils = mock(MediaUtils.class); Analytics analytics = mock(Analytics.class); when(formController.getAuditEventLogger()).thenReturn(logger); when(logger.isChangeReasonRequired()).thenReturn(false); viewModel = new FormSaveViewModel(savedStateHandle, () -> CURRENT_TIME, formSaver, mediaUtils, analytics); viewModel.formLoaded(formController); }
Source:
<code>public void unsubscribe() { if (once.compareAndSet(false, true)) { <START> threadWorker.schedule(new Action0() { <END> @Override public void call() { pool.release(threadWorker); } }); } innerSubscription.unsubscribe(); }</code><technical_language>EventLoopWorker implement Action0 schedule release</technical_language>

Target:
public void unsubscribe() { if (once.compareAndSet(false, true)) { threadWorker.schedule(this); } innerSubscription.unsubscribe(); }
Source:
<code>public void testSRTMWithTunnelInterpolation() throws Exception { GraphHopper tmpHopper = new GraphHopperOSM(). setOSMFile(osmFile). setStoreOnFlush(true). setCHEnabled(false). setGraphHopperLocation(tmpGraphFile). setEncodingManager(new EncodingManager("generic," + importVehicles, 8)); tmpHopper.setElevationProvider(new SRTMProvider().setCacheDir(new File(DIR))); tmpHopper.importOrLoad(); GHResponse rsp = tmpHopper.route(new GHRequest(43.74056471749763, 7.4299266210693755, 43.73790260334179, 7.427984089259056). setAlgorithm(ASTAR).setVehicle(vehicle).setWeighting(weightCalcStr)); PathWrapper arsp = rsp.getBest(); assertEquals(351.38545671859913, arsp.getDistance(), .1); assertEquals(6, arsp.getPoints().getSize()); assertTrue(arsp.getPoints().is3D()); assertEquals(Helper.createPointList3D( 43.7405648173518, 7.429926635993867, 17.0, <START> 43.74016602501644, 7.42986703134776, 19.042999267578125, END> 43.73963796510483, 7.429757507810537, 21.667999267578125, 43.739005969591574, 7.429468797805953, 25.024999618530273, 43.73845425408604, 7.428933846107137, 28.64699935913086, 43.73790260334179, 7.427984089259055, 31.32349967956543 ), arsp.getPoints()); }</code><technical_language>Oh, digits comma a bit ugly suggests a false precision. interpolating e.g. cm dm</technical_language>

Target:
public void testSRTMWithTunnelInterpolation() throws Exception { GraphHopper tmpHopper = new GraphHopperOSM().setOSMFile(osmFile).setStoreOnFlush(true) .setCHEnabled(false).setGraphHopperLocation(tmpGraphFile) .setEncodingManager(new EncodingManager(genericImportVehicles, 8)); tmpHopper.setElevationProvider(new SRTMProvider().setCacheDir(new File(DIR))); tmpHopper.importOrLoad(); GHResponse rsp = tmpHopper.route(new GHRequest(43.74056471749763, 7.4299266210693755, 43.73790260334179, 7.427984089259056).setAlgorithm(ASTAR) .setVehicle(vehicle).setWeighting(weightCalcStr)); PathWrapper arsp = rsp.getBest(); assertEquals(351.39, arsp.getDistance(), PRECISION); PointList pointList = arsp.getPoints(); assertEquals(6, pointList.getSize()); assertTrue(pointList.is3D()); assertEquals(17, pointList.getEle(0), PRECISION); assertEquals(19.04, pointList.getEle(1), PRECISION); assertEquals(21.67, pointList.getEle(2), PRECISION); assertEquals(25.03, pointList.getEle(3), PRECISION); assertEquals(28.65, pointList.getEle(4), PRECISION); assertEquals(31.32, pointList.getEle(5), PRECISION); }
Source:
<code>protected boolean hasIncomingChanges() { <START> TaskAttribute attribute = getModel().getTaskData().getRoot().getAttribute(getTaskAttribute().getId()); <END> if (attribute == null) { return false; } return getModel().hasIncomingChanges(attribute); }</code><technical_language>attribute a child of root, this paths</technical_language>

Target:
protected boolean hasIncomingChanges() { TaskAttribute attribute = getModel().getTaskData().getRoot().getMappedAttribute(getTaskAttribute().getPath()); if (attribute == null) { return false; } return getModel().hasIncomingChanges(attribute); }
Source:
<code>public void setCategory(SingleSignOnAccount ssoAccount, @NonNull DBNote note, @NonNull String category, @Nullable ISyncCallback callback) { note.setCategory(category); note.setStatus(DBStatus.LOCAL_EDITED); SQLiteDatabase db = this.getWritableDatabase(); ContentValues values = new ContentValues(); values.put(key_status, note.getStatus().getTitle()); <START> if (getCategoryIdByTitle(note.getAccountId(), category, false) == -1 && addCategory(note.getCategory(), note.getAccountId()) == -1) { Log.e(TAG, String.format("Error occurs when creating category: %s", note.getCategory())); } <END> int id = getCategoryIdByTitle(note.getAccountId(), note.getCategory(), true); values.put(key_category, id); db.update(table_notes, values, key_id + " = ?", new String[]{String.valueOf(note.getId())}); if (callback != null) { serverSyncHelper.addCallbackPush(ssoAccount, callback); } serverSyncHelper.scheduleSync(ssoAccount, true); }</code><technical_language>This needed getCategoryIdByTitle(..., ..., true) create category if exists. Therefore, this removed</technical_language>

Target:
public void setCategory(SingleSignOnAccount ssoAccount, @NonNull DBNote note, @NonNull String category, @Nullable ISyncCallback callback) { note.setCategory(category); note.setStatus(DBStatus.LOCAL_EDITED); SQLiteDatabase db = this.getWritableDatabase(); ContentValues values = new ContentValues(); values.put(key_status, note.getStatus().getTitle()); int id = getCategoryIdByTitle(note.getAccountId(), note.getCategory()); values.put(key_category, id); db.update(table_notes, values, key_id + " = ?", new String[]{String.valueOf(note.getId())}); removeEmptyCategory(note.getAccountId()); if (callback != null) { serverSyncHelper.addCallbackPush(ssoAccount, callback); } serverSyncHelper.scheduleSync(ssoAccount, true); }
Source:
<code>public Description matchMethodInvocation(MethodInvocationTree tree, VisitorState state) { if (!LOG_METHOD.matches(tree, state)) { return Description.NO_MATCH; } Optional<Description> wrappedThrowableDescription = checkThrowableArgumentNotWrapped(tree, state); if (wrappedThrowableDescription.isPresent()) { return wrappedThrowableDescription.get(); } List<? extends ExpressionTree> allArgs = tree.getArguments(); int startArgIndex = MARKER.matches(allArgs.get(0), state) ? 2 : 1; int lastArgIndex = allArgs.size() - 1; ExpressionTree lastArg = allArgs.get(lastArgIndex); if (startArgIndex == lastArgIndex && OBJECT_ARRAY.matches(lastArg, state)) { return Description.NO_MATCH; } boolean lastArgIsThrowable = THROWABLE.matches(lastArg, state); int lastNonThrowableArgIndex = lastArgIsThrowable ? lastArgIndex - 1 : lastArgIndex; List<Integer> badArgIndices = IntStream.rangeClosed(startArgIndex, lastNonThrowableArgIndex) .filter(i -> !ARG.matches(allArgs.get(i), state)) .boxed() <START> .collect(Collectors.toList()); <END> if (badArgIndices.isEmpty() || TestCheckUtils.isTestCode(state)) { return Description.NO_MATCH; } else { return buildDescription(tree) .setMessage("slf4j log statement does not use logsafe parameters for arguments " + badArgIndices) .build(); } }</code><technical_language>chance avoid stream here? This code is _super_ hot log a lot of things, large internal project in benefits compile speedup provide</technical_language>

Target:
public Description matchMethodInvocation(MethodInvocationTree tree, VisitorState state) { if (!LOG_METHOD.matches(tree, state)) { return Description.NO_MATCH; } Optional<Description> wrappedThrowableDescription = checkThrowableArgumentNotWrapped(tree, state); if (wrappedThrowableDescription.isPresent()) { return wrappedThrowableDescription.get(); } List<? extends ExpressionTree> allArgs = tree.getArguments(); int startArgIndex = MARKER.matches(allArgs.get(0), state) ? 2 : 1; int lastArgIndex = allArgs.size() - 1; ExpressionTree lastArg = allArgs.get(lastArgIndex); if (startArgIndex == lastArgIndex && OBJECT_ARRAY.matches(lastArg, state)) { return Description.NO_MATCH; } boolean lastArgIsThrowable = THROWABLE.matches(lastArg, state); int lastNonThrowableArgIndex = lastArgIsThrowable ? lastArgIndex - 1 : lastArgIndex; List<Integer> badArgs = getBadArgIndices(state, allArgs, startArgIndex, lastNonThrowableArgIndex); if (badArgs.isEmpty() || TestCheckUtils.isTestCode(state)) { return Description.NO_MATCH; } return buildDescription(tree) .setMessage("slf4j log statement does not use logsafe parameters for arguments " + badArgs) .build(); }
Source:
<code>public void storeServerMetrics(final String serverId, final ServerMetrics metrics) { if (metricCollectionEnabled) { if (numBlockByEvalIdForServer != null && numBlockByEvalIdForServer.containsKey(serverId)) { final int numModelBlocks = numBlockByEvalIdForServer.get(serverId); final DataInfo dataInfo = new DataInfoImpl(numModelBlocks); final EvaluatorParameters evaluatorParameters = new ServerEvaluatorParameters(serverId, dataInfo, metrics); synchronized (serverEvalParams) { if (!serverEvalParams.containsKey(serverId)) { serverEvalParams.put(serverId, new ArrayList<>()); } <START> if (initialEpochMetricArrived) { <END> serverEvalParams.get(serverId).add(evaluatorParameters); } } } else { LOG.log(Level.FINE, "No information about {0}. Dropping metric.", serverId); } } else { LOG.log(Level.FINE, "Metric collection disabled. Dropping metric from {0}", serverId); } if (dashboardSetupStatus.dashboardEnabled) { try { metricsRequestQueue.put(String.format("id=%s&metrics=%s&time=%d", serverId, metrics, System.currentTimeMillis())); } catch (InterruptedException e) { LOG.log(Level.WARNING, "Dashboard: Interrupted while taking metrics to send from the queue.", e); } } }</code><technical_language>applies here; move if statement in [L251](<LINK_0> here</technical_language>

Target:
public void storeServerMetrics(final String serverId, final ServerMetrics metrics) { if (metricCollectionEnabled) { if (numBlockByEvalIdForServer != null && numBlockByEvalIdForServer.containsKey(serverId)) { final int numModelBlocks = numBlockByEvalIdForServer.get(serverId); final DataInfo dataInfo = new DataInfoImpl(numModelBlocks); final EvaluatorParameters evaluatorParameters = new ServerEvaluatorParameters(serverId, dataInfo, metrics); synchronized (serverEvalParams) { if (workerEvalEpochParams.size() == numBlockByEvalIdForWorker.size()) { if (!serverEvalParams.containsKey(serverId)) { serverEvalParams.put(serverId, new ArrayList<>()); } if (metrics.getNumModelBlocks() == numModelBlocks) { serverEvalParams.get(serverId).add(evaluatorParameters); } else { LOG.log(Level.SEVERE, "Inconsistent NumModelBlocks: driver = {0}, {1} = {2}", new Object[] {numModelBlocks, serverId, metrics.getNumModelBlocks()}); } } } } else { LOG.log(Level.FINE, "No information about {0}. Dropping metric.", serverId); } } else { LOG.log(Level.FINE, "Metric collection disabled. Dropping metric from {0}", serverId); } if (dashboardSetupStatus.dashboardEnabled) { try { metricsRequestQueue.put(String.format("id=%s&metrics=%s&time=%d", serverId, metrics, System.currentTimeMillis())); } catch (InterruptedException e) { LOG.log(Level.WARNING, "Dashboard: Interrupted while taking metrics to send from the queue.", e); } } }
Source:
<code>public void start() { try { String localhost = InetAddress.getLocalHost().getCanonicalHostName(); attach(localhost, PORT); List<BreakpointRequest> requests= new ArrayList<>(); for (java.lang.reflect.Method fMethod : fMethods) { requests.add(createBreakpointRequest(fMethod)); } for (Constructor<?> <START> fConstructor : <END> fConstructors) { requests.add(createBreakpointRequest(fConstructor)); } fBreakpointRequests= requests.toArray(new BreakpointRequest[requests.size()]); fEventReader= new EventReader(fVM.eventQueue()); fEventReader.start(); } catch (IOException x) { x.printStackTrace(); } catch (IllegalConnectorArgumentsException x) { x.printStackTrace(); } finally { Assert.assertNotNull("Could not start performance meter, hints:\n1) check the command line arguments (see InvocationCountPerformanceMeter for details)\n2) use a different port number", fEventReader); } }</code><technical_language>rename constructor</technical_language>

Target:
public void start() { try { String localhost = InetAddress.getLocalHost().getCanonicalHostName(); attach(localhost, PORT); List<BreakpointRequest> requests= new ArrayList<>(); for (java.lang.reflect.Method method : fMethods) { requests.add(createBreakpointRequest(method)); } for (Constructor<?> constructor : fConstructors) { requests.add(createBreakpointRequest(constructor)); } fBreakpointRequests= requests.toArray(new BreakpointRequest[requests.size()]); fEventReader= new EventReader(fVM.eventQueue()); fEventReader.start(); } catch (IOException x) { x.printStackTrace(); } catch (IllegalConnectorArgumentsException x) { x.printStackTrace(); } finally { Assert.assertNotNull("Could not start performance meter, hints:\n1) check the command line arguments (see InvocationCountPerformanceMeter for details)\n2) use a different port number", fEventReader); } }
Source:
<code>public void sessionCreated(HttpSessionEvent se) { ServletContext servletContext; ApplicationContext ctx; JCommuneProperty property = null; try { servletContext = se.getSession().getServletContext(); ctx = WebApplicationContextUtils.getRequiredWebApplicationContext(servletContext); property = (JCommuneProperty) ctx.getBean("sessionTimeoutProperty"); locationService = (LocationService) ctx.getBean("locationService"); } catch (Exception ex) { <START> logger.warn("Bean instantiation error: " + ex.getMessage()); <END> } int value = property != null ? property.intValue() : 0; int timeoutInSeconds = (int) TimeUnit.SECONDS.convert(value, TimeUnit.MINUTES); if (timeoutInSeconds > 0) { se.getSession().setMaxInactiveInterval(timeoutInSeconds); } else { se.getSession().setMaxInactiveInterval(-1); } }</code><technical_language>re-throw error app crash startup</technical_language>

Target:
public void sessionCreated(HttpSessionEvent se) { try { if (sessionTimeoutProperty == null) { synchronized (this) { if (sessionTimeoutProperty == null){ ServletContext context = se.getSession().getServletContext(); sessionTimeoutProperty = getBeanFormApplicationContext(context, JCommuneProperty.class, "sessionTimeoutProperty"); locationService = getBeanFormApplicationContext(context, LocationService.class, "locationService"); int seconds = extractValueFromProperty(sessionTimeoutProperty); TIME_OUT_SECONDS = seconds > 0 ? seconds : -1; } } } se.getSession().setMaxInactiveInterval(TIME_OUT_SECONDS); } catch (Exception ex) { logger.warn("Bean instantiation error: " + ex); throw ex; } }
Source:
<code>static TransactionManagerContext createTransactionManager( TestableTimelockCluster cluster, String agent, AtlasDbRuntimeConfig runtimeConfigTemplate, Optional<LockDiagnosticComponents> diagnosticComponents, Schema... schemas) { List<String> serverUris = cluster.servers().stream() .map(server -> server.serverHolder().getTimelockUri()) .collect(Collectors.toList()); AtlasDbConfig config = ImmutableAtlasDbConfig.builder() .namespace(agent) .keyValueService(new InMemoryAtlasDbConfig()) .timelock(ImmutableTimeLockClientConfig.builder() .serversList(ImmutableServerListConfig.builder() .servers(serverUris) .sslConfiguration(SslConfiguration.of(Paths.get("var/security/trustStore.jks"))) .build()) <START> .client(Optional.of(agent)) <END> .build()) .build(); AtlasDbRuntimeConfig runtimeConfig = ImmutableAtlasDbRuntimeConfig .copyOf(runtimeConfigTemplate) .withRemotingClient(RemotingClientConfigs.DEFAULT); TransactionManager transactionManager = TransactionManagers.builder() .config(config) .userAgent(UserAgent.of(UserAgent.Agent.of("u" + agent, "0.0.0"))) .globalMetricsRegistry(new MetricRegistry()) .globalTaggedMetricRegistry(DefaultTaggedMetricRegistry.getDefault()) .runtimeConfigSupplier(() -> Optional.of(runtimeConfig)) .lockDiagnosticComponents(diagnosticComponents) .addSchemas(schemas) .build() .serializable(); return ImmutableTransactionManagerContext.builder() .transactionManager(transactionManager) .install(config) .runtime(runtimeConfig) .build(); }</code><technical_language>need this? I a break if turned out _must_ a client</technical_language>

Target:
static TransactionManagerContext createTransactionManager( TestableTimelockCluster cluster, String agent, AtlasDbRuntimeConfig runtimeConfigTemplate, Optional<LockDiagnosticComponents> diagnosticComponents, Schema... schemas) { List<String> serverUris = cluster.servers().stream() .map(server -> server.serverHolder().getTimelockUri()) .collect(Collectors.toList()); AtlasDbConfig config = ImmutableAtlasDbConfig.builder() .namespace(agent) .keyValueService(new InMemoryAtlasDbConfig()) .timelock(ImmutableTimeLockClientConfig.builder() .serversList(ImmutableServerListConfig.builder() .servers(serverUris) .sslConfiguration(SslConfiguration.of(Paths.get("var/security/trustStore.jks"))) .build()) .build()) .build(); AtlasDbRuntimeConfig runtimeConfig = ImmutableAtlasDbRuntimeConfig .copyOf(runtimeConfigTemplate) .withRemotingClient(RemotingClientConfigs.DEFAULT); TransactionManager transactionManager = TransactionManagers.builder() .config(config) .userAgent(UserAgent.of(UserAgent.Agent.of("u" + agent, "0.0.0"))) .globalMetricsRegistry(new MetricRegistry()) .globalTaggedMetricRegistry(DefaultTaggedMetricRegistry.getDefault()) .runtimeConfigSupplier(() -> Optional.of(runtimeConfig)) .lockDiagnosticComponents(diagnosticComponents) .addSchemas(schemas) .build() .serializable(); return ImmutableTransactionManagerContext.builder() .transactionManager(transactionManager) .install(config) .runtime(runtimeConfig) .build(); }
Source:
<code>private static List<BaseResource> getInlineResources(Object obj) { ArrayList<BaseResource> ret = new ArrayList<>(); for (Method method : getRelevantMethods(obj.getClass())) { Object inline = null; try { inline = method.invoke(obj); } catch (Exception e) { } if (inline != null) { if (inline instanceof BaseResource) { ret.add((BaseResource) inline); } else if (inline instanceof BaseResources) { BaseResources entities = (BaseResources)inline; Method getter = EntityHelper.getCollectionGetter(entities); try { List<BaseResource> entitiesList = (List<BaseResource>) getter.invoke(entities); for (BaseResource entity : entitiesList) { ret.add(entity); } } catch (Exception e) { <START> log.error("Error invoking " + method.getName() + " on " + entities.getClass().getSimpleName(), e); <END> } } else { ret.addAll(getInlineResources(inline)); } } } return ret; }</code><technical_language>slf4j instead of string concatenation: log.error( "Error invoking method '{}' class '{}'.", method.getName(), entities.getClass().getSimpleName() ); log.error("Exception", e); advantage of is string concatenation executed if log level ERROR is disabled. relevant here, ERROR disabled, useful for other cases, specially combined DEBUG level. Note need separate lines for message stack trace of a limitation in version of slf4j use</technical_language>

Target:
private static List<BaseResource> getInlineResources(Object obj) { ArrayList<BaseResource> ret = new ArrayList<>(); for (Method method : getRelevantMethods(obj.getClass())) { Object inline = null; try { inline = method.invoke(obj); } catch (Exception e) { } if (inline != null) { if (inline instanceof BaseResource) { ret.add((BaseResource) inline); } else if (inline instanceof BaseResources) { BaseResources entities = (BaseResources)inline; Method getter = EntityHelper.getCollectionGetter(entities); try { List<BaseResource> entitiesList = (List<BaseResource>) getter.invoke(entities); for (BaseResource entity : entitiesList) { ret.add(entity); } } catch (Exception e) { log.error( "Error invoking method '{}' on class '{}'.", method.getName(), entities.getClass().getSimpleName() ); log.error("Exception", e); } } else { ret.addAll(getInlineResources(inline)); } } } return ret; }