auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public boolean equals(Object other) { if (other instanceof BeatRange) { <START> BeatRange other2 = (BeatRange) other; <END> if (this.start == other2.start && this.length == other2.length) { return true; } } return false; }</code><technical_language>another beat? casts in if case "other" instead of making another beatrange "other2"</technical_language>

Target:
public boolean equals(Object other) { if (other instanceof BeatRange) { if (this.start == ((BeatRange) other).start && this.length == ((BeatRange) other).length) { return true; } } return false; }
Source:
<code>public static @Nullable ITmfStateSystem getStateSystem(ITmfTrace trace, String moduleId) { TmfStateSystemAnalysisModule module = trace.getAnalysisModuleOfClass(TmfStateSystemAnalysisModule.class, moduleId); if (module != null) { <START> module.schedule(); <END> module.waitForInitialization(); return module.getStateSystem(); } return null; }</code><technical_language>Feels check return of schedule(), I able get a hanging thread I changed LTTng Kernel Analysis non-automatic. I able get a hanging thread in CallStackView.getCallStackModule() line 1337. Also, in MemoryUsageViewer.updateData() line 153, StateSystemDisposedException logged error</technical_language>

Target:
public static @Nullable ITmfStateSystem getStateSystem(ITmfTrace trace, String moduleId) { TmfStateSystemAnalysisModule module = trace.getAnalysisModuleOfClass(TmfStateSystemAnalysisModule.class, moduleId); if (module != null) { IStatus status = module.schedule(); if (status.isOK()) { module.waitForInitialization(); return module.getStateSystem(); } } return null; }
Source:
<code>private boolean isOfType(String contentType, String expectedContentType, String expectedWithDelim) { <START> return contentType != null && (contentType.length() > expectedContentType.length() ? <END> contentType.startsWith(expectedWithDelim) : contentType.equals(expectedContentType)); }</code><technical_language>check startsWith</technical_language>

Target:
private boolean isOfType(String contentType, String expectedContentType, String expectedWithDelim) { return contentType != null && (contentType.equals(expectedContentType) || contentType.startsWith(expectedWithDelim)); }
Source:
<code>private void tryMirror(){ <START> if ((urlIndex+1) < urls.size()){ <END> urlIndex++; LoadWebViewUrl(urls.get(urlIndex)); } else { urlIndex = 0; LoadWebViewUrl(urls.get(urlIndex)); } }</code><technical_language>Added a check, jsonexception happen</technical_language>

Target:
private void tryMirror(){ if (urls.size() == 0) return; if ((urlIndex+1) < urls.size()){ urlIndex++; LoadWebViewUrl(urls.get(urlIndex)); } else { urlIndex = 0; LoadWebViewUrl(urls.get(urlIndex)); } }
Source:
<code>public void search() { eventsList = service.search(selectedService, selectedException, fromDate, toDate); <START> msgEventResult = CollectionUtils.isNotEmpty(eventsList) ? "Event record(s) found." : "No event record found."; <END> }</code><technical_language>Do want found? "Event records found" meaningful</technical_language>

Target:
public void search() { selectedEvent = null; eventsList = service.search(selectedService, selectedException, fromDate, toDate); msgEventResult = MessageFormat.format("{0} event record found.", getEvents().size()); }
Source:
<code>public boolean providePlayerCube(boolean canGenerate) { int cubeX = getX(cubeAddress); int cubeY = getY(cubeAddress); int cubeZ = getZ(cubeAddress); playerCubeMap.getWorld().getProfiler().startSection("getCube"); if(cube != null){ <START> this.cube.getTickets().remove(this); END> } if (canGenerate) { this.cube = this.cubeCache.getCube(cubeX, cubeY, cubeZ, IProviderExtras.Requirement.LIGHT); } else { this.cube = this.cubeCache.getCube(cubeX, cubeY, cubeZ, IProviderExtras.Requirement.LOAD); } if(this.cube != null){ this.cube.getTickets().add(this); } playerCubeMap.getWorld().getProfiler().endSection(); return this.cube != null; }</code><technical_language>allow adding ticket twice</technical_language>

Target:
public boolean providePlayerCube(boolean canGenerate) { int cubeX = getX(cubeAddress); int cubeY = getY(cubeAddress); int cubeZ = getZ(cubeAddress); playerCubeMap.getWorld().getProfiler().startSection("getCube"); if (canGenerate) { this.cube = this.cubeCache.getCube(cubeX, cubeY, cubeZ, IProviderExtras.Requirement.LIGHT); } else { this.cube = this.cubeCache.getCube(cubeX, cubeY, cubeZ, IProviderExtras.Requirement.LOAD); } if(this.cube != null){ this.cube.getTickets().add(this); } playerCubeMap.getWorld().getProfiler().endSection(); return this.cube != null; }
Source:
<code>public boolean isAudio() { return ((mMimeType != null && mMimeType.startsWith("audio/")) || <START> getMimeTypeFromName().startsWith("audio/")); <END> }</code><technical_language>isAudio, isVideo, isText, is Image exact code for string check, code simplified generic, private method is called for public ones</technical_language>

Target:
public boolean isAudio() { return isOfType("audio/"); }
Source:
<code>public void noNavigatorNoFactoryInstalled() throws Exception { assertThat(ExtensionList.lookup(SCMNavigatorDescriptor.class), contains(instanceOf(SingleSCMNavigator.DescriptorImpl.class))); <START> assertEquals(0, ExtensionList.lookup(MultiBranchProjectFactoryDescriptor.class).size()); END> assertThat(newItemTypes(), containsInAnyOrder()); }</code><technical_language>of defined test extensions here-any of MockXXX subtypes</technical_language>

Target:
public void noNavigatorNoFactoryInstalled() throws Exception { assumeThat(ExtensionList.lookup(SCMNavigatorDescriptor.class), hasSize(1)); assumeThat(ExtensionList.lookup(SCMNavigatorDescriptor.class).get(0).getClass(), is(SingleSCMNavigator.DescriptorImpl.class)); assumeThat(ExtensionList.lookup(MultiBranchProjectFactoryDescriptor.class), is(empty())); assertThat(newItemTypes(), containsInAnyOrder()); }
Source:
<code>public String getOptionValue(final String optionName) { <START> return (String)this.cmd.getOptionValue(optionName); <END> }</code><technical_language>a toString method instead of a cast</technical_language>

Target:
public String getOptionValue(final String optionName) { final Object val = this.cmd.getOptionValue(optionName); if (val == null) { return null; } return val.toString(); }
Source:
<code>private Function<Throwable, Throwable> getThrowableFunction(CoreEvent event) { return throwable -> { CoreEvent exceptionEvent = event; Throwable retryPolicyExhaustionCause = getMessagingExceptionCause(throwable); retryPolicyExhaustionCause = <START> suppressIfPresent(retryPolicyExhaustionCause, ConnectionException.class, false); <END> if (throwable instanceof MessagingException) { exceptionEvent = ((MessagingException) throwable).getEvent(); } return new MessagingException(exceptionEvent, new RetryPolicyExhaustedException(createStaticMessage(UNTIL_SUCCESSFUL_MSG_PREFIX, retryPolicyExhaustionCause .getMessage()), retryPolicyExhaustionCause, owner), owner); }; }</code><technical_language>logged in this case in troubleshooting</technical_language>

Target:
private Function<Throwable, Throwable> getThrowableFunction(CoreEvent event) { return throwable -> { CoreEvent exceptionEvent = event; Throwable retryPolicyExhaustionCause = suppressIfPresent(throwable, MuleException.class); RetryPolicyExhaustedException retryPolicyExhaustedException = new RetryPolicyExhaustedException(createStaticMessage(UNTIL_SUCCESSFUL_MSG), retryPolicyExhaustionCause, owner); retryPolicyExhaustedException.addInfo(MuleExceptionInfo.INFO_CAUSED_BY_KEY, retryPolicyExhaustionCause); if (throwable instanceof MessagingException) { exceptionEvent = ((MessagingException) throwable).getEvent(); } return new MessagingException(exceptionEvent, retryPolicyExhaustedException, owner); }; }
Source:
<code>public Object visitClearCommand(InvocationContext ctx, ClearCommand command) throws Throwable { <START> persistenceManager.clearAllStores(SHARED); <END> return null; }</code><technical_language>clear is non-transactional, I ignore ClearCommand (or throw UnsupportedOperationException)</technical_language>

Target:
public Object visitClearCommand(InvocationContext ctx, ClearCommand command) throws Throwable { throw new UnsupportedOperationException("Clear command not supported inside a transaction"); }
Source:
<code>protected boolean readElement(IConfigurationElement element, boolean add) { String tagName = element.getName(); <START> if (tagName.equals(TAG_PROFILE) <END> || tagName.equals(TAG_PACKAGE)) { String uri = element.getAttribute(ATT_URI); if (uri == null) { logMissingAttribute(element, ATT_URI); } else if (add) { String location = element.getAttribute(ATT_LOCATION); if (location != null) { URI profileLocation = URI.createURI(location); if (profileLocation.isRelative()) { profileLocation = URI.createPlatformPluginURI( element.getDeclaringExtension() .getContributor().getName() + '/' + location, false); } if (ePackageNsURIToPackageLocationMap != null){ ePackageNsURIToPackageLocationMap.put(uri, profileLocation); } if (tagName.equals(TAG_PROFILE)) { ePackageNsURIToProfileLocationMap.put(uri, profileLocation); } } return true; } else { if (ePackageNsURIToPackageLocationMap != null) { ePackageNsURIToPackageLocationMap.remove(uri); } if (tagName.equals(TAG_PROFILE)) { ePackageNsURIToProfileLocationMap.remove(uri); } return true; } } return false; }</code><technical_language>safely ensure profile location map is a subset of generic package one, I separate in end (so iterate profiles lookups for packages)</technical_language>

Target:
protected boolean readElement(IConfigurationElement element, boolean add) { String tagName = element.getName(); if (tagName.equals(TAG_PROFILE) || tagName.equals(TAG_PACKAGE)) { Map<String, URI> uriToLocationMap = tagName.equals(TAG_PROFILE) ? ePackageNsURIToProfileLocationMap : ePackageNsURIToPackageLocationMap; String uri = element.getAttribute(ATT_URI); if (uri == null) { logMissingAttribute(element, ATT_URI); } else if (add) { if (uriToLocationMap != null) { String location = element.getAttribute(ATT_LOCATION); if (location != null) { URI profileLocation = URI.createURI(location); if (profileLocation.isRelative()) { profileLocation = URI.createPlatformPluginURI( element.getDeclaringExtension() .getContributor().getName() + '/' + location, false); } uriToLocationMap.put(uri, profileLocation); } } return true; } else { uriToLocationMap.remove(uri); return true; } } return false; }
Source:
<code>private String acquireVF() { try { hostDeviceManager.acquireHostDevicesLock(getVdsId()); String vfToUse = findFreeVf(); <START> networkDeviceHelper.setVmIdOnVfs(getVdsId(), getVmId(), Collections.singleton(vfToUse)); <END> return vfToUse; } finally { hostDeviceManager.releaseHostDevicesLock(getVdsId()); } }</code><technical_language>vfToUse null. This problems, setVmIdOnVfs handle correctly, safer check (as case in original code)</technical_language>

Target:
private String acquireVF() { try { hostDeviceManager.acquireHostDevicesLock(getVdsId()); return findFreeVf(); } finally { hostDeviceManager.releaseHostDevicesLock(getVdsId()); } }
Source:
<code>public ConstraintWeightDescriptor(ConstraintConfigurationDescriptor<Solution_> constraintConfigurationDescriptor, MemberAccessor memberAccessor) { this.constraintConfigurationDescriptor = constraintConfigurationDescriptor; ConstraintWeight constraintWeightAnnotation = memberAccessor.getAnnotation(ConstraintWeight.class); String constraintPackage = constraintPackage = constraintWeightAnnotation.constraintPackage(); if (constraintPackage.isEmpty()) { <START> ConstraintConfiguration packAnnotation = memberAccessor.getDeclaringClass().getAnnotation(ConstraintConfiguration.class); <END> if (packAnnotation == null) { throw new IllegalStateException("Impossible state: " + ConstraintConfigurationDescriptor.class.getSimpleName() + " only reflects over members with a " + ConstraintConfiguration.class.getSimpleName() + " annotation."); } constraintPackage = packAnnotation.constraintPackage(); if (constraintPackage.isEmpty()) { constraintPackage = memberAccessor.getDeclaringClass().getPackage().getName(); } } this.constraintPackage = constraintPackage; this.constraintName = constraintWeightAnnotation.value(); this.memberAccessor = memberAccessor; }</code><technical_language>Is local variable name a leftover previous ConstraintPack naming</technical_language>

Target:
public ConstraintWeightDescriptor(ConstraintConfigurationDescriptor<Solution_> constraintConfigurationDescriptor, MemberAccessor memberAccessor) { this.constraintConfigurationDescriptor = constraintConfigurationDescriptor; ConstraintWeight constraintWeightAnnotation = memberAccessor.getAnnotation(ConstraintWeight.class); String constraintPackage = constraintWeightAnnotation.constraintPackage(); if (constraintPackage.isEmpty()) { ConstraintConfiguration constraintConfigurationAnnotation = memberAccessor.getDeclaringClass() .getAnnotation(ConstraintConfiguration.class); if (constraintConfigurationAnnotation == null) { throw new IllegalStateException("Impossible state: " + ConstraintConfigurationDescriptor.class.getSimpleName() + " only reflects over members with a " + ConstraintConfiguration.class.getSimpleName() + " annotation."); } constraintPackage = constraintConfigurationAnnotation.constraintPackage(); if (constraintPackage.isEmpty()) { constraintPackage = memberAccessor.getDeclaringClass().getPackage().getName(); } } this.constraintPackage = constraintPackage; this.constraintName = constraintWeightAnnotation.value(); this.memberAccessor = memberAccessor; }
Source:
<code>public static ResourceSet loadResourceWithProxies(URI resourceURI, final ResourceSet resourceSet) { try { <START> if (addResourceToSet(resourceSet, resourceURI)) { <END> return resourceSet; } } catch (final IOException ex) { Activator.getDefault().getReportService().report( new StatusReport(new Status(IStatus.ERROR, Activator.PLUGIN_ID, ex.getMessage(), ex))); } return null; }</code><technical_language>call new method null parameter</technical_language>

Target:
public static ResourceSet loadResourceWithProxies(URI resourceURI, final ResourceSet resourceSet) { try { if (addResourceToSet(resourceSet, resourceURI, null)) { return resourceSet; } } catch (final IOException ex) { Activator.getDefault().getReportService().report( new StatusReport(new Status(IStatus.ERROR, Activator.PLUGIN_ID, ex.getMessage(), ex))); } return null; }
Source:
<code>protected boolean isDuplicateEntry(String token, Usage usageRecord) { try { ClientResponse response = client.getEntry(token, usageRecord.getUuid()); if (response.getStatus() == 200) { return true; } } catch (Exception e) { LOG.warn(String.format("Could not verify duplicate entry for UUID: %s, attempt to re-push the record...", usageRecord.getUuid())); <START> return false; <END> } return false; }</code><technical_language>NIT: this needed this method returns false default</technical_language>

Target:
protected boolean isDuplicateEntry(String token, Usage usageRecord) { try { ClientResponse response = client.getEntry(token, usageRecord.getUuid()); if (response.getStatus() == 200) { return true; } } catch (Exception e) { LOG.warn(String.format("Could not verify duplicate entry for UUID: %s, attempt to re-push the record...", usageRecord.getUuid())); } return false; }
Source:
<code><START> protected static VariantContext liftSimpleVariant(final VariantContext source, final Interval target){ <END> if (target == null) return null; if (source.getReference().length() != target.length()) { return null; } final List<Allele> alleles = new ArrayList<>(); for (final Allele oldAllele : source.getAlleles()) { if (target.isPositiveStrand() || oldAllele.isSymbolic()) { alleles.add(oldAllele); } else { final Allele fixedAllele = Allele.create(SequenceUtil.reverseComplement(oldAllele.getBaseString()), oldAllele.isReference()); alleles.add(fixedAllele); } } final VariantContextBuilder builder = new VariantContextBuilder( source.getSource(), target.getContig(), target.getStart(), target.getEnd(), alleles); builder.id(source.getID()); return builder.make(); }</code><technical_language>Picky: need space bracket</technical_language>

Target:
protected static VariantContext liftSimpleVariant(final VariantContext source, final Interval target) { if (target == null) { return null; } if (source.getReference().length() != target.length()) { return null; } final List<Allele> alleles = new ArrayList<>(); for (final Allele oldAllele : source.getAlleles()) { if (target.isPositiveStrand() || oldAllele.isSymbolic()) { alleles.add(oldAllele); } else { final Allele fixedAllele = Allele.create(SequenceUtil.reverseComplement(oldAllele.getBaseString()), oldAllele.isReference()); alleles.add(fixedAllele); } } final VariantContextBuilder builder = new VariantContextBuilder( source.getSource(), target.getContig(), target.getStart(), target.getEnd(), alleles); builder.id(source.getID()); return builder.make(); }
Source:
<code>public FacultyMemberProfile commitValue() { FacultyMemberProfile facultyMemberEditor = getAttachedFacultyMemberProfile(); facultyMemberEditor.setFirstName(_firstName.getText()); facultyMemberEditor.setLastName(_lastName.getText()); facultyMemberEditor.setRank((Rank) _rank.getSelectedObject()); facultyMemberEditor.setResearchArea(_resArea.getText()); facultyMemberEditor.setPicture(_img); facultyMemberEditor.setJoinDate(_joinDate.getDate()); <START> if(_sabbatical.getSelectedIndex()==1) <END> facultyMemberEditor.setSabbatical(true); else { facultyMemberEditor.setSabbatical(false); } facultyMemberEditor.setSlug(_firstName.getText()+" "+_lastName.getText()); facultyMemberEditor.setDeleted(false); _facultyMemberDao.saveFacultyMemberProfile(facultyMemberEditor); return facultyMemberEditor; }</code><technical_language>this more concise: facultyMemberEditor.setSabbatical(_sabbatical.getSelectedInex() == 1);</technical_language>

Target:
public FacultyMemberProfile commitValue() { FacultyMemberProfile facultyMemberEditor = _facultyMemberDao.getAttachedFacultyMemberProfile(_facultyMemberProfile); facultyMemberEditor.setFirstName(_firstName.getText()); facultyMemberEditor.setLastName(_lastName.getText()); facultyMemberEditor.setRank((Rank) _rank.getSelectedObject()); facultyMemberEditor.setResearchArea(_resArea.getText()); facultyMemberEditor.setPicture(_img); facultyMemberEditor.setJoinDate(_joinDate.getDate()); if(_sabbatical.getSelectedIndex()==1) facultyMemberEditor.setSabbatical(_sabbatical.getSelectedIndex()==1); else { facultyMemberEditor.setSabbatical(_sabbatical.getSelectedIndex()==2); } facultyMemberEditor.setSlug(getLastName(_lastName.getText()).toLowerCase()+_firstName.getText()); facultyMemberEditor.setDeleted(false); _facultyMemberDao.saveFacultyMemberProfile(facultyMemberEditor); close(); return facultyMemberEditor; }
Source:
<code>public Map<Guid, List<String>> getHostNetworksByCluster(Guid clusterId) { MapSqlParameterSource parameterSource = getCustomMapSqlParameterSource() .addValue("cluster_id", clusterId); List<Pair<Guid, String>> list = <START> getCallsHandler().executeReadList("GetHostNetworksByCluster", new RowMapper<Pair<Guid, String>>() { <END> @Override public Pair<Guid, String> mapRow(ResultSet rs, int arg1) throws SQLException { return new Pair<Guid, String>(getGuid(rs, "vds_id"), rs.getString("network_name")); } }, parameterSource); Map<Guid, List<String>> map = new HashMap<Guid, List<String>>(); if (list != null) { for (Pair<Guid, String> pair : list) { List<String> hostNameList = map.get(pair.getFirst()); if (hostNameList == null) { hostNameList = new ArrayList<>(); map.put(pair.getFirst(), hostNameList); } hostNameList.add(pair.getSecond()); } } return map; }</code><technical_language>convention is mappers static in order reduce instantiations state. Please extract a private static class</technical_language>

Target:
public Map<Guid, List<String>> getHostNetworksByCluster(Guid clusterId) { MapSqlParameterSource parameterSource = getCustomMapSqlParameterSource() .addValue("cluster_id", clusterId); List<Pair<Guid, String>> hostNetworks = getCallsHandler().executeReadList("GetHostNetworksByCluster", HostNetworkNameMapper, parameterSource); Map<Guid, List<String>> neworksByHost = new HashMap<>(); for (Pair<Guid, String> pair : hostNetworks) { if (!neworksByHost.containsKey(pair.getFirst())) { neworksByHost.put(pair.getFirst(), new ArrayList<String>()); } neworksByHost.get(pair.getFirst()).add(pair.getSecond()); } return neworksByHost; }
Source:
<code>public void shouldPerformIndexScan() throws Exception { int label = token.nodeLabel( "Node" ); int prop = token.propertyKey( "prop" ); CapableIndexReference index = schemaRead.index( label, prop ); <START> IndexValueCapability wildcardCapability = index.value( new ValueGroup[]{null} ); <END> try ( NodeValueIndexCursor node = cursors.allocateNodeValueIndexCursor(); PrimitiveLongSet uniqueIds = Primitive.longSet() ) { read.nodeIndexScan( index, node, null ); assertFoundNodesAndValue( node, 24, uniqueIds, wildcardCapability ); } }</code><technical_language>WDYT passing empty var-args instead of new ValueGroup[]{null}</technical_language>

Target:
public void shouldPerformIndexScan() throws Exception { int label = token.nodeLabel( "Node" ); int prop = token.propertyKey( "prop" ); CapableIndexReference index = schemaRead.index( label, prop ); IndexValueCapability wildcardCapability = index.valueCapability( ValueGroup.UNKNOWN ); try ( NodeValueIndexCursor node = cursors.allocateNodeValueIndexCursor(); PrimitiveLongSet uniqueIds = Primitive.longSet() ) { read.nodeIndexScan( index, node, IndexOrder.NONE ); assertFoundNodesAndValue( node, 24, uniqueIds, wildcardCapability ); } }
Source:
<code>public Response update(String json) { if(!DeploymentEnvironment.isAppEngineDevelopment() && !user.get().getEmail().endsWith("@bedatadriven.com")) { return Response.status(Status.FORBIDDEN).build(); } Gson gson = new Gson(); final JsonElement jsonElement = gson.fromJson(json, JsonElement.class); return queryExecutor.doWork(new HibernateQueryExecutor.StoreSession<Response>() { @Override public Response execute(CollectionCatalog catalog) { Updater updater = new Updater(catalog); try { updater.execute(jsonElement.getAsJsonObject()); } catch (InvalidUpdateException e) { <START> throw new WebApplicationException(Response.status(Status.BAD_REQUEST).entity(e.getMessage()).build()); <END> } return Response.ok().build(); } }); }</code><technical_language>![MAJOR](<LINK_0> log rethrow this exception. [![rule](<LINK_1>](<LINK_2></technical_language>

Target:
public Response update(String json) { assertUserIsTrustedWhileInBeta(); Gson gson = new Gson(); final JsonElement jsonElement = gson.fromJson(json, JsonElement.class); return queryExecutor.doWork(new HibernateQueryExecutor.StoreSession<Response>() { @Override public Response execute(CollectionCatalog catalog) { Updater updater = new Updater(catalog); try { updater.execute(jsonElement.getAsJsonObject()); } catch (InvalidUpdateException e) { throw new WebApplicationException(Response.status(Status.BAD_REQUEST) .entity(e.getMessage()) .build()); } return Response.ok().build(); } }); }
Source:
<code>private void addDAGToCurrentDAG(ModuleMeta moduleMeta) { LogicalPlan subDag = moduleMeta.getDag(); String subDAGName = moduleMeta.getName(); String name; for (OperatorMeta operatorMeta : subDag.getAllOperators()) { name = subDAGName + MODULE_NAMESPACE_SEPARATOR + operatorMeta.getName(); <START> Operator op = this.addOperator(name, operatorMeta.getOperator()); <END> this.getMeta(op).copyFrom(operatorMeta); OperatorMeta operatorMetaNew = this.getOperatorMeta(name); operatorMetaNew.setModuleName(operatorMeta.getModuleName() == null ? subDAGName : subDAGName + MODULE_NAMESPACE_SEPARATOR + operatorMeta.getModuleName()); } for (StreamMeta streamMeta : subDag.getAllStreams()) { OutputPortMeta sourceMeta = streamMeta.getSource(); List<InputPort<?>> ports = new LinkedList<>(); for (InputPortMeta inputPortMeta : streamMeta.getSinks()) { ports.add(inputPortMeta.getPortObject()); } InputPort[] inputPorts = ports.toArray(new InputPort[]{}); name = subDAGName + MODULE_NAMESPACE_SEPARATOR + streamMeta.getName(); StreamMeta streamMetaNew = this.addStream(name, sourceMeta.getPortObject(), inputPorts); streamMetaNew.copyFrom(streamMeta); } }</code><technical_language>LogicalPlan class provide a new method allows add Operator existing OperatorMeta? private <T extends Operator> T addOperator(final String name, final OperatorMeta operatorMeta) { }</technical_language>

Target:
private void addDAGToCurrentDAG(ModuleMeta moduleMeta) { LogicalPlan subDag = moduleMeta.getDag(); String subDAGName = moduleMeta.getName(); String name; for (OperatorMeta operatorMeta : subDag.getAllOperators()) { name = subDAGName + MODULE_NAMESPACE_SEPARATOR + operatorMeta.getName(); Operator op = this.addOperator(name, operatorMeta.getOperator()); OperatorMeta operatorMetaNew = this.getMeta(op); operatorMetaNew.copyAttributesFrom(operatorMeta); operatorMetaNew.setModuleName(operatorMeta.getModuleName() == null ? subDAGName : subDAGName + MODULE_NAMESPACE_SEPARATOR + operatorMeta.getModuleName()); } for (StreamMeta streamMeta : subDag.getAllStreams()) { OutputPortMeta sourceMeta = streamMeta.getSource(); List<InputPort<?>> ports = new LinkedList<>(); for (InputPortMeta inputPortMeta : streamMeta.getSinks()) { ports.add(inputPortMeta.getPortObject()); } InputPort[] inputPorts = ports.toArray(new InputPort[]{}); name = subDAGName + MODULE_NAMESPACE_SEPARATOR + streamMeta.getName(); StreamMeta streamMetaNew = this.addStream(name, sourceMeta.getPortObject(), inputPorts); streamMetaNew.setLocality(streamMeta.getLocality()); } }
Source:
<code>public AccessContext(IASTName name) { this.name = name; <START> this.isPrefixLookup = false; <END> }</code><technical_language>Please delegate other constructor this(name, false); in constructor body</technical_language>

Target:
public AccessContext(IASTName name) { this(name, false); }
Source:
<code>protected boolean acquireLock() { if (getLock() == null) { if (!super.acquireLock()) { return false; } if (!Guid.Empty.equals(getVmId()) && isVmPrestarted()) { EngineLock runLock = vmPoolHandler.createLock(getVmId()); Map<String, Pair<String, String>> exclusiveLocks = new HashMap<>(); Map<String, Pair<String, String>> sharedLocks = new HashMap<>(); <START> exclusiveLocks.putAll(getContext().getLock().getExclusiveLocks()); <END> exclusiveLocks.putAll(runLock.getExclusiveLocks()); if (getContext().getLock().getSharedLocks() != null) { sharedLocks.putAll(getContext().getLock().getSharedLocks()); } if (runLock.getSharedLocks() != null) { sharedLocks.putAll(runLock.getSharedLocks()); } setLock(new EngineLock(exclusiveLocks, sharedLocks)); } } return true; }</code><technical_language>For exclusiveLocks need safeguarding</technical_language>

Target:
protected boolean acquireLock() { if (getLock() == null) { if (!super.acquireLock()) { return false; } if (!Guid.Empty.equals(getVmId()) && isVmPrestarted()) { EngineLock runLock = vmPoolHandler.createLock(getVmId()); Map<String, Pair<String, String>> exclusiveLocks = new HashMap<>(); Map<String, Pair<String, String>> sharedLocks = new HashMap<>(); if (getContext().getLock().getExclusiveLocks() != null) { exclusiveLocks.putAll(getContext().getLock().getExclusiveLocks()); } exclusiveLocks.putAll(runLock.getExclusiveLocks()); if (getContext().getLock().getSharedLocks() != null) { sharedLocks.putAll(getContext().getLock().getSharedLocks()); } if (runLock.getSharedLocks() != null) { sharedLocks.putAll(runLock.getSharedLocks()); } setLock(new EngineLock(exclusiveLocks, sharedLocks)); } } return true; }
Source:
<code>public void failed(final Exception ex) { <START> LOG.log(Level.WARNING, "Dashboard: Post request failed - ", ex); <END> }</code><technical_language>purpose of trailing - in logging msgs</technical_language>

Target:
public void failed(final Exception ex) { LOG.log(Level.WARNING, "Dashboard: Post request failed.", ex); }
Source:
<code>public List<String> readDepgraphs() { <START> if (depgraphs != null) { <END> return depgraphs; } List<String> result = new ArrayList<>(); for (String file : depgraphFiles) { try { result.add(Files.toString(new File(file), UTF_8)); } catch (FileNotFoundException e) { throw new IllegalArgumentException("depgraph file not found: " + file, e); } catch (IOException e) { throw new RuntimeException("error reading depgraph file " + file, e); } } return result; }</code><technical_language>AFAICT this in tests, actual code need caching. refactor avoid that? Also, build this options class is immutable parsed everything? odd this change state hold file contents</technical_language>

Target:
public List<String> readDepgraphs() { List<String> result = new ArrayList<>(); for (String file : depgraphFiles) { try { result.add(Files.toString(new File(file), UTF_8)); } catch (FileNotFoundException e) { throw new IllegalArgumentException("depgraph file not found: " + file, e); } catch (IOException e) { throw new RuntimeException("error reading depgraph file " + file, e); } } return result; }
Source:
<code>public void onEvent(Event event) { long eventSeenAt = 0L; boolean trackMetrics = false; EventType eventType = event.getHeader().getEventType(); if (eventType == EventType.QUERY) { transactionStartTime = event.getHeader().getTimestamp(); } else if (eventType == EventType.XID) { trackMetrics = true; eventSeenAt = System.currentTimeMillis(); long transactionCommitTime = event.getHeader().getTimestamp(); replicationLag = eventSeenAt - transactionCommitTime; <START> executionTime = transactionCommitTime - transactionStartTime; <END> } else if (eventType == EventType.GTID) { gtid = ((GtidEventData)event.getData()).getGtid(); } BinlogConnectorEvent ep = new BinlogConnectorEvent(event, client.getBinlogFilename(), client.getGtidSet(), gtid); while (mustStop.get() != true) { try { if ( queue.offer(ep, 100, TimeUnit.MILLISECONDS ) ) { break; } } catch (InterruptedException e) { return; } } if (trackMetrics) { queueTimer.update(System.currentTimeMillis() - eventSeenAt, TimeUnit.MILLISECONDS); } }</code><technical_language>Do need some sanity checking in case triggered a prior QUERY event type? (i.e. if transactionStartTime == 0 legitimate). guaranteed QUERY XID</technical_language>

Target:
public void onEvent(Event event) { long eventSeenAt = 0; boolean trackMetrics = false; if (event.getHeader().getEventType() == EventType.GTID) { gtid = ((GtidEventData)event.getData()).getGtid(); } BinlogConnectorEvent ep = new BinlogConnectorEvent(event, client.getBinlogFilename(), client.getGtidSet(), gtid); if (ep.isCommitEvent()) { trackMetrics = true; eventSeenAt = System.currentTimeMillis(); replicationLag = eventSeenAt - event.getHeader().getTimestamp(); } while (mustStop.get() != true) { try { if ( queue.offer(ep, 100, TimeUnit.MILLISECONDS ) ) { break; } } catch (InterruptedException e) { return; } } if (trackMetrics) { queueTimer.update(System.currentTimeMillis() - eventSeenAt, TimeUnit.MILLISECONDS); } }
Source:
<code><START> public String toString() { <END> String result = ""; if (major != null) { result += major.toString(); } if (minor != null) { result += (result.length() > 0 ? "." : "") + minor.toString(); } if (micro != null) { result += (result.length() > 0 ? "." : "") + micro.toString(); } if (qualifier != null) { result += qualifier.toString(); } return result; }</code><technical_language>reconstructing original string here, leading V? I if original string instead of reconstructing time</technical_language>

Target:
public String toString() { return orgVersion; }
Source:
<code>public void executeQueryWithSnapshotEngine() { <START> db = new EnterpriseGraphDatabaseFactory() <END> .newEmbeddedDatabaseBuilder( testDirectory.directory("withSnapshotEngine") ) .setConfig( new BoltConnector( "bolt" ).type, "BOLT" ) .setConfig( new BoltConnector( "bolt" ).enabled, "true" ) .setConfig( new BoltConnector( "bolt" ).listen_address, "localhost:0" ) .setConfig( GraphDatabaseSettings.snapshot_query, Settings.TRUE ) .newGraphDatabase(); initDatabase(); connectDirver(); verifyQueryExecution(); }</code><technical_language>extract duplicated code in a method single boolean argument test parametrized</technical_language>

Target:
public void executeQueryWithSnapshotEngine() { executeQuery( "withSnapshotEngine", Settings.TRUE ); }
Source:
<code>public void getInstanceAsync_nonLooperThreadShouldThrow() { DynamicRealm.getInstanceAsync(defaultConfig, new DynamicRealm.Callback() { @Override public void onSuccess(DynamicRealm realm) { <START> } <END> }); }</code><technical_language>fail(); in onSuccess()</technical_language>

Target:
public void getInstanceAsync_nonLooperThreadShouldThrow() { DynamicRealm.getInstanceAsync(defaultConfig, new DynamicRealm.Callback() { @Override public void onSuccess(DynamicRealm realm) { fail(); } }); }
Source:
<code>public void testHelpfulErrorOnNothingSet() throws Exception { try { h.createQuery("select * from something where name = :name").list(); fail("should have raised exception"); } catch (UnableToExecuteStatementException e) { <START> assertThat(e).isNotNull(); <END> } catch (Exception e) { fail("Raised incorrect exception"); } }</code><technical_language>Redundant assertion</technical_language>

Target:
public void testHelpfulErrorOnNothingSet() throws Exception { h.createQuery("select * from something where name = :name").list(); }
Source:
<code>public static InputStream getResource(String propertyName, String fileName, String defaultDir) { try { String filePath = System.getProperty(propertyName); InputStream in = loadFromFile(filePath); if (in != null) { logger.info("Loading resource from file name: {}," + " defined by Java property: {}", filePath, propertyName); return in; } in = ResourceUtils.class.getResourceAsStream( "/" + fileName); if (in != null) { logger.info( <START> "Info: Using relex algorithms file defined as a resource."); <END> return in; } File defaultRelexPath = new File(defaultDir, fileName); in = loadFromFile(defaultRelexPath); if (in != null) { logger.info( "Info: Using default relex algorithms file: {}", defaultRelexPath); return in; } throw new RuntimeException("Error loading " + fileName + " file."); } catch (FileNotFoundException exception) { throw new RuntimeException(exception); } }</code><technical_language>below: relex resource</technical_language>

Target:
public static InputStream getResource(String propertyName, String fileName, String defaultDir) { try { String filePath = System.getProperty(propertyName); InputStream in = loadFromFile(filePath); if (in != null) { logger.info("Info: Loading resource from file name: {}," + " defined by Java property: {}", filePath, propertyName); return in; } in = ResourceUtils.class.getResourceAsStream( "/" + fileName); if (in != null) { logger.info("Info: Loading resource from jar.", fileName); return in; } File defaultRelexPath = new File(defaultDir, fileName); in = loadFromFile(defaultRelexPath); if (in != null) { logger.info("Info: Loading resource from file {}/{}.", defaultDir, fileName); return in; } throw new RuntimeException("Error loading " + fileName + " file."); } catch (FileNotFoundException exception) { throw new RuntimeException(exception); } }
Source:
<code><START> public static List<MainType> getMainTypesByTumorTypes(Set<TumorType> tumorTypes) { <END> Set<MainType> mainTypes = new HashSet<>(); for (TumorType tumorType : tumorTypes) { if (tumorType.getMainType() != null && tumorType.getParent() != null) { mainTypes.add(tumorType.getMainType()); } } List<MainType> toReturn = new ArrayList<>(); toReturn.addAll(mainTypes); return toReturn; }</code><technical_language>good simplification</technical_language>

Target:
public static List<MainType> getMainTypesByTumorTypes(Set<TumorType> tumorTypes) { Set<MainType> mainTypes = new HashSet<>(); for (TumorType tumorType : tumorTypes) { if (tumorType.getMainType() != null && tumorType.getParent() != null) { mainTypes.add(tumorType.getMainType()); } } return new ArrayList<>(mainTypes); }
Source:
<code>public void checkSpecificAccessControl() { if (userInfo.isInstructor) { String courseId = getNonNullRequestParamValue(Const.ParamsNames.COURSE_ID); InstructorAttributes instructor = logic.getInstructorForGoogleId(courseId, userInfo.id); gateKeeper.verifyAccessible( instructor, logic.getCourse(courseId), Const.ParamsNames.INSTRUCTOR_PERMISSION_MODIFY_STUDENT); return; } <START> throw new UnauthorizedAccessException("Instructor privilege is required to delete students from course."); <END> }</code><technical_language>switch this entire block other around, i.e. throw if block (guard clause) java if (userInfo.isInstructor) { throw new UnauthorizedAccessException(...); } // ..</technical_language>

Target:
public void checkSpecificAccessControl() { if (!userInfo.isInstructor) { throw new UnauthorizedAccessException("Instructor privilege is required to delete students from course."); } String courseId = getNonNullRequestParamValue(Const.ParamsNames.COURSE_ID); InstructorAttributes instructor = logic.getInstructorForGoogleId(courseId, userInfo.id); gateKeeper.verifyAccessible( instructor, logic.getCourse(courseId), Const.ParamsNames.INSTRUCTOR_PERMISSION_MODIFY_STUDENT); }
Source:
<code>public static MutableOcflRepository createRepository(final Path ocflStorageRootDir, final Path ocflWorkDir) throws IOException { Files.createDirectories(ocflStorageRootDir); Files.createDirectories(ocflWorkDir); <START> log.info("Fedora OCFL persistence directories:\n- {}\n- {}", ocflStorageRootDir, ocflWorkDir); <END> final var defaultFcrepoAlg = ContentDigest.DEFAULT_DIGEST_ALGORITHM; final DigestAlgorithm ocflDigestAlg = translateFedoraDigestToOcfl(defaultFcrepoAlg); if (ocflDigestAlg == null) { throw new UnsupportedDigestAlgorithmException( "Unable to map Fedora default digest algorithm " + defaultFcrepoAlg + " into OCFL"); } final OcflConfig config = new OcflConfig(); config.setDefaultDigestAlgorithm(ocflDigestAlg); return new OcflRepositoryBuilder() .layoutConfig(DefaultLayoutConfig.nTupleHashConfig()) .ocflConfig(config) .storage((FileSystemOcflStorage.builder().repositoryRoot(ocflStorageRootDir).build())) .workDir(ocflWorkDir) .buildMutable(); }</code><technical_language>reduce this logging debug, in favor of cleaner output of OcflPropsConfig</technical_language>

Target:
public static MutableOcflRepository createRepository(final Path ocflStorageRootDir, final Path ocflWorkDir) throws IOException { Files.createDirectories(ocflStorageRootDir); Files.createDirectories(ocflWorkDir); log.debug("Fedora OCFL persistence directories:\n- {}\n- {}", ocflStorageRootDir, ocflWorkDir); final var defaultFcrepoAlg = ContentDigest.DEFAULT_DIGEST_ALGORITHM; final DigestAlgorithm ocflDigestAlg = translateFedoraDigestToOcfl(defaultFcrepoAlg); if (ocflDigestAlg == null) { throw new UnsupportedDigestAlgorithmException( "Unable to map Fedora default digest algorithm " + defaultFcrepoAlg + " into OCFL"); } final OcflConfig config = new OcflConfig(); config.setDefaultDigestAlgorithm(ocflDigestAlg); return new OcflRepositoryBuilder() .layoutConfig(DefaultLayoutConfig.nTupleHashConfig()) .ocflConfig(config) .storage((FileSystemOcflStorage.builder().repositoryRoot(ocflStorageRootDir).build())) .workDir(ocflWorkDir) .buildMutable(); }
Source:
<code>public String getName() { <START> return NbBundle.getMessage(this.getClass(), "CommonFilesNode.getName.text"); <END> }</code><technical_language>This text is a good candidate for replacement of hand-written key-value pair currently in Bundle.properties annotation defines text</technical_language>

Target:
public String getName() { return Bundle.CommonFilesNode_getName_text(); }
Source:
<code>private void visitClassOrInterface(String name, FunctionType ftype) { final boolean emitInstance = !ftype.isInterface(); if (emitInstance) { emit("class"); emit(name); visitTemplateTypes(ftype); emit("extends"); emit(name + INSTANCE_CLASS_SUFFIX); visitTemplateTypes(ftype); emit("{"); indent(); emitBreak(); visitProperties(ftype, true); unindent(); emit("}"); emitBreak(); } if (ftype.isConstructor()) { emit("class"); } else if (ftype.isInterface()) { emit("interface"); } else { checkState(false, "Unexpected function type " + ftype); } emit(emitInstance ? name + INSTANCE_CLASS_SUFFIX : name); visitTemplateTypes(ftype); if (ftype.getExtendedInterfacesCount() > 0) { emit("extends"); Iterator<ObjectType> it = ftype.getExtendedInterfaces().iterator(); emitCommaSeparatedInterfaces(it); } ObjectType superType = getSuperType(ftype); if (superType != null) { emit("extends"); if (isPrivate(superType.getJSDocInfo())) { emit(Constants.INTERNAL_NAMESPACE + ".PrivateClass"); } else { Visitor<Void> visitor = new ExtendsImplementsTypeVisitor( emitInstance && !isDefinedInPlatformExterns(superType)); superType.visit(visitor); } } Iterator<ObjectType> it = ftype.getOwnImplementedInterfaces().iterator(); if (it.hasNext()) { emit("implements"); emitCommaSeparatedInterfaces(it); } <START> boolean implementsIArrayLike = any(ftype.getOwnImplementedInterfaces(), IARRAYLIKE_PREDICATE); <END> visitObjectType(ftype, ftype.getPrototype(), ftype.isDict() || implementsIArrayLike); }</code><technical_language>implemented interfaces (immediate implemented?), transitively</technical_language>

Target:
private void visitClassOrInterface(String name, FunctionType ftype) { final boolean emitInstance = !ftype.isInterface(); if (emitInstance) { emit("class"); emit(name); visitTemplateTypes(ftype); emit("extends"); emit(name + INSTANCE_CLASS_SUFFIX); visitTemplateTypes(ftype); emit("{"); indent(); emitBreak(); visitProperties(ftype, true); unindent(); emit("}"); emitBreak(); } if (ftype.isConstructor()) { emit("class"); } else if (ftype.isInterface()) { emit("interface"); } else { checkState(false, "Unexpected function type " + ftype); } emit(emitInstance ? name + INSTANCE_CLASS_SUFFIX : name); visitTemplateTypes(ftype); if (ftype.getExtendedInterfacesCount() > 0) { emit("extends"); Iterator<ObjectType> it = ftype.getExtendedInterfaces().iterator(); emitCommaSeparatedInterfaces(it); } ObjectType superType = getSuperType(ftype); if (superType != null) { emit("extends"); if (isPrivate(superType.getJSDocInfo())) { emit(Constants.INTERNAL_NAMESPACE + ".PrivateClass"); } else { Visitor<Void> visitor = new ExtendsImplementsTypeVisitor( emitInstance && !isDefinedInPlatformExterns(superType)); superType.visit(visitor); } } Iterator<ObjectType> it = ftype.getOwnImplementedInterfaces().iterator(); if (it.hasNext()) { emit("implements"); emitCommaSeparatedInterfaces(it); } boolean implementsIArrayLike = any(ftype.getAllImplementedInterfaces(), IS_IARRAYLIKE); visitObjectType(ftype, ftype.getPrototype(), ftype.isDict() || implementsIArrayLike); }
Source:
<code>public Optional<ImmutableDyeableData> with(Key<? extends BaseValue<?>> key, Object value, ImmutableDyeableData immutable) { if (key.equals(Keys.DYE_COLOR)) { <START> return Optional.of(new ImmutableSpongeDyeableData((DyeColor) value)); <END> } return Optional.empty(); }</code><technical_language>this cached</technical_language>

Target:
public Optional<ImmutableDyeableData> with(Key<? extends BaseValue<?>> key, Object value, ImmutableDyeableData immutable) { if (key.equals(Keys.DYE_COLOR)) { return Optional.of(ImmutableDataCachingUtil.getManipulator(ImmutableDyeableData.class, value)); } return Optional.empty(); }
Source:
<code>protected void compute(CoreSession session, List<String> ids, Map<String, Serializable> properties) { <START> Collection<DocumentRef> refs = ids.stream().map(IdRef::new).collect(Collectors.toList()); <END> DocumentModelList docs = session.getDocuments(refs.toArray(new DocumentRef[refs.size()])); Collection<DocumentRef> proxies = docs.stream() .filter(DocumentModel::isProxy) .map(DocumentModel::getRef) .collect(Collectors.toList()); session.removeDocuments(proxies.toArray(new DocumentRef[0])); session.save(); }</code><technical_language>I wondering if a standard foreach simpler multiple streams</technical_language>

Target:
protected void compute(CoreSession session, List<String> ids, Map<String, Serializable> properties) { String query = String.format(QUERY_TEMPLATE, String.join("', '", ids)); Set<DocumentRef> proxies = new HashSet<>(); try (IterableQueryResult res = session.queryAndFetch(query, NXQL.NXQL)) { for (Map<String, Serializable> map : res) { proxies.add(new IdRef((String) map.get(NXQL.ECM_UUID))); } } session.removeDocuments(proxies.toArray(new DocumentRef[0])); session.save(); }
Source:
<code><START> public boolean doesUserHasPermissionToAddContent (final String containerInode) throws DotDataException { <END> if(!InodeUtils.isSet(containerInode)) { return false; } else { final User systemUser = APILocator.getUserAPI().getSystemUser(); Container container = null; try { container = APILocator.getContainerAPI().find(containerInode, systemUser, false); } catch (DotSecurityException e) { Logger.debug(this.getClass(), "Exception on doesUserHasPermissionToAddContent exception message: " + e.getMessage(), e); throw new DotRuntimeException(e); } final User loggedInUser = APILocator.getLoginServiceAPI().getLoggedInUser(); final List<ContentType> contentTypesInContainer = containerAPI.getContentTypesInContainer(loggedInUser, container); return !contentTypesInContainer.isEmpty(); } }</code><technical_language>Integration test for this new method? @freddyucv</technical_language>

Target:
public boolean doesUserHasPermissionToAddContent (final String containerInode) throws DotDataException { if(!InodeUtils.isSet(containerInode)) { return false; } else { final User systemUser = userAPI.getSystemUser(); Container container = null; try { container = containerAPI.find(containerInode, systemUser, false); } catch (DotSecurityException e) { Logger.debug(this.getClass(), "Exception on doesUserHasPermissionToAddContent exception message: " + e.getMessage(), e); throw new DotRuntimeException(e); } final List<ContentType> contentTypesInContainer = containerAPI.getContentTypesInContainer(backuser, container); return contentTypesInContainer != null && !contentTypesInContainer.isEmpty(); } }
Source:
<code>public void testHealthCheckIsRescheduled() { ArgumentCaptor<ServicePool.HealthCheckVerifier> verifyCapture = ArgumentCaptor.forClass(ServicePool.HealthCheckVerifier.class); verify(_healthCheckExecutor).scheduleAtFixedRate(verifyCapture.capture(), anyLong(), anyLong(), any(TimeUnit.class)); <START> ServicePool.HealthCheckVerifier verify = verifyCapture.getValue(); <END> when(_healthCheckExecutor.submit(any(ServicePool.HealthCheck.class))).thenThrow(NullPointerException.class); try { _pool.execute(NEVER_RETRY, new ServiceCallback<Service, Void>() { @Override public Void call(Service service) throws ServiceException { throw new ServiceException(); } }); fail(); } catch (MaxRetriesException expected) { } ArgumentCaptor<ServicePool.HealthCheck> healthCheckCapture = ArgumentCaptor.forClass(ServicePool.HealthCheck.class); verify(_healthCheckExecutor, times(1)).submit(healthCheckCapture.capture()); ServicePool.HealthCheck healthCheck = healthCheckCapture.getValue(); verify.run(); verify(_healthCheckExecutor, times(2)).submit(any(ServicePool.HealthCheck.class)); reset(_healthCheckExecutor); when(_healthCheckExecutor.submit(any(ServicePool.HealthCheck.class))).thenReturn(mock(Future.class)); verify.run(); verify(_healthCheckExecutor, times(1)).submit(any(ServicePool.HealthCheck.class)); verify.run(); verify(_healthCheckExecutor, times(1)).submit(any(ServicePool.HealthCheck.class)); }</code><technical_language>This name is a bit confusing mixed calls Mockito's verify() methods</technical_language>

Target:
public void testHealthCheckIsRescheduled() { ArgumentCaptor<ServicePool.HealthCheckVerifier> healthCheckVerifierCaptor = ArgumentCaptor.forClass(ServicePool.HealthCheckVerifier.class); verify(_healthCheckExecutor).scheduleAtFixedRate(healthCheckVerifierCaptor.capture(), anyLong(), anyLong(), any(TimeUnit.class)); ServicePool.HealthCheckVerifier healthCheckVerifier = healthCheckVerifierCaptor.getValue(); when(_healthCheckExecutor.submit(any(ServicePool.HealthCheck.class))).thenThrow(NullPointerException.class); try { _pool.execute(NEVER_RETRY, new ServiceCallback<Service, Void>() { @Override public Void call(Service service) throws ServiceException { throw new ServiceException(); } }); fail(); } catch (MaxRetriesException expected) { } verify(_healthCheckExecutor, times(1)).submit(any(ServicePool.HealthCheck.class)); healthCheckVerifier.run(); verify(_healthCheckExecutor, times(2)).submit(any(ServicePool.HealthCheck.class)); reset(_healthCheckExecutor); when(_healthCheckExecutor.submit(any(ServicePool.HealthCheck.class))).thenReturn(mock(Future.class)); healthCheckVerifier.run(); verify(_healthCheckExecutor, times(1)).submit(any(ServicePool.HealthCheck.class)); healthCheckVerifier.run(); verify(_healthCheckExecutor, times(1)).submit(any(ServicePool.HealthCheck.class)); }