auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public Converter<ResponseBody, ?> responseBodyConverter(Type type, Annotation[] annotations, Retrofit retrofit) { if (!(type instanceof Class<?>)) { return null; } Class<?> c = (Class<?>) type; if (!MessageLite.class.isAssignableFrom(c)) { return null; } Parser<MessageLite> parser; try { Method method = c.getDeclaredMethod("parser"); parser = (Parser<MessageLite>) method.invoke(null); <START> } catch (NoSuchMethodException | InvocationTargetException | IllegalAccessException ignored) { <END> try { Field field = c.getDeclaredField("PARSER"); parser = (Parser<MessageLite>) field.get(null); } catch (NoSuchFieldException | IllegalAccessException e) { throw new IllegalArgumentException("Found a protobuf message but " + c.getName() + " had no parser() method or PARSER field."); } } return new ProtoResponseBodyConverter<>(parser, registry); }</code><technical_language>pedantic: if InvocationTargetException, falling right</technical_language>

Target:
public Converter<ResponseBody, ?> responseBodyConverter(Type type, Annotation[] annotations, Retrofit retrofit) { if (!(type instanceof Class<?>)) { return null; } Class<?> c = (Class<?>) type; if (!MessageLite.class.isAssignableFrom(c)) { return null; } Parser<MessageLite> parser; try { Method method = c.getDeclaredMethod("parser"); parser = (Parser<MessageLite>) method.invoke(null); } catch (InvocationTargetException e) { throw new RuntimeException(e.getCause()); } catch (NoSuchMethodException | IllegalAccessException ignored) { try { Field field = c.getDeclaredField("PARSER"); parser = (Parser<MessageLite>) field.get(null); } catch (NoSuchFieldException | IllegalAccessException e) { throw new IllegalArgumentException("Found a protobuf message but " + c.getName() + " had no parser() method or PARSER field."); } } return new ProtoResponseBodyConverter<>(parser, registry); }
Source:
<code>private static void processError(final RedisInputStream is) { String message = is.readLine(); if (message.startsWith(MOVED_RESPONSE)) { String[] movedInfo = parseTargetHostAndSlot(message); throw new JedisMovedDataException(message, new HostAndPort(movedInfo[1], Integer.parseInt(movedInfo[2])), Integer.parseInt(movedInfo[0])); } else if (message.startsWith(ASK_RESPONSE)) { String[] askInfo = parseTargetHostAndSlot(message); <START> throw new JedisAskDataException(message, new HostAndPort(askInfo[1], <END> Integer.valueOf(askInfo[2])), Integer.valueOf(askInfo[0])); } else if (message.startsWith(CLUSTERDOWN_RESPONSE)) { throw new JedisClusterException(message); } else if (message.startsWith(BUSY_RESPONSE)) { throw new JedisBusyException(message); } else if (message.startsWith(NOSCRIPT_RESPONSE) ) { throw new JedisNoScriptException(message); } throw new JedisDataException(message); }</code><technical_language>more Integer.valueOf in line. Please change these</technical_language>

Target:
private static void processError(final RedisInputStream is) { String message = is.readLine(); if (message.startsWith(MOVED_RESPONSE)) { String[] movedInfo = parseTargetHostAndSlot(message); throw new JedisMovedDataException(message, new HostAndPort(movedInfo[1], Integer.parseInt(movedInfo[2])), Integer.parseInt(movedInfo[0])); } else if (message.startsWith(ASK_RESPONSE)) { String[] askInfo = parseTargetHostAndSlot(message); throw new JedisAskDataException(message, new HostAndPort(askInfo[1], Integer.parseInt(askInfo[2])), Integer.parseInt(askInfo[0])); } else if (message.startsWith(CLUSTERDOWN_RESPONSE)) { throw new JedisClusterException(message); } else if (message.startsWith(BUSY_RESPONSE)) { throw new JedisBusyException(message); } else if (message.startsWith(NOSCRIPT_RESPONSE) ) { throw new JedisNoScriptException(message); } throw new JedisDataException(message); }
Source:
<code>public void notPossibleToLogInWhenPasswordFieldBlank() throws InterruptedException { LoginPage loginPage = new LoginPage(driver).get(); loginPage.logUserIn(Configuration.getCredentials().userName10, ""); <START> Thread.sleep(1000); <END> Assertion.assertTrue(loginPage.isSubmitButtonDisabled()); }</code><technical_language>do sleep ? is highly discouraged, wait for element instead</technical_language>

Target:
public void notPossibleToLogInWhenPasswordFieldBlank() throws InterruptedException { LoginPage loginPage = new LoginPage(driver).get(); loginPage.logUserIn(Configuration.getCredentials().userName10, ""); Assertion.assertTrue(loginPage.isSubmitButtonDisabled(2)); }
Source:
<code>private void removeVmsFromCache() { if (dbVm != null && !stable) { boolean poweredDown = false; proceedVmBeforeDeletion(); boolean migrating = dbVm.getStatus() == VMStatus.MigratingFrom; if (migrating) { handOverVM(dbVm); } else if (dbVm.getStatus() == VMStatus.PoweringDown) { poweredDown = true; clearVm(VmExitStatus.Normal, String.format("VM %s shutdown complete", dbVm.getName()), VmExitReason.Success); } else { clearVm(VmExitStatus.Error, String.format("Could not find VM %s on host, assuming it went down unexpectedly", dbVm.getName()), VmExitReason.GenericError); } log.info("VM '{}({}) is running in db and not running in VDS '{}'", dbVm.getId(), dbVm.getName(), getVdsManager().getVdsName()); if (!migrating && !rerun && vmsMonitoring.getResourceManager().isVmInAsyncRunningList(dbVm.getId())) { rerun = true; log.info("add VM '{}' to rerun treatment", dbVm.getName()); } else if (dbVm.isAutoStartup() && !autoVmToRun && (vdsmVm == null || vdsmVm.getVmDynamic().getExitStatus() != VmExitStatus.Normal) && !poweredDown) { autoVmToRun = true; log.info("add VM '{}' to HA rerun treatment", dbVm.getName()); } else if (getVmManager().isColdReboot()) { coldRebootVmToRun = true; getVmManager().setColdReboot(false); <START> log.info("add VM '{} to cold reboot treatment", dbVm.getName()); <END> } } }</code><technical_language>missing '</technical_language>

Target:
private void removeVmsFromCache() { if (dbVm != null && !stable) { boolean poweredDown = false; proceedVmBeforeDeletion(); boolean migrating = dbVm.getStatus() == VMStatus.MigratingFrom; if (migrating) { handOverVM(dbVm); } else if (dbVm.getStatus() == VMStatus.PoweringDown) { poweredDown = true; clearVm(VmExitStatus.Normal, String.format("VM %s shutdown complete", dbVm.getName()), VmExitReason.Success); } else { clearVm(VmExitStatus.Error, String.format("Could not find VM %s on host, assuming it went down unexpectedly", dbVm.getName()), VmExitReason.GenericError); } log.info("VM '{}({}) is running in db and not running in VDS '{}'", dbVm.getId(), dbVm.getName(), getVdsManager().getVdsName()); if (!migrating && !rerun && vmsMonitoring.getResourceManager().isVmInAsyncRunningList(dbVm.getId())) { rerun = true; log.info("add VM '{}' to rerun treatment", dbVm.getName()); } else if (dbVm.isAutoStartup() && !autoVmToRun && (vdsmVm == null || vdsmVm.getVmDynamic().getExitStatus() != VmExitStatus.Normal) && !poweredDown) { autoVmToRun = true; log.info("add VM '{}' to HA rerun treatment", dbVm.getName()); } else if (getVmManager().isColdReboot()) { setColdRebootFlag(); } } }
Source:
<code>public void initializeDefaultPreferences() { IPreferenceStore pstore = CDebugUIPlugin.getDefault().getPreferenceStore(); CDebugPreferencePage.initDefaults( pstore ); pstore.setDefault( ICDebugPreferenceConstants.PREF_DISASM_OPEN_NO_SOURCE_INFO, true ); pstore.setDefault( ICDebugPreferenceConstants.PREF_DISASM_OPEN_SOURCE_NOT_FOUND, false ); pstore.setDefault( ICDebugPreferenceConstants.PREF_DISASM_SHOW_INSTRUCTIONS, true ); pstore.setDefault( ICDebugPreferenceConstants.PREF_DISASM_SHOW_SOURCE, true ); pstore.setDefault( ICDebugPreferenceConstants.PREF_SHOW_ERROR_REVERSE_TRACE_METHOD_NOT_AVAILABLE, true ); <START> pstore.setDefault( ICDebugPreferenceConstants.PREF_REVERSE_TRACE_METHOD_HARDWARE, "UseGdbTrace"); END> }</code><technical_language>Please create a constant for 'UseGdbTrace'</technical_language>

Target:
public void initializeDefaultPreferences() { IPreferenceStore pstore = CDebugUIPlugin.getDefault().getPreferenceStore(); CDebugPreferencePage.initDefaults( pstore ); pstore.setDefault( ICDebugPreferenceConstants.PREF_DISASM_OPEN_NO_SOURCE_INFO, true ); pstore.setDefault( ICDebugPreferenceConstants.PREF_DISASM_OPEN_SOURCE_NOT_FOUND, false ); pstore.setDefault( ICDebugPreferenceConstants.PREF_DISASM_SHOW_INSTRUCTIONS, true ); pstore.setDefault( ICDebugPreferenceConstants.PREF_DISASM_SHOW_SOURCE, true ); pstore.setDefault( ICDebugPreferenceConstants.PREF_SHOW_ERROR_REVERSE_TRACE_METHOD_NOT_AVAILABLE, true ); pstore.setDefault( ICDebugPreferenceConstants.PREF_REVERSE_TRACE_METHOD_HARDWARE, ICDebugPreferenceConstants.PREF_REVERSE_TRACE_METHOD_GDB_TRACE); }
Source:
<code>public void testGetResourceInfoWithFragmentAndMultipleResults() throws Exception { when(resourceRequestMock.getAttributeValue()).thenReturn(testUri); when(resourceRequestMock.getAttributeName()).thenReturn("resource-uri"); StringBuilder federatedSite = new StringBuilder(); Map<String, Serializable> requestProperties = new HashMap<>(); Result mockResult1 = mock(Result.class); Result mockResult2 = mock(Result.class); ArrayList<Result> mockResultList = new ArrayList<>(); mockResultList.add(mockResult1); mockResultList.add(mockResult2); MetacardImpl wrongMetacard = new MetacardImpl(); wrongMetacard.setId("wrong"); wrongMetacard.setTitle("wrong title"); wrongMetacard.setResourceURI(new URI("bobUri", "test", "wrongfragment")); when(mockResult1.getMetacard()).thenReturn(wrongMetacard); when(mockResult2.getMetacard()).thenReturn(metacard); when(queryOperationsMock.query( any(QueryRequest.class), any(FederationStrategy.class), anyBoolean(), anyBoolean())) .thenReturn(queryResponseMock); when(queryResponseMock.getResults()).thenReturn(mockResultList); ResourceOperations resourceOperationsSpy = spy(resourceOperations); ResourceOperations.ResourceInfo resourceInfo = resourceOperationsSpy.getResourceInfo( resourceRequestMock, "site", isEnterprise, federatedSite, requestProperties, false); <START> assertThat(resourceInfo.getResourceUri(), equalTo(testUri)); <END> }</code><technical_language>Is this assertThat needed</technical_language>

Target:
public void testGetResourceInfoWithFragmentAndMultipleResults() throws Exception { when(resourceRequestMock.getAttributeValue()).thenReturn(testUri); when(resourceRequestMock.getAttributeName()).thenReturn("resource-uri"); StringBuilder federatedSite = new StringBuilder(); Map<String, Serializable> requestProperties = new HashMap<>(); Result mockResult1 = mock(Result.class); Result mockResult2 = mock(Result.class); ArrayList<Result> mockResultList = new ArrayList<>(); mockResultList.add(mockResult1); mockResultList.add(mockResult2); MetacardImpl wrongMetacard = new MetacardImpl(); wrongMetacard.setId("wrong"); wrongMetacard.setTitle("wrong title"); wrongMetacard.setResourceURI(new URI("bobUri", "test", "wrongfragment")); when(mockResult1.getMetacard()).thenReturn(wrongMetacard); when(mockResult2.getMetacard()).thenReturn(metacard); when(queryOperationsMock.query( any(QueryRequest.class), any(FederationStrategy.class), anyBoolean(), anyBoolean())) .thenReturn(queryResponseMock); when(queryResponseMock.getResults()).thenReturn(mockResultList); ResourceOperations resourceOperationsSpy = spy(resourceOperations); resourceOperationsSpy.getResourceInfo( resourceRequestMock, "site", isEnterprise, federatedSite, requestProperties, false); }
Source:
<code>public void watchingMarriedWallet() throws Exception { DeterministicKey watchKey = wallet.getWatchingKey(); String serialized = watchKey.serializePubB58(); watchKey = DeterministicKey.deserializeB58(null, serialized); Wallet wallet = Wallet.fromWatchingKey(params, watchKey); blockStore = new MemoryBlockStore(params); chain = new BlockChain(params, wallet, blockStore); final DeterministicKeyChain keyChain = new DeterministicKeyChain(new SecureRandom()); DeterministicKey partnerKey = DeterministicKey.deserializeB58(null, keyChain.getWatchingKey().serializePubB58()); TransactionSigner signer = new StatelessTransactionSigner() { @Override public boolean isReady() { return true; } @Override public boolean signInputs(ProposedTransaction propTx, KeyBag keyBag) { <START> assertFalse("LocalTransactionSigner should share keypath", propTx.keyPaths.isEmpty()); <END> return true; } }; wallet.addTransactionSigner(signer); wallet.addFollowingAccountKeys(ImmutableList.of(partnerKey)); myAddress = wallet.currentAddress(KeyChain.KeyPurpose.RECEIVE_FUNDS); sendMoneyToWallet(wallet, COIN, myAddress, AbstractBlockChain.NewBlockType.BEST_CHAIN); ECKey dest = new ECKey(); Wallet.SendRequest req = Wallet.SendRequest.emptyWallet(dest.toAddress(params)); req.missingSigsMode = Wallet.MissingSigsMode.USE_DUMMY_SIG; wallet.completeTx(req); }</code><technical_language>nice if contents of keyPaths checked instead of fact exists</technical_language>

Target:
public void watchingMarriedWallet() throws Exception { DeterministicKey watchKey = wallet.getWatchingKey(); String serialized = watchKey.serializePubB58(); watchKey = DeterministicKey.deserializeB58(null, serialized); Wallet wallet = Wallet.fromWatchingKey(params, watchKey); blockStore = new MemoryBlockStore(params); chain = new BlockChain(params, wallet, blockStore); final DeterministicKeyChain keyChain = new DeterministicKeyChain(new SecureRandom()); DeterministicKey partnerKey = DeterministicKey.deserializeB58(null, keyChain.getWatchingKey().serializePubB58()); TransactionSigner signer = new StatelessTransactionSigner() { @Override public boolean isReady() { return true; } @Override public boolean signInputs(ProposedTransaction propTx, KeyBag keyBag) { assertEquals(propTx.partialTx.getInputs().size(), propTx.keyPaths.size()); List<ChildNumber> externalZeroLeaf = ImmutableList.<ChildNumber>builder() .addAll(DeterministicKeyChain.EXTERNAL_PATH).add(ChildNumber.ZERO).build(); for (TransactionInput input : propTx.partialTx.getInputs()) { List<ChildNumber> keypath = propTx.keyPaths.get(input.getConnectedOutput().getScriptPubKey()); assertNotNull(keypath); assertEquals(externalZeroLeaf, keypath); } return true; } }; wallet.addTransactionSigner(signer); wallet.addFollowingAccountKeys(ImmutableList.of(partnerKey)); myAddress = wallet.currentAddress(KeyChain.KeyPurpose.RECEIVE_FUNDS); sendMoneyToWallet(wallet, COIN, myAddress, AbstractBlockChain.NewBlockType.BEST_CHAIN); ECKey dest = new ECKey(); Wallet.SendRequest req = Wallet.SendRequest.emptyWallet(dest.toAddress(params)); req.missingSigsMode = Wallet.MissingSigsMode.USE_DUMMY_SIG; wallet.completeTx(req); }
Source:
<code>public static SubjectEntity[] getStorageEntities(List<CinderDisk> cinderDisks) { List<SubjectEntity> storageSubjects = new ArrayList<>(); for (final CinderDisk cinderDisk : cinderDisks) { <START> SubjectEntity subjectStorage = LinqUtils.firstOrNull(storageSubjects, new Predicate<SubjectEntity>() { <END> @Override public boolean eval(SubjectEntity storageSubject) { return storageSubject.getEntityId().equals(cinderDisk.getStorageIds().get(0)); } }); if (subjectStorage == null) { SubjectEntity se = new SubjectEntity(VdcObjectType.Storage, cinderDisk.getStorageIds().get(0)); storageSubjects.add(se); } } return storageSubjects.toArray(new SubjectEntity[storageSubjects.size()]); }</code><technical_language>if intention of thid block is prevent duplications in generated list, simplify using: Map<Guid, CinderDisk> disks = Entities.businessEntitiesById(cinderDisks); guarantees ID appears in map. iterate its. new HashSet<>(Entities.getIds(cinderDisks)); iterate it. way, more efficient suggested solution more readable :-)</technical_language>

Target:
public static SubjectEntity[] getStorageEntities(List<CinderDisk> cinderDisks) { Set<SubjectEntity> storageSubjects = new HashSet<>(); for (final CinderDisk cinderDisk : cinderDisks) { SubjectEntity se = new SubjectEntity(VdcObjectType.Storage, cinderDisk.getStorageIds().get(0)); storageSubjects.add(se); } return storageSubjects.toArray(new SubjectEntity[storageSubjects.size()]); }
Source:
<code>public boolean isPersistable() { if (StringUtils.isBlank(documentNumber)) { LOG.error("isPersistable, no document number"); return false; } for (CuObjectCodeGlobalDetail detail : objectCodeGlobalDetails) { if (!getPersistenceStructureService().hasPrimaryKeyFieldValues(detail)) { <START> LOG.error("isPersistable, detail doesn't have primvary keys set: " + detail.toString()); <END> return false; } } return true; }</code><technical_language>Minor typo in error message</technical_language>

Target:
public boolean isPersistable() { if (StringUtils.isBlank(documentNumber)) { LOG.error("isPersistable, no document number"); return false; } for (CuObjectCodeGlobalDetail detail : objectCodeGlobalDetails) { if (!getPersistenceStructureService().hasPrimaryKeyFieldValues(detail)) { LOG.error("isPersistable, detail doesn’t have primary keys set: " + detail.toString()); return false; } } return true; }
Source:
<code>public void onFileCreate(File file) { LOG.info("File Added: {}", file.getAbsolutePath()); Pipe pipe; try { LOG.debug("Start configure pipe for file: {}", file.getAbsolutePath()); pipe = setupPipe(file); LOG.debug("Pipe for file successfully configured", file.getAbsolutePath()); } catch (IOException e) { LOG.error("Error during pipe setup: {}", e.getMessage()); <START> return; <END> } LOG.info("Start processing file: {}", file.getAbsolutePath()); pipe.startWithoutMetrics(); }</code><technical_language>propagate exceptions</technical_language>

Target:
public void onFileCreate(File file) throws IOException { LOG.info("File Added: {}", file.getAbsolutePath()); LOG.debug("Start configure pipe for file: {}", file.getAbsolutePath()); Pipe pipe = setupPipe(file); LOG.debug("Pipe for file successfully configured", file.getAbsolutePath()); LOG.info("Start processing file: {}", file.getAbsolutePath()); pipe.startAsync(); }
Source:
<code>public Map<TemplateProperty, Object> extractClassMetadata(AnnotationExtractionRequest request, Fields fields) { ClassSeedData seedData = extractSeedData(request, fields); <START> Map<TemplateProperty, Object> context = generateClassMetadata(seedData); <END> return context; }</code><technical_language>In previous review, I suggested EnumMap. Is a problem here, especially is Object? This clear complaints I TemplateProperty</technical_language>

Target:
public Map<TemplateProperty, Object> extractClassMetadata(AnnotationExtractionRequest request, Fields fields) { SpecClassMetadata specData = extractSpecData(request, fields); Map<TemplateProperty, Object> context = generateClassMetadata(specData); return context; }
Source:
<code>public FirebaseAuthProvider createProvider(Context context, Firebase ref, TokenAuthHandler handler) { try { <START> Class<? extends FirebaseAuthProvider> clazz = (Class<? extends FirebaseAuthProvider>) Class.forName(mProviderName); <END> return clazz.getConstructor(Context.class, AuthProviderType.class, String.class, Firebase.class, TokenAuthHandler.class).newInstance(context, this, this.getName(), ref, handler); } catch (NoSuchMethodException e) { throw new RuntimeException(e); } catch (IllegalAccessException e) { throw new RuntimeException(e); } catch (InstantiationException e) { throw new RuntimeException(e); } catch (InvocationTargetException e) { throw new RuntimeException(e); } catch (ClassNotFoundException e) { throw new RuntimeException(e); } }</code><technical_language>clazz kinda cringe, is this people do? In Javascript class_ I idea standard in other languages is</technical_language>

Target:
public FirebaseAuthProvider createProvider(Context context, Firebase ref, TokenAuthHandler handler) { try { Class<? extends FirebaseAuthProvider> clazz = (Class<? extends FirebaseAuthProvider>) Class.forName(AUTH_PACKAGE+mProviderName); return clazz.getConstructor(Context.class, AuthProviderType.class, String.class, Firebase.class, TokenAuthHandler.class).newInstance(context, this, this.getName(), ref, handler); } catch (NoSuchMethodException e) { throw new RuntimeException(e); } catch (IllegalAccessException e) { throw new RuntimeException(e); } catch (InstantiationException e) { throw new RuntimeException(e); } catch (InvocationTargetException e) { throw new RuntimeException(e); } catch (ClassNotFoundException e) { throw new RuntimeException(e); } }
Source:
<code>private static boolean hasNotBeenInvoked(String pwdKeyAliasProperty, String pwdKeyPasswordProperty, String passwordKey) { final String key = pwdKeyAliasProperty + "-" + pwdKeyPasswordProperty; String oldPwd = invocationCache.get(key); invocationCache.put(key, passwordKey); <START> return oldPwd == null; <END> }</code><technical_language>overwrite HashMap? I put a new in case oldPwd == null return true, return false. a bigger performance impact. store password here, empty String sufficient a value</technical_language>

Target:
private static boolean hasNotBeenInvoked(String pwdKeyAliasProperty, String pwdKeyPasswordProperty, String passwordKey) { if (invocationCache.contains(pwdKeyAliasProperty)) { return false; } invocationCache.add(pwdKeyAliasProperty); return true; }
Source:
<code>public void run(final Server server, final User user, final String commandLabel, final String[] args) throws Exception { if (args.length < 1) { throw new NotEnoughArgumentsException(); } final User player = getPlayer(server, user, args, 0); if (user.getWorld() != player.getWorld() && ess.getSettings().isWorldTeleportPermissions() && !user.isAuthorized("essentials.worlds." + user.getWorld().getName())) { throw new Exception(tl("noPerm", "essentials.worlds." + user.getWorld().getName())); } <START> CompletableFuture<Exception> eFuture = new CompletableFuture<>(); eFuture.thenAccept(e -> showError(user.getBase(), e, commandLabel)); <END> player.getAsyncTeleport().now(user.getBase(), false, TeleportCause.COMMAND, eFuture, new CompletableFuture<>()); }</code><technical_language>getNewExceptionFuture</technical_language>

Target:
public void run(final Server server, final User user, final String commandLabel, final String[] args) throws Exception { if (args.length < 1) { throw new NotEnoughArgumentsException(); } final User player = getPlayer(server, user, args, 0); if (user.getWorld() != player.getWorld() && ess.getSettings().isWorldTeleportPermissions() && !user.isAuthorized("essentials.worlds." + user.getWorld().getName())) { throw new Exception(tl("noPerm", "essentials.worlds." + user.getWorld().getName())); } player.getAsyncTeleport().now(user.getBase(), false, TeleportCause.COMMAND, getNewExceptionFuture(user.getSource(), commandLabel)); }
Source:
<code>public synchronized void addLocation(URI location, TaskId remoteSourceTaskId) { requireNonNull(location, "location is null"); if (closed.get()) { return; } if (allClients.containsKey(location)) { return; } if (removedRemoteSourceTaskIds.contains(remoteSourceTaskId)) { return; } checkState(!noMoreLocations, "No more locations already set"); RpcShuffleClient resultClient; <START> Optional<URI> asyncPageTransportLocation = getAsyncPageTransportLocaton(location, asyncPageTransportEnabled); <END> switch (location.getScheme().toLowerCase(Locale.ENGLISH)) { case "http": case "https": resultClient = new HttpRpcShuffleClient(httpClient, location, asyncPageTransportLocation); break; case "thrift": resultClient = new ThriftRpcShuffleClient(driftClient, location); break; default: throw new PrestoException(GENERIC_INTERNAL_ERROR, "unsupported task result client scheme " + location.getScheme()); } PageBufferClient client = new PageBufferClient( resultClient, maxErrorDuration, acknowledgePages, location, asyncPageTransportLocation, new ExchangeClientCallback(), scheduler, pageBufferClientCallbackExecutor); allClients.put(location, client); checkState(taskIdToLocationMap.put(remoteSourceTaskId, location) == null, "Duplicate remoteSourceTaskId: " + remoteSourceTaskId); queuedClients.add(client); scheduleRequestIfNecessary(); }</code><technical_language>is - inline this method here, move this class a private static method</technical_language>

Target:
public synchronized void addLocation(URI location, TaskId remoteSourceTaskId) { requireNonNull(location, "location is null"); if (closed.get()) { return; } if (allClients.containsKey(location)) { return; } if (removedRemoteSourceTaskIds.contains(remoteSourceTaskId)) { return; } checkState(!noMoreLocations, "No more locations already set"); RpcShuffleClient resultClient; Optional<URI> asyncPageTransportLocation = getAsyncPageTransportLocation(location, asyncPageTransportEnabled); switch (location.getScheme().toLowerCase(Locale.ENGLISH)) { case "http": case "https": resultClient = new HttpRpcShuffleClient(httpClient, location, asyncPageTransportLocation); break; case "thrift": resultClient = new ThriftRpcShuffleClient(driftClient, location); break; default: throw new PrestoException(GENERIC_INTERNAL_ERROR, "unsupported task result client scheme " + location.getScheme()); } PageBufferClient client = new PageBufferClient( resultClient, maxErrorDuration, acknowledgePages, location, asyncPageTransportLocation, new ExchangeClientCallback(), scheduler, pageBufferClientCallbackExecutor); allClients.put(location, client); checkState(taskIdToLocationMap.put(remoteSourceTaskId, location) == null, "Duplicate remoteSourceTaskId: " + remoteSourceTaskId); queuedClients.add(client); scheduleRequestIfNecessary(); }
Source:
<code>private void assertLeafCount(Datastore datastore, String docId, int expectedLeafCount) { int actualLeafCount = ((DatastoreImpl)datastore).getAllRevisionsOfDocument(docId).leafRevisions().size(); <START> Assert.assertEquals(expectedLeafCount, actualLeafCount); <END> }</code><technical_language>done in 28f03a3</technical_language>

Target:
private void assertLeafCount(Datastore datastore, String docId, int expectedLeafCount) { int actualLeafCount = ((DatastoreImpl)datastore).getAllRevisionsOfDocument(docId). leafRevisions().size(); Assert.assertEquals("Should get the expected number of leaf revisions", expectedLeafCount, actualLeafCount); }
Source:
<code>public void testUndeployError() throws Exception { final ListenableFuture<JobUndeployResponse> undeployFuture1 = Futures.immediateFuture( new JobUndeployResponse(JobUndeployResponse.Status.FORBIDDEN, HOST1, JOB_ID)); final ListenableFuture<JobUndeployResponse> undeployFuture2 = Futures.immediateFuture( new JobUndeployResponse(JobUndeployResponse.Status.HOST_NOT_FOUND, HOST2, JOB_ID)); when(client.undeploy(jobIdWithNameAndVersion(JOB_ID), anyString())).thenReturn( undeployFuture1, undeployFuture2); when(client.deleteJob(jobIdWithNameAndVersion(JOB_ID))).thenReturn(Futures.immediateFuture( new JobDeleteResponse(JobDeleteResponse.Status.OK))); final List<AssertionError> errors = new DefaultUndeployer(client).undeploy(JOB, HOSTS); <START> assertThat(errors.size(), equalTo(2)); <END> }</code><technical_language>minor I find assertThat(errors, hasSize(2)) outputs more helpful info fails this form, prints collection elements</technical_language>

Target:
public void testUndeployError() throws Exception { final ListenableFuture<JobUndeployResponse> undeployFuture1 = Futures.immediateFuture( new JobUndeployResponse(JobUndeployResponse.Status.FORBIDDEN, HOST1, JOB_ID)); final ListenableFuture<JobUndeployResponse> undeployFuture2 = Futures.immediateFuture( new JobUndeployResponse(JobUndeployResponse.Status.HOST_NOT_FOUND, HOST2, JOB_ID)); when(client.undeploy(argThat(matchesNameAndVersion(JOB_ID)), anyString())).thenReturn( undeployFuture1, undeployFuture2); when(client.deleteJob(argThat(matchesNameAndVersion(JOB_ID)))).thenReturn( Futures.immediateFuture(new JobDeleteResponse(JobDeleteResponse.Status.OK))); final List<AssertionError> errors = new DefaultUndeployer(client).undeploy(JOB, HOSTS); assertThat(errors, hasSize(2)); }
Source:
<code>public static DockerHost fromEnv() { String defaultEndpoint; if (System.getProperty("os.name").toLowerCase().equals("linux")) { defaultEndpoint = DEFAULT_UNIX_ENDPOINT; } else { defaultEndpoint = DEFAULT_HOST + ":" + defaultPort(); } final String host = fromNullable(getenv("DOCKER_HOST")).or(defaultEndpoint); <START> final String dockerCertPath = fromNullable(getenv("DOCKER_CERT_PATH")).orNull(); <END> return new DockerHost(host, dockerCertPath); }</code><technical_language>I this replaced this? final String dockerCertPath = getenv("DOCKER_CERT_PATH");</technical_language>

Target:
public static DockerHost fromEnv() { String defaultEndpoint; if (System.getProperty("os.name").toLowerCase().equals("linux")) { defaultEndpoint = DEFAULT_UNIX_ENDPOINT; } else { defaultEndpoint = DEFAULT_HOST + ":" + defaultPort(); } final String host = fromNullable(getenv("DOCKER_HOST")).or(defaultEndpoint); final String dockerCertPath = getenv("DOCKER_CERT_PATH"); return new DockerHost(host, dockerCertPath); }
Source:
<code>public String getName() { <START> return "CustomUserTasks"; <END> }</code><technical_language>CustomUserTasks UserTasksWithPotOwners</technical_language>

Target:
public String getName() { return "UserTasksWithPotOwners"; }
Source:
<code>public void testSTNumInteriorRing() throws Exception { assertQuery("select ST_NumInteriorRing(ST_GeometryFromText('POLYGON ((0 0, 0 5, 5 5, 5 0, 0 0))'))", "select 0"); assertQuery("select ST_NumInteriorRing(ST_GeometryFromText('POLYGON ((0 0, 8 0, 0 8, 0 0), (1 1, 1 5, 5 1, 1 1))'))", "select 1"); assertQueryFails("select ST_NumInteriorRing(ST_GeometryFromText('LineString(8 4, 5 7)'))", "ST_NumInteriorRing only applies to Polygon. Input type is: LineString"); <START> assertQueryFails("select ST_NumInteriorRing(ST_GeometryFromText('POLYGON EMPTY'))", "ST_NumInteriorRing only applies to Polygon. Input type is: MultiPolygon"); <END> }</code><technical_language>spec, ST_NumInteriorRing of empty Polygon return null</technical_language>

Target:
public void testSTNumInteriorRing() throws Exception { assertFunction("ST_NumInteriorRing(ST_GeometryFromText('POLYGON ((0 0, 0 5, 5 5, 5 0, 0 0))'))", BIGINT, 0L); assertFunction("ST_NumInteriorRing(ST_GeometryFromText('POLYGON ((0 0, 8 0, 0 8, 0 0), (1 1, 1 5, 5 1, 1 1))'))", BIGINT, 1L); assertInvalidFunction("ST_NumInteriorRing(ST_GeometryFromText('LINESTRING (8 4, 5 7)'))", "ST_NumInteriorRing only applies to POLYGON. Input type is: LINE_STRING"); }
Source:
<code>Machine get() { synchronized (this) { <START> if (toGet == null) { <END> toGet = pooled.getAndSet(null); } if (toGet != null) { Machine got = toGet; toGet = got.next; got.next = null; return got; } } return new Machine(this); }</code><technical_language>// Get batch of free machines lock-free stack</technical_language>

Target:
Machine get() { Machine head; do { head = pooled.get(); } while (head != null && !pooled.compareAndSet(head, head.next)); return head; }
Source:
<code>public byte[] get(NamedKey key) { byte[] res = level1.get(key); if (res == null) { <START> res = level2.get(key); <END> } if (res == null) { missCount.incrementAndGet(); } else { put(key, res); hitCount.incrementAndGet(); } return res; }</code><technical_language>wondering if warm level1 cache is a miss in l1 cache hit in l2 cache</technical_language>

Target:
public byte[] get(NamedKey key) { byte[] res = level1.get(key); if (res == null) { res = level2.get(key); if(res != null) { level1.put(key, res); hitCount.incrementAndGet(); return res; } missCount.incrementAndGet(); } if (res != null) { hitCount.incrementAndGet(); } return res; }
Source:
<code><START> public <E extends RealmModel> void subscribeToObjects(final Class<E> clazz, String query, final PartialSyncCallback<E> callback) { <END> checkIfValid(); if (!configuration.isSyncConfiguration()) { throw new IllegalStateException("Partial sync is only available for synchronized Realm (Realm Object Server)"); } sharedRealm.capabilities.checkCanDeliverNotification(BaseRealm.LISTENER_NOT_ALLOWED_MESSAGE); String className = configuration.getSchemaMediator().getSimpleClassName(clazz); SharedRealm.PartialSyncCallback internalCallback = new SharedRealm.PartialSyncCallback(sharedRealm, className) { @Override public void onSuccess(io.realm.internal.Collection osResults) { RealmResults<E> results = new RealmResults<E>(Realm.this, osResults, clazz); callback.onSuccess(results); } @Override public void onError(RealmException error) { callback.onError(error); } }; sharedRealm.registerPartialSyncQuery(query, internalCallback); }</code><technical_language>nice idea</technical_language>

Target:
public <E extends RealmModel> void subscribeToObjects(final Class<E> clazz, String query, final PartialSyncCallback<E> callback) { checkIfValid(); if (!configuration.isSyncConfiguration()) { throw new IllegalStateException("Partial sync is only available for synchronized Realm (Realm Object Server)"); } sharedRealm.capabilities.checkCanDeliverNotification(BaseRealm.LISTENER_NOT_ALLOWED_MESSAGE); String className = configuration.getSchemaMediator().getSimpleClassName(clazz); SharedRealm.PartialSyncCallback internalCallback = new SharedRealm.PartialSyncCallback(className) { @Override public void onSuccess(io.realm.internal.Collection osResults) { RealmResults<E> results = new RealmResults<>(Realm.this, osResults, clazz); callback.onSuccess(results); } @Override public void onError(RealmException error) { callback.onError(error); } }; sharedRealm.registerPartialSyncQuery(query, internalCallback); }
Source:
<code>public synchronized void handleChildChange(String s, List<String> list) { <START> handleDataDeleted(s); <END> }</code><technical_language>Please refactor logic out a private method call handleResubscription() call in of methods</technical_language>

Target:
public synchronized void handleChildChange(String s, List<String> list) { handleResubscription(); }
Source:
<code>public Optional<Symbol> getAssignedSymbol(PlanNode node, Session session, Metadata metadata, SymbolAliases symbolAliases) { <START> Optional<TableHandleAndAssignments> tableHandleAndAssignments = extractTableHandleAndAssignments(node); <END> if (!tableHandleAndAssignments.isPresent()) { return Optional.empty(); } TableHandle tableHandle = tableHandleAndAssignments.get().tableHandle; Map<Symbol, ColumnHandle> assignments = tableHandleAndAssignments.get().assignments; TableMetadata tableMetadata = metadata.getTableMetadata(session, tableHandle); String actualTableName = tableMetadata.getTable().getTableName(); if (!tableName.equalsIgnoreCase(actualTableName)) { return Optional.empty(); } Optional<ColumnHandle> columnHandle = getColumnHandle(tableHandle, session, metadata); checkState(columnHandle.isPresent(), format("Table %s doesn't have column %s. Typo in test?", tableName, columnName)); return getAssignedSymbol(assignments, columnHandle.get()); }</code><technical_language>not: TableHandle tableHandle; Map<Symbol, ColumnHandle> assignments; if (node instanceof TableScanNode) { TableScanNode tableScanNode = (TableScanNode) node; tableHandle = tableScanNode.getTable(); assignments = tableScanNode.getAssignments(); } else if (node instanceof IndexSourceNode) { IndexSourceNode indexSourceNode = (IndexSourceNode) node; tableHandle = indexSourceNode.getTableHandle(); assignments = indexSourceNode.getAssignments(); } else { return Optional.empty(); } of duplication. here, I a point of introducing a new class visitor for this. Or, if insist is bad, consider introducing a base class for PlanNodes unify refer table? In fact TableScanNodes, practically</technical_language>

Target:
public Optional<Symbol> getAssignedSymbol(PlanNode node, Session session, Metadata metadata, SymbolAliases symbolAliases) { TableHandle tableHandle; Map<Symbol, ColumnHandle> assignments; if (node instanceof TableScanNode) { TableScanNode tableScanNode = (TableScanNode) node; tableHandle = tableScanNode.getTable(); assignments = tableScanNode.getAssignments(); } else if (node instanceof IndexSourceNode) { IndexSourceNode indexSourceNode = (IndexSourceNode) node; tableHandle = indexSourceNode.getTableHandle(); assignments = indexSourceNode.getAssignments(); } else { return Optional.empty(); } TableMetadata tableMetadata = metadata.getTableMetadata(session, tableHandle); String actualTableName = tableMetadata.getTable().getTableName(); if (!tableName.equalsIgnoreCase(actualTableName)) { return Optional.empty(); } Optional<ColumnHandle> columnHandle = getColumnHandle(tableHandle, session, metadata); checkState(columnHandle.isPresent(), format("Table %s doesn't have column %s. Typo in test?", tableName, columnName)); return getAssignedSymbol(assignments, columnHandle.get()); }
Source:
<code>public boolean isAnyInternalApiEnabled() { <START> return internalAPIList != null && internalAPIList.size() > 0; <END> }</code><technical_language>if condition in line 73 is removed, remove check 'internalAPIList != null' 'ConfigurationLoader.loadInternalAPIs' return null</technical_language>

Target:
public boolean isAnyInternalApiEnabled() { return internalApiEnabled; }
Source:
<code><START> protected InputSourceReader formattableReader( <END> InputRowSchema inputRowSchema, InputFormat inputFormat, @Nullable File temporaryDirectory ) throws IOException { return new InputEntityIteratingReader( inputRowSchema, inputFormat, createSplits(inputFormat, null).map(split -> new S3Entity(s3Client, split.get())), temporaryDirectory ); }</code><technical_language>Unit test coverage is missing for this method</technical_language>

Target:
protected InputSourceReader formattableReader( InputRowSchema inputRowSchema, InputFormat inputFormat, @Nullable File temporaryDirectory ) { return new InputEntityIteratingReader( inputRowSchema, inputFormat, createSplits(inputFormat, null).map(split -> new S3Entity(s3Client, split.get())), temporaryDirectory ); }
Source:
<code>public void cCreateStandaloneTaskReleaseUnAuthorized() { Task standAloneTask = taskRuntime.create(TaskPayloadBuilder.create() .withName("group task") .withGroup("activitiTeam") .build()); assertThat(standAloneTask.getAssignee()).isNull(); assertThat(standAloneTask.getStatus()).isEqualTo(Task.TaskStatus.CREATED); Exception e = null; try { <START> Task releasedTask = taskRuntime.release(TaskPayloadBuilder.release().withTaskId(standAloneTask.getId()).build()); <END> } catch (Exception ex) { e = ex; } assertThat(e).isNotNull(); assertThat(e).isInstanceOf(IllegalStateException.class); }</code><technical_language>@erdemedeiros please do.. I looked for but.. I in time</technical_language>

Target:
public void cCreateStandaloneTaskReleaseUnAuthorized() { Task standAloneTask = taskRuntime.create(TaskPayloadBuilder.create() .withName("group task") .withGroup("activitiTeam") .build()); assertThat(standAloneTask.getAssignee()).isNull(); assertThat(standAloneTask.getStatus()).isEqualTo(Task.TaskStatus.CREATED); Throwable thrown = catchThrowable(() -> { taskRuntime.release(TaskPayloadBuilder.release().withTaskId(standAloneTask.getId()).build()); } ); assertThat(thrown).isInstanceOf(IllegalStateException.class); }
Source:
<code>public List<models.Record> getLatestRecordFromConfID(int configuration_id) { try { Connection conn = getConnection(); <START> String sql = "SELECT record_id, date, comment, repo, author, isRunning FROM records WHERE configuration_id = ? ORDER BY date DESC;"; <END> PreparedStatement stmt = conn.prepareStatement(sql); stmt.setInt(1, configuration_id); ResultSet recordsRS = stmt.executeQuery(); List<models.Record> record = new ArrayList<>(); if (recordsRS.isBeforeFirst()) { recordsRS.first(); int record_id = recordsRS.getInt(1); models.Metrics metrics = getMetricsFromRecordID(record_id); models.Record latestRecord = new models.Record(Integer.toString(record_id), recordsRS.getTimestamp(2).toString(), recordsRS.getString(3), recordsRS.getString(4), recordsRS.getString(5), metrics, Integer.toString(configuration_id)); latestRecord.isRunning = recordsRS.getBoolean(6); record.add(latestRecord); } conn.close(); return record; } catch (Exception e) { throw new RuntimeException(e); } }</code><technical_language>adding a LIMIT 1 help</technical_language>

Target:
public List<models.Record> getLatestRecordFromConfID(int configuration_id) { try { Connection conn = getConnection(); String sql = "SELECT record_id, date, comment, repo, author, isRunning FROM records WHERE configuration_id = ? ORDER BY date DESC LIMIT 1;"; PreparedStatement stmt = conn.prepareStatement(sql); stmt.setInt(1, configuration_id); ResultSet recordsRS = stmt.executeQuery(); List<models.Record> record = new ArrayList<>(); if (recordsRS.isBeforeFirst()) { recordsRS.first(); int record_id = recordsRS.getInt(1); models.Metrics metrics = getMetricsFromRecordID(record_id); models.Record latestRecord = new models.Record(Integer.toString(record_id), recordsRS.getTimestamp(2).toString(), recordsRS.getString(3), recordsRS.getString(4), recordsRS.getString(5), metrics, Integer.toString(configuration_id)); latestRecord.isRunning = recordsRS.getBoolean(6); record.add(latestRecord); } conn.close(); return record; } catch (Exception e) { throw new RuntimeException(e); } }
Source:
<code>public void testSetPublicURI() throws IOException, GitAPIException { final JGitFileSystemProvider fsProvider = mock(JGitFileSystemProvider.class); final Git git = setupGit(); <START> final JGitFileSystemImpl fileSystem = new JGitFileSystemImpl(fsProvider, new HashMap<String, String>() {{ put("ssh", "localhost:8080/git"); }}, <END> git, createFSLock(git), "my-repo", CredentialsProvider.getDefault(), null, null); assertThat(checkProtocolPresent(fileSystem.toString(), "ssh")).isEqualTo(true); assertThat(checkProtocolPresent(fileSystem.toString(), "http")).isEqualTo(false); fileSystem.setPublicURI(new HashMap<String, String>() {{ put("http", "localhost:8080/git"); put("ssh", "localhost:8080/git"); }}); assertThat(checkProtocolPresent(fileSystem.toString(), "ssh")).isEqualTo(true); assertThat(checkProtocolPresent(fileSystem.toString(), "http")).isEqualTo(true); fileSystem.lock(); }</code><technical_language>In past, sonarcloud reported anonymous static initialization risk. @hasys implemented kind of builders due this. please replace HashMap constructions in this way? new Maps.Builder<String, String>() .put("ssh", "localhost:8080/git") .build()</technical_language>

Target:
public void testSetPublicURI() throws IOException, GitAPIException { final JGitFileSystemProvider fsProvider = mock(JGitFileSystemProvider.class); final Git git = setupGit(); final JGitFileSystemImpl fileSystem = new JGitFileSystemImpl(fsProvider, new Maps.Builder<String, String>() .put("ssh", "localhost:8080/git") .build(), git, createFSLock(git), "my-repo", CredentialsProvider.getDefault(), null, null); assertTrue(checkProtocolPresent(fileSystem.toString(), "ssh")); assertFalse(checkProtocolPresent(fileSystem.toString(), "http")); fileSystem.setPublicURI(new Maps.Builder<String, String>() .put("http", "localhost:8080/git") .put("ssh", "localhost:8080/git") .build()); assertTrue(checkProtocolPresent(fileSystem.toString(), "ssh")); assertTrue(checkProtocolPresent(fileSystem.toString(), "http")); }
Source:
<code>protected void runTask() { DayRangeGenerator dateRangeGenerator = new DayRangeGenerator() .withLookBack(lookBack) .withLookAhead(lookAhead); processingErrors = 0; DayRange dayRange = dateRangeGenerator.generate(clock.now().toLocalDate()); for (LocalDate date : dayRange) { ingestFeedFor(date); } if (processingErrors > 0) { throw new RuntimeException(String.format("Finished with %d error(s)", processingErrors)); } <START> reportStatus(String.format("Finished with %d error(s)", processingErrors)); <END> }</code><technical_language>This line get executed if failures :(</technical_language>

Target:
protected void runTask() { DayRangeGenerator dateRangeGenerator = new DayRangeGenerator() .withLookBack(lookBack) .withLookAhead(lookAhead); DayRange dayRange = dateRangeGenerator.generate(clock.now().toLocalDate()); int successFeeds = 0; int failFeeds = 0; UpdateProgress itemLevelProgress = new UpdateProgress(0,0); for (LocalDate date : dayRange) { String feedUri = feedUrl + date.toString("YYYY/MM/dd"); reportStatus("Ingesting " + feedUri); try { List<ItvWhatsOnEntry> entries = itvWhatsOnClient.get(feedUri); itemLevelProgress = itemLevelProgress.reduce(ingestFeedEntries(entries)); successFeeds++; } catch (Exception e) { failFeeds++; log.error("Exception fetching feed at " + feedUri, e); } } UpdateProgress feedLevelProgress = new UpdateProgress(successFeeds, failFeeds); String message = String.format("Finished. Feeds: %s. Items %s.", feedLevelProgress.toString(), itemLevelProgress.toString()); reportStatus(message); if (feedLevelProgress.hasFailures() || itemLevelProgress.hasFailures()) { throw new RuntimeException(message); } }
Source:
<code>protected AbstractToolbarItem<S> getItem(final ToolbarCommand<?> command) { return items .entrySet() .stream() .filter(e -> e.getKey().equals(command)) .findFirst() .orElse(null) <START> .getValue(); <END> }</code><technical_language>hey @manstis , quick this a potential NPE produced here? I for orElse(null).getValue()</technical_language>

Target:
protected AbstractToolbarItem<S> getItem(final ToolbarCommand<?> command) { return items .entrySet() .stream() .filter(e -> e.getKey().equals(command)) .findFirst() .map(Map.Entry::getValue) .orElse(null); }
Source:
<code>public IConnection findExistingOpenshiftConnection(IServer server, ADBInfo adb) { Properties dotcdkProps = new CDKServerUtility().getDotCDK(server); String authScheme = dotcdkProps.containsKey(DOTCDK_AUTH_SCHEME) ? dotcdkProps.getProperty(DOTCDK_AUTH_SCHEME) : "Basic"; String username = dotcdkProps.containsKey(DOTCDK_AUTH_USERNAME) ? dotcdkProps.getProperty(DOTCDK_AUTH_USERNAME) : "test-admin"; String password = "password"; Collection<IConnection> connections = ConnectionsRegistrySingleton.getInstance().getAll(); Iterator<IConnection> it = connections.iterator(); <START> String soughtHost = adb.openshiftHost + ":" + adb.openshiftPort; <END> boolean found = false; IConnection c = null; while(it.hasNext() && !found) { c = it.next(); if( c.getType() == ConnectionType.Kubernetes) { String host = c.getHost(); if( host.equals(soughtHost)) { found = true; } } } return c; }</code><technical_language>connections.stream().filter(c -> c.getType() == ConnectionType.Kubernetes && soughtHost.equals(c.getHost()) .findFirst().orElse(null)</technical_language>

Target:
public IConnection findExistingOpenshiftConnection(IServer server, ADBInfo adb) { Properties dotcdkProps = new CDKServerUtility().getDotCDK(server); String authScheme = dotcdkProps.containsKey(DOTCDK_AUTH_SCHEME) ? dotcdkProps.getProperty(DOTCDK_AUTH_SCHEME) : "Basic"; String username = dotcdkProps.containsKey(DOTCDK_AUTH_USERNAME) ? dotcdkProps.getProperty(DOTCDK_AUTH_USERNAME) : "test-admin"; String password = "password"; String soughtHost = adb.openshiftHost + ":" + adb.openshiftPort; Collection<IConnection> connections = ConnectionsRegistrySingleton.getInstance().getAll(); for(IConnection c : connections) { if( c.getType() == ConnectionType.Kubernetes) { String host = c.getHost(); if( host.equals(soughtHost)) { return c; } } } return null; }