auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public void testConstructorReturnsValue() throws Exception { IPackageFragment pack1 = fSourceFolder.createPackageFragment("test1", false, null); StringBuffer buf = new StringBuffer(); buf.append("package test1;\n"); buf.append("public class E {\n"); buf.append(" public E() {\n"); <START> buf.append(" return System.getAttributes();\n"); <END> buf.append(" }\n"); buf.append("}\n"); ICompilationUnit cu = pack1.createCompilationUnit("E.java", buf.toString(), false, null); CompilationUnit astRoot = getASTRoot(cu); ArrayList proposals = collectCorrections(cu, astRoot); assertNumberOfProposals(proposals, 2); assertCorrectLabels(proposals); { ASTRewriteCorrectionProposal proposal = (ASTRewriteCorrectionProposal) proposals.get(0); String preview = getPreviewContent(proposal); buf = new StringBuffer(); buf.append("package test1;\n"); buf.append("\n"); buf.append("import java.util.Properties;\n"); buf.append("\n"); buf.append("public class E {\n"); buf.append(" public Properties E() {\n"); buf.append(" return System.getAttributes();\n"); buf.append(" }\n"); buf.append("}\n"); assertEqualString(preview, buf.toString()); } { ASTRewriteCorrectionProposal proposal = (ASTRewriteCorrectionProposal) proposals.get(1); String preview = getPreviewContent(proposal); buf = new StringBuffer(); buf.append("package test1;\n"); buf.append("public class E {\n"); buf.append(" public E() {\n"); buf.append(" return;\n"); buf.append(" }\n"); buf.append("}\n"); assertEqualString(preview, buf.toString()); } }</code><technical_language>@sleshchenko this class is changed mistake</technical_language>

Target:
public void testConstructorReturnsValue() throws Exception { IPackageFragment pack1 = fSourceFolder.createPackageFragment("test1", false, null); StringBuffer buf = new StringBuffer(); buf.append("package test1;\n"); buf.append("public class E {\n"); buf.append(" public E() {\n"); buf.append(" return System.getProperties();\n"); buf.append(" }\n"); buf.append("}\n"); ICompilationUnit cu = pack1.createCompilationUnit("E.java", buf.toString(), false, null); CompilationUnit astRoot = getASTRoot(cu); ArrayList proposals = collectCorrections(cu, astRoot); assertNumberOfProposals(proposals, 2); assertCorrectLabels(proposals); { ASTRewriteCorrectionProposal proposal = (ASTRewriteCorrectionProposal) proposals.get(0); String preview = getPreviewContent(proposal); buf = new StringBuffer(); buf.append("package test1;\n"); buf.append("\n"); buf.append("import java.util.Properties;\n"); buf.append("\n"); buf.append("public class E {\n"); buf.append(" public Properties E() {\n"); buf.append(" return System.getProperties();\n"); buf.append(" }\n"); buf.append("}\n"); assertEqualString(preview, buf.toString()); } { ASTRewriteCorrectionProposal proposal = (ASTRewriteCorrectionProposal) proposals.get(1); String preview = getPreviewContent(proposal); buf = new StringBuffer(); buf.append("package test1;\n"); buf.append("public class E {\n"); buf.append(" public E() {\n"); buf.append(" return;\n"); buf.append(" }\n"); buf.append("}\n"); assertEqualString(preview, buf.toString()); } }
Source:
<code>public void visitNode(Tree tree) { if (tree.is(Tree.Kind.NEW_CLASS) && UNSAFE_PASSWORD_ENCODERS.anyMatch(((NewClassTree) tree))) { reportIssue(((NewClassTree) tree).identifier(), "Use secure password encoder."); } else if (tree.is(Tree.Kind.METHOD)) { <START> MethodInvocationVisitor visitor = new MethodInvocationVisitor(); <END> tree.accept(visitor); if (visitor.hasAuthentication && !visitor.setsPasswordEncoder) { reportIssue(visitor.tree, "Configure explicit password encoder."); } } }</code><technical_language>I check if semantic information if (!hasSemantic()) { return; }</technical_language>

Target:
public void visitNode(Tree tree) { if (!hasSemantic()) { return; } if (tree.is(Tree.Kind.NEW_CLASS) && UNSAFE_PASSWORD_ENCODERS.anyMatch(((NewClassTree) tree))) { reportIssue(((NewClassTree) tree).identifier(), "Use secure password encoder."); } else if (tree.is(Tree.Kind.METHOD)) { MethodInvocationVisitor visitor = new MethodInvocationVisitor(); tree.accept(visitor); if (visitor.hasAuthentication && !visitor.setsPasswordEncoder) { reportIssue(visitor.tree, "Configure explicit password encoder."); } } }
Source:
<code>public static byte[] buildUsermetadata(RestRequest restRequest) { Map<String, List<String>> args = restRequest.getArgs(); Map<String, List<String>> userMetadataMap = new HashMap<String, List<String>>(); <START> int size = 0; <END> size += 4; for (Map.Entry<String, List<String>> entry : args.entrySet()) { String key = entry.getKey(); if (key.startsWith(Headers.UserMetaData_Header_Prefix)) { userMetadataMap.put(key, args.get(key)); size += 4; size += key.getBytes().length; size += 4; for (String value : entry.getValue()) { size += 4; size += value.getBytes().length; } } } ByteBuffer userMetadata = null; if (size == 4) { userMetadata = ByteBuffer.allocate(0); } else { userMetadata = ByteBuffer.allocate(size); userMetadata.putInt(userMetadataMap.size()); for (Map.Entry<String, List<String>> entry : userMetadataMap.entrySet()) { String key = entry.getKey(); Utils.serializeNullableASCIIEncodedString(userMetadata, key); userMetadata.putInt(entry.getValue().size()); for (String value : entry.getValue()) { Utils.serializeNullableASCIIEncodedString(userMetadata, value); } } } return userMetadata.array(); }</code><technical_language>Is a reason StringBuilder instead of looping twice? (and get bytes in end). for pros cons</technical_language>

Target:
public static byte[] buildUsermetadata(RestRequest restRequest) throws RestServiceException { Map<String, List<String>> args = restRequest.getArgs(); Map<String, String> userMetadataMap = new HashMap<String, String>(); int sizeToAllocate = 0; for (Map.Entry<String, List<String>> entry : args.entrySet()) { String key = entry.getKey(); if (key.startsWith(Headers.UserMetaData_Header_Prefix)) { sizeToAllocate += 4; sizeToAllocate += key.getBytes().length; String value = getHeader(args, key, true); userMetadataMap.put(key, value); sizeToAllocate += 4; sizeToAllocate += value.getBytes().length; } } ByteBuffer userMetadata = null; if (sizeToAllocate == 0) { userMetadata = ByteBuffer.allocate(0); } else { sizeToAllocate += 2; sizeToAllocate += 4; sizeToAllocate += 4; sizeToAllocate += Crc_Size; userMetadata = ByteBuffer.allocate(sizeToAllocate); userMetadata.putShort(UserMetadata_Version_V1); userMetadata.putInt(sizeToAllocate - 6 - Crc_Size); userMetadata.putInt(userMetadataMap.size()); for (Map.Entry<String, String> entry : userMetadataMap.entrySet()) { String key = entry.getKey(); Utils.serializeString(userMetadata, key, StandardCharsets.US_ASCII); Utils.serializeString(userMetadata, entry.getValue(), StandardCharsets.US_ASCII); } Crc32 crc = new Crc32(); crc.update(userMetadata.array(), 0, sizeToAllocate - Crc_Size); userMetadata.putLong(crc.getValue()); } return userMetadata.array(); }
Source:
<code>protected List<LicenseNameWithText> getSortedLicenseNameWithTexts(Collection<LicenseInfoParsingResult> projectLicenseInfoResults) { Set<LicenseNameWithText> licenseNamesWithText = projectLicenseInfoResults.stream() .map(LicenseInfoParsingResult::getLicenseInfo) .filter(Objects::nonNull) .map(LicenseInfo::getLicenseNamesWithTexts) .filter(Objects::nonNull) .reduce(Sets::union) .orElse(Collections.emptySet()); List<LicenseNameWithText> lnwtsList = licenseNamesWithText.stream().filter(licenseNameWithText -> { <START> return !Strings.isNullOrEmpty(licenseNameWithText.getAcknowledgements()) <END> || !Strings.isNullOrEmpty(licenseNameWithText.getLicenseName()) || !Strings.isNullOrEmpty(licenseNameWithText.getLicenseText()); }).collect(Collectors.toList()); lnwtsList.sort(Comparator.comparing(LicenseNameWithText::getLicenseName, String.CASE_INSENSITIVE_ORDER)); return lnwtsList; }</code><technical_language>extract this isLicenseNameWithTextEmpty(). in filterEmptyLicenses()</technical_language>

Target:
protected List<LicenseNameWithText> getSortedLicenseNameWithTexts(Collection<LicenseInfoParsingResult> projectLicenseInfoResults) { Set<LicenseNameWithText> licenseNamesWithText = projectLicenseInfoResults.stream() .map(LicenseInfoParsingResult::getLicenseInfo) .filter(Objects::nonNull) .map(LicenseInfo::getLicenseNamesWithTexts) .filter(Objects::nonNull) .reduce(Sets::union) .orElse(Collections.emptySet()); List<LicenseNameWithText> lnwtsList = licenseNamesWithText.stream().filter(licenseNameWithText -> { return !LicenseNameWithTextUtils.isEmpty(licenseNameWithText); }).collect(Collectors.toList()); lnwtsList.sort(Comparator.comparing(LicenseNameWithText::getLicenseName, String.CASE_INSENSITIVE_ORDER)); return lnwtsList; }
Source:
<code>public void deleteColumn(TableName tableName, byte[] columnName) throws IOException { final String columnNameStr = Bytes.toString(columnName); Modification.Builder modification = Modification.newBuilder().setId(columnNameStr) .setDrop(true); <START> modifyColumn(tableName, columnNameStr, "update", modification); <END> }</code><technical_language>update -> delete</technical_language>

Target:
public void deleteColumn(TableName tableName, byte[] columnName) throws IOException { final String columnNameStr = Bytes.toString(columnName); Modification.Builder modification = Modification.newBuilder().setId(columnNameStr) .setDrop(true); modifyColumn(tableName, columnNameStr, "delete", modification); }
Source:
<code>public String generate(TreeLogger treeLogger, GeneratorContext generatorContext, String typeName) throws UnableToCompleteException { setClassName(typeName + "Bundle"); setTypeOracle(generatorContext.getTypeOracle()); setTreeLogger(treeLogger); setPropertyOracle(generatorContext.getPropertyOracle()); PrintWriter printWriter; printWriter = tryCreatePrintWriter(generatorContext); if (printWriter == null) { return typeName; } ClassSourceFileComposerFactory composer = initComposer(); writePresenterImports(composer, presenters); SourceWriter sourceWriter = composer.createSourceWriter(generatorContext, printWriter); writeStaticFields(sourceWriter, presenters); writeConstructor(sourceWriter, presenters); <START> closeDefinition(treeLogger, sourceWriter); <END> return getPackageName() + "." + getClassName(); }</code><technical_language>Tree logger need passed</technical_language>

Target:
public String generate(TreeLogger treeLogger, GeneratorContext generatorContext, String typeName) throws UnableToCompleteException { setClassName(typeName + SUFFIX); setTypeOracle(generatorContext.getTypeOracle()); setTreeLogger(treeLogger); setPropertyOracle(generatorContext.getPropertyOracle()); PrintWriter printWriter; printWriter = tryCreatePrintWriter(generatorContext); if (printWriter == null) { return typeName; } ClassSourceFileComposerFactory composer = initComposer(); writePresenterImports(composer, presenters); SourceWriter sourceWriter = composer.createSourceWriter(generatorContext, printWriter); writeStaticFields(sourceWriter, presenters); writeConstructor(sourceWriter, presenters); closeDefinition(sourceWriter); return getPackageName() + "." + getClassName(); }
Source:
<code>protected void finishModelStage(final OperationContext context, final ModelNode operation, String attributeName, ModelNode newValue, ModelNode oldValue, final Resource model) throws OperationFailedException { if (newValue.isDefined()) { <START> Set<String> subsystems = context.readResourceFromRoot(EMPTY_ADDRESS).getChildrenNames("subsystem"); <END> List<String> exposedSubsystems = new LinkedList<>(); for (ModelNode n: newValue.asList()) { exposedSubsystems.add(n.asString()); } validExposedSubsystems(subsystems, exposedSubsystems); } super.finishModelStage(context, operation, attributeName, newValue, oldValue, model); }</code><technical_language>read subsystem children avoid read model recursively. I suggest context.readResourceFromRoot(PathAddress.pathAddress(PathElement.pathElement(SUBSYSTEM)), false).getChildrenNames(SUBSYSTEM); instead</technical_language>

Target:
protected void finishModelStage(final OperationContext context, final ModelNode operation, String attributeName, ModelNode newValue, ModelNode oldValue, final Resource model) throws OperationFailedException { if (newValue.isDefined()) { Set<String> subsystems = context.readResourceFromRoot(PathAddress.pathAddress(PathElement.pathElement(SUBSYSTEM)), false).getChildrenNames(SUBSYSTEM); List<String> exposedSubsystems = new LinkedList<>(); for (ModelNode n: newValue.asList()) { exposedSubsystems.add(n.asString()); } validExposedSubsystems(subsystems, exposedSubsystems); } super.finishModelStage(context, operation, attributeName, newValue, oldValue, model); }
Source:
<code>public void byteSizedTieredCache() { CacheConfiguration<Long, String> usesConfiguredInCacheConfig = CacheConfigurationBuilder.newCacheConfigurationBuilder(Long.class, String.class) .withResourcePools(ResourcePoolsBuilder.newResourcePoolsBuilder() .heap(10, MemoryUnit.KB) .offheap(10, MemoryUnit.MB) .build()) <START> .withSizeOfMaxTraversals(1000) <END> .withSizeOfMaxSize(1000) .build(); CacheConfiguration<Long, String> usesDefaultSizeOfEngineConfig = CacheConfigurationBuilder.newCacheConfigurationBuilder(Long.class, String.class) .withResourcePools(ResourcePoolsBuilder.newResourcePoolsBuilder() .heap(10, MemoryUnit.KB) .offheap(10, MemoryUnit.MB) .build()) .build(); CacheManager cacheManager = CacheManagerBuilder.newCacheManagerBuilder() .withDefaultSizeOfMaxSize(500) .withDefaultSizeOfMaxTraversals(2000) .withCache("usesConfiguredInCache", usesConfiguredInCacheConfig) .withCache("usesDefaultSizeOfEngine", usesDefaultSizeOfEngineConfig) .build(true); Cache<Long, String> usesConfiguredInCache = cacheManager.getCache("usesConfiguredInCache", Long.class, String.class); usesConfiguredInCache.put(1L, "one"); assertThat(usesConfiguredInCache.get(1L), equalTo("one")); Cache<Long, String> usesDefaultSizeOfEngine = cacheManager.getCache("usesDefaultSizeOfEngine", Long.class, String.class); usesDefaultSizeOfEngine.put(1L, "one"); assertThat(usesDefaultSizeOfEngine.get(1L), equalTo("one")); cacheManager.close(); }</code><technical_language>conversation @chrisdennis @AbfrmBlr: new DefaultSizeOfEngineConfiguration(long size, MemoryUnit unit, long objectGraphSize)</technical_language>

Target:
public void byteSizedTieredCache() { CacheConfiguration<Long, String> usesConfiguredInCacheConfig = CacheConfigurationBuilder.newCacheConfigurationBuilder(Long.class, String.class) .withResourcePools(ResourcePoolsBuilder.newResourcePoolsBuilder() .heap(10, MemoryUnit.KB) .offheap(10, MemoryUnit.MB) .build()) .withSizeOfMaxObjectGraph(1000) .withSizeOfMaxObjectSize(1000, MemoryUnit.B) .build(); CacheConfiguration<Long, String> usesDefaultSizeOfEngineConfig = CacheConfigurationBuilder.newCacheConfigurationBuilder(Long.class, String.class) .withResourcePools(ResourcePoolsBuilder.newResourcePoolsBuilder() .heap(10, MemoryUnit.KB) .offheap(10, MemoryUnit.MB) .build()) .build(); CacheManager cacheManager = CacheManagerBuilder.newCacheManagerBuilder() .withDefaultSizeOfMaxObjectSize(500, MemoryUnit.B) .withDefaultSizeOfMaxObjectGraph(2000) .withCache("usesConfiguredInCache", usesConfiguredInCacheConfig) .withCache("usesDefaultSizeOfEngine", usesDefaultSizeOfEngineConfig) .build(true); Cache<Long, String> usesConfiguredInCache = cacheManager.getCache("usesConfiguredInCache", Long.class, String.class); usesConfiguredInCache.put(1L, "one"); assertThat(usesConfiguredInCache.get(1L), equalTo("one")); Cache<Long, String> usesDefaultSizeOfEngine = cacheManager.getCache("usesDefaultSizeOfEngine", Long.class, String.class); usesDefaultSizeOfEngine.put(1L, "one"); assertThat(usesDefaultSizeOfEngine.get(1L), equalTo("one")); cacheManager.close(); }
Source:
<code>public boolean isSameDestinationAs(@Nullable Object obj) { if (this == obj) return true; if (!(obj instanceof RouteInfo)) return false; RouteInfo target = (RouteInfo) obj; if (mDestination <START> == target.getDestination()) <END> { return true; } return false; }</code><technical_language>This is incorrect compares object pointer, contents of object. need equals(), or, if null, Objects.equals(). I destination null, say: ... RouteInfo target = (RouteInfo) obj; return mDestination.equals(target.mDestination);</technical_language>

Target:
public boolean isSameDestinationAs(@Nullable Object obj) { if (this == obj) return true; if (!(obj instanceof RouteInfo)) return false; RouteInfo target = (RouteInfo) obj; if (Objects.equals(mDestination, target.getDestination())) { return true; } return false; }
Source:
<code>public GroupRest getBitstreamReadGroup(@Nullable HttpServletRequest request, UUID collectionId, @Nullable Pageable optionalPageable, Projection projection) { try { Context context = obtainContext(); Collection collection = collectionService.find(context, collectionId); if (collection == null) { throw new ResourceNotFoundException("No such collection: " + collectionId); } List<Group> bitstreamGroups = authorizeService .getAuthorizedGroups(context, collection, Constants.DEFAULT_BITSTREAM_READ); Group bitstreamReadGroup = bitstreamGroups.get(0); <START> if (!authorizeService.isAdmin(context) && !authorizeService.authorizeActionBoolean(context, collection, <END> Constants.ADMIN, true)) { throw new AccessDeniedException( "The current user was not allowed to retrieve the bitstreamReadGroup for" + " collection: " + collectionId); } if (bitstreamReadGroup == null) { return null; } return converter.toRest(bitstreamReadGroup, projection); } catch (SQLException e) { throw new RuntimeException(e); } }</code><technical_language>This if clause moved up. reason load DEFAULT_BITSTREAM_READ group if access it</technical_language>

Target:
public GroupRest getBitstreamReadGroup(@Nullable HttpServletRequest request, UUID collectionId, @Nullable Pageable optionalPageable, Projection projection) { try { Context context = obtainContext(); Collection collection = collectionService.find(context, collectionId); if (collection == null) { throw new ResourceNotFoundException("No such collection: " + collectionId); } try { AuthorizeUtil.authorizeManageDefaultReadGroup(context, collection); } catch (AuthorizeException e) { throw new AccessDeniedException("The current user was not allowed to retrieve the " + "bitstreamReadGroup for collection: " + collectionId); } List<Group> bitstreamGroups = authorizeService .getAuthorizedGroups(context, collection, Constants.DEFAULT_BITSTREAM_READ); Group bitstreamReadGroup = bitstreamGroups.get(0); if (bitstreamReadGroup == null) { return null; } return converter.toRest(bitstreamReadGroup, projection); } catch (SQLException e) { throw new RuntimeException(e); } }
Source:
<code>public void shouldNotDownloadMusicWhenDoesNotExist() { when(dao.load(music)).thenReturn(music); when(musics.getFile(music)).thenReturn(new File("/tmp/uploads/Music_" + music.getId() + ".mp3")); try { <START> controller.download(music); <END> } catch (FileNotFoundException e) { verify(musics).getFile(music); } }</code><technical_language>If want exception thrown, Assert.fail("should throw exception"); this line</technical_language>

Target:
public void shouldNotDownloadMusicWhenDoesNotExist() { when(dao.load(music)).thenReturn(music); when(musics.getFile(music)).thenReturn(new File("/tmp/uploads/Music_" + music.getId() + ".mp3")); try { controller.download(music); fail("Should throw an exception."); } catch (FileNotFoundException e) { verify(musics).getFile(music); } }
Source:
<code>public void BotHod() { int size = tiles.size(); int mode = (int) Math.sqrt(size); Random rand = new Random(); if (ModeBotOrNot.isBot() == 1) { int l = rand.nextInt(mode) + 0; int z = rand.nextInt(mode) + 0; while (massiveTiles[l][z].isOpen()) { l = rand.nextInt(mode) + 0; z = rand.nextInt(mode) + 0; } firstselected = massiveTiles[l][z]; firstselected.open(() -> { }); l = rand.nextInt(mode) + 0; z = rand.nextInt(mode) + 0; while (massiveTiles[l][z].isOpen() || firstselected.equals(massiveTiles[l][z])) { l = rand.nextInt(mode) + 0; z = rand.nextInt(mode) + 0; } secondselected = massiveTiles[l][z]; secondselected.openBot(() -> { }); if (!firstselected.text.getText().equals(secondselected.text.getText())) { firstselected.waitBeforeClose(); secondselected.waitBeforeClose(); } else { firstselected.setOpen(); secondselected.setOpen(); } ModeBotOrNot.setBot(0); firstselected = null; secondselected = null; } <START> <END> }</code><technical_language>" "</technical_language>

Target:
public void BotHod() { int size = tiles.size(); int mode = (int) Math.sqrt(size); Random rand = new Random(); if (BotMode.getBotMode() == 1) { int l = rand.nextInt(mode) + 0; int z = rand.nextInt(mode) + 0; while (massiveTiles[l][z].isOpen()) { l = rand.nextInt(mode) + 0; z = rand.nextInt(mode) + 0; } firstselected = massiveTiles[l][z]; firstselected.open(() -> { }); l = rand.nextInt(mode) + 0; z = rand.nextInt(mode) + 0; while (massiveTiles[l][z].isOpen() || firstselected.equals(massiveTiles[l][z])) { l = rand.nextInt(mode) + 0; z = rand.nextInt(mode) + 0; } secondselected = massiveTiles[l][z]; secondselected.openBot(() -> { }); if (!firstselected.text.getText().equals(secondselected.text.getText())) { firstselected.waitBeforeClose(); secondselected.waitBeforeClose(); } else { firstselected.setOpen(); secondselected.setOpen(); } BotMode.setBotMode(0); firstselected = null; secondselected = null; } }
Source:
<code>private Long convertListOfStringToTime(List<String> serverTimeInformation) { <START> return convertListOfStringToMicros(serverTimeInformation) / 1000; <END> }</code><technical_language>TimeUnit constants well</technical_language>

Target:
private Long convertListOfStringToTime(List<String> serverTimeInformation) { return TimeUnit.MICROSECONDS.toMillis(convertListOfStringToMicros(serverTimeInformation)); }
Source:
<code>public Map<String, String> getCustomValues() { Map<String, String> map = new HashMap<>(); <START> map.put(GlusterConstants.VOLUME_SNAPSHOT_NAME, getParameters().getSnapshotName()); <END> return map; }</code><technical_language>addCustomValue(GlusterConstants.VOLUME_SNAPSHOT_NAME, getParameters().getSnapshotName()); return super.getCustomValues();</technical_language>

Target:
public Map<String, String> getCustomValues() { addCustomValue(GlusterConstants.VOLUME_SNAPSHOT_NAME, getParameters().getSnapshotName()); return super.getCustomValues(); }
Source:
<code>private SystemStreamMetadata constructSystemStreamMetadata( String streamName, Map<SystemStreamPartition, List<IncomingMessageEnvelope>> sspToMessagesForSystem) { Map<Partition, SystemStreamMetadata.SystemStreamPartitionMetadata> partitionMetadata = sspToMessagesForSystem .entrySet() .stream() .collect(Collectors.toMap(entry -> entry.getKey().getPartition(), entry -> { List<IncomingMessageEnvelope> messages = entry.getValue(); <START> Integer oldestOffset = null; Integer newestOffset = null; int upcomingOffset = 0; <END> if (!messages.isEmpty() && !messages.get(messages.size() - 1).isEndOfStream()) { oldestOffset = 0; newestOffset = messages.size() - 1; upcomingOffset = messages.size(); } else if (messages.size() > 1 && messages.get(messages.size() - 1).isEndOfStream()) { oldestOffset = 0; newestOffset = messages.size() - 2; upcomingOffset = messages.size() - 1; } return new SystemStreamMetadata.SystemStreamPartitionMetadata( oldestOffset == null ? null : oldestOffset.toString(), newestOffset == null ? null : newestOffset.toString(), Integer.toString(upcomingOffset)); })); return new SystemStreamMetadata(streamName, partitionMetadata); }</code><technical_language>simplify this default original values 0, messages.size() - 1, messages.size modify in case of message end of stream</technical_language>

Target:
private SystemStreamMetadata constructSystemStreamMetadata( String streamName, Map<SystemStreamPartition, List<IncomingMessageEnvelope>> sspToMessagesForSystem) { Map<Partition, SystemStreamMetadata.SystemStreamPartitionMetadata> partitionMetadata = sspToMessagesForSystem .entrySet() .stream() .collect(Collectors.toMap(entry -> entry.getKey().getPartition(), entry -> { List<IncomingMessageEnvelope> messages = entry.getValue(); Integer oldestOffset; Integer newestOffset; int upcomingOffset; if (messages.isEmpty()) { oldestOffset = null; newestOffset = null; upcomingOffset = 0; } else if (messages.get(messages.size() - 1).isEndOfStream()) { if (messages.size() > 1) { oldestOffset = 0; newestOffset = messages.size() - 2; upcomingOffset = messages.size() - 1; } else { oldestOffset = null; newestOffset = null; upcomingOffset = 0; } } else { oldestOffset = 0; newestOffset = messages.size() - 1; upcomingOffset = messages.size(); } return new SystemStreamMetadata.SystemStreamPartitionMetadata( oldestOffset == null ? null : oldestOffset.toString(), newestOffset == null ? null : newestOffset.toString(), Integer.toString(upcomingOffset)); })); return new SystemStreamMetadata(streamName, partitionMetadata); }
Source:
<code>private List<CertificationResultTestProcedureEntity> getTestProcedureEntitiesForListing(Long listingId) { String hql = "SELECT tp " + "FROM CertificationResultTestProcedureEntity tp " + "LEFT OUTER JOIN FETCH tp.testProcedure " + "WHERE (NOT tp.deleted = true) " + "AND tp.certificationResultId IN " + "(SELECT cr.id " + "FROM CertificationResultEntity cr " <START> + "WHERE cr.certifiedProductId = :listingId)"; <END> return entityManager.createQuery(hql, CertificationResultTestProcedureEntity.class) .setParameter("listingId", listingId) .getResultList(); }</code><technical_language>Do need "and cr.deleted = false" type of statement part of "IN" clause? I thinking it</technical_language>

Target:
private List<CertificationResultTestProcedureEntity> getTestProcedureEntitiesForListing(Long listingId) { String hql = "SELECT tp " + "FROM CertificationResultTestProcedureEntity tp " + "LEFT OUTER JOIN FETCH tp.testProcedure " + "WHERE (NOT tp.deleted = true) " + "AND tp.certificationResultId IN " + "(SELECT cr.id " + "FROM CertificationResultEntity cr " + "WHERE cr.certifiedProductId = :listingId " + "AND cr.deleted = false)"; return entityManager.createQuery(hql, CertificationResultTestProcedureEntity.class) .setParameter("listingId", listingId) .getResultList(); }
Source:
<code>private static HttpRequest convertLanguageParsingRequestToHttpRequest(LanguageParsingRequest languageParsingRequest) throws JsonProcessingException { ObjectMapper objectMapper = new ObjectMapper(); String requestBody = objectMapper.writeValueAsString(languageParsingRequest); HttpRequest.BodyPublisher bodyPublisher = HttpRequest.BodyPublishers.ofString(requestBody); <START> return HttpRequest.newBuilder().uri(URI.create("http://localhost:3000/parse")).POST(bodyPublisher).build(); <END> }</code><technical_language>localhost:3000 from</technical_language>

Target:
private static HttpRequest convertLanguageParsingRequestToHttpRequest(LanguageParsingRequest languageParsingRequest) throws JsonProcessingException { ObjectMapper objectMapper = new ObjectMapper(); String requestBody = objectMapper.writeValueAsString(languageParsingRequest); HttpRequest.BodyPublisher bodyPublisher = HttpRequest.BodyPublishers.ofString(requestBody); return HttpRequest.newBuilder().uri(URI.create(LANGUAGE_PARSER_ENDPOINT)).POST(bodyPublisher).build(); }
Source:
<code>public TransferResult<CFValue, CFStore> visitMethodInvocation( final MethodInvocationNode node, final TransferInput<CFValue, CFStore> input) { TransferResult<CFValue, CFStore> result = super.visitMethodInvocation(node, input); String methodName = node.getTarget().getMethod().getSimpleName().toString(); methodName = atypeFactory.adjustMethodNameUsingValueChecker(methodName, node.getTree()); Node receiver = node.getTarget().getReceiver(); <START> if (!"<init>".equals(methodName) && receiver != null) { <END> accumulate(receiver, result, methodName); } return result; }</code><technical_language>This test methodName late. For efficiency, occur assignment reassignment. More importantly, methodName "<init>"? If method is <init>, node a ConstructorInvocationNode? Also, reassignment occur receiver != null test</technical_language>

Target:
public TransferResult<CFValue, CFStore> visitMethodInvocation( final MethodInvocationNode node, final TransferInput<CFValue, CFStore> input) { TransferResult<CFValue, CFStore> result = super.visitMethodInvocation(node, input); Node receiver = node.getTarget().getReceiver(); if (receiver != null) { String methodName = node.getTarget().getMethod().getSimpleName().toString(); methodName = atypeFactory.adjustMethodNameUsingValueChecker(methodName, node.getTree()); accumulate(receiver, result, methodName); } return result; }
Source:
<code>public boolean requireReauthentication(UserSessionModel userSession, AuthenticationSessionModel authSession) { String requireReauthentication = authSession.getAuthNote(SamlProtocol.SAML_LOGIN_REQUEST_FORCEAUTHN); <START> if (requireReauthentication == null || requireReauthentication.isEmpty()) <END> return false; return requireReauthentication.equals(SamlProtocol.SAML_FORCEAUTHN_REQUIREMENT); }</code><technical_language>This rest of method replaced with: suggestion return Objects.equals(SamlProtocol.SAML_FORCEAUTHN_REQUIREMENT, requireReauthentication);</technical_language>

Target:
public boolean requireReauthentication(UserSessionModel userSession, AuthenticationSessionModel authSession) { String requireReauthentication = authSession.getAuthNote(SamlProtocol.SAML_LOGIN_REQUEST_FORCEAUTHN); return Objects.equals(SamlProtocol.SAML_FORCEAUTHN_REQUIREMENT, requireReauthentication); }
Source:
<code><START> public static String sha1(String value) { <END> return Hashing.sha1().hashString(value, Charsets.UTF_8).toString().substring(0, 7); }</code><technical_language>Please in method name is shorter a regular SHA-1 hash</technical_language>

Target:
public static String sha1(String value) { return Hashing.sha1().hashString(value, Charsets.UTF_8).toString(); }
Source:
<code>public void close() { if (sequenceReader!=null) { try { sequenceReader.close(); } catch (IOException e) { log.error("error occurred when closing sequence reader", e); <START> } <END> } }</code><technical_language>eating exception here</technical_language>

Target:
public void close() throws IOException { if (sequenceReader != null) { sequenceReader.close(); } }
Source:
<code>private void scheduleImmediateDelivery() { cancelDelayedDelivery(); while (state == State.RUNNING) { DeliveryAttempt previous = immediateDelivery.get(); if (previous != null && !previous.isDone()) <START> previous.cancel(); <END> DeliveryAttempt current = new DeliveryAttempt(); if (immediateDelivery.compareAndSet(previous, current)) { current.executeNow(); return; } } }</code><technical_language>deliverEvents handle interruptions, this is essentially a no-op if previous is executing</technical_language>

Target:
private void scheduleImmediateDelivery() { cancelDelayedDelivery(); while (state == State.RUNNING) { DeliveryAttempt previous = immediateDelivery.get(); if (previous != null) previous.cancel(); DeliveryAttempt current = new DeliveryAttempt(); if (immediateDelivery.compareAndSet(previous, current)) { current.executeNow(); return; } } }
Source:
<code>private SortedSet<LocalizedMessage> getFilteredMessages(String fileName, FileContents fileContents) { final SortedSet<LocalizedMessage> result = new TreeSet<>(messages); for (final LocalizedMessage element : messages) { <START> final TreeWalkerAuditEvent event = new TreeWalkerAuditEvent(fileContents, fileName, <END> element); for (final TreeWalkerFilter filter : filters) { if (!filter.accept(event)) { result.remove(element); break; } } } return result; }</code><technical_language>a bit weird formatting. Please drop line =</technical_language>

Target:
private SortedSet<LocalizedMessage> getFilteredMessages(String fileName, FileContents fileContents) { final SortedSet<LocalizedMessage> result = new TreeSet<>(messages); for (LocalizedMessage element : messages) { final TreeWalkerAuditEvent event = new TreeWalkerAuditEvent(fileContents, fileName, element); for (TreeWalkerFilter filter : filters) { if (!filter.accept(event)) { result.remove(element); break; } } } return result; }
Source:
<code>public static boolean allowReplacement(String currReplState, String replacementReplState){ if ((currReplState == null) || (currReplState.isEmpty())) { return true; } if ((replacementReplState == null) || (replacementReplState.isEmpty())) { return false; } long currReplStateLong = Long.parseLong(currReplState.replaceAll("\\D","")); long replacementReplStateLong = Long.parseLong(replacementReplState.replaceAll("\\D","")); if ((currReplStateLong != 0) || (replacementReplStateLong != 0)){ return ((currReplStateLong - replacementReplStateLong) < 0); } <START> return (collator.compare(currReplState.toLowerCase(), replacementReplState.toLowerCase()) < 0); <END> }</code><technical_language>shouldnt this a similar logic EventDumpDirComparator</technical_language>

Target:
public static boolean allowReplacement(String currReplState, String replacementReplState){ if ((currReplState == null) || (currReplState.isEmpty())) { return true; } if ((replacementReplState == null) || (replacementReplState.isEmpty())) { return false; } long currReplStateLong = Long.parseLong(currReplState.replaceAll("\\D","")); long replacementReplStateLong = Long.parseLong(replacementReplState.replaceAll("\\D","")); return ((currReplStateLong - replacementReplStateLong) < 0); }
Source:
<code>public void destroy(String name) throws CachePersistenceException { while (true) { if (entity == null) { try { entity = entityFactory.retrieve(entityIdentifier, serviceConfiguration.getServerConfiguration()); } catch (EntityNotFoundException e) { break; } catch (TimeoutException e) { throw new CachePersistenceException("Could not connect to the cluster tier manager '" + entityIdentifier + "'; retrieve operation timed out", e); } catch (DestroyInProgressException e) { <START> try { <END> silentDestroy(); break; } catch (ConnectionClosedException | ConnectionShutdownException e1) { reconnect(); } } catch (ConnectionClosedException | ConnectionShutdownException e) { reconnect(); } } try { if (entity != null) { entityFactory.destroyClusteredStoreEntity(entityIdentifier, name); break; } } catch (EntityNotFoundException e) { LOGGER.debug("Destruction of cluster tier failed as it does not exist", name); break; } catch (ConnectionClosedException | ConnectionShutdownException e) { handleConnectionClosedException(); } } }</code><technical_language>try { silentDestroy(); // left do break; } catch (ConnectionClosedException | ConnectionShutdownException e1) { reconnect(); } This block of code is repeating multiple places. if extract out a method reuse</technical_language>

Target:
public void destroy(String name) throws CachePersistenceException { while (true) { if (entity == null) { try { entity = entityFactory.retrieve(entityIdentifier, serviceConfiguration.getServerConfiguration()); } catch (EntityNotFoundException e) { break; } catch (TimeoutException e) { throw new CachePersistenceException("Could not connect to the cluster tier manager '" + entityIdentifier + "'; retrieve operation timed out", e); } catch (DestroyInProgressException e) { if (silentDestroyUtil()) { break; } } catch (ConnectionClosedException | ConnectionShutdownException e) { reconnect(); } } try { if (entity != null) { entityFactory.destroyClusteredStoreEntity(entityIdentifier, name); break; } } catch (EntityNotFoundException e) { LOGGER.debug("Destruction of cluster tier failed as it does not exist", name); break; } catch (ConnectionClosedException | ConnectionShutdownException e) { handleConnectionClosedException(); } } }
Source:
<code>protected void save() { final Command continueSaveOnceValid = () -> super.save(); sessionValidateCommand .execute(new ClientSessionCommand.Callback<Collection<DiagramElementViolation<RuleViolation>>>() { @Override public void onSuccess() { if (hasUnsavedChanges()) { continueSaveOnceValid.execute(); } else { errorPopupPresenter.showMessage("You have no unsaved changes."); } } @Override public void onError(final Collection<DiagramElementViolation<RuleViolation>> violations) { final Violation.Type maxSeverity = ValidationUtils.getMaxSeverity(violations); if (maxSeverity.equals(Violation.Type.ERROR)) { onValidationFailed(violations); } else { if (hasUnsavedChanges()) { continueSaveOnceValid.execute(); } else { <START> errorPopupPresenter.showMessage("You have no unsaved changes."); <END> } } } }); }</code><technical_language>I duplicated localized literal. @romartin do handle for now</technical_language>

Target:
protected void save() { final Command continueSaveOnceValid = () -> super.save(); sessionValidateCommand .execute(new ClientSessionCommand.Callback<Collection<DiagramElementViolation<RuleViolation>>>() { @Override public void onSuccess() { continueSaveOnceValid.execute(); } @Override public void onError(final Collection<DiagramElementViolation<RuleViolation>> violations) { final Violation.Type maxSeverity = ValidationUtils.getMaxSeverity(violations); if (maxSeverity.equals(Violation.Type.ERROR)) { onValidationFailed(violations); } else { continueSaveOnceValid.execute(); } } }); }
Source:
<code>public void addQueueAndAssignPermission(String queueName, QueueRolePermission[] queueRolePermissions) throws QueueManagerException { String tenantBasedQueueName = Utils.getTenantBasedQueueName(queueName); if (!QueueManagementBeans.queueExists(tenantBasedQueueName)) { createQueue(tenantBasedQueueName); updatePermission(tenantBasedQueueName, queueRolePermissions); } else { throw new QueueManagerException("Queue with the name: " + queueName + " already exists!", <START> new RuntimeException("Queue with the name: " + queueName + " already exists!")); <END> } }</code><technical_language>this funky! re-visit</technical_language>

Target:
public void addQueueAndAssignPermission(String queueName, QueueRolePermission[] queueRolePermissions) throws QueueManagerException { String tenantBasedQueueName = Utils.getTenantBasedQueueName(queueName); if (!QueueManagementBeans.queueExists(tenantBasedQueueName)) { createQueue(tenantBasedQueueName); updatePermission(tenantBasedQueueName, queueRolePermissions); } else { throw new QueueManagerException("Queue with the name: " + queueName + " already exists!"); } }
Source:
<code>Connection start() { log.info("Starting PubSub connection"); ProjectSubscriptionName subscriptionName = ProjectSubscriptionName .of(projectId, subscriptionId); FlowControlSettings flowControlSettings = FlowControlSettings.newBuilder() .setMaxOutstandingElementCount(maxOutstandingElementCount) .setMaxOutstandingRequestBytes(maxOutstandingRequestBytes) .build(); ExecutorProvider executorProvider = InstantiatingExecutorProvider.newBuilder().setExecutorThreadCount(threads).build(); log.info("Subscribing to {}", subscriptionName); final Receiver receiver = new Receiver(consumer, reporter, errors, consumed); subscriber = Subscriber .newBuilder(subscriptionName, receiver) .setFlowControlSettings(flowControlSettings) .setParallelPullCount(threads) .setExecutorProvider(executorProvider) .setChannelProvider(channelProvider) .setCredentialsProvider(credentialsProvider) .build(); subscriber.addListener( new Subscriber.Listener() { @Override public void failed(Subscriber.State from, Throwable failure) { <START> log.error( <END> "An error on subscriber happened (from state: " + from.name() + ")", failure); }}, MoreExecutors.directExecutor()); subscriber.startAsync().awaitRunning(); log.info("PubSub connection started"); return this; }</code><technical_language>if a handler crash? JVM stay stop anything? Generally, in favor of crashing hard recover letting process supervisor restart it</technical_language>

Target:
Connection start() { log.info("Starting PubSub connection"); ProjectSubscriptionName subscriptionName = ProjectSubscriptionName .of(projectId, subscriptionId); FlowControlSettings flowControlSettings = FlowControlSettings.newBuilder() .setMaxOutstandingElementCount(maxOutstandingElementCount) .setMaxOutstandingRequestBytes(maxOutstandingRequestBytes) .build(); ExecutorProvider executorProvider = InstantiatingExecutorProvider.newBuilder().setExecutorThreadCount(threads).build(); log.info("Subscribing to {}", subscriptionName); final Receiver receiver = new Receiver(consumer, reporter, errors, consumed); subscriber = Subscriber .newBuilder(subscriptionName, receiver) .setFlowControlSettings(flowControlSettings) .setParallelPullCount(threads) .setExecutorProvider(executorProvider) .setChannelProvider(channelProvider) .setCredentialsProvider(credentialsProvider) .build(); subscriber.addListener( new Subscriber.Listener() { @Override public void failed(Subscriber.State from, Throwable failure) { log.error( "An error on subscriber happened (from state: " + from.name() + ")", failure); System.exit(1); } }, MoreExecutors.directExecutor()); subscriber.startAsync().awaitRunning(); log.info("PubSub connection started"); return this; }
Source:
<code>public void handleMessage(Message msg) { switch (msg.arg2) { case COMMAND_START_REPLICATION: startReplications(); notifyTestOperationComplete(); break; case COMMAND_STOP_REPLICATION: stopReplications(); notifyTestOperationComplete(); break; } Intent intent = msg.getData().getParcelable(EXTRA_INTENT); <START> WakefulBroadcastReceiver.completeWakefulIntent(intent); <END> }</code><technical_language>I if this in a finally other parts of method in a try ensure WakeLock is released if is some kind of RuntimeException of starting stopping code</technical_language>

Target:
public void handleMessage(Message msg) { try { switch (msg.arg2) { case COMMAND_START_REPLICATION: startReplications(); notifyTestOperationComplete(); break; case COMMAND_STOP_REPLICATION: stopReplications(); notifyTestOperationComplete(); break; } } finally { Intent intent = msg.getData().getParcelable(EXTRA_INTENT); WakefulBroadcastReceiver.completeWakefulIntent(intent); } }
Source:
<code>public AnalyzedAlterTableDropCheckConstraint analyze(Table<?> table, String name, CoordinatorTxnCtx txnCtx) { DocTableInfo tableInfo = (DocTableInfo) schemas.resolveTableInfo( table.getName(), Operation.ALTER, txnCtx.sessionContext().user(), txnCtx.sessionContext().searchPath()); List<CheckConstraint<Symbol>> checkConstraints = tableInfo.checkConstraints(); <START> for (int i = 0; i < checkConstraints.size(); i++) { <END> if (name.equals(checkConstraints.get(i).name())) { return new AnalyzedAlterTableDropCheckConstraint(tableInfo, name); } } throw new IllegalArgumentException(String.format( Locale.ENGLISH, "Cannot find a CHECK CONSTRAINT named [%s], available constraints are: %s", name, Lists2.map(checkConstraints, CheckConstraint::name))); }</code><technical_language>minor (maybe personal preference): done simple for(var checkContraint : checkConstraints)</technical_language>

Target:
public AnalyzedAlterTableDropCheckConstraint analyze(Table<?> table, String name, CoordinatorTxnCtx txnCtx) { DocTableInfo tableInfo = (DocTableInfo) schemas.resolveTableInfo( table.getName(), Operation.ALTER, txnCtx.sessionContext().user(), txnCtx.sessionContext().searchPath()); List<CheckConstraint<Symbol>> checkConstraints = tableInfo.checkConstraints(); for (var checkConstraint : checkConstraints) { if (name.equals(checkConstraint.name())) { return new AnalyzedAlterTableDropCheckConstraint(tableInfo, name); } } throw new IllegalArgumentException(String.format( Locale.ENGLISH, "Cannot find a CHECK CONSTRAINT named [%s], available constraints are: %s", name, Lists2.map(checkConstraints, CheckConstraint::name))); }
Source:
<code>protected void computeLocations() { boolean hasLocations = !Strings.isBlank(locations); if (app != null) { if (hasLocations && isYamlApp()) { <START> log.warn("YAML app combined with command line locations; command line locations will take precedence"); <END> } else if (!hasLocations && isYamlApp()) { log.info("No locations supplied; defaulting to locations defined in YAML (if any)"); } else if (!hasLocations) { log.info("No locations supplied; starting with no locations"); } } else if (hasLocations) { log.error("Locations specified without any applications; ignoring locations"); } }</code><technical_language>log.info. yaml define a location, warn</technical_language>

Target:
protected void computeLocations() { boolean hasLocations = !Strings.isBlank(locations); if (app != null) { if (hasLocations && isYamlApp()) { log.info("YAML app combined with command line locations; YAML locations will take precedence"); } else if (!hasLocations && isYamlApp()) { log.info("No locations supplied; defaulting to locations defined in YAML (if any)"); } else if (!hasLocations) { log.info("No locations supplied; starting with no locations"); } } else if (hasLocations) { log.error("Locations specified without any applications; ignoring locations"); } }
Source:
<code>public void removeTube() { if (removeTubeButton.getAttribute("disabled") == null) { removeTubeButton.click(); } else { <START> log.error("* * * * * * * * * Error: removeTubeButton is not clickable * * * * * * * * * "); <END> } confirmAndWaitForRefresh(); }</code><technical_language>Is a reason prevent this throwing exception? error in page test logic, right</technical_language>

Target:
public void removeTube() { if (removeTubeButton.isEnabled()) { removeTubeButton.click(); } else { throw new IllegalStateException("Error: removeTubeButton is not clickable"); } confirmAndWaitForRefresh(); }
Source:
<code>public void onLoadFinished(Loader<Cursor> cursorLoaderLoader, Cursor cursorLoader) { adapter.swapCursor(cursorLoader); boolean visible = recentSearchesList.getCount() > 0; deleteButton.setVisibility(visible ? View.VISIBLE : View.INVISIBLE); <START> if (!isAdded()) { <END> return; } getActivity().supportInvalidateOptionsMenu(); }</code><technical_language>move this isAdded() check top of function? I recall prevent a crash (that reproduced), err side of caution</technical_language>

Target:
public void onLoadFinished(Loader<Cursor> cursorLoaderLoader, Cursor cursorLoader) { if (!isAdded()) { return; } adapter.swapCursor(cursorLoader); boolean visible = recentSearchesList.getCount() > 0; deleteButton.setVisibility(visible ? View.VISIBLE : View.INVISIBLE); getActivity().supportInvalidateOptionsMenu(); }
Source:
<code>public final String getErrorMessageTitle() { try { return errorMessage.split("[\\r\\n]+")[0]; <START> } catch(ArrayIndexOutOfBoundsException e) { <END> return ""; } }</code><technical_language>this - this is more cure for result I prefer code prevent this situation</technical_language>

Target:
public final String getErrorMessageTitle() { return errorMessage.split("[\\r?\\n]+", -1)[0]; }
Source:
<code>private void process() { byte[] frame = Arrays.copyOfRange(frameBytes, 4, frameBytes.length); TTransport input = new TMemoryInputTransport(frame); <START> FBoundedMemoryBuffer output = new FBoundedMemoryBuffer(TNatsServiceTransport.NATS_MAX_MESSAGE_SIZE); <END> try { processor.process(inputProtoFactory.getProtocol(input), outputProtoFactory.getProtocol(output)); } catch (TException e) { LOGGER.warning("error processing frame: " + e.getMessage()); return; } if (output.length() == 0) { return; } byte[] response = new byte[output.length() + 4]; ProtocolUtils.writeInt(output.length(), response, 0); System.arraycopy(output.getArray(), 0, response, 4, output.length()); try { conn.publish(reply, response); } catch (IOException e) { LOGGER.warning("failed to send response: " + e.getMessage()); } }</code><technical_language>this TNatsServiceTransport.NATS_MAX_MESSAGE_SIZE write frame size end</technical_language>

Target:
private void process() { byte[] frame = Arrays.copyOfRange(frameBytes, 4, frameBytes.length); TTransport input = new TMemoryInputTransport(frame); FBoundedMemoryBuffer output = new FBoundedMemoryBuffer(TNatsServiceTransport.NATS_MAX_MESSAGE_SIZE - 4); try { processor.process(inputProtoFactory.getProtocol(input), outputProtoFactory.getProtocol(output)); } catch (TException e) { LOGGER.warning("error processing frame: " + e.getMessage()); return; } if (output.length() == 0) { return; } byte[] response = new byte[output.length() + 4]; ProtocolUtils.writeInt(output.length(), response, 0); System.arraycopy(output.getArray(), 0, response, 4, output.length()); try { conn.publish(reply, response); } catch (IOException e) { LOGGER.warning("failed to send response: " + e.getMessage()); } }