auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
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.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); }

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:
public void notPossibleToLogInWhenPasswordFieldBlank() throws InterruptedException { LoginPage loginPage = new LoginPage(driver).get(); loginPage.logUserIn(Configuration.getCredentials().userName10, ""); Thread.sleep(1000); Assertion.assertTrue(loginPage.isSubmitButtonDisabled()); }

Target:
public void notPossibleToLogInWhenPasswordFieldBlank() throws InterruptedException { LoginPage loginPage = new LoginPage(driver).get(); loginPage.logUserIn(Configuration.getCredentials().userName10, ""); Assertion.assertTrue(loginPage.isSubmitButtonDisabled(2)); }
Source:
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); log.info("add VM '{} to cold reboot treatment", dbVm.getName()); } } }

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

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:
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); assertThat(resourceInfo.getResourceUri(), equalTo(testUri)); }

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:
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) { assertFalse("LocalTransactionSigner should share keypath", propTx.keyPaths.isEmpty()); 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); }

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:
public static SubjectEntity[] getStorageEntities(List<CinderDisk> cinderDisks) { List<SubjectEntity> storageSubjects = new ArrayList<>(); for (final CinderDisk cinderDisk : cinderDisks) { SubjectEntity subjectStorage = LinqUtils.firstOrNull(storageSubjects, new Predicate<SubjectEntity>() { @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()]); }

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:
public FileProvisioning(String configFile) { this.config = Utilities.parseConfig(configFile); this.threads = config.getInt(FileProvisioning.FILE_PROVISION_THREADS, FileProvisioning.DEFAULT_THREADS); this.cache = isCacheOn(config); try { PluginManager pluginManager = FileProvisionUtil.getPluginManager(config); this.plugins = pluginManager.getExtensions(ProvisionInterface.class); this.preProvisionPlugins = pluginManager.getExtensions(PreProvisionInterface.class); this.pluginsMap = this.plugins .stream() .collect(Collectors.toMap(plugin -> plugin.getClass().getName().split("\\$")[0], plugin -> plugin)); this.preProvisionMap = this.preProvisionPlugins .stream() .collect(Collectors.toMap(plugin -> plugin.getClass().getName().split("\\$")[0], plugin -> plugin)); List<PluginWrapper> pluginWrappers = pluginManager.getPlugins(); for (PluginWrapper pluginWrapper : pluginWrappers) { SubnodeConfiguration section = config.getSection(pluginWrapper.getPluginId()); Map<String, String> sectionConfig = new HashMap<>(); Iterator<String> keys = section.getKeys(); keys.forEachRemaining(key -> sectionConfig.put(key, section.getString(key))); String pluginClass = pluginWrapper.getDescriptor().getPluginClass(); if (pluginsMap.containsKey(pluginClass)) { pluginsMap.get(pluginClass).setConfiguration(sectionConfig); } if (preProvisionMap.containsKey(pluginClass)) { preProvisionMap.get(pluginClass).setConfiguration(sectionConfig); } } } catch (UnexpectedCharacterException e) { LOG.error("Could not load plugins: " + e.toString(), e); throw new RuntimeException(e); } }

Target:
public FileProvisioning(String configFile) { this.config = Utilities.parseConfig(configFile); this.threads = config.getInt(FileProvisioning.FILE_PROVISION_THREADS, FileProvisioning.DEFAULT_THREADS); this.cache = isCacheOn(config); try { PluginManager pluginManager = FileProvisionUtil.getPluginManager(config); this.plugins = pluginManager.getExtensions(ProvisionInterface.class); this.preProvisionPlugins = pluginManager.getExtensions(PreProvisionInterface.class); this.pluginsMap = this.plugins .stream() .collect(Collectors.toMap(plugin -> findPluginName(plugin.getClass().getName()), plugin -> plugin)); this.preProvisionMap = this.preProvisionPlugins .stream() .collect(Collectors.toMap(plugin -> findPluginName(plugin.getClass().getName()), plugin -> plugin)); List<PluginWrapper> pluginWrappers = pluginManager.getPlugins(); for (PluginWrapper pluginWrapper : pluginWrappers) { SubnodeConfiguration section = config.getSection(pluginWrapper.getPluginId()); Map<String, String> sectionConfig = new HashMap<>(); Iterator<String> keys = section.getKeys(); keys.forEachRemaining(key -> sectionConfig.put(key, section.getString(key))); String pluginClass = pluginWrapper.getDescriptor().getPluginClass(); if (pluginsMap.containsKey(pluginClass)) { pluginsMap.get(pluginClass).setConfiguration(sectionConfig); } if (preProvisionMap.containsKey(pluginClass)) { preProvisionMap.get(pluginClass).setConfiguration(sectionConfig); } } } catch (UnexpectedCharacterException e) { LOG.error("Could not load plugins: " + e.toString(), e); throw new RuntimeException(e); } }
Source:
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 primvary keys set: " + detail.toString()); return false; } } return true; }

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:
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()); return; } LOG.info("Start processing file: {}", file.getAbsolutePath()); pipe.startWithoutMetrics(); }

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:
public Map<TemplateProperty, Object> extractClassMetadata(AnnotationExtractionRequest request, Fields fields) { ClassSeedData seedData = extractSeedData(request, fields); Map<TemplateProperty, Object> context = generateClassMetadata(seedData); return context; }

Target:
public Map<TemplateProperty, Object> extractClassMetadata(AnnotationExtractionRequest request, Fields fields) { SpecClassMetadata specData = extractSpecData(request, fields); Map<TemplateProperty, Object> context = generateClassMetadata(specData); return context; }
Source:
public FirebaseAuthProvider createProvider(Context context, Firebase ref, TokenAuthHandler handler) { try { Class<? extends FirebaseAuthProvider> clazz = (Class<? extends FirebaseAuthProvider>) Class.forName(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); } }

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:
private static boolean hasNotBeenInvoked(String pwdKeyAliasProperty, String pwdKeyPasswordProperty, String passwordKey) { final String key = pwdKeyAliasProperty + "-" + pwdKeyPasswordProperty; String oldPwd = invocationCache.get(key); invocationCache.put(key, passwordKey); return oldPwd == null; }

Target:
private static boolean hasNotBeenInvoked(String pwdKeyAliasProperty, String pwdKeyPasswordProperty, String passwordKey) { if (invocationCache.contains(pwdKeyAliasProperty)) { return false; } invocationCache.add(pwdKeyAliasProperty); return true; }
Source:
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())); } CompletableFuture<Exception> eFuture = new CompletableFuture<>(); eFuture.thenAccept(e -> showError(user.getBase(), e, commandLabel)); player.getAsyncTeleport().now(user.getBase(), false, TeleportCause.COMMAND, eFuture, new CompletableFuture<>()); }

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

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:
private void assertLeafCount(Datastore datastore, String docId, int expectedLeafCount) { int actualLeafCount = ((DatastoreImpl)datastore).getAllRevisionsOfDocument(docId).leafRevisions().size(); Assert.assertEquals(expectedLeafCount, actualLeafCount); }

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:
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); assertThat(errors.size(), equalTo(2)); }

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:
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 = fromNullable(getenv("DOCKER_CERT_PATH")).orNull(); return new DockerHost(host, dockerCertPath); }

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:
public String getName() { return "CustomUserTasks"; }

Target:
public String getName() { return "UserTasksWithPotOwners"; }
Source:
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"); assertQueryFails("select ST_NumInteriorRing(ST_GeometryFromText('POLYGON EMPTY'))", "ST_NumInteriorRing only applies to Polygon. Input type is: MultiPolygon"); }

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:
Machine get() { synchronized (this) { if (toGet == null) { toGet = pooled.getAndSet(null); } if (toGet != null) { Machine got = toGet; toGet = got.next; got.next = null; return got; } } return new Machine(this); }

Target:
Machine get() { Machine head; do { head = pooled.get(); } while (head != null && !pooled.compareAndSet(head, head.next)); return head; }
Source:
public byte[] get(NamedKey key) { byte[] res = level1.get(key); if (res == null) { res = level2.get(key); } if (res == null) { missCount.incrementAndGet(); } else { put(key, res); hitCount.incrementAndGet(); } return res; }

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

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:
public synchronized void handleChildChange(String s, List<String> list) { handleDataDeleted(s); }

Target:
public synchronized void handleChildChange(String s, List<String> list) { handleResubscription(); }
Source:
public Optional<Symbol> getAssignedSymbol(PlanNode node, Session session, Metadata metadata, SymbolAliases symbolAliases) { Optional<TableHandleAndAssignments> tableHandleAndAssignments = extractTableHandleAndAssignments(node); 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()); }

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:
public boolean isAnyInternalApiEnabled() { return internalAPIList != null && internalAPIList.size() > 0; }

Target:
public boolean isAnyInternalApiEnabled() { return internalApiEnabled; }
Source:
protected InputSourceReader formattableReader( 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 ); }

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:
public static void getFileFromServer(String path, Bundle params, String filePath) { byte[] bf = new byte[FILE_BUFFER_SIZE]; int current = 0; InputStream is = null; HttpURLConnection connect = null; BufferedInputStream bis = null; OutputStream fos = null; try { fos = new FileOutputStream(filePath); String completePath = null; if (params != null) { StringBuilder sb = new StringBuilder(); sb.append(path).append('?'); boolean first = true; for (String key : params.keySet()) { if (!first) { sb.append('&'); } else { first = false; } sb.append(URLEncoder.encode(key)) .append('=') .append(URLEncoder.encode(params.getString(key))); } completePath = sb.toString(); } URL url = new URL(completePath); connect = (HttpURLConnection) url.openConnection(); connect.setDoInput(true); connect.setConnectTimeout(CONNECTION_TIME_OUT); connect.setReadTimeout(SOCKET_TIME_OUT); int code = connect.getResponseCode(); if (code == HttpURLConnection.HTTP_OK) { is = connect.getInputStream(); bis = new BufferedInputStream(is); while ((current = bis.read(bf)) != FILE_END) { fos.write(bf, 0, current); } } } catch (MalformedURLException e) { LogUtils.logD(e.getMessage()); } catch (IOException e) { LogUtils.logD(e.getMessage()); } catch (Exception e) { LogUtils.logD(e.getMessage()); } finally { try { if (bis != null) { bis.close(); } if (is != null) { is.close(); } if (fos != null) { fos.close(); } if (connect != null) { connect.disconnect(); } } catch (IOException e) { LogUtils.logD(e.getMessage()); } } }

Target:
public static boolean getFileFromServer(String path, Bundle params, String filePath) { byte[] bf = new byte[FILE_BUFFER_SIZE]; int current = 0; InputStream is = null; HttpURLConnection connect = null; BufferedInputStream bis = null; OutputStream fos = null; try { fos = new FileOutputStream(filePath); String completePath = path; if(params != null && !params.isEmpty()){ StringBuilder sb = new StringBuilder(); sb.append(path).append('?'); boolean first = true; for (String key : params.keySet()) { if (!first) { sb.append('&'); } else { first = false; } sb.append(URLEncoder.encode(key)) .append('=') .append(URLEncoder.encode(params.getString(key))); } completePath = sb.toString(); } URL url = new URL(completePath); connect = (HttpURLConnection) url.openConnection(); connect.setDoInput(true); connect.setConnectTimeout(CONNECTION_TIME_OUT); connect.setReadTimeout(SOCKET_TIME_OUT); int code = connect.getResponseCode(); if (code == HttpURLConnection.HTTP_OK) { is = connect.getInputStream(); bis = new BufferedInputStream(is); while ((current = bis.read(bf)) != FILE_END) { fos.write(bf, 0, current); } } return true; } catch (MalformedURLException e) { LogUtils.logE(e.getMessage()); return false; } catch (IOException e) { LogUtils.logE(e.getMessage()); return false; } catch (Exception e) { LogUtils.logE(e.getMessage()); return false; } finally { try { if (bis != null) { bis.close(); } if (is != null) { is.close(); } if (fos != null) { fos.close(); } if (connect != null) { connect.disconnect(); } } catch (IOException e) { LogUtils.logE(e.getMessage()); } } }
Source:
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 { Task releasedTask = taskRuntime.release(TaskPayloadBuilder.release().withTaskId(standAloneTask.getId()).build()); } catch (Exception ex) { e = ex; } assertThat(e).isNotNull(); assertThat(e).isInstanceOf(IllegalStateException.class); }

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

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:
public void testSetPublicURI() throws IOException, GitAPIException { final JGitFileSystemProvider fsProvider = mock(JGitFileSystemProvider.class); final Git git = setupGit(); final JGitFileSystemImpl fileSystem = new JGitFileSystemImpl(fsProvider, new HashMap<String, String>() {{ put("ssh", "localhost:8080/git"); }}, 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(); }

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:
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)); } reportStatus(String.format("Finished with %d error(s)", processingErrors)); }

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:
protected AbstractToolbarItem<S> getItem(final ToolbarCommand<?> command) { return items .entrySet() .stream() .filter(e -> e.getKey().equals(command)) .findFirst() .orElse(null) .getValue(); }

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:
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(); String soughtHost = adb.openshiftHost + ":" + adb.openshiftPort; 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; }

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; }
Source:
public DefaultCacheManager(String globalConfigurationFile, String defaultConfigurationFile, String namedCacheFile, boolean start) throws IOException { ParserRegistry parserRegistry = new ParserRegistry(); ConfigurationBuilderHolder globalConfigurationBuilderHolder = parserRegistry.parseFile(globalConfigurationFile); ConfigurationBuilderHolder defaultConfigurationBuilderHolder = parserRegistry.parseFile(defaultConfigurationFile); globalConfiguration = globalConfigurationBuilderHolder.getGlobalConfigurationBuilder().build(); defaultConfiguration = defaultConfigurationBuilderHolder.getDefaultConfigurationBuilder().build(); if (namedCacheFile != null) { ConfigurationBuilderHolder namedConfigurationBuilderHolder = parserRegistry.parseFile(namedCacheFile); Entry<String, ConfigurationBuilder> entry = namedConfigurationBuilderHolder.getNamedConfigurationBuilders().entrySet().iterator().next(); ConfigurationBuilder builder = entry.getValue(); builder.validate(globalConfiguration); configurationOverrides.put(entry.getKey(), builder.build()); } globalComponentRegistry = new GlobalComponentRegistry(this.globalConfiguration, this, caches.keySet()); authzHelper = new AuthorizationHelper(globalConfiguration.security(), AuditContext.CACHEMANAGER, globalConfiguration.globalJmxStatistics().cacheManagerName()); if (start) start(); }

Target:
public DefaultCacheManager(String globalConfigurationFile, String defaultConfigurationFile, String namedCacheFile, boolean start) throws IOException { ParserRegistry parserRegistry = new ParserRegistry(); ConfigurationBuilderHolder globalConfigurationBuilderHolder = parserRegistry.parseFile(globalConfigurationFile); ConfigurationBuilderHolder defaultConfigurationBuilderHolder = parserRegistry.parseFile(defaultConfigurationFile); globalConfiguration = globalConfigurationBuilderHolder.getGlobalConfigurationBuilder().build(); defaultConfiguration = defaultConfigurationBuilderHolder.getDefaultConfigurationBuilder().build(globalConfiguration); if (namedCacheFile != null) { ConfigurationBuilderHolder namedConfigurationBuilderHolder = parserRegistry.parseFile(namedCacheFile); Entry<String, ConfigurationBuilder> entry = namedConfigurationBuilderHolder.getNamedConfigurationBuilders().entrySet().iterator().next(); ConfigurationBuilder builder = entry.getValue(); configurationOverrides.put(entry.getKey(), builder.build(globalConfiguration)); } globalComponentRegistry = new GlobalComponentRegistry(this.globalConfiguration, this, caches.keySet()); authzHelper = new AuthorizationHelper(globalConfiguration.security(), AuditContext.CACHEMANAGER, globalConfiguration.globalJmxStatistics().cacheManagerName()); if (start) start(); }