auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public void shouldListAllPatientIdentifiersWithVoidedIdentifiersForAPatient() throws Exception { String urlString = getURI(); urlString += "?includeAll=true"; <START> MockHttpServletRequest req = request(RequestMethod.GET, urlString); <END> SimpleObject result = deserialize(handle(req)); assertNotNull(result); assertNotEquals(getAllCount(), Util.getResultsSize(result)); }</code><technical_language>do includeAll parameter here? <LINK_0></technical_language>

Target:
public void shouldListAllPatientIdentifiersWithVoidedIdentifiersForAPatient() throws Exception { assertEquals(false, service.getPatientIdentifierByUuid(getUuid()).isVoided()); MockHttpServletRequest req = request(RequestMethod.DELETE, getURI() + "/" + getUuid()); final String reason = "none"; req.addParameter("reason", reason); handle(req); assertEquals(true, service.getPatientIdentifierByUuid(getUuid()).isVoided()); SimpleObject result = deserialize(handle(newGetRequest(getURI(), new Parameter( RestConstants.REQUEST_PROPERTY_FOR_INCLUDE_ALL, "true")))); assertNotEquals(getAllCount(), Util.getResultsSize(result)); SimpleObject nextResult = deserialize(handle(newGetRequest(getURI(), new Parameter( RestConstants.REQUEST_PROPERTY_FOR_INCLUDE_ALL, "false")))); assertEquals(getAllCount(), Util.getResultsSize(nextResult)); }
Source:
<code>private final void decrementResponseOrExpired() { int decrementedValue = responsesAndExpirations.decrementAndGet(); if (decrementedValue == 0) { <START> if (!condition.isSignaled() & requestedCLAchieved) <END> { replicaPlan.keyspace().metric.writeFailedIdealCL.inc(); } else { replicaPlan.keyspace().metric.idealCLWriteLatency.addNano(System.nanoTime() - queryStartNanoTime); } } }</code><technical_language>Is this intentionally a bitwise AND</technical_language>

Target:
private final void decrementResponseOrExpired() { int decrementedValue = responsesAndExpirations.decrementAndGet(); if (decrementedValue == 0) { if (!condition.isSignaled() && requestedCLAchieved) { replicaPlan.keyspace().metric.writeFailedIdealCL.inc(); } else { replicaPlan.keyspace().metric.idealCLWriteLatency.addNano(System.nanoTime() - queryStartNanoTime); } } }
Source:
<code>private Node tryToLookupNode(NodeSource nodeSource, int lookUpTimeout, String nodeUrl) { Node node; try { logger.info("Trying to lookup a node to recover: " + nodeUrl); node = nodeSource.lookupNode(nodeUrl, lookUpTimeout); } catch (Exception e) { <START> logger.warn("Node to recover could not be looked up at URL: " + nodeUrl); <END> node = null; } return node; }</code><technical_language>e.getMessage()</technical_language>

Target:
private Node tryToLookupNode(NodeSource nodeSource, int lookUpTimeout, String nodeUrl) { Node node = null; try { logger.info("Trying to lookup node to recover: " + nodeUrl); node = nodeSource.lookupNode(nodeUrl, lookUpTimeout); } catch (Exception e) { logger.warn("Node to recover could not be looked up"); } return node; }
Source:
<code>private JoinEnumerationResult setJoinNodeProperties(JoinNode joinNode) { if (isAtMostScalar(joinNode.getRight(), lookup)) { return createJoinEnumerationResult(joinNode.withDistributionType(REPLICATED)); } if (isAtMostScalar(joinNode.getLeft(), lookup)) { return createJoinEnumerationResult(joinNode.flipChildren().withDistributionType(REPLICATED)); } List<JoinEnumerationResult> possibleJoinNodes = new ArrayList<>(); <START> FeaturesConfig.JoinDistributionType joinDistributionType = getJoinDistributionType(session); <END> if (joinDistributionType.canRepartition() && !joinNode.isCrossJoin()) { possibleJoinNodes.add(createJoinEnumerationResult(joinNode.withDistributionType(PARTITIONED))); possibleJoinNodes.add(createJoinEnumerationResult(joinNode.flipChildren().withDistributionType(PARTITIONED))); } if (joinDistributionType.canReplicate()) { possibleJoinNodes.add(createJoinEnumerationResult(joinNode.withDistributionType(REPLICATED))); possibleJoinNodes.add(createJoinEnumerationResult(joinNode.flipChildren().withDistributionType(REPLICATED))); } if (possibleJoinNodes.stream().anyMatch(UNKNOWN_COST_RESULT::equals)) { return UNKNOWN_COST_RESULT; } return resultComparator.min(possibleJoinNodes); }</code><technical_language>Import JoinDistributionType</technical_language>

Target:
private JoinEnumerationResult setJoinNodeProperties(JoinNode joinNode) { if (isAtMostScalar(joinNode.getRight(), lookup)) { return createJoinEnumerationResult(joinNode.withDistributionType(REPLICATED)); } if (isAtMostScalar(joinNode.getLeft(), lookup)) { return createJoinEnumerationResult(joinNode.flipChildren().withDistributionType(REPLICATED)); } List<JoinEnumerationResult> possibleJoinNodes = new ArrayList<>(); JoinDistributionType joinDistributionType = getJoinDistributionType(session); if (joinDistributionType.canRepartition() && !joinNode.isCrossJoin()) { possibleJoinNodes.add(createJoinEnumerationResult(joinNode.withDistributionType(PARTITIONED))); possibleJoinNodes.add(createJoinEnumerationResult(joinNode.flipChildren().withDistributionType(PARTITIONED))); } if (joinDistributionType.canReplicate()) { possibleJoinNodes.add(createJoinEnumerationResult(joinNode.withDistributionType(REPLICATED))); possibleJoinNodes.add(createJoinEnumerationResult(joinNode.flipChildren().withDistributionType(REPLICATED))); } if (possibleJoinNodes.stream().anyMatch(UNKNOWN_COST_RESULT::equals)) { return UNKNOWN_COST_RESULT; } return resultComparator.min(possibleJoinNodes); }
Source:
<code>public Mono<AmqpReceiveLink> createReceiveLink(String linkName, String entityPath, ReceiveMode receiveMode, String transferEntityPath, MessagingEntityType entityType) { <START> return createReceiveLink(linkName, entityPath, receiveMode, null, <END> transferEntityPath, entityType); }</code><technical_language>performing operations, created a separate method in ReactorSession for creating a consumer a sessionId. This call that</technical_language>

Target:
public Mono<AmqpReceiveLink> createReceiveLink(String linkName, String entityPath, ReceiveMode receiveMode, String transferEntityPath, MessagingEntityType entityType) { return createSession(entityPath).cast(ServiceBusSession.class) .flatMap(session -> { logger.verbose("Get or create consumer for path: '{}'", entityPath); final AmqpRetryPolicy retryPolicy = RetryUtil.getRetryPolicy(retryOptions); return session.createConsumer(linkName, entityPath, entityType, retryOptions.getTryTimeout(), retryPolicy, receiveMode); }); }
Source:
<code>public void stop() { <START> scheduledExec.shutdownNow(); <END> scheduledExec = null; }</code><technical_language>This stop if cache is enabled, synchronization i</technical_language>

Target:
public void stop() { if (!lifecycleLock.canStop()) { throw new ISE("can't stop."); } log.info("MetadataSegmentView is stopping."); if (isCacheEnabled) { scheduledExec.shutdown(); } log.info("MetadataSegmentView Stopped."); }
Source:
<code>public long deleteHorizonMs() { <START> return loadFullBatch().deleteHorizonMs(); <END> }</code><technical_language>this is a legacy record, deleteHorizonMs is set. avoid loading full batch? Ditto in isDeleteHorizonSet below</technical_language>

Target:
public long deleteHorizonMs() { return RecordBatch.NO_TIMESTAMP; }
Source:
<code>private Map<String, Object> getTaskCompletionRowStats() { Map<String, Object> metrics = Maps.newHashMap(); <START> if (rowIngestionMeters != null) { <END> metrics.put( "buildSegments", rowIngestionMeters.getTotals() ); } return metrics; }</code><technical_language>fact some null checks others, clear if rowIngestionMeters accessed in multiple threads, leads suggest rowIngestionMeters created final in constructor accessed everywhere. Is overhead small enough a problem</technical_language>

Target:
private Map<String, Object> getTaskCompletionRowStats() { Map<String, Object> metrics = Maps.newHashMap(); metrics.put( RowIngestionMeters.BUILD_SEGMENTS, rowIngestionMeters.getTotals() ); return metrics; }
Source:
<code>public void doNotDeactivateWithoutWritePermissions() throws InvalidIpForApiKeyException, ApiKeyNotFoundException, RevokedApiKeyException, IOException { ApplicationConfiguration configuration = ApplicationConfiguration.defaultConfiguration(); when(configurationFetcher.configurationFor(request)).thenReturn(Maybe.just(configuration)); when(request.getParameter("source")).thenReturn("upcoming.radiotimes.com"); when(request.getParameter("valid_uris")).thenReturn("uri1,uri2,uri3"); controller.unpublishContent(request, response); ArgumentCaptor<AtlasErrorSummary> argument = ArgumentCaptor.forClass( AtlasErrorSummary.class ); verify(modelWriter, atLeast(2)) .writeError(eq(request), eq(response), argument.capture()); <START> assertEquals("403", argument.getValue().statusCode().toString()); <END> assertEquals("API key does not have write permission", argument.getValue().message() ); }</code><technical_language>Prefer assertThat(something, is(something));. more readable</technical_language>

Target:
public void doNotDeactivateWithoutWritePermissions() throws InvalidIpForApiKeyException, ApiKeyNotFoundException, RevokedApiKeyException, IOException { ApplicationConfiguration configuration = ApplicationConfiguration.defaultConfiguration(); when(configurationFetcher.configurationFor(request)).thenReturn(Maybe.just(configuration)); when(request.getParameter("source")).thenReturn("upcoming.radiotimes.com"); when(request.getParameter("valid_uris")).thenReturn("uri1,uri2,uri3"); controller.unpublishContent(request, response); ArgumentCaptor<AtlasErrorSummary> argument = ArgumentCaptor.forClass( AtlasErrorSummary.class ); verify(modelWriter).writeError(eq(request), eq(response), argument.capture()); assertThat("403", is(argument.getValue().statusCode().toString())); assertThat("API key does not have write permission", is(argument.getValue().message()) ); }
Source:
<code>protected void configure() { bind(CacheDeleteHandler.class); bind(CapabilityDefinition.class) .annotatedWith(Exports.named(DELETE_PROJECT)) .to(DeleteProjectCapability.class); bind(DatabaseDeleteHandler.class) .to(registerDatabaseHandler()); bind(FilesystemDeleteHandler.class); install(new RestApiModule() { @Override protected void configure() { delete(PROJECT_KIND) .to(DeleteProject.class); post(PROJECT_KIND) <START> .to(DeleteProject.class); <END> } }); }</code><technical_language>moment a idea do POST request, request 'POST /projects/myProject' is obvious this is a deletion. In other cases, e.g. deletion of group members this obvious URL: 'POST /groups/myGroup/members.delete' [1]. if do similar here. [1] <LINK_0></technical_language>

Target:
protected void configure() { bind(CacheDeleteHandler.class); bind(CapabilityDefinition.class) .annotatedWith(Exports.named(DELETE_PROJECT)) .to(DeleteProjectCapability.class); bind(DatabaseDeleteHandler.class) .to(registerDatabaseHandler()); bind(FilesystemDeleteHandler.class); install(new RestApiModule() { @Override protected void configure() { delete(PROJECT_KIND) .to(DeleteProject.class); post(PROJECT_KIND, "delete") .to(DeleteProject.class); } }); }
Source:
<code>private ListView.OnItemClickListener getNavDrawerClickListener() { return new ListView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { drawerLayout.closeDrawer(navDrawerList); switch(drawerItemsShowing[position].id) { case SYNC_DRAWER_ITEM_ID: activity.sendFormsOrSync(true); break; case SAVED_FORMS_ITEM_ID: activity.goToFormArchive(false); break; case UPDATE_DRAWER_ITEM_ID: activity.launchUpdateActivity(); break; case ABOUT_CC_DRAWER_ITEM_ID: activity.showAboutCommCareDialog(); break; case SETTINGS_DRAWER_ITEM_ID: <START> activity.createPreferencesMenu(activity); <END> break; case ADVANCED_DRAWER_ITEM_ID: activity.startAdvancedActionsActivity(); break; case CHANGE_LANGUAGE_DRAWER_ITEM_ID: activity.showLocaleChangeMenu(null); break; case LOGOUT_DRAWER_ITEM_ID: activity.userTriggeredLogout(); break; } } }; }</code><technical_language>activity.createPreferencesMenu(activity) HomeScreenBaseActivity.createPreferencesMenu(activity) non-static in argument</technical_language>

Target:
private ListView.OnItemClickListener getNavDrawerClickListener() { return new ListView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { drawerLayout.closeDrawer(navDrawerList); switch(drawerItemsShowing[position].id) { case SYNC_DRAWER_ITEM_ID: activity.sendFormsOrSync(true); break; case SAVED_FORMS_ITEM_ID: activity.goToFormArchive(false); break; case UPDATE_DRAWER_ITEM_ID: activity.launchUpdateActivity(); break; case ABOUT_CC_DRAWER_ITEM_ID: activity.showAboutCommCareDialog(); break; case SETTINGS_DRAWER_ITEM_ID: HomeScreenBaseActivity.createPreferencesMenu(activity); break; case ADVANCED_DRAWER_ITEM_ID: activity.startAdvancedActionsActivity(); break; case CHANGE_LANGUAGE_DRAWER_ITEM_ID: activity.showLocaleChangeMenu(null); break; case LOGOUT_DRAWER_ITEM_ID: activity.userTriggeredLogout(); break; } } }; }
Source:
<code>private String getIssue(String filename) throws IOException, InterruptedException { String issueId = ""; Path path = Paths.get(filename); if(Files.notExists(path)){ return null; } try (BufferedReader br = Files.newBufferedReader(path)) { String issue; while ((issue = br.readLine()) != null) { issueId = issue; } <START> return issueId.trim().length() > 0 ? issueId : null; <END> } catch (FileNotFoundException e) { return null; } }</code><technical_language>safer StringUtils.isEmpty (to manage issueId == null)</technical_language>

Target:
private String getIssue(String filename) throws IOException, InterruptedException { String issueId = ""; Path path = Paths.get(filename); if(Files.notExists(path)){ return null; } try (BufferedReader br = Files.newBufferedReader(path)) { String issue; while ((issue = br.readLine()) != null) { issueId = issue; } return StringUtils.trimToNull(issueId); } catch (FileNotFoundException e) { return null; } }
Source:
<code><START> private void addCommonModelAttributesAndValidate(HttpServletRequest request, Model model, @SiteParam Site site, @RequestParam("id") String articleId) throws IOException { <END> Map<?, ?> articleMetadata = requestArticleMetadata(articleId); validateArticleVisibility(site, articleMetadata); addCrossPublishedJournals(request, model, site, articleMetadata); model.addAttribute("article", articleMetadata); model.addAttribute("containingLists", getContainingArticleLists(articleId, site)); model.addAttribute("categoryTerms", getCategoryTerms(articleMetadata)); requestAuthors(model, articleId); }</code><technical_language>This method more use! in renderCitationDownloadPage check for others</technical_language>

Target:
private Map<?, ?> addCommonModelAttributesAndValidate(HttpServletRequest request, Model model, @SiteParam Site site, @RequestParam("id") String articleId) throws IOException { Map<?, ?> articleMetadata = requestArticleMetadata(articleId); validateArticleVisibility(site, articleMetadata); addCrossPublishedJournals(request, model, site, articleMetadata); model.addAttribute("article", articleMetadata); model.addAttribute("containingLists", getContainingArticleLists(articleId, site)); model.addAttribute("categoryTerms", getCategoryTerms(articleMetadata)); requestAuthors(model, articleId); return articleMetadata; }
Source:
<code>public void init() { if (!initialized) { <START> final ByteBuffer buffer = bufferSupplier.get().duplicate(); <END> final int usedBufferEnd = getUserBufferCapacity(cardinalityWithMissingValue); buffer.position(0); buffer.limit(usedBufferEnd); usedFlagBuffer = buffer.slice(); buffer.position(usedBufferEnd); buffer.limit(buffer.capacity()); valBuffer = buffer.slice(); reset(); initialized = true; } }</code><technical_language>duplicate()</technical_language>

Target:
public void init() { if (!initialized) { final ByteBuffer buffer = bufferSupplier.get(); final int usedFlagBufferEnd = getUsedFlagBufferCapacity(cardinalityWithMissingValue); buffer.position(0); buffer.limit(usedFlagBufferEnd); usedFlagBuffer = buffer.slice(); buffer.position(usedFlagBufferEnd); buffer.limit(buffer.capacity()); valBuffer = buffer.slice(); reset(); initialized = true; } }
Source:
<code>private void addSiblingNode(int indexOfNode) { synchronized (latestBranch) { final long splitTime = treeEnd; assert (indexOfNode < latestBranch.size()); if (indexOfNode == 0) { addNewRootNode(); return; } <START> if (((CoreNode) latestBranch.get(indexOfNode - 1)).getNbChildren() == config.getMaxChildren()) { <END> addSiblingNode(indexOfNode - 1); return; } for (int i = indexOfNode; i < latestBranch.size(); i++) { latestBranch.get(i).closeThisNode(splitTime); treeIO.writeNode(latestBranch.get(i)); CoreNode prevNode = (CoreNode) latestBranch.get(i - 1); HTNode newNode; switch (latestBranch.get(i).getNodeType()) { case CORE: newNode = initNewCoreNode(prevNode.getSequenceNumber(), splitTime + 1); break; case LEAF: newNode = initNewLeafNode(prevNode.getSequenceNumber(), splitTime + 1); break; default: throw new IllegalStateException(); } prevNode.linkNewChild(newNode); latestBranch.set(i, newNode); } } }</code><technical_language>Is this cast safe? indexOfNode - 1 return a CoreNode always? Asserts work in production code later, in months, classes changed, asserts condition false fails. replace assert a throw IllegalStateException or... whatever</technical_language>

Target:
private void addSiblingNode(int indexOfNode) { synchronized (latestBranch) { final long splitTime = treeEnd; if (indexOfNode >= latestBranch.size()) { throw new IllegalStateException(); } if (indexOfNode == 0) { addNewRootNode(); return; } if (((CoreNode) latestBranch.get(indexOfNode - 1)).getNbChildren() == config.getMaxChildren()) { addSiblingNode(indexOfNode - 1); return; } for (int i = indexOfNode; i < latestBranch.size(); i++) { latestBranch.get(i).closeThisNode(splitTime); treeIO.writeNode(latestBranch.get(i)); CoreNode prevNode = (CoreNode) latestBranch.get(i - 1); HTNode newNode; switch (latestBranch.get(i).getNodeType()) { case CORE: newNode = initNewCoreNode(prevNode.getSequenceNumber(), splitTime + 1); break; case LEAF: newNode = initNewLeafNode(prevNode.getSequenceNumber(), splitTime + 1); break; default: throw new IllegalStateException(); } prevNode.linkNewChild(newNode); latestBranch.set(i, newNode); } } }
Source:
<code>public ExternalIdPConfig getIdPConfigByName(String idpName, String tenantDomain) { ExternalIdPConfig externalIdPConfig = null; IdentityProvider idpDO = null; if (log.isDebugEnabled()) { log.debug("Trying to find the IdP for name: " + idpName); } try { IdentityProviderManager idpManager = IdentityProviderManager.getInstance(); idpDO = idpManager.getEnabledIdPByName(idpName, tenantDomain); if (idpDO != null) { if (log.isDebugEnabled()) { log.debug("A registered IdP was found"); } externalIdPConfig = new ExternalIdPConfig(idpDO); } else { if (log.isDebugEnabled()) { log.debug("A registered IdP was not found the given name"); } } } catch (IdentityProviderManagementException e) { <START> log.error("Exception while getting IdP by name", e); <END> } return externalIdPConfig; }</code><technical_language>Ideally throwing this exception client decide do it. Lets change this throw exception in authentication framework catch exception, log continue</technical_language>

Target:
public ExternalIdPConfig getIdPConfigByName(String idpName, String tenantDomain) throws IdentityProviderManagementException { ExternalIdPConfig externalIdPConfig = null; IdentityProvider idpDO = null; if (log.isDebugEnabled()) { log.debug("Trying to find the IdP for name: " + idpName); } try { IdentityProviderManager idpManager = IdentityProviderManager.getInstance(); idpDO = idpManager.getEnabledIdPByName(idpName, tenantDomain); if (idpDO != null) { if (log.isDebugEnabled()) { log.debug("A registered IdP was found"); } externalIdPConfig = new ExternalIdPConfig(idpDO); } else { if (log.isDebugEnabled()) { log.debug("A registered IdP was not found the given name"); } } } catch (IdentityProviderManagementException e) { throw new IdentityProviderManagementException("Exception while getting IdP by name", e); } return externalIdPConfig; }
Source:
<code>public void generateChunk(CoreChunk chunk, Region chunkRegion) { BaseFacet baseFacet = chunkRegion.getFacet(BaseFacet.class); for (Base base : baseFacet.getBases()) { BlockRegion baseRegion = base.getArea(); BlockRegion flagRegion = base.getFlagArea(); for (Vector3ic baseBlockPosition : baseRegion) { if (chunkRegion.getRegion().contains(baseBlockPosition) && baseBlockPosition.x() > 0) { <START> chunk.setBlock(ChunkMath.calcRelativeBlockPos(baseBlockPosition, new Vector3i()), redBaseStone); <END> } else if (chunkRegion.getRegion().contains(baseBlockPosition)) { chunk.setBlock(ChunkMath.calcRelativeBlockPos(baseBlockPosition, new Vector3i()), blackBaseStone); } } for (Vector3ic flagPosition : flagRegion) { if (chunkRegion.getRegion().contains(flagPosition) && flagPosition.x() > 0) { chunk.setBlock(ChunkMath.calcRelativeBlockPos(flagPosition, new Vector3i()), redFlag); } else if (chunkRegion.getRegion().contains(flagPosition)) { chunk.setBlock(ChunkMath.calcRelativeBlockPos(flagPosition, new Vector3i()), blackFlag); } } } }</code><technical_language>reuse tmp vector</technical_language>

Target:
public void generateChunk(CoreChunk chunk, Region chunkRegion) { BaseFacet baseFacet = chunkRegion.getFacet(BaseFacet.class); Vector3i tempPos = new Vector3i(); for (Base base : baseFacet.getBases()) { BlockRegion baseRegion = base.getArea(); BlockRegion flagRegion = base.getFlagArea(); for (Vector3ic baseBlockPosition : baseRegion) { if (chunkRegion.getRegion().contains(baseBlockPosition) && baseBlockPosition.x() > 0) { chunk.setBlock(ChunkMath.calcRelativeBlockPos(baseBlockPosition, tempPos), redBaseStone); } else if (chunkRegion.getRegion().contains(baseBlockPosition)) { chunk.setBlock(ChunkMath.calcRelativeBlockPos(baseBlockPosition, tempPos), blackBaseStone); } } for (Vector3ic flagPosition : flagRegion) { if (chunkRegion.getRegion().contains(flagPosition) && flagPosition.x() > 0) { chunk.setBlock(ChunkMath.calcRelativeBlockPos(flagPosition, tempPos), redFlag); } else if (chunkRegion.getRegion().contains(flagPosition)) { chunk.setBlock(ChunkMath.calcRelativeBlockPos(flagPosition, tempPos), blackFlag); } } } }
Source:
<code>public Journey getJourneyInfo(String dgw) { String apiResponse = getJourneyInfoFromApi(dgw); List<JourneyInfo> infoList = JsonJavaConverter.toJavaList(apiResponse, JourneyInfo[].class); if (infoList == null) { return null; } Collections.sort(infoList, new Comparator<JourneyInfo>() { @Override <START> public int compare(JourneyInfo lhs, JourneyInfo rhs) { <END> if (rhs.getTimestamp() > lhs.getTimestamp()) { return 1; } else { return -1; } } }); String destination = null; String journeyId = null; for (JourneyInfo info : infoList) { if (info.getResourceSpec().equals(RESOURCE_SPEC_DESTINATION)) { destination = info.getValue(); break; } } for (JourneyInfo info : infoList) { if (info.getResourceSpec().equals(RESOURCE_SPEC_JOURNEY_ID)) { journeyId = info.getValue(); break; } } Journey ret = new Journey(destination, journeyId); return ret; }</code><technical_language>This method return 0 if rhs.getTimestamp() == lhs.getTimestamp()</technical_language>

Target:
public Journey getJourneyInfo(String dgw) { String apiResponse = getJourneyInfoFromApi(dgw); List<JourneyInfo> infoList = JsonJavaConverter.toJavaList(apiResponse, JourneyInfo[].class); if (infoList == null) { return null; } Collections.sort(infoList, new Comparator<JourneyInfo>() { @Override public int compare(JourneyInfo lhs, JourneyInfo rhs) { if (rhs.getTimestamp() > lhs.getTimestamp()) { return 1; } else { return rhs.getTimestamp() == lhs.getTimestamp() ? 0 : -1; } } }); String destination = null; String journeyId = null; for (JourneyInfo info : infoList) { if (info.getResourceSpec().equals(RESOURCE_SPEC_DESTINATION)) { destination = info.getValue(); break; } } for (JourneyInfo info : infoList) { if (info.getResourceSpec().equals(RESOURCE_SPEC_JOURNEY_ID)) { journeyId = info.getValue(); break; } } Journey ret = new Journey(destination, journeyId); return ret; }
Source:
<code>private String loadResponseFromFile(String resourceName) throws IOException { <START> URL r = getResource(UpdateMetricsResponseHandler.class, resourceName); <END> ByteSource source = new ByteSource() { @Override public InputStream openStream() throws IOException { return r.openStream(); } }; return source.asCharSource(UTF_8).read(); }</code><technical_language>a copy/paste UpdateCountResponseUnitTest, more succinct ways read a test resource a string, simply org.apache.commons.io.IOUtils</technical_language>

Target:
private String loadResponseFromFile(String resourceName) throws IOException { return IOUtils.toString(getClass().getResourceAsStream(resourceName), UTF_8); }
Source:
<code>public long getEntryLastModified() { if (modTimes == null) return 0; Long cutOff = Long.valueOf(super.getEntryLastModified()); <START> SortedSet<Long> head = modTimes.headSet(cutOff, true); <END> return head.isEmpty() ? 0 : head.last().longValue(); }</code><technical_language>headSet(Object,boolean) is a Java 6 API. need define cutOff super.getEntryLastModified() - 1 instead</technical_language>

Target:
public long getEntryLastModified() { if (modTimes == null) return 0; Long cutOff = Long.valueOf(super.getEntryLastModified() + 1); SortedSet<Long> head = modTimes.headSet(cutOff); return head.isEmpty() ? 0 : head.last().longValue(); }
Source:
<code>public void configureSessionTimeout() { HttpSession httpSession = (HttpSession) FacesContext.getCurrentInstance().getExternalContext().getSession(false); if (httpSession != null) { <START> logger.info("jsession: "+httpSession.getId()+" setting the lifespan of the session to " + systemConfig.getLoginSessionTimeout() + " minutes"); <END> httpSession.setMaxInactiveInterval(systemConfig.getLoginSessionTimeout() * 60); } }</code><technical_language>This reduced logger.fine</technical_language>

Target:
public void configureSessionTimeout() { HttpSession httpSession = (HttpSession) FacesContext.getCurrentInstance().getExternalContext().getSession(false); if (httpSession != null) { logger.fine("jsession: "+httpSession.getId()+" setting the lifespan of the session to " + systemConfig.getLoginSessionTimeout() + " minutes"); httpSession.setMaxInactiveInterval(systemConfig.getLoginSessionTimeout() * 60); } }
Source:
<code>public void addApplications(List<Map<String, Object>> applicationURLList) { for (Map<String, Object> curURL : applicationURLList) { String value = "value"; try { appService.addApplication(new URI((String) curURL.get(value))); } catch (URISyntaxException use) { LOGGER.warn("Could not add application with url {}, not a valid URL.", curURL.get(value)); } catch (ApplicationServiceException ase) { <START> LOGGER.warn("Could not add application with url due to error.", curURL.get(value), ase); <END> } } }</code><technical_language>exception logged passing parameters in. log exception stack trace debug level</technical_language>

Target:
public void addApplications(List<Map<String, Object>> applicationURLList) { for (Map<String, Object> curURL : applicationURLList) { String applicationUrl = (String) curURL.get("value"); try { appService.addApplication(new URI(applicationUrl)); } catch (URISyntaxException use) { LOGGER.warn("Could not add application with url {}, not a valid URL.", applicationUrl); LOGGER.debug("Could not add application", use); } catch (ApplicationServiceException ase) { LOGGER.warn( "Could not add application with url due to error {}.", applicationUrl, ase.getMessage()); LOGGER.debug("Could not add application", ase); } } }
Source:
<code>public static void addFileHandler(String fileName) { try { FileHandler fh = new FileHandler(fileName); fh.setFormatter(new SimpleFormatter()); <START> OVIRT_LOGGER.addHandler(fh); <END> } catch (SecurityException | IOException ex) { throw new IllegalArgumentException( String.format("Error accessing log file '%s': '%s'", fileName, ex.getMessage()), ex); } }</code><technical_language>is dad handler root logger</technical_language>

Target:
public static void addFileHandler(String fileName) { try { FileHandler fh = new FileHandler(fileName); fh.setFormatter(new SimpleFormatter()); Logger.getLogger("").addHandler(fh); } catch (SecurityException | IOException ex) { throw new IllegalArgumentException( String.format("Error accessing log file '%s': '%s'", fileName, ex.getMessage()), ex); } }
Source:
<code>public String getStatementName(StatementContext statementContext) { final String rawSql = statementContext.getRawSql(); <START> if (rawSql == null || rawSql.length() == 0) { <END> return "sql.empty"; } return null; }</code><technical_language>rawSql.isEmpty()</technical_language>

Target:
public String getStatementName(StatementContext statementContext) { final String rawSql = statementContext.getRawSql(); return rawSql == null || rawSql.isEmpty() ? "sql.empty" : null; }
Source:
<code>public static Layout single(int port) { return new TestLayoutBuilder() .addLayoutServer(port) .addSequencer(port) .buildSegment() .buildStripe() .addLogUnit(port) .addToSegment() .addToLayout() <START> .setClusterId(UUID.fromString("00000000-0000-0000-0000-000000000000")) <END> .build(); }</code><technical_language>Layout.INVALID_CLUSTER_ID, please replace occurences in other test files</technical_language>

Target:
public static Layout single(int port) { return new TestLayoutBuilder() .addLayoutServer(port) .addSequencer(port) .buildSegment() .buildStripe() .addLogUnit(port) .addToSegment() .addToLayout() .setClusterId(Layout.INVALID_CLUSTER_ID) .build(); }
Source:
<code>private static MoPubErrorCode toMoPubErrorCode(final int applovinErrorCode) { if ( applovinErrorCode == AppLovinErrorCodes.NO_FILL ) { return MoPubErrorCode.NETWORK_NO_FILL; } <START> else if ( applovinErrorCode == AppLovinErrorCodes.UNSPECIFIED_ERROR ) <END> { return MoPubErrorCode.NETWORK_INVALID_STATE; } else if ( applovinErrorCode == AppLovinErrorCodes.NO_NETWORK ) { return MoPubErrorCode.NO_CONNECTION; } else if ( applovinErrorCode == AppLovinErrorCodes.FETCH_AD_TIMEOUT ) { return MoPubErrorCode.NETWORK_TIMEOUT; } else { return MoPubErrorCode.UNSPECIFIED; } }</code><technical_language>This mapped MoPubErrorCode.UNSPECIFIED</technical_language>

Target:
private static MoPubErrorCode toMoPubErrorCode(final int applovinErrorCode) { if ( applovinErrorCode == AppLovinErrorCodes.NO_FILL ) { return MoPubErrorCode.NETWORK_NO_FILL; } else if ( applovinErrorCode == AppLovinErrorCodes.UNSPECIFIED_ERROR ) { return MoPubErrorCode.UNSPECIFIED; } else if ( applovinErrorCode == AppLovinErrorCodes.NO_NETWORK ) { return MoPubErrorCode.NO_CONNECTION; } else if ( applovinErrorCode == AppLovinErrorCodes.FETCH_AD_TIMEOUT ) { return MoPubErrorCode.NETWORK_TIMEOUT; } else { return MoPubErrorCode.UNSPECIFIED; } }
Source:
<code>public void rejectsInvalidValue() { <START> final String cookiename = "cookiename"; <END> new RsWithCookie(new RsEmpty(), cookiename, "wo\"rks"); }</code><technical_language>@dalifreire this variable is unnecessary, inline</technical_language>

Target:
public void rejectsInvalidValue() { new RsWithCookie(new RsEmpty(), "cookiename", "wo\"rks"); }
Source:
<code>public static ChangeAddress ofOldAddressToNewAddress(final Address oldAddress, final Address newAddress) { <START> if (oldAddress.getId() == null) { <END> throw new IllegalArgumentException(format("The address %s should have an id.", oldAddress)); } return of(oldAddress.getId(), oldAddress.getKey(), newAddress); }</code><technical_language>check improved exception is thrown if id **and** key null</technical_language>

Target:
public static ChangeAddress ofOldAddressToNewAddress(final Address oldAddress, final Address newAddress) { if (oldAddress.getId() == null && oldAddress.getKey() == null) { throw new IllegalArgumentException(format("The address %s should have an id or a key.", oldAddress)); } if (oldAddress.getId() != null) { return of(oldAddress.getId(), newAddress); } else { return of(newAddress, oldAddress.getKey()); } }
Source:
<code>public List<Double> roundPercentages(List<Double> percentages) { <START> if (percentages == null || percentages.size() == 0) return null; <END> int size = percentages.size(); for (int i = 0; i < size; i++) { double percentage = percentages.get(i); double rounded = roundDouble(percentage); percentages.set(i, rounded); } double delta = 100.0 - percentages.stream().mapToDouble(d -> d).sum(); if (delta > 0.0) { Double lastRule = percentages.get(size - 1) + roundDouble(delta); percentages.set(size - 1, lastRule); } return percentages; }</code><technical_language>Please avoid internal code duplication, of "roundPercetanges" method calls other converting data structure</technical_language>

Target:
List<Double> roundPercentages(List<Double> percentages) { Double[] array = percentages.toArray(new Double[percentages.size()]); double[] rounded = roundPercentages(ArrayUtils.toPrimitive(array)); return Arrays.asList(ArrayUtils.toObject(rounded)); }
Source:
<code>public final int getBucketPosition(final double position) { <START> return modelVar.getBucketCache().bucketPosition(position); <END> }</code><technical_language>modelVar renamed model</technical_language>

Target:
public final int getBucketPosition(final double position) { return model.getBucketCache().bucketPercentagePosition(position); }
Source:
<code><START> protected void toLegacyText(StringBuilder builder) <END> { builder.append(this.selector); }</code><technical_language>Override</technical_language>

Target:
protected void toLegacyText(StringBuilder builder) { builder.append( this.selector ); super.toLegacyText( builder ); }
Source:
<code>public synchronized void scheduleReconnect() { logger.debug("{} scheduleReconnect()", logPrefix()); if (!isEventLoopGroupActive()) { logger.debug("isEventLoopGroupActive() == false"); return; } if (commandHandler != null && commandHandler.isClosed()) { logger.debug("Skip reconnect scheduling, CommandHandler is closed"); return; } if ((channel == null || !channel.isActive()) && !isWaitingReconnection) { attempts++; final int attempt = attempts; <START> int timeout = (int) reconnectDelay.getTimeUnit().toMillis(reconnectDelay.createDelay(attempt)); <END> logger.debug("Reconnect attempt {}, delay {}ms", attempt, timeout); isWaitingReconnection = true; timer.newTimeout(it -> { if (!isEventLoopGroupActive()) { logger.debug("isEventLoopGroupActive() == false"); return; } reconnectWorkers.submit(() -> { ConnectionWatchdog.this.run(); return null; }); }, timeout, TimeUnit.MILLISECONDS); } else { logger.debug("{} Skipping scheduleReconnect() because I have an active channel", logPrefix()); } }</code><technical_language>synchronization isWaitingReconnection.compareAndSet(false, true) happen here, obtaining delay</technical_language>

Target:
public void scheduleReconnect() { logger.debug("{} scheduleReconnect()", logPrefix()); if (!isEventLoopGroupActive()) { logger.debug("isEventLoopGroupActive() == false"); return; } if (commandHandler != null && commandHandler.isClosed()) { logger.debug("Skip reconnect scheduling, CommandHandler is closed"); return; } if ((channel == null || !channel.isActive()) && !isWaitingReconnection.get()) { if (!isWaitingReconnection.compareAndSet(false, true)) { return; } attempts++; final int attempt = attempts; int timeout = (int) reconnectDelay.getTimeUnit().toMillis(reconnectDelay.createDelay(attempt)); logger.debug("Reconnect attempt {}, delay {}ms", attempt, timeout); this.reconnectScheduleTimeout = timer.newTimeout(it -> { if (!isEventLoopGroupActive()) { logger.debug("isEventLoopGroupActive() == false"); return; } reconnectWorkers.submit(() -> { ConnectionWatchdog.this.run(it); return null; }); }, timeout, TimeUnit.MILLISECONDS); if (!isWaitingReconnection.get()) { reconnectScheduleTimeout = null; } } else { logger.debug("{} Skipping scheduleReconnect() because I have an active channel", logPrefix()); } }
Source:
<code>public IUser getUserByLogin(String login) { <START> List<UserPrivileges> privileges = Arrays.asList(UserPrivileges.READ_PROJECT, UserPrivileges.DOWNLOAD, UserPrivileges.RUN_EXPERIMENT); <END> IUserGroup group = new LocalUserGroup("guest", privileges, 0, 0); IUser user = new LocalUser(1, login, login, login, login, new ArrayList<LocalGeppettoProject>(), group); return user; }</code><technical_language>@jrmartin this change, permission of guest user propagated frontend making run experiment stuff active for guest users in a persistenceless deployment? (like geppetto live for example)</technical_language>

Target:
public IUser getUserByLogin(String login) { IUserGroup group = new LocalUserGroup("guest", getUserPrivileges(), 0, 0); IUser user = new LocalUser(1, login, login, login, login, new ArrayList<LocalGeppettoProject>(), group); return user; }
Source:
<code>public boolean waitForCompletion(long timeoutMillis) throws InterruptedException { boolean res = true; for (EventBundlePipe pipe : pipes) { <START> res = res && pipe.waitForCompletion(timeoutMillis); <END> } return res; }</code><technical_language>IMPORTANT res = pipe.waitForCompletion(timeoutMillis) && res fails complete boolean expression short-circuit other waits get executed.</technical_language>

Target:
public boolean waitForCompletion(long timeoutMillis) throws InterruptedException { boolean res = true; for (EventBundlePipe pipe : pipes) { res = pipe.waitForCompletion(timeoutMillis) && res; } return res; }
Source:
<code>public void testUpdateContainerId() { ServerTemplate serverTemplate = createServerTemplate(); ContainerSpec containerToDeploy = new ContainerSpec(CONTAINER_ID, CONTAINER_NAME, serverTemplate, releaseId, KieContainerStatus.STOPPED, Collections.EMPTY_MAP); mgmtControllerClient.saveContainerSpec(serverTemplate.getId(), containerToDeploy); ContainerSpec containerResponseEntity = mgmtControllerClient.getContainerInfo(kieServerInfo.getServerId(), CONTAINER_ID); checkContainer(containerResponseEntity, KieContainerStatus.STOPPED); assertEquals(CONTAINER_NAME, containerResponseEntity.getContainerName()); containerToDeploy.setId("newID"); try { mgmtControllerClient.updateContainerSpec(serverTemplate.getId(), CONTAINER_ID, containerToDeploy); fail("Container has updated id."); } catch (UnexpectedResponseCodeException e) { <START> assertEquals(404, e.getResponseCode()); <END> KieServerAssert.assertResultContainsString(e.getMessage(), "no container with id newID"); } }</code><technical_language>response code 400</technical_language>

Target:
public void testUpdateContainerId() { ServerTemplate serverTemplate = createServerTemplate(); ContainerSpec containerToDeploy = new ContainerSpec(CONTAINER_ID, CONTAINER_NAME, serverTemplate, releaseId, KieContainerStatus.STOPPED, Collections.EMPTY_MAP); mgmtControllerClient.saveContainerSpec(serverTemplate.getId(), containerToDeploy); ContainerSpec containerResponseEntity = mgmtControllerClient.getContainerInfo(kieServerInfo.getServerId(), CONTAINER_ID); checkContainer(containerResponseEntity, KieContainerStatus.STOPPED); assertEquals(CONTAINER_NAME, containerResponseEntity.getContainerName()); containerToDeploy.setId("newID"); try { mgmtControllerClient.updateContainerSpec(serverTemplate.getId(), CONTAINER_ID, containerToDeploy); fail("Container has updated id."); } catch (UnexpectedResponseCodeException e) { assertEquals(400, e.getResponseCode()); KieServerAssert.assertResultContainsString(e.getMessage(), "Cannot update container newID on container " + CONTAINER_ID); } }
Source:
<code>private SAMRecord getNextRecord() { final long startCoordinate = this.stream.getFilePointer(); final SAMRecord next = this.bamRecordCodec.decode(); final long stopCoordinate = this.stream.getFilePointer(); if (HtsgetBAMFileReader.this.mReader != null && next != null) { next.setFileSource(new SAMFileSource( <START> HtsgetBAMFileReader.this.mReader, <END> new BAMFileSpan(new Chunk(startCoordinate, stopCoordinate)))); } return next; }</code><technical_language>I a good idea try attach file spans here. I a idea provide a null file span. stream position is based individual request entire bam file consistency operations. In practice this attempt give bam record a unique identifier relies consistent unique record. give in this case I think</technical_language>

Target:
private SAMRecord getNextRecord() { final SAMRecord next = this.bamRecordCodec.decode(); if (HtsgetBAMFileReader.this.mReader != null && next != null) { next.setFileSource(new SAMFileSource( HtsgetBAMFileReader.this.mReader, null)); } return next; }
Source:
<code>public String getQuestionSpecificEditFormHtml(int questionNumber) { return FeedbackQuestionFormTemplates.populateTemplate( FeedbackQuestionFormTemplates.CONTRIB_EDIT_FORM, "${questionNumber}", Integer.toString(questionNumber), <START> "${allowingNotSureOrNot}", (isNotSureAllowed) ? "checked=\"checked\"" : "", <END> "${Const.ParamsNames.FEEDBACK_QUESTION_CONTRIBISNOTSUREALLOWED}", Const.ParamsNames.FEEDBACK_QUESTION_CONTRIBISNOTSUREALLOWED); }</code><technical_language>${allowingNotSureOrNot} -> ${isNotSureAllowedChecked}</technical_language>

Target:
public String getQuestionSpecificEditFormHtml(int questionNumber) { return FeedbackQuestionFormTemplates.populateTemplate( FeedbackQuestionFormTemplates.CONTRIB_EDIT_FORM, "${questionNumber}", Integer.toString(questionNumber), "${isNotSureAllowedChecked}", (isNotSureAllowed) ? "checked=\"checked\"" : "", "${Const.ParamsNames.FEEDBACK_QUESTION_CONTRIBISNOTSUREALLOWED}", Const.ParamsNames.FEEDBACK_QUESTION_CONTRIBISNOTSUREALLOWED); }
Source:
<code>public VdcActionParametersBase(ParametersMap map) { for (Map.Entry<Parameter, Serializable> entry : map.entrySet()) { put(Parameter.getByUuid(entry.getKey().getUuid().toString()), entry.getValue()); } <START> } <END></code><technical_language>this I need understand... discuss this VdcParameter infrastructure, I done automatically while de-serialized</technical_language>

Target:
public VdcActionParametersBase(ParametersMap map) { super(map); }
Source:
<code>public void installPluginFromStream(String originalName, InputStream in) throws IOException, PluginInstallException { String fileName = originalName; if (!(fileName.endsWith(".jar") || fileName.endsWith(".js"))) { throw new PluginInstallException( "Can only install files with '.jar' or '.js' extension"); } File tmp = asTemp(in, ".next_" + fileName + "_", ".tmp", pluginsDir); String name = Objects.firstNonNull(getGerritPluginName(tmp), nameOf(fileName)); <START> if (!originalName.equals(name)) { <END> log.warn(String.format("Plugin provides its own name: <%s>," + " use it instead of the input name: <%s>", name, originalName)); } String fileExtension = getExtension(originalName); File dst = new File(pluginsDir, name + fileExtension); synchronized (this) { Plugin active = running.get(name); if (active != null) { name = active.getSrcFile().getName(); log.info(String.format("Replacing plugin %s", active.getName())); File old = new File(pluginsDir, ".last_" + name); old.delete(); active.getSrcFile().renameTo(old); } new File(pluginsDir, name + ".disabled").delete(); tmp.renameTo(dst); try { Plugin plugin = runPlugin(name, dst, active); if (active == null) { log.info(String.format("Installed plugin %s", plugin.getName())); } } catch (PluginInstallException e) { dst.delete(); throw e; } cleanInBackground(); } }</code><technical_language>This condition is false now: originalName = "foo.jar" name of plugin "foo" "bar" if plugin defines name, is "foo.jar"</technical_language>

Target:
public void installPluginFromStream(String originalName, InputStream in) throws IOException, PluginInstallException { String fileName = originalName; if (!(fileName.endsWith(".jar") || fileName.endsWith(".js"))) { fileName += ".jar"; } File tmp = asTemp(in, ".next_" + fileName + "_", ".tmp", pluginsDir); String name = Objects.firstNonNull(getGerritPluginName(tmp), nameOf(fileName)); if (!originalName.equals(name)) { log.warn(String.format("Plugin provides its own name: <%s>," + " use it instead of the input name: <%s>", name, originalName)); } String fileExtension = getExtension(originalName); File dst = new File(pluginsDir, name + fileExtension); synchronized (this) { Plugin active = running.get(name); if (active != null) { fileName = active.getSrcFile().getName(); log.info(String.format("Replacing plugin %s", active.getName())); File old = new File(pluginsDir, ".last_" + fileName); old.delete(); active.getSrcFile().renameTo(old); } new File(pluginsDir, fileName + ".disabled").delete(); tmp.renameTo(dst); try { Plugin plugin = runPlugin(name, dst, active); if (active == null) { log.info(String.format("Installed plugin %s", plugin.getName())); } } catch (PluginInstallException e) { dst.delete(); throw e; } cleanInBackground(); } }
Source:
<code>void receiveMessageAndCompleteFailLockLost(MessagingEntityType entityType, boolean isSessionEnabled) { <START> if (!isSessionEnabled) return; <END> setSenderAndReceiver(entityType, isSessionEnabled); int maxMessages = 1; final String messageId = UUID.randomUUID().toString(); final ServiceBusMessage message = getMessage(messageId, isSessionEnabled); sendMessage(message); final Stream<ServiceBusReceivedMessage> messages = receiver.receive(maxMessages, TIMEOUT) .stream() .map(ServiceBusReceivedMessageContext::getMessage); final AtomicInteger receivedMessageCount = new AtomicInteger(); messages.forEach(receivedMessage -> { assertMessageEquals(receivedMessage, messageId, isSessionEnabled); Mono.empty().delaySubscription(MESSAGE_LOCK_EXPIRED_TIME).block(); try { receiver.complete(receivedMessage); assertFalse(true, "Complete should have failed because of lock token expired."); } catch (Exception ex) { assertTrue( ex instanceof AmqpException); AmqpErrorCondition lockErrorCondition; if (isSessionEnabled) { lockErrorCondition = AmqpErrorCondition.fromString("com.microsoft:session-cannot-be-locked"); } else { lockErrorCondition = AmqpErrorCondition.fromString("com.microsoft:message-lock-lost"); } assertTrue((((AmqpException)ex).getErrorCondition() == lockErrorCondition)); } messagesPending.decrementAndGet(); receivedMessageCount.incrementAndGet(); }); assertEquals(maxMessages, receivedMessageCount.get()); }</code><technical_language>This messageEntityWithSessions method source in this case</technical_language>

Target:
void receiveMessageAndCompleteFailLockLost(MessagingEntityType entityType, boolean isSessionEnabled) { if (!isSessionEnabled) return; setSenderAndReceiver(entityType, isSessionEnabled); int maxMessages = 1; final String messageId = UUID.randomUUID().toString(); final ServiceBusMessage message = getMessage(messageId, isSessionEnabled); sendMessage(message); final Stream<ServiceBusReceivedMessage> messages = receiver.receive(maxMessages, TIMEOUT) .stream() .map(ServiceBusReceivedMessageContext::getMessage); final AtomicInteger receivedMessageCount = new AtomicInteger(); messages.forEach(receivedMessage -> { assertMessageEquals(receivedMessage, messageId, isSessionEnabled); Mono.empty().delaySubscription(MESSAGE_LOCK_EXPIRED_TIME).block(); try { receiver.complete(receivedMessage); assertFalse(true, "Complete should have failed because of lock token expired."); } catch (Exception ex) { assertTrue( ex instanceof AmqpException); AmqpErrorCondition lockErrorCondition; if (isSessionEnabled) { lockErrorCondition = AmqpErrorCondition.fromString("com.microsoft:session-cannot-be-locked"); } else { lockErrorCondition = AmqpErrorCondition.fromString("com.microsoft:message-lock-lost"); } assertTrue((((AmqpException)ex).getErrorCondition() == lockErrorCondition)); } receivedMessageCount.incrementAndGet(); }); assertEquals(maxMessages, receivedMessageCount.get()); }