auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public CompletableFuture<Void> visitGetAllCommand(InvocationContext ctx, GetAllCommand command) throws Throwable { if (ctx.isInTxScope()) return ctx.continueInvocation(); return ctx.onReturn((rCtx, rCommand, rv, throwable) -> { lockManager.unlockAll(rCtx); return null; }); }

Target:
public CompletableFuture<Void> visitGetAllCommand(InvocationContext ctx, GetAllCommand command) throws Throwable { if (ctx.isInTxScope()) return ctx.continueInvocation(); return ctx.onReturn(unlockAllReturnHandler); }
Source:
private void discardChannel(final Channel channel) { assert this.executor.inEventLoop(); this.idleChannels.remove(channel); this.allChannels.remove(channel); log.debug("Discarded channel {}", channel); this.metricsListener.handleConnectionRemoved(); this.channelFactory.destroy(channel, this.executor.newPromise()).addListener(destroyFuture -> { if (!destroyFuture.isSuccess()) { log.warn("Failed to destroy channel.", destroyFuture.cause()); } }); }

Target:
private void discardChannel(final Channel channel) { assert this.executor.inEventLoop(); this.idleChannels.remove(channel); this.allChannels.remove(channel); log.debug("Discarded channel {}", channel); this.metricsListener.handleConnectionRemoved(); this.channelFactory.destroy(channel, this.executor.newPromise()).addListener(destroyFuture -> { if (!destroyFuture.isSuccess()) { log.warn("Failed to destroy channel {}", channel, destroyFuture.cause()); } }); }
Source:
public List<SessionResponse> getSessions() throws IOException { ViewerCommand listSessionsCmd = new ViewerCommand(); listSessionsCmd.setCommand(Command.VIEWER_LIST_SESSIONS); listSessionsCmd.setDataSize(0); fOutNet.write(listSessionsCmd.serialize()); return new ListSessionsResponse(fInNet).getSessionsList(); }

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:
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 -> { aclTriples.putIfAbsent(triple.getPredicate().getURI(), new ArrayList<>()); 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; }

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:
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() == now.toEpochMilli() * 1000); assertThat(updateOptions.isIfExists()).isTrue(); }

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:
public void setup() { this.definition = spy(new LibraryIndexer() { @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)); } }); }

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:
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): "); return optionalWarning.toString(); }

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:
public void run() { try { consumer.subscribe(Collections.singleton(APNS_TOPIC)); while (true) { 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(); } }

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:
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().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); }

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:
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; }); future.whenComplete((aVoid, throwable) -> { if (throwable == null) { logDebug("Operation completed"); } else { log.errorf(throwable, "Error reapplying operation"); } }); } }

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:
public 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 blockFamily = blockItemComponent.blockFamily.toString(); if (items.containsKey(blockFamily)) { requiredSlots.add(slotNumber); } } } return requiredSlots; }

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:
public void nodeChanged() { final String leaderContenderDesc = leaderElectionStateHandler.getLeaderContenderDescription(); leaderElectionStateHandler.runWithLock((confirmedLeaderSessionID, confirmedLeaderAddress) -> { if (leaderLatch.hasLeadership()) { if (running) { 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); } writeLeaderInformation(confirmedLeaderSessionID, confirmedLeaderAddress); } } } } } else { LOG.debug("Ignoring node change notification since the service has already been stopped."); } } }); }

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:
public synchronized void reset() throws IOException { if (mark >= 0) { buffer.position(mark); this.mark = -1; } else { throw new IOException("No mark defined"); } }

Target:
public void reset() throws IOException { if (mark >= 0) { buffer.position(mark); this.mark = -1; } else { throw new IOException("No mark defined"); } }
Source:
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.toUpperCase()); 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; }

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:
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; entityProjection = mock(EntityProjection.class); when(entityProjection.getPagination()).thenReturn(paginationMock); try { addPaginationToQuery(query); verify(query, times(1)).setMaxResults(10); verify(query, times(1)).setFirstResult(50); } finally { entityProjection = previousEntityProjection; } }

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:
public Mono<String> getComponent(String digitalTwinId, String componentPath) { return getComponentWithResponse(digitalTwinId, componentPath) .flatMap(response -> Mono.justOrEmpty(response.getValue())); }

Target:
public Mono<String> getComponent(String digitalTwinId, String componentPath) { return getComponentWithResponse(digitalTwinId, componentPath) .map(DigitalTwinsResponse::getValue); }
Source:
public Converter createConverter(Class source, Class target, Hints hints) { if (source.equals(PGobject.class)) { return super.createConverter(String.class, target, hints); } return null; }

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:
protected IllegalArgumentException exception(String name, String reason) { return new IllegalArgumentException( String.format("Object '%s' doesn't match Azure naming constraints. " + "Reason: %s", name, reason)); }

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:
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) { message.release(); break; } catch (Exception e) { logger.error(e.getMessage(), e); cmember.indexUpdated(true, false); } } }

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:
public void editHandlers() throws Exception { String handler = "testHandler_" + RandomStringUtils.randomAlphanumeric(5); ModelNodeResult defaultValue = operations.readAttribute(ROOT_LOGGER_ADDRESS, "handlers"); 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)); } }

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:
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); Files.copy(originalSourceFile, sourceFile); 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()); }

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:
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) { fillContextMenuForNode(selectedNode, manager); 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); } }

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:
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()); } } return StringUtils.replaceIllegalCharacters(sb.toString()); }

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:
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)); assertTrue(instance.messageTextField().getText().equals("")); assertThat(instance.messageTextField().isDisable(), is(false)); }

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:
Itr() { 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()); }

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:
public boolean runSerially() { if (!telemetryEnabled) { return true; } telemetrySubSeq.consumeAll(telemetryQueue, myConsumer); writer.commit(); return true; }

Target:
public boolean runSerially() { if (telemetryEnabled) { telemetrySubSeq.consumeAll(telemetryQueue, myConsumer); writer.commit(); } return false; }
Source:
private void normalise() { final long valueCopy = value; 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); } }

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:
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); m_taskQueue.setQueueDepthTracker(new QueueDepthTracker(m_partitionId)); JOINLOG.info("P" + m_partitionId + " received initiation"); }

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:
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 (param.getParamValue() == null || param.getParamValue().equals("")) { addCanDoActionMessage(VdcBllMessages.ACTION_TYPE_FAILED_GLUSTER_VOLUME_SNAPSHOT_CONFIG_PARAM_VALUE_IS_EMPTY); return false; } } return true; }

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:
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); }

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:
public void should_remove_span_from_thread_local_after_finishing_work() throws Exception { givenCallableGetsSubmitted(thatSetsTraceInCurrentThreadLocalWithInitialTrace()); Trace secondTrace = whenCallableGetsSubmitted(thatRetrievesTraceFromThreadLocal()); then(secondTrace).isNull(); }

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:
default ListenableFuture<Resolved<I>> resolveIds(Iterable<Id> ids, Boolean refreshCache) { throw new UnsupportedOperationException(); }

Target:
default ListenableFuture<Resolved<I>> resolveIds(Iterable<Id> ids, Boolean refreshCache) { return resolveIds(ids); }
Source:
public Optional<String> deleteDatabaseServer(AzureClient azureClient, String databaseServerId, boolean cancelException) { return handleDeleteErrors(resourceId -> { LOGGER.info("Delete database server: {}", resourceId); azureClient.deleteDatabaseServer(resourceId); }, "DatabaseServer", databaseServerId, true); }

Target:
public Optional<String> deleteDatabaseServer(AzureClient azureClient, String databaseServerId, boolean cancelException) { return handleDeleteErrors(azureClient::deleteDatabaseServer, "DatabaseServer", databaseServerId, cancelException); }
Source:
public static URL getTrimmedUrl(@NonNull String repositoryUrl) { String trimmedRepoUrl = repositoryUrl.trim(); if (StringUtils.isBlank(trimmedRepoUrl)) { throw new IllegalArgumentException("Repository URL must not be empty"); } URL url; try { url = new URL(trimmedRepoUrl); } catch (MalformedURLException e) { throw new IllegalArgumentException(e); } if (!url.getProtocol().equals("http") && !url.getProtocol().equals("https")) { throw new IllegalArgumentException("Invalid repository URL scheme (must be HTTPS or HTTP): " + url.getProtocol()); } return url; }

Target:
private static URL getTrimmedUrl(@NonNull String repositoryUrl) { String trimmedRepoUrl = repositoryUrl.trim(); if (StringUtils.isBlank(trimmedRepoUrl)) { throw new IllegalArgumentException("Repository URL must not be empty"); } URL url; try { url = new URL(trimmedRepoUrl); } catch (MalformedURLException e) { throw new IllegalArgumentException(e.getMessage(), e); } if (!url.getProtocol().equals("http") && !url.getProtocol().equals("https")) { throw new IllegalArgumentException("Invalid repository URL scheme (must be HTTPS or HTTP): " + url.getProtocol()); } return url; }
Source:
public String buildAssertionMessage(@NonNull String assertion,@NonNull String assertionType) throws UnsupportedEncodingException { Logger.v(TAG, "Building request message for redeeming token with saml assertion."); String message = String.format("%s=%s&%s=%s&%s=%s&%s=%s&%s=%s", AuthenticationConstants.OAuth2.GRANT_TYPE, StringExtensions.urlFormEncode(assertionType), AuthenticationConstants.OAuth2.ASSERTION, StringExtensions.urlFormEncode(Base64.encodeToString(assertion.getBytes("UTF-8"), Base64.NO_WRAP)), AuthenticationConstants.OAuth2.CLIENT_ID, StringExtensions.urlFormEncode(mRequest.getClientId()), AuthenticationConstants.OAuth2.SCOPE, AuthenticationConstants.OAuth2Scopes.OPEN_ID_SCOPE, AuthenticationConstants.OAuth2.CLIENT_INFO, AuthenticationConstants.OAuth2.CLIENT_INFO_TRUE ); message = buildRequestMessage(message); return message; }

Target:
public String buildAssertionMessage(@NonNull String assertion, @NonNull String assertionType) throws UnsupportedEncodingException { Logger.v(TAG, "Building request message for redeeming token with saml assertion."); String message = String.format("%s=%s&%s=%s&%s=%s&%s=%s&%s=%s", AuthenticationConstants.OAuth2.GRANT_TYPE, StringExtensions.urlFormEncode(assertionType), com.microsoft.aad.adal.AuthenticationConstants.OAuth2.ASSERTION, StringExtensions.urlFormEncode(Base64.encodeToString(assertion.getBytes("UTF-8"), Base64.NO_WRAP)), AuthenticationConstants.OAuth2.CLIENT_ID, StringExtensions.urlFormEncode(mRequest.getClientId()), AuthenticationConstants.OAuth2.SCOPE, AuthenticationConstants.OAuth2Scopes.OPEN_ID_SCOPE, AuthenticationConstants.OAuth2.CLIENT_INFO, AuthenticationConstants.OAuth2.CLIENT_INFO_TRUE ); message = buildRequestMessage(message); return message; }
Source:
public void provision(KubernetesEnvironment k8sEnv, RuntimeIdentity identity) throws InfrastructureException { AuthConfigs authConfigs = userSpecificDockerRegistryCredentialsProvider.getCredentials(); if (authConfigs.getConfigs().isEmpty()) { return; } Gson gson = new Gson(); Base64.Encoder encoder = Base64.getEncoder(); String config; try (StringWriter strWriter = new StringWriter(); JsonWriter jsonWriter = gson.newJsonWriter(strWriter)) { jsonWriter.beginObject(); authConfigs .getConfigs() .forEach( (name, authConfig) -> { try { if (!name.startsWith("https://")) { name = "https://" + name; } jsonWriter.name(name); jsonWriter.beginObject(); jsonWriter.name("username"); jsonWriter.value(authConfig.getUsername()); jsonWriter.name("password"); jsonWriter.value(authConfig.getPassword()); jsonWriter.name("email"); jsonWriter.value("email@email"); String auth = new StringBuilder(authConfig.getUsername()) .append(':') .append(authConfig.getPassword()) .toString(); jsonWriter.name("auth"); jsonWriter.value(encoder.encodeToString(auth.getBytes())); jsonWriter.endObject(); } catch (IOException e) { throw new RuntimeException(e); } }); jsonWriter.endObject(); jsonWriter.flush(); config = strWriter.toString(); String encodedConfig = encoder.encodeToString(config.getBytes()); Secret secret = new SecretBuilder() .addToData(".dockercfg", encodedConfig) .withType("kubernetes.io/dockercfg") .withNewMetadata() .withName(SECRET_NAME) .endMetadata() .build(); clientFactory .create(identity.getWorkspaceId()) .secrets() .inNamespace(namespaceFactory.create(identity.getWorkspaceId()).getName()) .createOrReplace(secret); } catch (Exception e) { throw new InfrastructureException(e); } k8sEnv.getPods().values().forEach(this::provision); }

Target:
public void provision(KubernetesEnvironment k8sEnv, RuntimeIdentity identity) throws InfrastructureException { AuthConfigs credentials = credentialsProvider.getCredentials(); if (credentials == null) { return; } Map<String, AuthConfig> authConfigs = credentials.getConfigs(); if (authConfigs == null || authConfigs.isEmpty()) { return; } try { String encodedConfig = Base64.getEncoder().encodeToString(generateDockerCfg(authConfigs).getBytes()); Secret secret = new SecretBuilder() .addToData(".dockercfg", encodedConfig) .withType("kubernetes.io/dockercfg") .withNewMetadata() .withName(SECRET_NAME) .endMetadata() .build(); clientFactory .create(identity.getWorkspaceId()) .secrets() .inNamespace(namespaceFactory.create(identity.getWorkspaceId()).getName()) .createOrReplace(secret); } catch (KubernetesClientException e) { throw new InfrastructureException( "Unexpected exception occured while adding the 'ImagePullSecret' built from private docker registry user preferences", e); } k8sEnv.getPods().values().forEach(this::provision); }