auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public List<SessionResponse> getSessions() throws IOException { ViewerCommand listSessionsCmd = new ViewerCommand(); listSessionsCmd.setCommand(Command.VIEWER_LIST_SESSIONS); listSessionsCmd.setDataSize(0); <START> fOutNet.write(listSessionsCmd.serialize()); <END> return new ListSessionsResponse(fInNet).getSessionsList(); }</code><technical_language>call .flush(), don't. Is logic it</technical_language>

Target:
public List<SessionResponse> getSessions() throws IOException { ViewerCommand listSessionsCmd = new ViewerCommand(Command.VIEWER_LIST_SESSIONS, 0,0); fOutNet.write(listSessionsCmd.serialize()); fOutNet.flush(); return new ListSessionsResponse(fInNet).getSessionsList(); }
Source:
<code>return triple -> typeLookup.contains(FOAF_GROUP) && triple.predicateMatches(createURI(FOAF_MEMBER_VALUE)); }; static final Predicate<Triple> hasAclPredicate = triple -> triple.getPredicate().getNameSpace().equals(WEBAC_NAMESPACE_VALUE); private List<WebACAuthorization> getAuthorizations(final String location) { final Session internalSession = sessionFactory.getInternalSession(); final List<WebACAuthorization> authorizations = new ArrayList<>(); final IdentifierConverter<Resource, FedoraResource> translator = new DefaultIdentifierTranslator(internalSession); LOGGER.debug("Effective ACL: {}", location); if (location.startsWith(FEDORA_INTERNAL_PREFIX)) { final FedoraResource resource = nodeService.find(internalSession, location.substring(FEDORA_INTERNAL_PREFIX.length())); resource.getChildren().forEach(child -> { if (child.getTypes().contains(WEBAC_AUTHORIZATION)) { final Map<String, List<String>> aclTriples = new HashMap<>(); child.getTriples(translator, PROPERTIES).filter(hasAclPredicate) .forEach(triple -> { <START> aclTriples.putIfAbsent(triple.getPredicate().getURI(), new ArrayList<>()); <END> if (triple.getObject().isURI()) { aclTriples.get(triple.getPredicate().getURI()).add(triple.getObject().getURI()); } else if (triple.getObject().isLiteral()) { aclTriples.get(triple.getPredicate().getURI()).add( triple.getObject().getLiteralValue().toString()); } }); LOGGER.debug("Adding acl:Authorization from {}", child.getPath()); authorizations.add(createAuthorizationFromMap(aclTriples)); } }); } return authorizations; }</code><technical_language>need do this get below, [computeIfAbsent](<LINK_0>, returns a value. List<String> = aclTriples.computeIfAbsent ; things.add(); things.add();</technical_language>

Target:
types.contains(FOAF_GROUP) && triple.predicateMatches(createURI(FOAF_MEMBER_VALUE)); private static final Predicate<Triple> hasAclPredicate = triple -> triple.getPredicate().getNameSpace().equals(WEBAC_NAMESPACE_VALUE); private List<WebACAuthorization> getAuthorizations(final String location) { final Session internalSession = sessionFactory.getInternalSession(); final List<WebACAuthorization> authorizations = new ArrayList<>(); final IdentifierConverter<Resource, FedoraResource> translator = new DefaultIdentifierTranslator(internalSession); LOGGER.debug("Effective ACL: {}", location); if (location.startsWith(FEDORA_INTERNAL_PREFIX)) { final FedoraResource resource = nodeService.find(internalSession, location.substring(FEDORA_INTERNAL_PREFIX.length())); resource.getChildren().forEach(child -> { if (child.getTypes().contains(WEBAC_AUTHORIZATION)) { final Map<String, List<String>> aclTriples = new HashMap<>(); child.getTriples(translator, PROPERTIES).filter(hasAclPredicate) .forEach(triple -> { final List<String> values = aclTriples.computeIfAbsent(triple.getPredicate().getURI(), key -> new ArrayList<>()); nodeToStringStream(triple.getObject()).forEach(values::add); }); LOGGER.debug("Adding acl:Authorization from {}", child.getPath()); authorizations.add(createAuthorizationFromMap(aclTriples)); } }); } return authorizations; }
Source:
<code>public void shouldConfigureUpdateOptions() { Instant now = LocalDateTime.now().toInstant(ZoneOffset.UTC); UpdateOptions updateOptions = UpdateOptions.builder() .ttl(10) .timestamp(now) .withIfExists() .build(); assertThat(updateOptions.getTtl()).isEqualTo(Duration.ofSeconds(10)); <START> assertThat(updateOptions.getTimestamp() == now.toEpochMilli() * 1000); <END> assertThat(updateOptions.isIfExists()).isTrue(); }</code><technical_language>assertThat(mutated.getTimestamp()).isEqualTo(now.toEpochMilli() * 1000)</technical_language>

Target:
public void shouldConfigureUpdateOptions() { Instant now = LocalDateTime.now().toInstant(ZoneOffset.UTC); UpdateOptions updateOptions = UpdateOptions.builder() .ttl(10) .timestamp(now) .withIfExists() .build(); assertThat(updateOptions.getTtl()).isEqualTo(Duration.ofSeconds(10)); assertThat(updateOptions.getTimestamp()).isEqualTo(now.toEpochMilli() * 1000); assertThat(updateOptions.isIfExists()).isTrue(); }
Source:
<code>public void setup() { <START> this.definition = spy(new LibraryIndexer() { <END> @Override protected boolean isFolder(final org.uberfire.java.nio.file.Path path) { return isFolder; } @Override protected Set<ResourceTypeDefinition> getResourceTypeDefinitionList() { ResourceTypeDefinition resourceTypeDefinition = mock(ResourceTypeDefinition.class); when(resourceTypeDefinition.accept(any())).thenReturn(isAccepted); return new HashSet<>(Arrays.asList(resourceTypeDefinition)); } }); }</code><technical_language>I mixing spy method overrides in this test. if stick approach. Ideally, override methods in class test all. encapsulate behaviour need mock in interface inject. (For example, mock Instance, a wrapper interface for Files a default impl dispatches static methods.) if want do that, I settle for sticking method overrides, mocking of protected methods, please both</technical_language>

Target:
public void setup() { ResourceTypeDefinition resourceTypeDefinition = mock(ResourceTypeDefinition.class); when(resourceTypeDefinition.accept(any())).thenReturn(isAccepted); final Path p = mock(Path.class); when(p.getFileName()).thenReturn(fileName); this.definition = spy(new LibraryIndexer()); doReturn(this.isFolder).when(this.definition).isFolder(any()); doReturn(new HashSet<>(Arrays.asList(resourceTypeDefinition))).when(this.definition).getVisibleResourceTypes(); doReturn(p).when(this.definition).convertPath(any()); doReturn(fileName.startsWith(".")).when(this.definition).isHidden(any()); }
Source:
<code>private String getInitialPasswordWarning() { StringBuilder optionalWarning = new StringBuilder(); Property authenticatorProperty = Property.INSTANCE_SECURITY_AUTHENTICATOR; if (SiteConfiguration.getInstance().get(authenticatorProperty).equals(authenticatorProperty.getDefaultValue())) optionalWarning.append(": "); else optionalWarning.append(" (this may not be applicable for your security setup): "); <START> return optionalWarning.toString(); <END> }</code><technical_language>avoid of StringBuilder here, is a single string return in case, concatenated else method. Other that, this change good me. Thanks for contribution</technical_language>

Target:
private String getInitialPasswordWarning() { String optionalWarning; Property authenticatorProperty = Property.INSTANCE_SECURITY_AUTHENTICATOR; if (SiteConfiguration.getInstance().get(authenticatorProperty).equals(authenticatorProperty.getDefaultValue())) optionalWarning = ": "; else optionalWarning = " (this may not be applicable for your security setup): "; return optionalWarning; }
Source:
<code>public void run() { try { consumer.subscribe(Collections.singleton(APNS_TOPIC)); while (true) { final ConsumerRecords<String, MessageHolderWithTokens> records = consumer.poll(Long.MAX_VALUE); <START> <END> records.forEach(record -> { final MessageHolderWithTokens messageContainer = record.value(); sender.sendPushMessage(messageContainer.getVariant(), messageContainer.getDeviceTokens(), messageContainer.getUnifiedPushMessage(), messageContainer.getPushMessageInformation().getId(), new NotificationSenderCallback() { @Override public void onSuccess() { } @Override public void onError(String reason) { } }); }); } } catch (WakeupException e) { if (isRunning()) { logger.log(Level.FINE, "Exception on close", e); throw e; } } catch (Exception e) { logger.log(Level.SEVERE, "error", e); } finally { logger.info("Close the consumer."); consumer.close(); } }</code><technical_language>Remove empty lines</technical_language>

Target:
public void run() { try { consumer.subscribe(Collections.singleton(APNS_TOPIC)); while (isRunning()) { final ConsumerRecords<String, MessageHolderWithTokens> records = consumer.poll(Long.MAX_VALUE); records.forEach(record -> { final MessageHolderWithTokens messageContainer = record.value(); sender.sendPushMessage(messageContainer.getVariant(), messageContainer.getDeviceTokens(), messageContainer.getUnifiedPushMessage(), messageContainer.getPushMessageInformation().getId(), new NotificationSenderCallback() { @Override public void onSuccess() { } @Override public void onError(String reason) { } }); }); } } catch (WakeupException e) { if (isRunning()) { LOGGER.log(Level.FINE, "Exception on close", e); throw e; } } catch (Exception e) { LOGGER.log(Level.SEVERE, "error", e); } finally { LOGGER.info("Close the consumer."); consumer.close(); } }
Source:
<code>public Result readTasks(long fromTaskId, List<String> status, LocalDateTime fromLastModificationDate, int pageSize, TaskInputVariablesReadMode taskInputVariablesReadMode) { final List<TaskData> result = new ArrayList<>(); boolean finished = false; List<TaskData> partialResult; TaskDataList taskDataList; TaskData lastItem = null; LocalDateTime queryTime = null; long taskId = fromTaskId; int nextPageSize = pageSize; while (!finished) { taskDataList = runtimeClient.findTasks(taskId, status, fromLastModificationDate, 0, nextPageSize, taskInputVariablesReadMode); partialResult = new ArrayList<>(taskDataList.getItems()); if (queryTime == null) { queryTime = taskDataList.getQueryTime(); } if (partialResult.isEmpty()) { <START> finished = true; <END> } else { if (lastItem == null || partialResult.size() > 1) { lastItem = partialResult.remove(partialResult.size() - 1); taskId = lastItem.getTaskId(); nextPageSize = pageSize; result.addAll(partialResult); } else { if (lastItem.getTaskId().equals(partialResult.get(0).getTaskId())) { if (partialResult.get(0).getPotentialOwners().size() < nextPageSize) { result.add(partialResult.get(0)); finished = true; } else { nextPageSize = nextPageSize * 2; } } else { lastItem = partialResult.get(0); taskId = lastItem.getTaskId(); nextPageSize = pageSize; } } } } return new Result(queryTime, result); }</code><technical_language>method is complex sonarcloud complains cognitive complexity a threshold [1]. tests for this method complicated logic difficult write them. [1] <LINK_0></technical_language>

Target:
public Result readTasks(long fromTaskId, List<String> status, LocalDateTime fromLastModificationDate, int pageSize, TaskInputVariablesReadMode taskInputVariablesReadMode) { final List<TaskData> result = new ArrayList<>(); boolean finished = false; List<TaskData> partialResult; TaskDataList taskDataList; TaskData lastItem = null; LocalDateTime queryTime = null; long taskId = fromTaskId; int nextPageSize = pageSize; while (!finished) { taskDataList = runtimeClient.findTasks(taskId, status, fromLastModificationDate, 0, nextPageSize, taskInputVariablesReadMode); partialResult = new ArrayList<>(taskDataList.getItems()); if (queryTime == null) { queryTime = taskDataList.getQueryTime(); } if (partialResult.isEmpty()) { finished = true; } else { if (lastItem == null || partialResult.size() > 1) { lastItem = partialResult.remove(partialResult.size() - 1); taskId = lastItem.getTaskId(); nextPageSize = pageSize; result.addAll(partialResult); } else { if (lastItem.getTaskId().equals(partialResult.get(0).getTaskId())) { if (partialResult.get(0).getPotentialOwners().isEmpty()) { result.add(partialResult.get(0)); lastItem = null; taskId++; nextPageSize = pageSize; } else if (partialResult.get(0).getPotentialOwners().size() < nextPageSize) { result.add(partialResult.get(0)); finished = true; } else { nextPageSize = nextPageSize * 2; } } else { lastItem = partialResult.get(0); taskId = lastItem.getTaskId(); nextPageSize = pageSize; } } } } return new Result(queryTime, result); }
Source:
<code>public void lockObtainFailed(List<LuceneWork> failingOperations) { logDebug("Operation %s failed due to lock already in used", failingOperations); try { Thread.sleep(POLL_WAIT); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } Address lockHolder = getLockHolder(getIndexName()); clearIfNeeded(lockHolder); if (failingOperations.stream().anyMatch(w -> w.getIdInString() != null)) { logDebug("Retrying operations %s", failingOperations); <START> CompletableFuture<Void> future = CompletableFuture.supplyAsync(() -> { <END> performOperations(failingOperations, null); return null; }); future.whenComplete((aVoid, throwable) -> { if (throwable == null) { logDebug("Operation completed"); } else { log.errorf(throwable, "Error reapplying operation"); } }); } }</code><technical_language>I wonder, this done in a specific thread pool? operations IO right? in common fork join pool</technical_language>

Target:
public void lockObtainFailed(List<LuceneWork> failingOperations) { logDebug("Operation %s failed due to lock already in used", failingOperations); try { Thread.sleep(POLL_WAIT); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } Address lockHolder = getLockHolder(getIndexName()); clearIfNeeded(lockHolder); if (failingOperations.stream().anyMatch(w -> w.getIdInString() != null)) { logDebug("Retrying operations %s", failingOperations); CompletableFuture<Void> future = CompletableFuture.supplyAsync(() -> { performOperations(failingOperations, null); return null; }, asyncExecutor); future.whenComplete((aVoid, throwable) -> { if (throwable == null) { logDebug("Operation completed"); } else { log.errorf(throwable, "Error reapplying operation"); } }); } }
Source:
<code><START> public List<Integer> getSlotsForRequiredItems(Map<String, Integer> items, EntityRef player) { <END> List<Integer> requiredSlots = new ArrayList<>(); int inventorySize = inventoryManager.getNumSlots(player); for(int slotNumber = 0; slotNumber <= inventorySize; slotNumber++) { EntityRef inventorySlot = inventoryManager.getItemInSlot(player, slotNumber); BlockItemComponent blockItemComponent = inventorySlot.getComponent(BlockItemComponent.class); if (blockItemComponent != null) { String blockFamily = blockItemComponent.blockFamily.toString(); if (items.containsKey(blockFamily)) { requiredSlots.add(slotNumber); } } } return requiredSlots; }</code><technical_language>this method private</technical_language>

Target:
private List<Integer> getSlotsForRequiredItems(Map<String, Integer> items, EntityRef player) { List<Integer> requiredSlots = new ArrayList<>(); int inventorySize = inventoryManager.getNumSlots(player); for (int slotNumber = 0; slotNumber <= inventorySize; slotNumber++) { EntityRef inventorySlot = inventoryManager.getItemInSlot(player, slotNumber); BlockItemComponent blockItemComponent = inventorySlot.getComponent(BlockItemComponent.class); if (blockItemComponent != null) { String blockFamilyName = blockItemComponent.blockFamily.toString(); if (items.containsKey(blockFamilyName)) { int requiredNumber = items.get(blockFamilyName); if (requiredNumber <= inventoryManager.getStackSize(inventorySlot)) { requiredSlots.add(slotNumber); } else { logger.info("You don't have enough({} required) blocks to spawn the Oreon", requiredNumber, blockFamilyName); break; } } } } return requiredSlots; }
Source:
<code>public void nodeChanged() { final String leaderContenderDesc = leaderElectionStateHandler.getLeaderContenderDescription(); leaderElectionStateHandler.runWithLock((confirmedLeaderSessionID, confirmedLeaderAddress) -> { if (leaderLatch.hasLeadership()) { if (running) { <START> if (LOG.isDebugEnabled()) { LOG.debug( "Leader node changed while is the leader with session ID {}.", leaderContenderDesc, confirmedLeaderSessionID); } if (confirmedLeaderSessionID != null) { ChildData childData = cache.getCurrentData(); if (childData == null) { if (LOG.isDebugEnabled()) { LOG.debug( "Writing leader information into empty node by {}.", leaderContenderDesc); } writeLeaderInformation(confirmedLeaderSessionID, confirmedLeaderAddress); } else { byte[] data = childData.getData(); if (data == null || data.length == 0) { if (LOG.isDebugEnabled()) { LOG.debug( "Writing leader information into node with empty data field by {}.", leaderContenderDesc); } writeLeaderInformation(confirmedLeaderSessionID, confirmedLeaderAddress); } else { ByteArrayInputStream bais = new ByteArrayInputStream(data); ObjectInputStream ois = new ObjectInputStream(bais); String leaderAddress = ois.readUTF(); UUID leaderSessionID = (UUID) ois.readObject(); if (!leaderAddress.equals(confirmedLeaderAddress) || (leaderSessionID == null || !leaderSessionID.equals(confirmedLeaderSessionID))) { if (LOG.isDebugEnabled()) { LOG.debug( "Correcting leader information by {}.", leaderContenderDesc); <END> } writeLeaderInformation(confirmedLeaderSessionID, confirmedLeaderAddress); } } } } } else { LOG.debug("Ignoring node change notification since the service has already been stopped."); } } }); }</code><technical_language>I good driver extract leader information service decide handle (e.g. needs rewrite leader information not)</technical_language>

Target:
public void nodeChanged() throws Exception { if (leaderLatch.hasLeadership()) { ChildData childData = cache.getCurrentData(); if (childData != null) { final byte[] data = childData.getData(); if (data != null && data.length > 0) { final ByteArrayInputStream bais = new ByteArrayInputStream(data); final ObjectInputStream ois = new ObjectInputStream(bais); final String leaderAddress = ois.readUTF(); final UUID leaderSessionID = (UUID) ois.readObject(); leaderElectionEventHandler.onLeaderInformationChange( LeaderInformation.known(leaderSessionID, leaderAddress)); return; } } leaderElectionEventHandler.onLeaderInformationChange(LeaderInformation.empty()); } }
Source:
<code><START> public synchronized void reset() throws IOException { <END> if (mark >= 0) { buffer.position(mark); this.mark = -1; } else { throw new IOException("No mark defined"); } }</code><technical_language>This class is thread safe. synchronized is unnecessary I is misleading</technical_language>

Target:
public void reset() throws IOException { if (mark >= 0) { buffer.position(mark); this.mark = -1; } else { throw new IOException("No mark defined"); } }
Source:
<code>public static Datasource getDatasource(final CRConfigUtil requestProcessorConfig) { Datasource ds = null; Properties dsHandle = requestProcessorConfig.getDatasourceHandleProperties(); Properties dsProps = requestProcessorConfig.getDatasourceProperties(); String dsName = requestProcessorConfig.getDatasourceName(); if(dsName != null && dsName != ""){ try { <START> ds = PortalConnectorFactory.createDatasource(dsName.toUpperCase()); <END> log.debug("Datasource fetched for " + requestProcessorConfig.getName()); } catch (NodeException e) { log.error("Error while fetching datasource", e); } } else{ if (dsHandle != null && dsHandle.size() != 0) { if (dsHandle.containsKey("portalnodedb")) { String key = (String) dsHandle.get("portalnodedb"); ds = PortalNodeInteractor.getPortalnodeDatasource(key); } else if (dsProps != null && dsProps.size() != 0) { boolean mccr = ObjectTransformer.getBoolean(dsProps.get("mccr"), false); if (mccr) { ds = PortalConnectorFactory.createWritableMultichannellingDatasource(CRUtil.propertiesToMap(dsHandle), CRUtil.propertiesToMap(dsProps)); } else { ds = PortalConnectorFactory.createWriteableDatasource(dsHandle, dsProps); } } else { ds = PortalConnectorFactory.createWriteableDatasource(dsHandle); } log.debug("Datasource created for " + requestProcessorConfig.getName()); if (ds != null) { getInstance().accquireDS(); } } else { log.debug("No Datasource created for " + requestProcessorConfig.getName()); } } return ds; }</code><technical_language>convert dsName convertKey() (instead for dsName.toUpperCase())</technical_language>

Target:
public static Datasource getDatasource( final CRConfigUtil requestProcessorConfig) { Datasource ds = null; Properties dsHandle = requestProcessorConfig .getDatasourceHandleProperties(); Properties dsProps = requestProcessorConfig.getDatasourceProperties(); String dsName = requestProcessorConfig.getDatasourceName(); if (dsName != null && dsName != "") { try { ds = PortalConnectorFactory.createDatasource(dsName); log.debug("Datasource fetched for " + requestProcessorConfig.getName()); } catch (NodeException e) { log.error("Error while fetching datasource", e); } } else { if (dsHandle != null && dsHandle.size() != 0) { if (dsHandle.containsKey("portalnodedb")) { String key = (String) dsHandle.get("portalnodedb"); ds = PortalNodeInteractor.getPortalnodeDatasource(key); } else if (dsProps != null && dsProps.size() != 0) { boolean mccr = ObjectTransformer.getBoolean( dsProps.get("mccr"), false); if (mccr) { ds = PortalConnectorFactory .createWritableMultichannellingDatasource( CRUtil.propertiesToMap(dsHandle), CRUtil.propertiesToMap(dsProps)); } else { ds = PortalConnectorFactory.createWriteableDatasource( dsHandle, dsProps); } } else { ds = PortalConnectorFactory .createWriteableDatasource(dsHandle); } log.debug("Datasource created for " + requestProcessorConfig.getName()); if (ds != null) { getInstance().accquireDS(); } } else { log.debug("No Datasource created for " + requestProcessorConfig.getName()); } } return ds; }
Source:
<code>public void testSettingQueryPagination() { Query query = mock(Query.class); PaginationImpl paginationMock = mock(PaginationImpl.class); when(paginationMock.getLimit()).thenReturn(10); when(paginationMock.getOffset()).thenReturn(50); EntityProjection previousEntityProjection = entityProjection; <START> entityProjection = mock(EntityProjection.class); <END> when(entityProjection.getPagination()).thenReturn(paginationMock); try { addPaginationToQuery(query); verify(query, times(1)).setMaxResults(10); verify(query, times(1)).setFirstResult(50); } finally { entityProjection = previousEntityProjection; } }</code><technical_language>Setting resetting mock this (including code) hacky. I suggest initialize this class a mock entity projection. add a @BeforeEach AfterEach annotation resets mocks. method setup projection that. sense</technical_language>

Target:
public void testSettingQueryPagination() { Query query = mock(Query.class); PaginationImpl paginationMock = mock(PaginationImpl.class); when(paginationMock.getLimit()).thenReturn(10); when(paginationMock.getOffset()).thenReturn(50); when(this.entityProjection.getPagination()).thenReturn(paginationMock); addPaginationToQuery(query); verify(query, times(1)).setMaxResults(10); verify(query, times(1)).setFirstResult(50); }
Source:
<code>public Mono<String> getComponent(String digitalTwinId, String componentPath) { return getComponentWithResponse(digitalTwinId, componentPath) <START> .flatMap(response -> Mono.justOrEmpty(response.getValue())); <END> }</code><technical_language>a map instead</technical_language>

Target:
public Mono<String> getComponent(String digitalTwinId, String componentPath) { return getComponentWithResponse(digitalTwinId, componentPath) .map(DigitalTwinsResponse::getValue); }
Source:
<code>public Converter createConverter(Class source, Class target, Hints hints) { <START> if (source.equals(PGobject.class)) { <END> return super.createConverter(String.class, target, hints); } return null; }</code><technical_language>confused here... base class is registered in SPI, in classpath, checks source this one. So, is this adding base class is covering? For PGObject converted base class, a Node no? this class check un-necessary</technical_language>

Target:
public Converter createConverter(Class source, Class target, Hints hints) { if (source.equals(PGobject.class)) { if (target.equals(Document.class)) { return new StringToDocumentConverter() { @Override public <T> T convert(Object source, Class<T> target) throws Exception { return super.convert(source.toString(), target); } }; } else if (target.equals(DocumentFragment.class)) { return new StringToDocumentFragmentConverter(){ @Override public <T> T convert(Object source, Class<T> target) throws Exception { return super.convert(source.toString(), target); } }; } } return null; }
Source:
<code>protected IllegalArgumentException exception(String name, String reason) { return new IllegalArgumentException( <START> String.format("Object '%s' doesn't match Azure naming constraints. " + "Reason: %s", name, <END> reason)); }</code><technical_language>here. is need break string</technical_language>

Target:
protected IllegalArgumentException exception(String name, String reason) { return new IllegalArgumentException(String.format("Object '%s' doesn't match Azure naming constraints: %s", name, reason)); }
Source:
<code>public void run() { while (true) { Message message = null; lock.lock(); try { while (message == null) { message = workQueue.poll(); if (message == null) { numWaiters++; queueEmpty.await(); numWaiters--; } } } catch (InterruptedException e) { break; } finally { lock.unlock(); } try { message.handle(handler); message.release(); } catch (InterruptedException e) { <START> message.release(); <END> break; } catch (Exception e) { logger.error(e.getMessage(), e); cmember.indexUpdated(true, false); } } }</code><technical_language>finally avoid message leak better? try { } finally { message.release() }</technical_language>

Target:
public void run() { while (true) { Message message = null; lock.lock(); try { while ((message = workQueue.poll()) == null) { numWaiters++; queueEmpty.await(); numWaiters--; } } catch (InterruptedException e) { break; } finally { lock.unlock(); } try { message.handle(handler); } catch (InterruptedException e) { break; } catch (Exception e) { logger.error(e.getMessage(), e); cmember.indexUpdated(true, false); } finally { message.release(); } } }
Source:
<code>public void editHandlers() throws Exception { String handler = "testHandler_" + RandomStringUtils.randomAlphanumeric(5); <START> ModelNodeResult defaultValue = operations.readAttribute(ROOT_LOGGER_ADDRESS, "handlers"); <END> client.apply(Logging.handler() .console() .add(handler) .build()); try { editTextAreaAndVerify(ROOT_LOGGER_ADDRESS, "handlers", new String[]{handler}); } finally { operations.writeAttribute(ROOT_LOGGER_ADDRESS, "handlers", defaultValue.value()); new ResourceVerifier(ROOT_LOGGER_ADDRESS, client, 4000).verifyAttribute("handlers", defaultValue.value()); client.apply(Logging.handler().console().remove(handler)); } }</code><technical_language>org.wildfly.extras.creaper.core.online.operations.ReadAttributeOption#NOT_INCLUDE_DEFAULTS real orig is returned OK, big issue</technical_language>

Target:
public void editHandlers() throws Exception { String handler = "testHandler_" + RandomStringUtils.randomAlphanumeric(5); ModelNodeResult originalHandlersResult = operations.readAttribute(ROOT_LOGGER_ADDRESS, "handlers", ReadAttributeOption.NOT_INCLUDE_DEFAULTS); client.apply(Logging.handler() .console() .add(handler) .build()); try { editTextAreaAndVerify(ROOT_LOGGER_ADDRESS, "handlers", new String[]{handler}); } finally { operations.writeAttribute(ROOT_LOGGER_ADDRESS, "handlers", originalHandlersResult.value()); ResourceVerifier rootLoggerVerifier = new ResourceVerifier(ROOT_LOGGER_ADDRESS, client, 4000); if (originalHandlersResult.hasDefinedValue()) { rootLoggerVerifier.verifyAttribute("handlers", originalHandlersResult.value()); } else { rootLoggerVerifier.verifyAttributeIsUndefined("handlers"); } client.apply(Logging.handler().console().remove(handler)); } }
Source:
<code>protected void doTestFormat(Map<String, String> options, Formatter formatter, String fileUnderTest, String expectedSha512) throws IOException { File originalSourceFile = new File("src/test/resources/", fileUnderTest); File sourceFile = new File("target/testoutput/", fileUnderTest); <START> Files.copy(originalSourceFile, sourceFile); <END> if (null == options) { options = new HashMap<>(); } final File targetDir = new File("target/testoutput"); targetDir.mkdirs(); formatter.init(options, new TestConfigurationSource(targetDir)); Result result = formatter.formatFile(sourceFile, LineEnding.CRLF, false); Assert.assertEquals(Result.SUCCESS, result); byte[] sha512 = Files.asByteSource(sourceFile).hash(Hashing.sha512()).asBytes(); StringBuilder sb = new StringBuilder(); for (int i = 0; i < sha512.length; i++) { sb.append(Integer.toString((sha512[i] & 0xff) + 0x100, 16).substring(1)); } Assert.assertEquals(expectedSha512, sb.toString()); }</code><technical_language>clear this file copy moved code created parent directory. If copy handles case directory exist, lines for creating targetDir removed. Otherwise, need precede copy</technical_language>

Target:
protected void doTestFormat(Map<String, String> options, Formatter formatter, String fileUnderTest, String expectedSha512) throws IOException { File originalSourceFile = new File("src/test/resources/", fileUnderTest); File sourceFile = new File("target/testoutput/", fileUnderTest); if (null == options) { options = new HashMap<>(); } final File targetDir = new File("target/testoutput"); targetDir.mkdirs(); Files.copy(originalSourceFile, sourceFile); formatter.init(options, new TestConfigurationSource(targetDir)); Result result = formatter.formatFile(sourceFile, LineEnding.CRLF, false); Assertions.assertEquals(Result.SUCCESS, result); byte[] sha512 = Files.asByteSource(sourceFile).hash(Hashing.sha512()).asBytes(); StringBuilder sb = new StringBuilder(); for (int i = 0; i < sha512.length; i++) { sb.append(Integer.toString((sha512[i] & 0xff) + 0x100, 16).substring(1)); } Assertions.assertEquals(expectedSha512, sb.toString()); }
Source:
<code>protected void fillContextMenu(IMenuManager manager) { final ISelection selection = fViewer.getSelection(); ITmfFilterTreeNode filterTreeNode = null; if (selection instanceof StructuredSelection) { Object element = ((StructuredSelection) selection).getFirstElement(); if (element instanceof ITmfFilterTreeNode) { filterTreeNode = (ITmfFilterTreeNode) element; } } if (fIsDialog ) { final ITmfFilterTreeNode selectedNode = filterTreeNode; if (selectedNode != null) { <START> fillContextMenuForNode(selectedNode, manager); <END> if (selectedNode.getValidChildren().size() > 0) { manager.add(new Separator()); } Action deleteAction = new Action(Messages.FilterViewer_DeleteActionText) { @Override public void run() { selectedNode.remove(); fViewer.refresh(); } }; deleteAction.setImageDescriptor(PlatformUI.getWorkbench().getSharedImages().getImageDescriptor(ISharedImages.IMG_TOOL_DELETE)); deleteAction.setActionDefinitionId(IWorkbenchCommandConstants.EDIT_DELETE); deleteAction.setAccelerator(SWT.DEL); manager.add(deleteAction); manager.add(new Separator()); } } else { if (filterTreeNode != null) { fillContextMenuForNode(filterTreeNode, manager); } manager.add(new Separator("delete")); } manager.add(new Separator("edit")); if (fViewer.getInput() instanceof TmfFilterRootNode || filterTreeNode == null) { manager.add(new Separator()); ITmfFilterTreeNode root = (ITmfFilterTreeNode) fViewer.getInput(); fillContextMenuForNode(root, manager); } }</code><technical_language>I previous (left) code executed in cases add Delete action for dialogs? "delete" "edit" separators common need add new ones</technical_language>

Target:
protected void fillContextMenu(IMenuManager manager) { final ISelection selection = fViewer.getSelection(); ITmfFilterTreeNode filterTreeNode = null; if (selection instanceof StructuredSelection) { Object element = ((StructuredSelection) selection).getFirstElement(); if (element instanceof ITmfFilterTreeNode) { filterTreeNode = (ITmfFilterTreeNode) element; } } final ITmfFilterTreeNode selectedNode = filterTreeNode; if (selectedNode != null) { fillContextMenuForNode(selectedNode, manager); } manager.add(new Separator("delete")); if (fIsDialog && (selectedNode != null)) { Action deleteAction = new Action(Messages.FilterViewer_DeleteActionText) { @Override public void run() { selectedNode.remove(); fViewer.refresh(); } }; deleteAction.setImageDescriptor(PlatformUI.getWorkbench().getSharedImages().getImageDescriptor(ISharedImages.IMG_TOOL_DELETE)); deleteAction.setActionDefinitionId(IWorkbenchCommandConstants.EDIT_DELETE); deleteAction.setAccelerator(SWT.DEL); manager.add(deleteAction); } manager.add(new Separator("edit")); if (fViewer.getInput() instanceof TmfFilterRootNode || filterTreeNode == null) { manager.add(new Separator()); ITmfFilterTreeNode root = (ITmfFilterTreeNode) fViewer.getInput(); fillContextMenuForNode(root, manager); } }
Source:
<code>private String getFilePrefix(ReusableAudioPacket packet) { StringBuilder sb = new StringBuilder(); sb.append(SystemProperties.getInstance().getApplicationFolder("recordings")); sb.append(File.separator); Metadata metadata = packet.getMetadata(); sb.append(metadata.hasChannelConfigurationSystem() ? metadata.getChannelConfigurationSystem() + "_" : ""); sb.append(metadata.hasChannelConfigurationSite() ? metadata.getChannelConfigurationSite() + "_" : ""); sb.append(metadata.hasChannelConfigurationName() ? metadata.getChannelConfigurationName() + "_" : ""); if(metadata.getPrimaryAddressTo().hasIdentifier()) { sb.append("_TO_").append(metadata.getPrimaryAddressTo().getIdentifier()); if(metadata.getPrimaryAddressFrom().hasIdentifier()) { sb.append("_FROM_").append(metadata.getPrimaryAddressFrom().getIdentifier()); } } <START> return StringUtils.replaceIllegalCharacters(sb.toString()); <END> }</code><technical_language>please move clean method of System/Site/Name values added. Otherwise, clean method invalid linux filepaths. sb.append(metadata.hasChannelConfigurationSystem() ? StringUtils.replaceIllegalCharacters(metadata.getChannelConfigurationSystem()) + "_" : ""); sb.append(metadata.hasChannelConfigurationSite() ? StringUtils.replaceIllegalCharacters(metadata.getChannelConfigurationSite()) + "_" : ""); sb.append(metadata.hasChannelConfigurationName() ? StringUtils.replaceIllegalCharacters(metadata.getChannelConfigurationName()) + "_" : "");</technical_language>

Target:
private String getFilePrefix(ReusableAudioPacket packet) { Path baseFilePath = SystemProperties.getInstance().getApplicationFolder("recordings"); Metadata metadata = packet.getMetadata(); StringBuilder sb = new StringBuilder(); sb.append(metadata.hasChannelConfigurationSystem() ? metadata.getChannelConfigurationSystem() + "_" : ""); sb.append(metadata.hasChannelConfigurationSite() ? metadata.getChannelConfigurationSite() + "_" : ""); sb.append(metadata.hasChannelConfigurationName() ? metadata.getChannelConfigurationName() + "_" : ""); if(metadata.getPrimaryAddressTo().hasIdentifier()) { sb.append("_TO_").append(metadata.getPrimaryAddressTo().getIdentifier()); if(metadata.getPrimaryAddressFrom().hasIdentifier()) { sb.append("_FROM_").append(metadata.getPrimaryAddressFrom().getIdentifier()); } } String cleanedFileName = StringUtils.replaceIllegalCharacters(sb.toString()); return baseFilePath.resolve(cleanedFileName).toString(); }
Source:
<code>public void testOnSendMessageSuccessful() throws Exception { String receiver = "receiver"; String message = "Some message"; instance.messageTextField().setText(message); instance.setReceiver(receiver); when(chatService.sendMessageInBackground(eq(receiver), any())).thenReturn(completedFuture(message)); instance.onSendMessage(); verify(chatService).sendMessageInBackground(eq(receiver), eq(message)); <START> assertTrue(instance.messageTextField().getText().equals("")); <END> assertThat(instance.messageTextField().isDisable(), is(false)); }</code><technical_language>changing this, work</technical_language>

Target:
public void testOnSendMessageSuccessful() { String receiver = "receiver"; String message = "Some message"; instance.messageTextField().setText(message); instance.setReceiver(receiver); when(chatService.sendMessageInBackground(eq(receiver), any())).thenReturn(completedFuture(message)); instance.onSendMessage(); verify(chatService).sendMessageInBackground(eq(receiver), eq(message)); assertThat(instance.messageTextField().getText(), is(isEmptyString())); assertThat(instance.messageTextField().isDisable(), is(false)); }
Source:
<code><START> Itr() { <END> Set<Deque<T>> queues = new LinkedHashSet<>(); fInputLock.lock(); try { queues.add(fInputBuffer); Iterator<Deque<T>> queueIterator = fInnerQueue.descendingIterator(); while (queueIterator.hasNext()) { queues.add(queueIterator.next()); } } finally { fInputLock.unlock(); } fOutputLock.lock(); try { Iterator<Deque<T>> queueIterator = fInnerQueue.descendingIterator(); while (queueIterator.hasNext()) { queues.add(queueIterator.next()); } queues.add(fOutputBuffer); } finally { fOutputLock.unlock(); } fQueueIterator = checkNotNull(queues.iterator()); }</code><technical_language>I understand need lock, I greatly reduce amount of time lock here, avoid queue twice. I iterator in proper sequence. New patch incoming soon</technical_language>

Target:
Itr() { Deque<T> inputBuffer; Deque<T> outputBuffer; int innerQueueSize; Iterator<Deque<T>> queueIterator; fInputLock.lock(); try { inputBuffer = fInputBuffer; innerQueueSize = fInnerQueue.size(); queueIterator = fInnerQueue.descendingIterator(); } finally { fInputLock.unlock(); } fOutputLock.lock(); try { outputBuffer = fOutputBuffer; } finally { fOutputLock.unlock(); } Deque<Deque<T>> queues = new ArrayDeque<>(innerQueueSize + 2); queues.add(inputBuffer); boolean found = false; while (queueIterator.hasNext()) { Deque<T> queue = queueIterator.next(); queues.add(queue); if (queue == outputBuffer) { found = true; } } if (!found) { if (queues.size() <= 1 || !queues.getLast().isEmpty()) { queues.add(outputBuffer); } } fQueueIterator = checkNotNull(queues.iterator()); }
Source:
<code>public boolean runSerially() { if (!telemetryEnabled) { return true; } <START> telemetrySubSeq.consumeAll(telemetryQueue, myConsumer); <END> writer.commit(); return true; }</code><technical_language>considering of consumeAll() return of runSerially() 'false'. This is case telemetry is disabled, allow this method simpler. runSerially() returns success status. True tells CPU scheduler this job called soon possible. False means run useful call is necessary</technical_language>

Target:
public boolean runSerially() { if (telemetryEnabled) { telemetrySubSeq.consumeAll(telemetryQueue, myConsumer); writer.commit(); } return false; }
Source:
<code>private void normalise() { <START> final long valueCopy = value; <END> final int scaleCopy = scale; if (value == 0) { scale = 0; } else if (0 < scale) { while (value % 10 == 0 && 0 < scale) { value /= 10; --scale; } } else if (scale < 0) { while (!isOutsideLimits(value, VALUE_MIN_VAL, VALUE_MAX_VAL) && scale < 0) { value *= 10; ++scale; } } if (isOutsideLimits(scale, SCALE_MIN_VAL, SCALE_MAX_VAL) || isOutsideLimits(value, VALUE_MIN_VAL, VALUE_MAX_VAL)) { throw new ArithmeticException("Out of range: value: " + valueCopy + ", exponent: " + scaleCopy); } }</code><technical_language>copies in ArithmeticException method references them. arithemtic exception throw new values reset fields copy started with? easier write this code perform operations local variables set fields end if limits</technical_language>

Target:
private void normalise() { long value = this.value; int scale = this.scale; if (value == 0) { scale = 0; } else if (0 < scale) { while (value % 10 == 0 && 0 < scale) { value /= 10; --scale; } } else if (scale < 0) { while (!isOutsideLimits(value, VALUE_MIN_VAL, VALUE_MAX_VAL) && scale < 0) { value *= 10; ++scale; } } if (isOutsideLimits(scale, SCALE_MIN_VAL, SCALE_MAX_VAL) || isOutsideLimits(value, VALUE_MIN_VAL, VALUE_MAX_VAL)) { throw new ArithmeticException("Out of range: value: " + this.value + ", scale: " + this.scale); } this.value = value; this.scale = scale; }
Source:
<code>private void doInitiation(RejoinMessage message) { m_coordinatorHsId = message.m_sourceHSId; registerSnapshotMonitor(message.getSnapshotNonce()); long sinkHSId = m_dataSink.initialize(message.getSnapshotSourceCount(), message.getSnapshotBufferPool()); RejoinMessage msg = new RejoinMessage(m_mailbox.getHSId(), -1, sinkHSId); m_mailbox.send(m_coordinatorHsId, msg); m_taskQueue.offer(this); <START> m_taskQueue.setQueueDepthTracker(new QueueDepthTracker(m_partitionId)); <END> JOINLOG.info("P" + m_partitionId + " received initiation"); }</code><technical_language>Do do this for RejoinProducer too</technical_language>

Target:
private void doInitiation(RejoinMessage message) { m_coordinatorHsId = message.m_sourceHSId; registerSnapshotMonitor(message.getSnapshotNonce()); long sinkHSId = m_dataSink.initialize(message.getSnapshotSourceCount(), message.getSnapshotBufferPool()); RejoinMessage msg = new RejoinMessage(m_mailbox.getHSId(), -1, sinkHSId); m_mailbox.send(m_coordinatorHsId, msg); m_taskQueue.offer(this); JOINLOG.info("P" + m_partitionId + " received initiation"); }
Source:
<code>protected boolean canDoAction() { if (!super.canDoAction()) { return false; } if (getParameters().getClusterId() == null) { addCanDoActionMessage(VdcBllMessages.ACTION_TYPE_FAILED_CLUSTER_IS_NOT_VALID); return false; } if (getParameters().getConfigParams() == null || getParameters().getConfigParams().isEmpty()) { addCanDoActionMessage(VdcBllMessages.ACTION_TYPE_FAILED_GLUSTER_VOLUME_SNAPSHOT_CONFIG_PARAMS_IS_EMPTY); return false; } for (GlusterVolumeSnapshotConfig param : getParameters().getConfigParams()) { <START> if (param.getParamValue() == null || param.getParamValue().equals("")) { <END> addCanDoActionMessage(VdcBllMessages.ACTION_TYPE_FAILED_GLUSTER_VOLUME_SNAPSHOT_CONFIG_PARAM_VALUE_IS_EMPTY); return false; } } return true; }</code><technical_language>StringUtils.isBlank</technical_language>

Target:
protected boolean canDoAction() { if (!super.canDoAction()) { return false; } if (getParameters().getClusterId() == null) { addCanDoActionMessage(VdcBllMessages.ACTION_TYPE_FAILED_CLUSTER_IS_NOT_VALID); return false; } if (getParameters().getConfigParams() == null || getParameters().getConfigParams().isEmpty()) { addCanDoActionMessage(VdcBllMessages.ACTION_TYPE_FAILED_GLUSTER_VOLUME_SNAPSHOT_CONFIG_PARAMS_IS_EMPTY); return false; } for (GlusterVolumeSnapshotConfig param : getParameters().getConfigParams()) { if (StringUtils.isEmpty(param.getParamValue())) { addCanDoActionMessage(VdcBllMessages.ACTION_TYPE_FAILED_GLUSTER_VOLUME_SNAPSHOT_CONFIG_PARAM_VALUE_IS_EMPTY); return false; } } return true; }
Source:
<code>public void onBeforeRead(RepositoryStreamContext ctx) throws IOException { RepositoryPath repositoryPath = (RepositoryPath) ctx.getPath(); String path = RepositoryFiles.stringValue(repositoryPath); logger.debug(String.format("Reading /" + repositoryPath.getRepository().getStorage().getId() + "/" + repositoryPath.getRepository().getId() + "/%s", path)); if (!RepositoryFiles.isArtifact(repositoryPath)) { return; } Repository repository = repositoryPath.getRepository(); String storageId = repository.getStorage().getId(); String repositoryId = repository.getId(); ArtifactEntry artifactEntry = provideArtirfactEntry(storageId, repositoryId, path); artifactEntry.setLastUsed(new Date()); artifactEntry.setDownloadCount(artifactEntry.getDownloadCount() + 1); artifactEntryService.save(artifactEntry); }</code><technical_language>I assume asking > if (!RepositoryFiles.isArtifact(repositoryPath)) If so, it, database a metadata/ArtifactEntry read/write file from/to system, I understand</technical_language>

Target:
public void onBeforeRead(RepositoryStreamContext ctx) throws IOException { RepositoryPath repositoryPath = (RepositoryPath) ctx.getPath(); String path = RepositoryFiles.stringValue(repositoryPath); logger.debug(String.format("Reading /" + repositoryPath.getRepository().getStorage().getId() + "/" + repositoryPath.getRepository().getId() + "/%s", path)); if (!RepositoryFiles.isArtifact(repositoryPath)) { return; } Repository repository = repositoryPath.getRepository(); String storageId = repository.getStorage().getId(); String repositoryId = repository.getId(); ArtifactEntry artifactEntry = provideArtifactEntry(storageId, repositoryId, path); Assert.notNull(artifactEntry.getUuid(), String.format("Invalid [%s] for [%s]", ArtifactEntry.class.getSimpleName(), ctx.getPath())); artifactEntry.setLastUsed(new Date()); artifactEntry.setDownloadCount(artifactEntry.getDownloadCount() + 1); artifactEntryService.save(artifactEntry); }
Source:
<code>public void should_remove_span_from_thread_local_after_finishing_work() throws Exception { givenCallableGetsSubmitted(thatSetsTraceInCurrentThreadLocalWithInitialTrace()); Trace secondTrace = whenCallableGetsSubmitted(thatRetrievesTraceFromThreadLocal()); <START> then(secondTrace).isNull(); <END> }</code><technical_language>This pass: @RunWith(MockitoJUnitRunner.class) public class TraceCallableTest { ExecutorService executor = Executors.newSingleThreadExecutor(); TraceManager traceManager = new DefaultTraceManager(new AlwaysSampler(), new RandomUuidGenerator(), Mockito.mock(ApplicationEventPublisher.class)); @Test public void should_remove_span_from_thread_local_after_finishing_work() throws Exception { Trace firstTrace = givenCallableGetsSubmitted(thatSetsTraceInCurrentThreadLocalWithInitialTrace()); Trace secondTrace = whenCallableGetsSubmitted(thatRetrievesTraceFromThreadLocal()); then(secondTrace.getSpan().getTraceId()).isNotEqualTo(firstTrace.getSpan().getTraceId()); } private Callable<Trace> thatSetsTraceInCurrentThreadLocalWithInitialTrace() { return new Callable<Trace>() { @Override public Trace call() throws Exception { return TraceContextHolder.getCurrentTrace(); } }; } private Callable<Trace> thatRetrievesTraceFromThreadLocal() { return new Callable<Trace>() { @Override public Trace call() throws Exception { return TraceContextHolder.getCurrentTrace(); } }; } private Trace givenCallableGetsSubmitted(Callable<Trace> callable) throws InterruptedException, java.util.concurrent.ExecutionException { return whenCallableGetsSubmitted(callable); } private Trace whenCallableGetsSubmitted(Callable<Trace> callable) throws InterruptedException, java.util.concurrent.ExecutionException { return this.executor.submit(new TraceCallable<>(this.traceManager, callable)) .get(); } }</technical_language>

Target:
public void should_remove_span_from_thread_local_after_finishing_work() throws Exception { Trace firstTrace = givenCallableGetsSubmitted(thatSetsTraceInCurrentThreadLocalWithInitialTrace()); Trace secondTrace = whenCallableGetsSubmitted(thatRetrievesTraceFromThreadLocal()); then(secondTrace.getSpan().getTraceId()).isNotEqualTo(firstTrace.getSpan().getTraceId()); }
Source:
<code>default ListenableFuture<Resolved<I>> resolveIds(Iterable<Id> ids, Boolean refreshCache) { <START> throw new UnsupportedOperationException(); <END> }</code><technical_language>this proxy plain resolveIds method</technical_language>

Target:
default ListenableFuture<Resolved<I>> resolveIds(Iterable<Id> ids, Boolean refreshCache) { return resolveIds(ids); }
Source:
<code>public Optional<String> deleteDatabaseServer(AzureClient azureClient, String databaseServerId, boolean cancelException) { return handleDeleteErrors(resourceId -> { LOGGER.info("Delete database server: {}", resourceId); <START> azureClient.deleteDatabaseServer(resourceId); <END> }, "DatabaseServer", databaseServerId, true); }</code><technical_language>This async operation need wait for throw a CloudbreakServiceException doOnError()</technical_language>

Target:
public Optional<String> deleteDatabaseServer(AzureClient azureClient, String databaseServerId, boolean cancelException) { return handleDeleteErrors(azureClient::deleteDatabaseServer, "DatabaseServer", databaseServerId, cancelException); }