auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>Mono<Response<String>> renewLeaseWithResponse(Context context) { context = context == null ? Context.NONE : context; if (this.isShareFile) { <START> throw logger.logExceptionAsError(new IllegalArgumentException("Cannot renew a lease on a share file.")); <END> } else { return this.client.shares().renewLeaseWithRestResponseAsync(null, this.leaseId, null, null, null, context.addData(AZ_TRACING_NAMESPACE_KEY, STORAGE_TRACING_NAMESPACE_VALUE)) .map(rb -> new SimpleResponse<>(rb, rb.getDeserializedHeaders().getLeaseId())); } }</code><technical_language>this UnsupportedOperationException</technical_language>

Target:
Mono<Response<String>> renewLeaseWithResponse(Context context) { context = context == null ? Context.NONE : context; if (this.isShareFile) { throw logger.logExceptionAsError(new UnsupportedOperationException( "Cannot renew a lease on a share file.")); } else { return this.client.shares().renewLeaseWithRestResponseAsync(null, this.leaseId, null, null, null, context.addData(AZ_TRACING_NAMESPACE_KEY, STORAGE_TRACING_NAMESPACE_VALUE)) .map(rb -> new SimpleResponse<>(rb, rb.getDeserializedHeaders().getLeaseId())); } }
Source:
<code>private String getStoragePath( ConcreteResource resource ) { String storagePath = resource.getPath(); if ( pathGenerators != null ) { <START> for ( final PathGenerator generator : pathGenerators ) <END> { final ConcreteResource storeRes = new ConcreteResource( resource.getLocation(), storagePath ); storagePath = generator.getPath( storeRes ); } } return storagePath; }</code><technical_language>Do a case for passing in multiple PathGenerator instances? this logic simply storagePath PathGenerator iterates over? If need multiple PathGenerator instances, simplify pass in, I think</technical_language>

Target:
private String getStoragePath( ConcreteResource resource ) { String storagePath = resource.getPath(); if ( pathGenerator != null ) { final ConcreteResource storeRes = new ConcreteResource( resource.getLocation(), storagePath ); storagePath = pathGenerator.getPath( storeRes ); } return storagePath; }
Source:
<code>private String getTileEntityName(TileEntity tileEntity) { <START> String className = tileEntity.getClass().getSimpleName(); <END> ResourceLocation registryId = TileEntity.getKey(tileEntity.getClass()); if (registryId == null) return className; else { return registryId.toString(); } }</code><technical_language>Calculate this if registry id is null, is a waste time memory</technical_language>

Target:
private String getTileEntityName(TileEntity tileEntity) { ResourceLocation registryId = TileEntity.getKey(tileEntity.getClass()); if (registryId == null) return tileEntity.getClass().getSimpleName(); else { return registryId.toString(); } }
Source:
<code>public boolean isUniqueItemName(DispoProgram program, String setId, String name) { <START> IOseeBranch branch = TokenFactory.createBranch(program.getGuid(), program.getUuid(), program.getName()); <END> ArtifactReadable setArt = findDispoArtifact(branch, setId, DispoConstants.DispoSet); ResultSet<ArtifactReadable> results = getQuery() .fromBranch(branch) .andRelatedTo(CoreRelationTypes.Default_Hierarchical__Parent, setArt) .andTypeEquals(DispoConstants.DispoItem) .andNameEquals(name) .getResults(); return results.isEmpty(); }</code><technical_language>a 'getIOseeBranch' function in DispoProgram</technical_language>

Target:
public boolean isUniqueItemName(DispoProgram program, String setId, String name) { IOseeBranch branch = getProgramBranch(program); ArtifactReadable setArt = findDispoArtifact(branch, setId, DispoConstants.DispoSet); ResultSet<ArtifactReadable> results = getQuery() .fromBranch(branch) .andRelatedTo(CoreRelationTypes.Default_Hierarchical__Parent, setArt) .andTypeEquals(DispoConstants.DispoItem) .andNameEquals(name) .getResults(); return results.isEmpty(); }
Source:
<code>public SqlStatements() { attributes = Collections.synchronizedMap(new HashMap<>()); templateEngine = new DefinedAttributeTemplateEngine(); sqlParser = new ColonPrefixSqlParser(); sqlLogger = SqlLogger.NOP_SQL_LOGGER; queryTimeout = null; allowUnusedBindings = false; customizers = new CopyOnWriteArrayList<>(); <START> } <END></code><technical_language>more defensive sense</technical_language>

Target:
public SqlStatements() { attributes = Collections.synchronizedMap(new HashMap<>()); templateEngine = new DefinedAttributeTemplateEngine(); sqlParser = new ColonPrefixSqlParser(); sqlLogger = SqlLogger.NOP_SQL_LOGGER; queryTimeout = null; }
Source:
<code>private int makeRequest(String urlString, JsonStream.Streamable streamable, Map<String, String> headers) throws NetworkException { checkHasNetworkConnection(urlString); HttpURLConnection conn = null; try { URL url = new URL(urlString); conn = (HttpURLConnection) url.openConnection(); conn.setDoOutput(true); conn.setChunkedStreamingMode(0); conn.addRequestProperty("Content-Type", "application/json"); for (Map.Entry<String, String> entry : headers.entrySet()) { conn.addRequestProperty(entry.getKey(), entry.getValue()); } OutputStream out = null; try { out = conn.getOutputStream(); Charset charset = Charset.forName("UTF-8"); BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(out, charset)); <START> JsonStream stream = new JsonStream(writer); <END> streamable.toStream(stream); stream.close(); } finally { IOUtils.closeQuietly(out); } return conn.getResponseCode(); } catch (IOException exception) { throw new NetworkException(urlString, exception); } finally { IOUtils.close(conn); } }</code><technical_language>do of other objects need closed</technical_language>

Target:
private int makeRequest(String urlString, JsonStream.Streamable streamable, Map<String, String> headers) throws NetworkException { checkHasNetworkConnection(urlString); HttpURLConnection conn = null; try { URL url = new URL(urlString); conn = (HttpURLConnection) url.openConnection(); conn.setDoOutput(true); conn.setChunkedStreamingMode(0); conn.addRequestProperty("Content-Type", "application/json"); for (Map.Entry<String, String> entry : headers.entrySet()) { conn.addRequestProperty(entry.getKey(), entry.getValue()); } JsonStream stream = null; try { OutputStream out = conn.getOutputStream(); Charset charset = Charset.forName("UTF-8"); BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(out, charset)); stream = new JsonStream(writer); streamable.toStream(stream); } finally { IOUtils.closeQuietly(stream); } return conn.getResponseCode(); } catch (IOException exception) { throw new NetworkException(urlString, exception); } finally { IOUtils.close(conn); } }
Source:
<code>private void scheduleCompaction(long lastApplied) { long compactTime = System.currentTimeMillis(); long lastCompactTime = this.compactTime; this.compactTime = compactTime; if (lastCompactTime > 0) { <START> Duration duration = Duration.ofMillis((compactTime - lastCompactTime) / 2); <END> logger.trace("Scheduling compaction for {}", duration); threadContext.schedule(duration, () -> compactLogs(lastApplied)); } else { scheduleSnapshots(); } }</code><technical_language>Do want set a minimum and/or maximum for this duration? get a state compaction held for a long time? rounds get normal interval</technical_language>

Target:
private void scheduleCompaction(long lastApplied) { logger.trace("Scheduling compaction in {}", COMPACT_INTERVAL); threadContext.schedule(COMPACT_INTERVAL, () -> compactLogs(lastApplied)); }
Source:
<code>public <T> T createInstance(StoreConfiguration cfg) { if (cfg instanceof DeployedStoreConfiguration) { DeployedStoreConfiguration deployedConfiguration = (DeployedStoreConfiguration) cfg; DeployedCacheStoreMetadata deployedCacheStoreMetadata = null; try { deployedCacheStoreMetadata = getPromise(deployedConfiguration.getCustomStoreClassName()).get(TIMEOUT_SECONDS, TimeUnit.SECONDS); return (T) deployedCacheStoreMetadata.getLoaderWriterRawInstance(); } catch (InterruptedException e) { <START> InfinispanLogger.ROOT_LOGGER.error("Could not get Custom Cache Store metadata (" + deployedConfiguration.getCustomStoreClassName() + ") because of an InterruptionException.", e); <END> } catch (ExecutionException e) { InfinispanLogger.ROOT_LOGGER.error("Could not get Custom Cache Store metadata (" + deployedConfiguration.getCustomStoreClassName() + ") because of an ExecutionException.", e); } catch (TimeoutException e) { InfinispanLogger.ROOT_LOGGER.error("Could not get Custom Cache Store metadata (" + deployedConfiguration.getCustomStoreClassName() + ") within given time.", e); } } return null; }</code><technical_language>I thinking reset interrupt flag interrupt lost. Thread.currentThread().interrupt(); I familiar server details for interrupts</technical_language>

Target:
public <T> T createInstance(StoreConfiguration cfg) { if (cfg instanceof DeployedStoreConfiguration) { DeployedStoreConfiguration deployedConfiguration = (DeployedStoreConfiguration) cfg; DeployedCacheStoreMetadata deployedCacheStoreMetadata = null; try { deployedCacheStoreMetadata = getPromise(deployedConfiguration.getCustomStoreClassName()).get(TIMEOUT_SECONDS, TimeUnit.SECONDS); return (T) deployedCacheStoreMetadata.getLoaderWriterRawInstance(); } catch (InterruptedException | ExecutionException e) { throw new IllegalStateException("An error occurred while processing the deployment", e); } catch (TimeoutException e) { InfinispanLogger.ROOT_LOGGER.error("Could not get Custom Cache Store metadata (" + deployedConfiguration.getCustomStoreClassName() + ") within given time.", e); } } return null; }
Source:
<code>public ServerConfigurationNotFoundException(String serverId) { <START> super(serverId == null || serverId.isEmpty() ? "Server Id not supplied and no default server could be found" : "Server configuration, " + serverId + ", not found."); <END> }</code><technical_language>Consider adding more hints rectify problem</technical_language>

Target:
public ServerConfigurationNotFoundException(String serverId) { super( serverId == null || serverId.isEmpty() ? "Server Id not supplied and no default server could be found" : "Server configuration, '" + serverId + "', not found. The serverId parameter needs to match the Server ID of a configured OctopusDeploy server at Manage Jenkins -> Configure System -> OctopusDeploy Plugin"); }
Source:
<code>public void filterByThreadName(String name) { ITmfTrace trace = TmfTraceManager.getInstance().getActiveTrace(); if (trace == null) { return; } List<Integer> TIDS = findMatchName(name, trace); if (TIDS.size() == 0) { return; } String regexList = ""; Integer index = 0; for (Integer TID : TIDS) { <START> regexList += " TID == " + TID; END> index++; if (index != TIDS.size()) { regexList += " ||"; } } applyGlobalFilter(regexList); }</code><technical_language>OsStrings.tid() + IFilterStrings.EQUAL + tid, strings defined somewhere</technical_language>

Target:
public void filterByThreadName(String name) { ITmfTrace trace = TmfTraceManager.getInstance().getActiveTrace(); if (trace == null) { return; } List<Integer> tids = findMatchName(name, trace); if (tids.size() == 0) { return; } String regexList = ""; Integer index = 0; for (Integer tid : tids) { regexList += OsStrings.tid() + IFilterStrings.EQUAL + tid; index++; if (index != tids.size()) { regexList += ' ' + IFilterStrings.OR + ' '; } } applyGlobalFilter(regexList); }
Source:
<code><START> private void assemble() <END> { for (ItemStack in : currentRecipe.input) { if (in == null) { continue; } int found = 0; for (int i = 0; i < items.length; ++i) { if (items[i] == null) { continue; } if (items[i].isItemEqual(in)) { int supply = items[i].stackSize; int toBeFound = in.stackSize - found; if (supply >= toBeFound) { found += decrStackSize(i, toBeFound).stackSize; } else { found += decrStackSize(i, supply).stackSize; } if (found >= in.stackSize) { break; } } } } }</code><technical_language>I refactor function a single "assemble" function, of functions do simply same</technical_language>

Target:
private void assemble() { Object[] stacks; if (currentRecipe instanceof AssemblyOreRecipe) stacks = ((AssemblyOreRecipe) currentRecipe).recipe.toArray(); else stacks = currentRecipe.input; for (Object in : stacks) { if (in == null) { continue; } StackWrapper stack = new StackWrapper(in); int found = 0; for (int i = 0; i < items.length; ++i) { if (items[i] == null) { continue; } if (stack.isItemEqual(items[i])) { int supply = items[i].stackSize; int toBeFound = stack.stackSize - found; if (supply >= toBeFound) { found += decrStackSize(i, toBeFound).stackSize; } else { found += decrStackSize(i, supply).stackSize; } if (found >= stack.stackSize) { break; } } } } }
Source:
<code>private static String getTsvFromTumorTypes(Map<String, TumorType> tumorTypes) { List<String> rows = new ArrayList<>(); rows.add(TSV_HEADER); for (String code : tumorTypes.keySet()) { TumorType tumorType = tumorTypes.get(code); Map<String, TumorType> children = tumorType.getChildren(); for (String childCode : children.keySet()) { addTumorTypeToRows(children.get(childCode), rows, new ArrayList<String>()); } } <START> return StringUtils.join(rows, "\n"); <END> }</code><technical_language>This put a newline row. line terminated a new line? I generally do (to lines in format), standard is</technical_language>

Target:
private static String getTsvFromTumorTypes(Map<String, TumorType> tumorTypes) { List<String> rows = new ArrayList<>(); rows.add(TSV_HEADER); for (String code : tumorTypes.keySet()) { TumorType tumorType = tumorTypes.get(code); Map<String, TumorType> children = tumorType.getChildren(); for (String childCode : children.keySet()) { addTumorTypeToRows(children.get(childCode), rows, new ArrayList<String>()); } } return StringUtils.join(rows, "\n") + "\n"; }
Source:
<code>public Result apply(AggregationNode node, Captures captures, Context context) { boolean anyRewritten = false; ImmutableMap.Builder<Symbol, Aggregation> aggregations = ImmutableMap.builder(); for (Map.Entry<Symbol, Aggregation> entry : node.getAggregations().entrySet()) { Aggregation aggregation = entry.getValue(); if (functionRegistry.getAggregateFunctionImplementation(aggregation.getSignature()).isOrderSensitive()) { aggregations.put(entry); <START> } <END> else if (aggregation.getOrderBy().isEmpty()) { aggregations.put(entry); } else { anyRewritten = true; aggregations.put(entry.getKey(), new Aggregation(aggregation.getCall(), aggregation.getSignature(), aggregation.getMask(), ImmutableList.of(), ImmutableList.of())); } } if (!anyRewritten) { return Result.empty(); } return Result.ofPlanNode(new AggregationNode(node.getId(), node.getSource(), aggregations.build(), node.getGroupingSets(), node.getStep(), node.getHashSymbol(), node.getGroupIdSymbol())); }</code><technical_language>add a check if of aggregations contains ORDER clause bail out early if not. rules get applied times optimization process, no-op case lightweight possible</technical_language>

Target:
public Result apply(AggregationNode node, Captures captures, Context context) { if (node.getAggregations().values().stream().allMatch(aggregation -> aggregation.getOrderBy().isEmpty())) { return Result.empty(); } boolean anyRewritten = false; ImmutableMap.Builder<Symbol, Aggregation> aggregations = ImmutableMap.builder(); for (Map.Entry<Symbol, Aggregation> entry : node.getAggregations().entrySet()) { Aggregation aggregation = entry.getValue(); if (aggregation.getOrderBy().isEmpty()) { aggregations.put(entry); } else if (functionRegistry.getAggregateFunctionImplementation(aggregation.getSignature()).isOrderSensitive()) { aggregations.put(entry); } else { anyRewritten = true; aggregations.put(entry.getKey(), new Aggregation(aggregation.getCall(), aggregation.getSignature(), aggregation.getMask(), ImmutableList.of(), ImmutableList.of())); } } if (!anyRewritten) { return Result.empty(); } return Result.ofPlanNode(new AggregationNode(node.getId(), node.getSource(), aggregations.build(), node.getGroupingSets(), node.getStep(), node.getHashSymbol(), node.getGroupIdSymbol())); }
Source:
<code>public Flux<Long> scheduleMessages(Iterable<ServiceBusMessage> messages, OffsetDateTime scheduledEnqueueTime, ServiceBusTransactionContext transactionContext) { if (Objects.isNull(messages)) { return fluxError(logger, new NullPointerException("'messages' cannot be null.")); } if (Objects.isNull(scheduledEnqueueTime)) { return fluxError(logger, new NullPointerException("'scheduledEnqueueTime' cannot be null.")); } <START> return getSendLink().flatMapMany(link -> link.getLinkSize() <END> .flatMapMany(size -> { int maxSize = size > 0 ? size : MAX_MESSAGE_LENGTH_BYTES; final CreateBatchOptions batchOptions = new CreateBatchOptions(); batchOptions.setMaximumSizeInBytes(maxSize); return createBatch(batchOptions).flatMapMany(messageBatch -> { AtomicInteger index = new AtomicInteger(); messages.forEach(message -> { index.incrementAndGet(); boolean added = messageBatch.tryAdd(message); if (!added) { final String error = String.format(Locale.US, "Messages exceed max allowed size '%s' bytes for all the messages together." + " Failed to add message at index '%s'.", maxSize, index.get()); throw logger.logExceptionAsError(new AmqpException(false, AmqpErrorCondition.LINK_PAYLOAD_SIZE_EXCEEDED, error, link.getErrorContext())); } }); return connectionProcessor .flatMap(connection -> connection.getManagementNode(entityName, entityType)) .flatMapMany(managementNode -> managementNode.schedule(messageBatch.getMessages(), scheduledEnqueueTime, messageBatch.getMaxSizeInBytes(), link.getLinkName(), transactionContext)); }); })); }</code><technical_language>duplicate createBatch() logic? default default batch size</technical_language>

Target:
public Flux<Long> scheduleMessages(Iterable<ServiceBusMessage> messages, OffsetDateTime scheduledEnqueueTime, ServiceBusTransactionContext transactionContext) { if (Objects.isNull(messages)) { return fluxError(logger, new NullPointerException("'messages' cannot be null.")); } if (Objects.isNull(scheduledEnqueueTime)) { return fluxError(logger, new NullPointerException("'scheduledEnqueueTime' cannot be null.")); } return getSendLink().flatMapMany(link -> createMessageBatch() .flatMapMany(messageBatch -> { int index = 0; for (ServiceBusMessage message : messages) { if (!messageBatch.tryAddMessage(message)) { final String error = String.format(Locale.US, "Messages exceed max allowed size for all the messages together. " + "Failed to add message at index '%s'.", index); throw logger.logExceptionAsError(new AmqpException(false, AmqpErrorCondition.LINK_PAYLOAD_SIZE_EXCEEDED, error, link.getErrorContext())); } ++index; } return connectionProcessor .flatMap(connection -> connection.getManagementNode(entityName, entityType)) .flatMapMany(managementNode -> managementNode.schedule(messageBatch.getMessages(), scheduledEnqueueTime, messageBatch.getMaxSizeInBytes(), link.getLinkName(), transactionContext)); })); }
Source:
<code>void initTable(ApplicationConstants constants) { <START> getTable().enableColumnResizing(); <END> TextColumnWithTooltip<VmTemplate> nameColumn = new TextColumnWithTooltip<VmTemplate>() { @Override public String getValue(VmTemplate object) { return object.getName(); } }; getTable().addColumn(nameColumn, constants.nameTemplate(), "220px"); TextColumnWithTooltip<VmTemplate> disksColumn = new TextColumnWithTooltip<VmTemplate>() { @Override public String getValue(VmTemplate object) { return String.valueOf(object.getDiskMap().size()); } }; getTable().addColumn(disksColumn, constants.disksTemplate(), "220px"); DiskSizeColumn<VmTemplate> sizeColumn = new DiskSizeColumn<VmTemplate>() { @Override protected Long getRawValue(VmTemplate object) { return Double.valueOf(object.getActualDiskSize()).longValue(); } }; getTable().addColumn(sizeColumn, constants.actualSizeTemplate(), "220px"); FullDateTimeColumn<VmTemplate> dateColumn = new FullDateTimeColumn<VmTemplate>() { @Override protected Date getRawValue(VmTemplate object) { return object.getCreationDate(); } }; getTable().addColumn(dateColumn, constants.creationDateTemplate(), "220px"); }</code><technical_language>fixed in <LINK_0></technical_language>

Target:
void initTable(ApplicationConstants constants) { getTable().enableColumnResizing(); TextColumnWithTooltip<VmTemplate> nameColumn = new TextColumnWithTooltip<VmTemplate>() { @Override public String getValue(VmTemplate object) { return object.getName(); } }; getTable().addColumn(nameColumn, constants.nameTemplate(), "200px"); TextColumnWithTooltip<VmTemplate> disksColumn = new TextColumnWithTooltip<VmTemplate>() { @Override public String getValue(VmTemplate object) { return String.valueOf(object.getDiskMap().size()); } }; getTable().addColumn(disksColumn, constants.disksTemplate(), "200px"); DiskSizeColumn<VmTemplate> sizeColumn = new DiskSizeColumn<VmTemplate>() { @Override protected Long getRawValue(VmTemplate object) { return Double.valueOf(object.getActualDiskSize()).longValue(); } }; getTable().addColumn(sizeColumn, constants.actualSizeTemplate(), "200px"); FullDateTimeColumn<VmTemplate> dateColumn = new FullDateTimeColumn<VmTemplate>() { @Override protected Date getRawValue(VmTemplate object) { return object.getCreationDate(); } }; getTable().addColumn(dateColumn, constants.creationDateTemplate(), "200px"); }
Source:
<code>public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) { if (holder.getItemViewType() == 0) { ExampleItemModel detailItem = dataSource.get(position); ViewHolder viewHolder = (ViewHolder) holder; <START> if (Build.VERSION.SDK_INT >= detailItem.getMinSdkVersion()) { <END> String imageUrl = context.getString(detailItem.getImageUrl()); if (!imageUrl.isEmpty()) { Picasso.with(context) .load(imageUrl) .into(viewHolder.imageView); } else { viewHolder.imageView.setImageDrawable(null); } if (detailItem.getShowNewIcon()) { viewHolder.newIconImageView.setImageDrawable(ContextCompat.getDrawable(context, R.drawable.new_icon)); } else { viewHolder.newIconImageView.setImageDrawable(null); } viewHolder.titleTextView.setText(context.getString(detailItem.getTitle())); viewHolder.descriptionTextView.setText(context.getString(detailItem.getDescription())); } } }</code><technical_language>instead of wrapping code a if (Build.VERSION.SDK_INT >= detailItem.getMinSdkVersion()), do a if (Build.VERSION.SDK_INT < detailItem.getMinSdkVersion()) { return; } previous if code level of indentation</technical_language>

Target:
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) { if (holder.getItemViewType() != 0) { return; } ExampleItemModel detailItem = dataSource.get(position); ViewHolder viewHolder = (ViewHolder) holder; if (Build.VERSION.SDK_INT < detailItem.getMinSdkVersion()) { return; } String imageUrl = context.getString(detailItem.getImageUrl()); if (imageUrl.isEmpty()) { viewHolder.imageView.setImageDrawable(null); } else { Picasso.with(context) .load(imageUrl) .into(viewHolder.imageView); } if (detailItem.getShowNewIcon()) { viewHolder.newIconImageView.setImageDrawable(ContextCompat.getDrawable(context, R.drawable.new_icon)); } else { viewHolder.newIconImageView.setImageDrawable(null); } viewHolder.titleTextView.setText(context.getString(detailItem.getTitle())); viewHolder.descriptionTextView.setText(context.getString(detailItem.getDescription())); }
Source:
<code>private void initTable(final ApplicationConstants constants, final ApplicationMessages messages) { getTable().enableColumnResizing(); getTable().addColumn(new TextColumnWithTooltip<QuotaStorage>() { @Override public String getValue(QuotaStorage object) { return object.getStorageName() == null || object.getStorageName().equals("") ? constants.utlQuotaAllStoragesQuotaPopup() : object.getStorageName(); } }, constants.nameQuotaStorage(), "400px"); getTable().addColumn(new TextColumnWithEditableTooltip<QuotaStorage>() { @Override public String getValue(QuotaStorage object) { if (object.getStorageSizeGB() == null) { return ""; } else if (object.getStorageSizeGB().equals(QuotaStorage.UNLIMITED)) { return messages.unlimitedStorageConsumption(object.getStorageSizeGBUsage() == 0 ? "0" : diskSizeRenderer.render(object.getStorageSizeGBUsage())); } else { return messages.limitedStorageConsumption(object.getStorageSizeGBUsage() == 0 ? "0" : diskSizeRenderer.render(object.getStorageSizeGBUsage()) ,object.getStorageSizeGB()); } } @Override public TextCellWithEditableTooltip getCell() { TextCellWithEditableTooltip textCellWithEditableTooltip = super.getCell(); <START> textCellWithEditableTooltip.setTooltip(constants.quotaCalculationsMessage()); <END> return textCellWithEditableTooltip; } }, constants.usedStorageTotalQuotaStorage(), "400px"); }</code><technical_language>thought, refactor 'setTitle' (causes unrelated changes ;)</technical_language>

Target:
private void initTable(final ApplicationConstants constants, final ApplicationMessages messages) { getTable().enableColumnResizing(); getTable().addColumn(new TextColumnWithTooltip<QuotaStorage>() { @Override public String getValue(QuotaStorage object) { return object.getStorageName() == null || object.getStorageName().equals("") ? constants.utlQuotaAllStoragesQuotaPopup() : object.getStorageName(); } }, constants.nameQuotaStorage(), "400px"); getTable().addColumn(new TextColumnWithEditableTooltip<QuotaStorage>() { @Override public String getValue(QuotaStorage object) { if (object.getStorageSizeGB() == null) { return ""; } else if (object.getStorageSizeGB().equals(QuotaStorage.UNLIMITED)) { return messages.unlimitedStorageConsumption(object.getStorageSizeGBUsage() == 0 ? "0" : diskSizeRenderer.render(object.getStorageSizeGBUsage())); } else { return messages.limitedStorageConsumption(object.getStorageSizeGBUsage() == 0 ? "0" : diskSizeRenderer.render(object.getStorageSizeGBUsage()) ,object.getStorageSizeGB()); } } @Override public TextCellWithEditableTooltip getCell() { TextCellWithEditableTooltip textCellWithEditableTooltip = super.getCell(); textCellWithEditableTooltip.setTitle(constants.quotaCalculationsMessage()); return textCellWithEditableTooltip; } }, constants.usedStorageTotalQuotaStorage(), "400px"); }
Source:
<code>public void clickOnStackButton() { seleniumWebDriverHelper <START> .waitVisibility(By.xpath(" END> .click(); }</code><technical_language>simplified seleniumWebDriverHelper.waitAndClick() method</technical_language>

Target:
public void clickOnStackButton() { seleniumWebDriverHelper.waitAndClick(By.xpath(" }
Source:
<code>public boolean equals(Object object) { if (object == null) { return false; } if (object == this) { return true; } <START> if (object.getClass() != getClass()) { <END> return false; } XarSecurityRule rhs = (XarSecurityRule) object; return new EqualsBuilder() .appendSuper(super.equals(object)) .append(this.right, rhs.right) .append(this.simple, rhs.simple) .append(this.securityTool, rhs.securityTool) .isEquals(); }</code><technical_language>instanceof XarSecurityRule instead avoid need for null check ;)</technical_language>

Target:
public boolean equals(Object object) { if (object == this) { return true; } if (!(object instanceof XarSecurityRule)) { return false; } XarSecurityRule rhs = (XarSecurityRule) object; return new EqualsBuilder() .append(this.right, rhs.right) .append(this.simple, rhs.simple) .isEquals(); }
Source:
<code>public ListenableFuture<List<Pair<DataSegmentChangeRequest, Status>>> processBatch(List<DataSegmentChangeRequest> changeRequests) { boolean isAnyRequestDone = false; <START> Map<DataSegmentChangeRequest, AtomicReference<Status>> statuses = new HashMap<>(changeRequests.size()); <END> for (DataSegmentChangeRequest cr : changeRequests) { AtomicReference<Status> status = processRequest(cr); if (status.get().getState() != Status.STATE.PENDING) { isAnyRequestDone = true; } statuses.put(cr, status); } CustomSettableFuture future = new CustomSettableFuture(waitingFutures, statuses); if (isAnyRequestDone) { future.resolve(); } else { synchronized (waitingFutures) { waitingFutures.add(future); } } return future; }</code><technical_language>This constructor sets initial capacity, is "make large enough hold N things". Maps.newHashMapWithExpectedSize() is a option. Or, for poor man's attempt it, 2x size passing in</technical_language>

Target:
public ListenableFuture<List<DataSegmentChangeRequestAndStatus>> processBatch(List<DataSegmentChangeRequest> changeRequests) { boolean isAnyRequestDone = false; Map<DataSegmentChangeRequest, AtomicReference<Status>> statuses = Maps.newHashMapWithExpectedSize(changeRequests.size()); for (DataSegmentChangeRequest cr : changeRequests) { AtomicReference<Status> status = processRequest(cr); if (status.get().getState() != Status.STATE.PENDING) { isAnyRequestDone = true; } statuses.put(cr, status); } CustomSettableFuture future = new CustomSettableFuture(waitingFutures, statuses); if (isAnyRequestDone) { future.resolve(); } else { synchronized (waitingFutures) { waitingFutures.add(future); } } return future; }
Source:
<code>private void removeImageFromDB() { final DiskImage diskImage = getDiskImage(); final List<Snapshot> updatedSnapshots; try { VM vm = getVmForNonShareableDiskImage(diskImage); if (getParameters().isRemoveFromSnapshots() && vm != null) { lockVmSnapshotsWithWait(vm); updatedSnapshots = prepareSnapshotConfigWithoutImage(diskImage.getId()); } else { updatedSnapshots = Collections.emptyList(); } TransactionSupport.executeInScope(TransactionScopeOption.Required, () -> { diskImageDynamicDao.remove(diskImage.getImageId()); Guid imageTemplate = diskImage.getImageTemplateId(); Guid currentGuid = diskImage.getImageId(); while (!currentGuid.equals(imageTemplate) && !currentGuid.equals(Guid.Empty)) { removeChildren(currentGuid); DiskImage image = diskImageDao.getSnapshotById(currentGuid); if (image != null) { removeSnapshot(image); currentGuid = image.getParentId(); } else { currentGuid = Guid.Empty; log.warn( "'image' (snapshot of image '{}') is null, cannot remove it.", diskImage.getImageId()); } } baseDiskDao.remove(diskImage.getId()); vmDeviceDao.remove(new VmDeviceId(diskImage.getId(), null)); <START> updatedSnapshots.forEach(s -> snapshotDao.update(s)); <END> return null; }); } finally { if (getSnapshotsEngineLock() != null) { lockManager.releaseLock(getSnapshotsEngineLock()); } } }</code><technical_language>following: updatedSnapshots.forEach(snapshotDao::update)</technical_language>

Target:
private void removeImageFromDB() { final DiskImage diskImage = getDiskImage(); final List<Snapshot> updatedSnapshots; try { VM vm = getVmForNonShareableDiskImage(diskImage); if (getParameters().isRemoveFromSnapshots() && vm != null) { lockVmSnapshotsWithWait(vm); updatedSnapshots = prepareSnapshotConfigWithoutImage(diskImage.getId()); } else { updatedSnapshots = Collections.emptyList(); } TransactionSupport.executeInScope(TransactionScopeOption.Required, () -> { diskImageDynamicDao.remove(diskImage.getImageId()); Guid imageTemplate = diskImage.getImageTemplateId(); Guid currentGuid = diskImage.getImageId(); while (!currentGuid.equals(imageTemplate) && !currentGuid.equals(Guid.Empty)) { removeChildren(currentGuid); DiskImage image = diskImageDao.getSnapshotById(currentGuid); if (image != null) { removeSnapshot(image); currentGuid = image.getParentId(); } else { currentGuid = Guid.Empty; log.warn( "'image' (snapshot of image '{}') is null, cannot remove it.", diskImage.getImageId()); } } baseDiskDao.remove(diskImage.getId()); vmDeviceDao.remove(new VmDeviceId(diskImage.getId(), null)); updatedSnapshots.forEach(snapshotDao::update); return null; }); } finally { if (getSnapshotsEngineLock() != null) { lockManager.releaseLock(getSnapshotsEngineLock()); } } }
Source:
<code>public void revertBlock() { <START> PaperLib.getChunkAtAsync(block.getLocation()).thenAccept(result -> <END> this.state.update(true, physicsblocks.contains(this.state.getType())) ); instances.remove(this.block); REVERT_QUEUE.remove(this); if (this.revertTask != null) { this.revertTask.run(); } }</code><technical_language>This need kind of null check if Paper</technical_language>

Target:
public void revertBlock() { PaperLib.getChunkAtAsync(block.getLocation()).thenAccept(result -> this.state.update(true, GeneralMethods.isLightEmitting(this.state.getType())) ); instances.remove(this.block); REVERT_QUEUE.remove(this); if (this.revertTask != null) { this.revertTask.run(); } }
Source:
<code>private boolean shouldSynthesizeBrand(BtVodDataRow row) { <START> return canParseBrandFromEpisode(row) || canParseBrandFromSeries(row); <END> }</code><technical_language>synthesize brand if is a BRAND_IA_ID value, create brand ID. Update: ah contained in canParseBrandFromEpisode. I think, for clarity, belongs in this method. functionality matches method name then</technical_language>

Target:
private boolean shouldSynthesizeBrand(BtVodDataRow row) { return !isBrand(row) && (canParseBrandFromEpisode(row) || canParseBrandFromSeries(row)); }
Source:
<code>public static Object valueToLocalDateTime(ValueTimestamp value) throws SQLException { long dateValue = value.getDateValue(); long timeNanos = value.getTimeNanos(); try { Object localDate = localDateFromDateValue(dateValue); Object localDateTime = LOCAL_DATE_AT_START_OF_DAY.invoke(localDate); return LOCAL_DATE_TIME_PLUS_NANOS.invoke(localDateTime, timeNanos); } catch (IllegalAccessException e) { throw DbException.convert(e); } catch (InvocationTargetException e) { <START> throw DbException.convertInvocation(e, "timestampe conversion failed"); <END> } }</code><technical_language>timestamp</technical_language>

Target:
public static Object valueToLocalDateTime(ValueTimestamp value) throws SQLException { long dateValue = value.getDateValue(); long timeNanos = value.getTimeNanos(); try { Object localDate = localDateFromDateValue(dateValue); Object localDateTime = LOCAL_DATE_AT_START_OF_DAY.invoke(localDate); return LOCAL_DATE_TIME_PLUS_NANOS.invoke(localDateTime, timeNanos); } catch (IllegalAccessException e) { throw DbException.convert(e); } catch (InvocationTargetException e) { throw DbException.convertInvocation(e, "timestamp conversion failed"); } }
Source:
<code>public void accept(MessageSendingResult result) { timer.stop(); if (result.succeeded()) { rateLimiter.registerSuccessfulSending(); handleMessageSendingSuccess(message, result); } else { handleFailedSending(message, result); if (!isTtlExceeded(message) && shouldRetrySending(result)) { retrySingleThreadExecutor.schedule(() -> retrySending(result), <START> extractRetryDelay(result), TimeUnit.MILLISECONDS); <END> } else { handleMessageDiscarding(message, result); } } }</code><technical_language>this is ok schedule tasks delay received header: - validate if is reasonable boundries (0, maxMessageBackoff) - discard message if retry-after is message TTL respect TTL policy</technical_language>

Target:
public void accept(MessageSendingResult result) { timer.stop(); if (result.succeeded()) { rateLimiter.registerSuccessfulSending(); handleMessageSendingSuccess(message, result); } else { handleFailedSending(message, result); if (!attemptResending(result)) { handleMessageDiscarding(message, result); } } }
Source:
<code>public void removeEntry(String type, String value) throws Exception { <START> if (type.compareTo("provider") == 0) { <END> for (int i = 0; i < this.providers.size(); ++i) { if (this.providers.get(i).compareTo(value) == 0) { this.removeEntry(i); i--; } } } else if (type.compareTo("client") == 0) { for (int i = 0; i < this.clients.size(); ++i) { if (this.clients.get(i).compareTo(value) == 0) { this.removeEntry(i); i--; } } } else if (type.compareTo("server") == 0) { for (int i = 0; i < this.servers.size(); ++i) { if (this.servers.get(i).compareTo(value) == 0) { this.removeEntry(i); i--; } } } else if (type.compareTo("secret") == 0) { for (int i = 0; i < this.secrets.size(); ++i) { if (this.secrets.get(i).compareTo(value) == 0) { this.removeEntry(i); i--; } } } else if (type.compareTo("ipAddress") == 0) { for (int i = 0; i < this.ipAddresses.size(); ++i) { if (this.ipAddresses.get(i).compareTo(value) == 0) { this.removeEntry(i); i--; } } } else { } writeToFile(); }</code><technical_language>please reverse comparison "a string constant".equals(anotherString)</technical_language>

Target:
public void removeEntry(String type, String value) throws Exception { if ("provider".equals(type)) { checkAndRemove(this.providers, value); } else if ("client".equals(type)) { checkAndRemove(this.clients, value); } else if ("server".equals(type)) { checkAndRemove(this.servers, value); } else if ("secret".equals(type)) { checkAndRemove(this.secrets, value); } else if ("ipAddress".equals(type)) { checkAndRemove(this.ipAddresses, value); } else { } writeToFile(); }
Source:
<code>public void run(SparkExecutionPluginContext context, JavaRDD<StructuredRecord> input) throws Exception { if (!input.isEmpty()) { final Schema inputSchema = input.first().getSchema(); final Map<String, Integer> featuresList = SparkUtils.getFeatureList(inputSchema, config.featureFieldsToInclude, config.featureFieldsToExclude, config.labelField); JavaRDD<LabeledPoint> trainingData = input.map(new Function<StructuredRecord, LabeledPoint>() { @Override public LabeledPoint call(StructuredRecord record) throws Exception { List<Double> featureList = new ArrayList<>(); List<Integer> featureIndex = new ArrayList<>(); <START> int counter = 0; <END> for (String field : featuresList.keySet()) { if (record.get(field) != null) { featureList.add(((Number) record.get(field)).doubleValue()); featureIndex.add(counter); } counter++; } Double prediction = record.get(config.labelField); if (prediction == null) { throw new IllegalArgumentException(String.format("Value of Label field %s value must not be null.", config.labelField)); } return new LabeledPoint(prediction, Vectors.sparse(counter, Ints.toArray(featureIndex), Doubles.toArray(featureList))); } }); trainingData.cache(); FileSet outputFS = context.getDataset(config.fileSetName); trainModel(context.getSparkContext().sc(), null, trainingData, outputFS.getBaseLocation().append(config.path).toURI().getPath()); } }</code><technical_language>size featuresList.size(). featureList featureIndex lists arrays. turn lists arrays save traversals</technical_language>

Target:
public void run(SparkExecutionPluginContext context, JavaRDD<StructuredRecord> input) throws Exception { if (!input.isEmpty()) { final Schema inputSchema = input.first().getSchema(); final Map<String, Integer> featuresList = SparkUtils.getFeatureList(inputSchema, config.featureFieldsToInclude, config.featureFieldsToExclude, config.labelField); JavaRDD<StructuredRecord> filteredData = input.filter(new Function<StructuredRecord, Boolean>() { @Override public Boolean call(StructuredRecord record) throws Exception { if (record.get(config.labelField) == null) { return false; } return true; } }); JavaRDD<LabeledPoint> trainingData = filteredData.map(new Function<StructuredRecord, LabeledPoint>() { @Override public LabeledPoint call(StructuredRecord record) throws Exception { List<Double> featureList = new ArrayList<>(); List<Integer> featureIndex = new ArrayList<>(); int counter = 0; for (String field : featuresList.keySet()) { if (record.get(field) != null) { featureList.add(((Number) record.get(field)).doubleValue()); featureIndex.add(counter); } counter++; } return new LabeledPoint((Double) record.get(config.labelField), Vectors.sparse(counter, Ints.toArray(featureIndex), Doubles.toArray(featureList))); } }); trainingData.cache(); FileSet outputFS = context.getDataset(config.fileSetName); trainModel(context.getSparkContext().sc(), inputSchema, trainingData, outputFS.getBaseLocation().append(config.path).toURI().getPath()); } }
Source:
<code>private boolean checkCanPerformRegularUpdate(List<VM> vmsDiskPluggedTo) { for (VM vm : vmsDiskPluggedTo) { Guid vmId = vm.getId(); if (oldDisk.getDiskInterface() != newDisk.getDiskInterface()) { List<VmNetworkInterface> allVmInterfaces = getVmNetworkInterfaceDao().getAllForVm(vmId); List<Disk> allVmDisks = new LinkedList<Disk>(getOtherVmDisks(vmId)); allVmDisks.add(newDisk); if (!checkPciAndIdeLimit(vm.getNumOfMonitors(), allVmInterfaces, allVmDisks, getReturnValue().getCanDoActionMessages())) { return false; } } } if (newDisk.isBoot()) { <START> if (!isVMsContainingBootableDisks(newDisk, vmsDiskPluggedTo)) { <END> return false; } } return true; }</code><technical_language>This is a confusing function name ("if VM contains a boot disk fail". Huh?!)</technical_language>

Target:
private boolean checkCanPerformRegularUpdate(List<VM> vmsDiskPluggedTo) { for (VM vm : vmsDiskPluggedTo) { Guid vmId = vm.getId(); if (oldDisk.getDiskInterface() != newDisk.getDiskInterface()) { List<VmNetworkInterface> allVmInterfaces = getVmNetworkInterfaceDao().getAllForVm(vmId); List<Disk> allVmDisks = new LinkedList<Disk>(getOtherVmDisks(vmId)); allVmDisks.add(newDisk); if (!checkPciAndIdeLimit(vm.getNumOfMonitors(), allVmInterfaces, allVmDisks, getReturnValue().getCanDoActionMessages())) { return false; } } } if (newDisk.isBoot()) { if (!validate(noVmsContainBootableDisks(vmsDiskPluggedTo))) { return false; } } return true; }
Source:
<code>public void gauge(String label, double value, String topic) { String key = label + "_" + topic; <START> if (mGaugeCache.size() <= mConfig.getMicroMeterCacheSize()) { <END> mGaugeCache.put(key, value); } else { LOG.error("Gauge cache size reached maximum, this may result in inaccurate metrics, " + "you can increase cache size by changing " + "\"secor.monitoring.metrics.collector.micrometer.cache.size\" property."); } Metrics.gauge(label, Collections.singletonList( Tag.of("topic", topic)), mGaugeCache, g -> g.get(key)); }</code><technical_language>I do cache size check issue error message cache needs grow, time gauge is called (there frequent)</technical_language>

Target:
public void gauge(String label, double value, String topic) { String key = label + "_" + topic; if (!mGaugeCache.containsKey(key) && mGaugeCache.size() >= mConfig.getMicroMeterCacheSize()) { LOG.error("Gauge cache size reached maximum, this may result in inaccurate metrics, " + "you can increase cache size by changing " + "\"secor.monitoring.metrics.collector.micrometer.cache.size\" property."); return; } mGaugeCache.put(key, value); Metrics.gauge(label, Collections.singletonList( Tag.of("topic", topic)), mGaugeCache, g -> g.get(key)); }
Source:
<code><START> public synchronized void setLastPacketReceivedTimestamp(double currentTimestamp) { <END> connectionLatch.setValue((currentTimestamp - lastPacketReceivedTimestamp) < timeOut.get()); this.lastPacketReceivedTimestamp = currentTimestamp; }</code><technical_language>synchronized? I other threads involved here..</technical_language>

Target:
public void setLastPacketReceivedTimestamp(double currentTimestamp) { if (lastPacketReceivedTimestamp != null) { connectionLatch.setValue((currentTimestamp - lastPacketReceivedTimestamp) < timeOut.get()); } this.lastPacketReceivedTimestamp = currentTimestamp; }
Source:
<code>protected boolean checkNumaValid() { List<VmNumaNode> vmNumaNodes = getParameters().getVmNumaNodeList(); if (vmNumaNodes == null || vmNumaNodes.size() == 0) { return true; } VM vm = getVm(); <START> Guid vdsId = vm.getDedicatedVmForVds(); <END> if (pinHost && vdsId == null) { return failCanDoAction(VdcBllMessages.VM_NUMA_PINNED_VDS_NOT_EXIST); } List<VdsNumaNode> vdsNumaNodes = new ArrayList<>(); if (pinHost) { vdsNumaNodes = getVdsNumaNodeDao().getAllVdsNumaNodeByVdsId(vdsId); if (vdsNumaNodes == null || vdsNumaNodes.size() == 0) { return failCanDoAction(VdcBllMessages.VM_NUMA_PINNED_VDS_NODE_EMPTY); } } boolean memStrict = vm.getNumaTuneMode() == NumaTuneMode.STRICT; for (VmNumaNode vmNumaNode : vmNumaNodes) { for (Pair<Guid, Pair<Boolean, Integer>> pair : vmNumaNode.getVdsNumaNodeList()) { if (pair == null || pair.getSecond() == null || pair.getSecond().getSecond() == null) { return failCanDoAction(VdcBllMessages.VM_NUMA_NODE_PINNED_INDEX_ERROR); } Integer index = pair.getSecond().getSecond(); for (VdsNumaNode vdsNumaNode : vdsNumaNodes) { if (vdsNumaNode.getIndex() == index) { if (memStrict && vmNumaNode.getMemTotal() > vdsNumaNode.getMemTotal()) { return failCanDoAction(VdcBllMessages.VM_NUMA_NODE_MEMRORY_ERROR); } break; } } } } return true; }</code><technical_language>MigrationSupport field, check if vm is pinned not</technical_language>

Target:
protected boolean checkNumaValid() { List<VmNumaNode> vmNumaNodes = getParameters().getVmNumaNodeList(); if (vmNumaNodes == null || vmNumaNodes.size() == 0) { return true; } VM vm = getVm(); boolean pinHost = vm.getMigrationSupport() == MigrationSupport.PINNED_TO_HOST; Guid vdsId = vm.getDedicatedVmForVds(); if (pinHost && vdsId == null) { return failCanDoAction(VdcBllMessages.VM_NUMA_PINNED_VDS_NOT_EXIST); } List<VdsNumaNode> vdsNumaNodes = new ArrayList<>(); if (pinHost) { vdsNumaNodes = getVdsNumaNodeDao().getAllVdsNumaNodeByVdsId(vdsId); if (vdsNumaNodes == null || vdsNumaNodes.size() == 0) { return failCanDoAction(VdcBllMessages.VM_NUMA_PINNED_VDS_NODE_EMPTY); } } boolean memStrict = vm.getNumaTuneMode() == NumaTuneMode.STRICT; for (VmNumaNode vmNumaNode : vmNumaNodes) { for (Pair<Guid, Pair<Boolean, Integer>> pair : vmNumaNode.getVdsNumaNodeList()) { if (pair == null || pair.getSecond() == null || pair.getSecond().getSecond() == null) { return failCanDoAction(VdcBllMessages.VM_NUMA_NODE_PINNED_INDEX_ERROR); } Integer index = pair.getSecond().getSecond(); for (VdsNumaNode vdsNumaNode : vdsNumaNodes) { if (vdsNumaNode.getIndex() == index) { if (memStrict && vmNumaNode.getMemTotal() > vdsNumaNode.getMemTotal()) { return failCanDoAction(VdcBllMessages.VM_NUMA_NODE_MEMRORY_ERROR); } break; } } } } return true; }
Source:
<code>public void testSendFilterAnnotation() throws Exception { AmqpClient client = createAmqpClient(); AmqpConnection connection = addConnection(client.connect()); AmqpSession session = connection.createSession(); AmqpSender sender = session.createSender(getQueueName()); AmqpMessage message = new AmqpMessage(); message.setMessageId("msg" + 1); message.setMessageAnnotation("serialNo", 1); message.setText("Test-Message"); sender.send(message); message = new AmqpMessage(); message.setMessageId("msg" + 2); message.setMessageAnnotation("serialNo", 2); message.setText("Test-Message 2"); sender.send(message); sender.close(); LOG.debug("Attempting to read message with receiver"); <START> AmqpReceiver receiver = session.createReceiver(getQueueName(), "\"m.serialNo\"=2"); <END> receiver.flow(2); AmqpMessage received = receiver.receive(10, TimeUnit.SECONDS); assertNotNull("Should have read message", received); assertEquals("msg2", received.getMessageId()); received.accept(); Assert.assertNull(receiver.receiveNoWait()); receiver.close(); connection.close(); }</code><technical_language>change x-opt- prefixed annotation</technical_language>

Target:
public void testSendFilterAnnotation() throws Exception { AmqpClient client = createAmqpClient(); AmqpConnection connection = addConnection(client.connect()); AmqpSession session = connection.createSession(); AmqpSender sender = session.createSender(getQueueName()); AmqpMessage message = new AmqpMessage(); message.setMessageId("msg" + 1); message.setMessageAnnotation("x-opt-serialNo", 1); message.setText("Test-Message"); sender.send(message); message = new AmqpMessage(); message.setMessageId("msg" + 2); message.setMessageAnnotation("x-opt-serialNo", 2); message.setText("Test-Message 2"); sender.send(message); sender.close(); LOG.debug("Attempting to read message with receiver"); AmqpReceiver receiver = session.createReceiver(getQueueName(), "\"m.x-opt-serialNo\"=2"); receiver.flow(2); AmqpMessage received = receiver.receive(10, TimeUnit.SECONDS); assertNotNull("Should have read message", received); assertEquals("msg2", received.getMessageId()); received.accept(); Assert.assertNull(receiver.receiveNoWait()); receiver.close(); connection.close(); }