auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
private void deleteSubnet(GcpContext context, AuthenticatedContext auth, Network network, String subnetId) throws IOException { CloudResource subnetResource = createNamedResource(GCP_SUBNET, subnetId); try { CloudResource deletedResource = gcpSubnetResourceBuilder.delete(context, auth, subnetResource, network); if (deletedResource != null) { PollTask<List<CloudResourceStatus>> task = statusCheckFactory.newPollResourceTask( gcpSubnetResourceBuilder, auth, Collections.singletonList(deletedResource), context, true); syncPollingScheduler.schedule(task); } } catch (Exception e) { LOGGER.debug("Skipping resource creation: {}", e.getMessage()); } }

Target:
private void deleteSubnet(GcpContext context, AuthenticatedContext auth, Network network, String subnetId) throws IOException { CloudResource subnetResource = createNamedResource(GCP_SUBNET, subnetId); try { CloudResource deletedResource = gcpSubnetResourceBuilder.delete(context, auth, subnetResource, network); if (deletedResource != null) { PollTask<List<CloudResourceStatus>> task = statusCheckFactory.newPollResourceTask( gcpSubnetResourceBuilder, auth, Collections.singletonList(deletedResource), context, true); syncPollingScheduler.schedule(task); } } catch (Exception e) { LOGGER.debug("Skipping resource deletion: {}", e.getMessage()); } }
Source:
public Set<SystemPackage> getObject() { final long start = System.currentTimeMillis(); Set<SystemPackage> systemPackages = createSystemPackages(); final long finish = System.currentTimeMillis(); if (logger.isInfoEnabled() && (finish - start) > 1500L) { logger.info("System Package scanning took '{}' milliseconds. Possible improvement: enable System Package " + "cache by adding 'osgi.container.system-package-cache.mode:ENABLE' " + "to 'osgi-container.properties' (DISABLE by default because of #281)", (finish - start)); } return systemPackages; }

Target:
public Set<SystemPackage> getObject() { final long start = System.currentTimeMillis(); Set<SystemPackage> systemPackages = createSystemPackages(); final long finish = System.currentTimeMillis(); if (finish - start > 1500L) { logger.info("System Package scanning took '{}' milliseconds. Possible improvement: enable System Package " + "cache by adding 'osgi.container.system-package-cache.mode:ENABLE' " + "to 'osgi-container.properties'", (finish - start)); } return systemPackages; }
Source:
public void setTaskScheduler(TaskScheduler taskScheduler) { setTaskScheduler(taskScheduler); }

Target:
public void setTaskScheduler(TaskScheduler taskScheduler) { super.setTaskScheduler(taskScheduler); }
Source:
public void apply(RequestTemplate requestTemplate) { String accessToken = accessTokenGenerator.getAccessToken(APIConstants.KEY_MANAGER_OAUTH2_REST_API_MGT_SCOPES); requestTemplate.header("Authorization", "Bearer " + accessToken); }

Target:
public void apply(RequestTemplate requestTemplate) { String accessToken = accessTokenGenerator.getAccessToken(APIConstants.KEY_MANAGER_OAUTH2_REST_API_MGT_SCOPES); requestTemplate .header(APIConstants.AUTHORIZATION_HEADER_DEFAULT, APIConstants.AUTHORIZATION_BEARER + accessToken); }
Source:
public void submitWithoutConfirmationEmail() { WebElement sendEmailChecbox = browser.driver.findElement(By.name(Const.ParamsNames.SEND_SUBMISSION_EMAIL)); WebElement submitButton = browser.driver.findElement(By.id("response_submit_button")); if (sendEmailChecbox.isSelected()) { click(sendEmailChecbox); } click(submitButton); waitForPageToLoad(); }

Target:
public void submitWithoutConfirmationEmail() { WebElement sendEmailChecbox = browser.driver.findElement(By.name(Const.ParamsNames.SEND_SUBMISSION_EMAIL)); if (sendEmailChecbox.isSelected()) { click(sendEmailChecbox); } clickSubmitButton(); }
Source:
public void activateDeviceRequest(final String organisationIdentification, @Identification final String deviceIdentification) throws FunctionalException { LOGGER.debug("Activating device on behalf of organisation [{}]", deviceIdentification, organisationIdentification); final Organisation organisation = this.findOrganisation(organisationIdentification); this.isAllowed(organisation, PlatformFunction.DEACTIVATE_DEVICE); if (this.deviceRepository.findByDeviceIdentification(deviceIdentification) == null) { throw new FunctionalException(FunctionalExceptionType.UNKNOWN_DEVICE, ComponentType.WS_ADMIN); } this.enqueueActivateDeviceRequest(organisationIdentification, deviceIdentification); }

Target:
public void activateDeviceRequest(final String organisationIdentification, @Identification final String deviceIdentification) throws FunctionalException { LOGGER.debug("Activating device on behalf of organisation [{}]", deviceIdentification, organisationIdentification); final Organisation organisation = this.findOrganisation(organisationIdentification); this.isAllowed(organisation, PlatformFunction.ACTIVATE_DEVICE); if (this.deviceRepository.findByDeviceIdentification(deviceIdentification) == null) { throw new FunctionalException(FunctionalExceptionType.UNKNOWN_DEVICE, ComponentType.WS_ADMIN); } this.enqueueActivateDeviceRequest(organisationIdentification, deviceIdentification); }
Source:
public void close() { for (final Iterator<Runnable> i = cleanup.iterator(); i.hasNext();) { try { i.next().run(); } catch (Throwable err) { log.error("Failed to execute per-request cleanup", err); } i.remove(); } }

Target:
public void close() { for (final Iterator<Runnable> i = cleanup.iterator(); i.hasNext();) { try { i.next().run(); } catch (Throwable err) { log.error("Failed to execute cleanup for PrologEnvironment", err); } i.remove(); } }
Source:
@Override public double getHitRate(){ return (getHitCount()*1.0)/getRequestCount(); }

Target:
@Override public double getHitRate(){ return getRequestCount()>0?((getHitCount()*1.0)/getRequestCount()):0; }
Source:
private Set<String> indicesFromElastic() throws IOException { final String endpoint = "/_alias"; final Response response = client.performRequest(new Request("GET", endpoint)); try (InputStream is = response.getEntity().getContent()) { final JsonNode root = mapper.readTree(is); if (!root.isObject() || root.size() == 0) { final String message = String.format(Locale.ROOT, "Invalid response for %s/%s " + "Expected object of at least size 1 got %s (of size %d)", response.getHost(), response.getRequestLine(), root.getNodeType(), root.size()); throw new IllegalStateException(message); } Set<String> indices = Sets.newHashSet(root.fieldNames()); return indices; } }

Target:
private Set<String> indicesFromElastic() throws IOException { final String endpoint = "/_alias"; final Response response = client.performRequest(new Request("GET", endpoint)); try (InputStream is = response.getEntity().getContent()) { final JsonNode root = mapper.readTree(is); if (!(root.isObject() && root.size() > 0)) { final String message = String.format(Locale.ROOT, "Invalid response for %s/%s " + "Expected object of at least size 1 got %s (of size %d)", response.getHost(), response.getRequestLine(), root.getNodeType(), root.size()); throw new IllegalStateException(message); } Set<String> indices = Sets.newHashSet(root.fieldNames()); return indices; } }
Source:
public boolean onCommand(CommandPerformEvent event) { if (event.getArgs().length == 0) { return false; } else { try { HttpResponse<JsonNode> jsonResponse = Unirest.get("<LINK_0>") .field("a", "get_info") .header("accept", "application/json") .asJson(); double dogeyer = jsonResponse.getBody().getObject().getJSONObject("data").getJSONObject("info").getDouble("doge_usd"); double amtInUSDtoDoge = Double.parseDouble(event.getArgs()[0]); amtInUSDtoDoge = amtInUSDtoDoge / dogeyer; double amtInDogetoUSD = Double.parseDouble(event.getArgs()[0]); amtInDogetoUSD = amtInDogetoUSD * dogeyer; amtInDogetoUSD = (double) Math.round(amtInDogetoUSD * 100) / 100; amtInUSDtoDoge = (double) Math.round(amtInUSDtoDoge * 100) / 100; event.respond(Colors.BOLD + "USD --> Doge: " + Colors.NORMAL + Colors.UNDERLINE + amtInUSDtoDoge); event.respond(Colors.BOLD + "Doge --> USD: " + Colors.NORMAL + Colors.UNDERLINE + amtInDogetoUSD); } catch (UnirestException e) { e.printStackTrace(); } return true; } }

Target:
public boolean onCommand(CommandPerformEvent event) { if (event.getArgs().length == 0) { return false; } else { try { HttpResponse<JsonNode> jsonResponse = Unirest.get("<LINK_0>") .field("a", "get_info") .header("accept", "application/json") .asJson(); double amtFromDogeApi = jsonResponse.getBody().getObject().getJSONObject("data").getJSONObject("info").getDouble("doge_usd"); double amtInUSDtoDoge = Double.parseDouble(event.getArgs()[0]); amtInUSDtoDoge = amtInUSDtoDoge / amtFromDogeApi; double amtInDogetoUSD = Double.parseDouble(event.getArgs()[0]); amtInDogetoUSD = amtInDogetoUSD * amtFromDogeApi; amtInDogetoUSD = (double) Math.round(amtInDogetoUSD * 100) / 100; amtInUSDtoDoge = (double) Math.round(amtInUSDtoDoge * 100) / 100; event.respond(Colors.BOLD + "USD --> Doge: " + Colors.NORMAL + Colors.UNDERLINE + amtInUSDtoDoge); event.respond(Colors.BOLD + "Doge --> USD: " + Colors.NORMAL + Colors.UNDERLINE + amtInDogetoUSD); } catch (UnirestException e) { throw new DogeCoinException("An error occurred in the conversion process", e); } return true; } }
Source:
public static int getSegmentForKey(Object key, Cache cache) { KeyPartitioner keyPartitioner = extractComponent(cache, KeyPartitioner.class); if (keyPartitioner != null) { return keyPartitioner.getSegment(key); } return SegmentSpecificCommand.UNKNOWN_SEGMENT; }

Target:
public static int getSegmentForKey(Object key, Cache cache) { KeyPartitioner keyPartitioner = extractComponent(cache, KeyPartitioner.class); return keyPartitioner.getSegment(key); }
Source:
public static void main(String args[]) { try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(TestNews.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(TestNews.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(TestNews.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(TestNews.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } TestNews test = new TestNews(); test.setVisible(true); try { userDirectory = new ClassPathResource("NewsData").getFile().toString() + "\\"; WORD_VECTORS_PATH = userDirectory + "NewsWordVector.txt"; tokenizerFactory = new DefaultTokenizerFactory(); tokenizerFactory.setTokenPreProcessor(new CommonPreprocessor()); net = ModelSerializer.restoreMultiLayerNetwork(userDirectory + "NewsModel.net"); wordVectors = WordVectorSerializer.loadTxtVectors(new File(WORD_VECTORS_PATH)); } catch (Exception e) { } }

Target:
public static void main(String args[]) { try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { Logger.getLogger(TestNews.class.getName()).log(Level.SEVERE, null, ex); } catch (InstantiationException ex) { Logger.getLogger(TestNews.class.getName()).log(Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { Logger.getLogger(TestNews.class.getName()).log(Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { Logger.getLogger(TestNews.class.getName()).log(Level.SEVERE, null, ex); } TestNews test = new TestNews(); test.setVisible(true); try { userDirectory = new ClassPathResource("NewsData").getFile().getAbsolutePath() + File.separator; WORD_VECTORS_PATH = userDirectory + "NewsWordVector.txt"; tokenizerFactory = new DefaultTokenizerFactory(); tokenizerFactory.setTokenPreProcessor(new CommonPreprocessor()); net = ModelSerializer.restoreMultiLayerNetwork(userDirectory + "NewsModel.net"); wordVectors = WordVectorSerializer.loadTxtVectors(new File(WORD_VECTORS_PATH)); } catch (Exception e) { } }
Source:
public void onCreate() { super.onCreate(); initExceptionHandling(); AppCompatDelegate.setCompatVectorFromResourcesEnabled(true); bus = new Bus(); ViewAnimations.init(getResources()); currentTheme = unmarshalCurrentTheme(); appLanguageState = new AppLanguageState(this); funnelManager = new FunnelManager(this); sessionFunnel = new SessionFunnel(this); editTokenStorage = new EditTokenStorage(this); cookieManager = new SharedPreferenceCookieManager(); database = new Database(this); enableWebViewDebugging(); OkHttpConnectionFactory okHttpConnectionFactory = new OkHttpConnectionFactory(this); Api.setConnectionFactory(okHttpConnectionFactory); Set<RequestListener> requestListeners = new HashSet<>(); requestListeners.add(new RequestLoggingListener()); ImagePipelineConfig config = OkHttpImagePipelineConfigFactory .newBuilder(this, okHttpConnectionFactory.client()) .setRequestListeners(requestListeners) .build(); Fresco.initialize(this, config); zeroHandler = new WikipediaZeroHandler(this); pageCache = new PageCache(this); AccountUtil.createAccountForLoggedInUser(); UserOptionContentResolver.registerAppSyncObserver(this); registerReadingListPageObserver(); }

Target:
public void onCreate() { super.onCreate(); initExceptionHandling(); AppCompatDelegate.setCompatVectorFromResourcesEnabled(true); bus = new Bus(); ViewAnimations.init(getResources()); currentTheme = unmarshalCurrentTheme(); appLanguageState = new AppLanguageState(this); funnelManager = new FunnelManager(this); sessionFunnel = new SessionFunnel(this); editTokenStorage = new EditTokenStorage(this); cookieManager = new SharedPreferenceCookieManager(); database = new Database(this); enableWebViewDebugging(); OkHttpConnectionFactory okHttpConnectionFactory = new OkHttpConnectionFactory(this); Api.setConnectionFactory(okHttpConnectionFactory); ImagePipelineConfig config = OkHttpImagePipelineConfigFactory .newBuilder(this, okHttpConnectionFactory.client()) .build(); Fresco.initialize(this, config); zeroHandler = new WikipediaZeroHandler(this); pageCache = new PageCache(this); AccountUtil.createAccountForLoggedInUser(); UserOptionContentResolver.registerAppSyncObserver(this); registerReadingListPageObserver(); }
Source:
void writeMasterPasswordInfo(Resource file,String message,char[] masterPasswordArray) throws IOException { BufferedWriter w = new BufferedWriter(new OutputStreamWriter(file.out())); DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss"); w.write("This file was created at "+dateFormat.format(new Date())); w.newLine(); w.newLine(); w.write(message); if (masterPasswordArray!=null) w.write(masterPasswordArray); w.newLine(); w.newLine(); w.write("Test the master password by logging in as user \"root\""); w.newLine(); w.newLine(); w.write("This file should be removed after reading !!!."); w.newLine(); w.close(); }

Target:
void writeMasterPasswordInfo(Resource file, String message, char[] masterPasswordArray) throws IOException { try (BufferedWriter w = new BufferedWriter(new OutputStreamWriter(file.out()))) { DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss"); w.write("This file was created at " + dateFormat.format(new Date())); w.newLine(); w.newLine(); w.write(message); if (masterPasswordArray != null) { w.write(masterPasswordArray); } w.newLine(); w.newLine(); w.write("Test the master password by logging in as user \"root\""); w.newLine(); w.newLine(); w.write("This file should be removed after reading !!!."); w.newLine(); } }
Source:
public static Sso map(SsoMethod entity, Sso template) { Sso model = (template == null) ? new Sso() : template; model.setMethods(new Methods()); if (entity == SsoMethod.GUEST_AGENT) { model.getMethods().getMethods().add(org.ovirt.engine.api.model.SsoMethod.GUEST_AGENT.toString()); } else if (entity == SsoMethod.NONE) { model.getMethods().getMethods().add(org.ovirt.engine.api.model.SsoMethod.NONE.toString()); } return model; }

Target:
public static Sso map(SsoMethod entity, Sso template) { Sso model = (template == null) ? new Sso() : template; model.setMethods(new Methods()); if (entity == SsoMethod.GUEST_AGENT) { model.getMethods().getMethods().add(org.ovirt.engine.api.model.SsoMethod.GUEST_AGENT.toString()); } return model; }
Source:
public void testCreateUpdateAndDeleteFloatingIP() { for (String region : api.getConfiguredRegions()) { FloatingIPApi floatingIPApi = api.getFloatingIPApi(region); NetworkApi networkApi = api.getNetworkApi(region); FloatingIP floatingIPGet = null; Network network; try { network = networkApi.list().concat().firstMatch(new Predicate<Network>() { @Override public boolean apply(@Nullable Network input) { return input.getExternal(); } }).orNull(); if (network == null) Assert.fail("Cannot find a suitable external network. Please add it manually or contact your administrator"); FloatingIP floatingIP = floatingIPApi.create(FloatingIP.createBuilder(network.getId()).availabilityZone(network.getAvailabilityZone()).build()); Set<FloatingIP> floatingIPs = floatingIPApi.list().concat().toSet(); floatingIPGet = floatingIPApi.get(floatingIP.getId()); assertNotNull(floatingIPGet); assertTrue(floatingIPs.contains(floatingIP)); } finally { assertTrue(floatingIPApi.delete(floatingIPGet.getId())); } } }

Target:
public void testCreateUpdateAndDeleteFloatingIP() { for (String region : api.getConfiguredRegions()) { FloatingIPApi floatingIPApi = api.getFloatingIPApi(region); NetworkApi networkApi = api.getNetworkApi(region); FloatingIP floatingIPGet = null; Network network; try { network = networkApi.list().concat().firstMatch(new Predicate<Network>() { @Override public boolean apply(Network input) { return input.getExternal(); } }).orNull(); if (network == null) Assert.fail("Cannot find a suitable external network. Please add it manually or contact your administrator"); FloatingIP floatingIP = floatingIPApi.create(FloatingIP.createBuilder(network.getId()).availabilityZone(network.getAvailabilityZone()).build()); Set<FloatingIP> floatingIPs = floatingIPApi.list().concat().toSet(); floatingIPGet = floatingIPApi.get(floatingIP.getId()); assertNotNull(floatingIPGet); assertTrue(floatingIPs.contains(floatingIP)); } finally { assertTrue(floatingIPApi.delete(floatingIPGet.getId())); } } }
Source:
public RedisResponse executeCommandWithResponse(Command command, ExecutionHandlerContext context) { List<byte[]> commandElems = command.getProcessedCommand(); byte[] byteField = commandElems.get(FIELD_INDEX); ByteArrayWrapper field = new ByteArrayWrapper(byteField); ByteArrayWrapper key = command.getKey(); RedisHash map = getRedisHash(context, key); boolean hasField = map.containsKey(field); return RedisResponse.integer(hasField ? EXISTS : NOT_EXISTS); }

Target:
public RedisResponse executeCommandWithResponse(Command command, ExecutionHandlerContext context) { List<byte[]> commandElems = command.getProcessedCommand(); byte[] byteField = commandElems.get(FIELD_INDEX); ByteArrayWrapper field = new ByteArrayWrapper(byteField); ByteArrayWrapper key = command.getKey(); RedisHashCommands redisHashCommands = createRedisHashCommands(context); return RedisResponse.integer(redisHashCommands.hexists(key, field)); }
Source:
public void onResponse(Map<String, Object> response) { try { continueRefreshCapabilities(new AtomicBoolean(), vds, oldVDS, (VDSReturnValue) response.get("result")); } catch (Throwable t) { onFailure(t); } finally { if (vds != null) { updateDynamicData(vds.getDynamicData()); updateNumaData(vds); monitoringStrategy.processHardwareCapabilities(vds); resourceManager.getEventListener().handleVdsVersion(vds.getId()); } } }

Target:
public void onResponse(Map<String, Object> response) { try { processRefreshCapabilitiesResponse(new AtomicBoolean(), vds, vds.clone(), (VDSReturnValue) response.get("result")); } catch (Throwable t) { onFailure(t); } finally { if (vds != null) { updateDynamicData(vds.getDynamicData()); updateNumaData(vds); monitoringStrategy.processHardwareCapabilities(vds); resourceManager.getEventListener().handleVdsVersion(vds.getId()); } } }
Source:
private void writeServerEnvProperties(File file, Map<String, String> mavenProperties) throws IOException { makeParentDirectory(file); PrintWriter writer = null; try { writer = new PrintWriter(file, "UTF-8"); writer.println(HEADER); for (Map.Entry<String, String> entry : mavenProperties.entrySet()) { String key = entry.getKey(); writer.print(key); writer.print("="); String value = entry.getValue(); writer.println((value != null) ? value.replace("\\", "/") : ""); if (value == null) { log.error("The value of the server.env property " + entry.getKey() + " is null. Verify if the needed POM properties are set correctly."); } } } finally { if (writer != null) { writer.close(); } } }

Target:
private void writeServerEnvProperties(File file, Map<String, String> mavenProperties) throws IOException { makeParentDirectory(file); PrintWriter writer = null; try { writer = new PrintWriter(file, "UTF-8"); writer.println(HEADER); for (Map.Entry<String, String> entry : mavenProperties.entrySet()) { String key = entry.getKey(); writer.print(key); writer.print("="); String value = entry.getValue(); writer.println((value != null) ? value.replace("\\", "/") : ""); if (value == null) { log.warn("The value of the server.env property " + entry.getKey() + " is null. Verify if the needed POM properties are set correctly."); } } } finally { if (writer != null) { writer.close(); } } }
Source:
private Collection<ClusterNode> nodes() throws IgniteCheckedException { CacheMode cacheMode = cctx.config().getCacheMode(); Integer part = partition(); switch (cacheMode) { case LOCAL: if (prj != null) U.warn(log, "Ignoring query projection because it's executed over LOCAL cache " + "(only local node will be queried): " + this); if (type == SCAN && cctx.config().getCacheMode() == LOCAL && part != null && part >= cctx.affinity().partitions()) throw new IgniteCheckedException("Invalid partition number: " + part); return Collections.singletonList(cctx.localNode()); case REPLICATED: if (prj != null || part != null) return nodes(cctx, prj, part); if (cctx.affinityNode() && !cctx.topology().localPartitionMap().hasMovingPartitions()) return Collections.singletonList(cctx.localNode()); Collection<ClusterNode> affNodes = nodes(cctx, null, null); List<ClusterNode> nodes = new ArrayList<>(affNodes); Collections.shuffle(nodes); for (ClusterNode node : nodes) { if (!cctx.topology().partitions(node.id()).hasMovingPartitions()) { return Collections.singletonList(node); } } return affNodes; case PARTITIONED: return nodes(cctx, prj, part); default: throw new IllegalStateException("Unknown cache distribution mode: " + cacheMode); } }

Target:
private Collection<ClusterNode> nodes() throws IgniteCheckedException { CacheMode cacheMode = cctx.config().getCacheMode(); Integer part = partition(); switch (cacheMode) { case LOCAL: if (prj != null) U.warn(log, "Ignoring query projection because it's executed over LOCAL cache " + "(only local node will be queried): " + this); if (type == SCAN && cctx.config().getCacheMode() == LOCAL && part != null && part >= cctx.affinity().partitions()) throw new IgniteCheckedException("Invalid partition number: " + part); return Collections.singletonList(cctx.localNode()); case REPLICATED: if (prj != null || part != null) return nodes(cctx, prj, part); GridDhtPartitionTopology topology = cctx.topology(); if (cctx.affinityNode() && !topology.localPartitionMap().hasMovingPartitions()) return Collections.singletonList(cctx.localNode()); topology.readLock(); try { Collection<ClusterNode> affNodes = nodes(cctx, null, null); List<ClusterNode> nodes = new ArrayList<>(affNodes); Collections.shuffle(nodes); for (ClusterNode node : nodes) { if (!topology.partitions(node.id()).hasMovingPartitions()) return Collections.singletonList(node); } return affNodes; } finally { topology.readUnlock(); } case PARTITIONED: return nodes(cctx, prj, part); default: throw new IllegalStateException("Unknown cache distribution mode: " + cacheMode); } }
Source:
public PreparedStatement addPrepared(PreparedStatement stmt) { PreparedStatement previous = preparedQueries.putIfAbsent(stmt.getPreparedId().id, stmt); if (previous != null) { logger.warn("Re-preparing already prepared query is generally an anti-pattern and will likely affect performance. " + "Consider preparing the statement only once. Query='{}'", stmt.getQueryString()); if (previous.getPreparedId().getResultMetadataId().equals(stmt.getPreparedId().metadata)) { return previous; } else { preparedQueries.put(stmt.getPreparedId().id, stmt); return stmt; } } return stmt; }

Target:
public PreparedStatement addPrepared(PreparedStatement stmt) { PreparedStatement previous = preparedQueries.putIfAbsent(stmt.getPreparedId().boundValuesMetadata.id, stmt); if (previous != null) { logger.warn("Re-preparing already prepared query is generally an anti-pattern and will likely affect performance. " + "Consider preparing the statement only once. Query='{}'", stmt.getQueryString()); previous.getPreparedId().resultSetMetadata = stmt.getPreparedId().resultSetMetadata; return previous; } return stmt; }
Source:
private List<LogsForNamespaceAndUseCase> fetchHistoryFromRemote(List<HistoryQuery> historyQueries, TimeLockPaxosHistoryProvider remote) { try { return remote.getPaxosHistory(AUTH_HEADER, historyQueries); } catch (Exception e) { log.warn("The remote failed to provide the history," + "we cannot perform corruption checks without history from all nodes."); throw new RuntimeException(e.getCause()); } }

Target:
private PaxosHistoryOnRemote fetchHistoryFromRemote(List<HistoryQuery> historyQueries, TimeLockPaxosHistoryProvider remote) { try { return remote.getPaxosHistory(AUTH_HEADER, historyQueries); } catch (Exception exception) { log.warn("The remote failed to provide the history," + "we cannot perform corruption checks without history from all nodes.", exception); throw exception; } }
Source:
public BranchMergeOperation exclude(String ... ids) { return exclude(Arrays.copyOf(ids, ids.length)); }

Target:
public BranchMergeOperation exclude(String ... ids) { return exclude(ImmutableSet.copyOf(ids)); }
Source:
public final ClientBuilder readTimeout(long readTimeout, TimeUnit unit) { if (thisReadTimeout.isPresent()) { Preconditions.checkArgument(!thisReadTimeout.isPresent(), "readTimeout already set"); } thisReadTimeout = Optional.of(Duration.millis(TimeUnit.MILLISECONDS.convert(readTimeout, unit))); return this; }

Target:
public final ClientBuilder readTimeout(long readTimeout, TimeUnit unit) { Preconditions.checkArgument(!thisReadTimeout.isPresent(), "readTimeout already set"); thisReadTimeout = Optional.of(Duration.millis(TimeUnit.MILLISECONDS.convert(readTimeout, unit))); return this; }
Source:
protected void formatColumnValue(StringBuilder builder, String schemaName, Map<String, String> schemaParameters, Schema.Type type, Object value) { if (schemaName != null) { super.formatColumnValue(builder, schemaName, schemaParameters, type, value); } if (Schema.Type.BOOLEAN.equals(type)) { builder.append((Boolean) value ? "TRUE" : "FALSE"); return; } super.formatColumnValue(builder, schemaName, schemaParameters, type, value); }

Target:
protected void formatColumnValue(StringBuilder builder, String schemaName, Map<String, String> schemaParameters, Schema.Type type, Object value) { if (schemaName != null && super.formatLogicalColumnValue(builder, schemaName, value)) { return; } if (Schema.Type.BOOLEAN.equals(type)) { builder.append((Boolean) value ? "TRUE" : "FALSE"); return; } super.formatColumnValue(builder, schemaName, schemaParameters, type, value); }
Source:
public void testAsyncConnectionWithReconnect() throws IOException, InterruptedException { TestHandler handler = new TestHandler(); Connection nc = null; int port = NatsTestServer.nextPort(); Options options = new Options.Builder(). server("nats://localhost:"+port). maxReconnects(-1). reconnectWait(Duration.ofMillis(100)). connectionListener(handler). build(); try { Nats.connectAsynchronously(options, true); sleep(5000); nc = handler.getConnection(); assertNotNull(nc); handler.prepForStatusChange(Events.RECONNECTED); try (NatsTestServer ts = new NatsTestServer(port, false)) { allowTimeToConnectAssertOpen(nc, handler); } } finally { closeConnectionAssertClosed(nc); } }

Target:
public void testAsyncConnectionWithReconnect() throws IOException, InterruptedException { TestHandler handler = new TestHandler(); Connection nc = null; int port = NatsTestServer.nextPort(); Options options = new Options.Builder(). server("nats://localhost:"+port). maxReconnects(-1). reconnectWait(Duration.ofMillis(100)). connectionListener(handler). build(); try { Nats.connectAsynchronously(options, true); sleep(5000); nc = handler.getConnection(); assertNotNull(nc); handler.prepForStatusChange(Events.RECONNECTED); try (NatsTestServer ts = new NatsTestServer(port, false)) { waitThenAssertConnected(nc, handler); } } finally { closeThenAssertClosed(nc); } }
Source:
public void onClusterProvisioned(ClusterProvisionedEvent event) { if (event.getClusterId() == getClusterId()) { LOG.info("Removing temporary configurations after successful deployment of cluster id={} name={}", getClusterId(), getClusterName()); for (Map.Entry<String, Set<String>> e : BlueprintConfigurationProcessor.TEMPORARY_PROPERTIES_FOR_CLUSTER_DEPLOYMENT.entrySet()) { try { configHelper.updateConfigType(this, getCurrentStackVersion(), controller, e.getKey(), Collections.emptyMap(), e.getValue(), "internal", "Removing temporary configurations after successful deployment" ); setBlueprintProvisioningState(BlueprintProvisioningState.FINISHED); metadataHolder.updateData(controller.getClusterMetadataOnConfigsUpdate(this)); LOG.info("Removed temporary configurations: / {}", e.getKey(), e.getValue()); } catch (AmbariException ex) { LOG.warn("Failed to remove temporary configurations: / {}", e.getKey(), e.getValue(), ex); } } } }

Target:
public void onClusterProvisioned(ClusterProvisionedEvent event) { if (event.getClusterId() == getClusterId()) { LOG.info("Removing temporary configurations after successful deployment of cluster id={} name={}", getClusterId(), getClusterName()); for (Map.Entry<String, Set<String>> e : BlueprintConfigurationProcessor.TEMPORARY_PROPERTIES_FOR_CLUSTER_DEPLOYMENT.entrySet()) { try { configHelper.updateConfigType(this, getCurrentStackVersion(), controller, e.getKey(), Collections.emptyMap(), e.getValue(), "internal", "Removing temporary configurations after successful deployment" ); LOG.info("Removed temporary configurations: / {}", e.getKey(), e.getValue()); } catch (AmbariException ex) { LOG.warn("Failed to remove temporary configurations: / {}", e.getKey(), e.getValue(), ex); } } changeBlueprintProvisioningState(BlueprintProvisioningState.FINISHED); } }
Source:
public boolean isSearchIconClickable() { try { return searchIconClickableLink.isDisplayed(); } catch (NoSuchElementException e) { PageObjectLogging.logInfo(e.getMessage()); return false; } }

Target:
public boolean isSearchIconClickable() { try { searchIconClickableLink.isDisplayed(); wait.forElementClickable(searchIconClickableLink, 0); return true; } catch (NoSuchElementException e) { PageObjectLogging.logInfo(e.getMessage()); return false; } catch (TimeoutException e) { PageObjectLogging.logInfo(e.getMessage()); return false; } }
Source:
public static void registerGcm(final Context context) { if (gcmRegistered) { return; } gcmRegistered = true; new Thread(() -> { try { @SuppressWarnings("deprecation") final String gcmRegistrationId = GoogleCloudMessaging.getInstance(context).register(GOOGLE_PUSH_SENDER_ID); if (Util.isNullOrEmpty(gcmRegistrationId)) { Lg.e("got empty gcm registration id from google server"); return; } if (!StorePushId.httpPostStorePushId(gcmRegistrationId)) { Lg.e("ERROR: failed to store gcm push notification registration id=", gcmRegistrationId, " on simlar server"); return; } Lg.i("gcm push notification registration id=", gcmRegistrationId, " stored on simlar server"); } catch (final IOException e) { Lg.ex(e, "gcm registration IOException"); } }).start(); }

Target:
public static void registerGcm(final Context context) { if (gcmRegistered) { return; } gcmRegistered = true; new Thread(() -> { try { @SuppressWarnings("deprecation") final String gcmRegistrationId = GoogleCloudMessaging.getInstance(context).register(GOOGLE_PUSH_SENDER_ID); if (Util.isNullOrEmpty(gcmRegistrationId)) { Lg.e("got empty gcm registration id from google server"); return; } if (!StorePushId.httpPostStorePushId(gcmRegistrationId)) { Lg.e("failed to store gcm push notification registration id=", gcmRegistrationId, " on simlar server"); return; } Lg.i("gcm push notification registration id=", gcmRegistrationId, " stored on simlar server"); } catch (final IOException e) { Lg.ex(e, "gcm registration IOException"); } }).start(); }
Source:
protected HttpURLConnection createConnection(String uri) throws IOException { URL url = new URL(createUri(uri)); if (proxy != null) return (HttpURLConnection) url.openConnection(proxy); return (HttpURLConnection) url.openConnection(); }

Target:
protected HttpURLConnection createConnection(String uri) throws IOException { URL url = new URL(createUri(uri)); if (proxy != null) { return (HttpURLConnection) url.openConnection(proxy); } return (HttpURLConnection) url.openConnection(); }
Source:
public boolean onTouch(View v, MotionEvent event) { boolean openUrl = ((WebContentDisplayScreenlet) getScreenlet()).onWebContentTouched(v, event); boolean isClick = event.getAction() == MotionEvent.ACTION_UP; if (!openUrl && isClick) { WebView.HitTestResult result = webView.getHitTestResult(); LiferayLogger.i("Event: " + event.toString()); LiferayLogger.i("Extra: " + result.getExtra()); ((WebContentDisplayScreenlet) getScreenlet()).onWebContentClicked(result); return true; } LiferayLogger.i("Open in browser: " + (openUrl ? "Yes" : "No")); return false; }

Target:
public boolean onTouch(View v, MotionEvent event) { return ((WebContentDisplayScreenlet) getScreenlet()).onWebContentTouched(webView, event); }
Source:
public void hibernateMigrate() throws DataMigrationException, XWikiException { getStore().executeWrite(getXWikiContext(), new MigrateIVFCallback()); }

Target:
public void hibernateMigrate() throws DataMigrationException, XWikiException { getStore().executeWrite(getXWikiContext(), new MigrateMoICallback()); }
Source:
private void pingTaskNodeAndInitiateRestart(InternalTask task) { RunningTaskData runningTask = jobs.getRunningTask(task.getId()); if (runningTask != null) { Node nodeUsedToExecuteTask = runningTask.getNodeExecutor(); try { nodeUsedToExecuteTask.getNumberOfActiveObjects(); long taskLauncherFailureTime = System.currentTimeMillis() - runningTask.getFirstTaskLauncherFailureTime(); if (taskLauncherFailureTime > PASchedulerProperties.SCHEDULER_TASKLAUNCHER_PING_TIMEOUT.getValueAsLong()) { tlogger.error(task.getId(), "task launcher failed and was not accessible after " + taskLauncherFailureTime + " ms, initiate task restart."); runningTask.setRestarting(true); restartTaskOnNodeFailure(task); } } catch (Exception e) { int attempts = runningTask.increaseAndGetPingAttempts(); String nodeUrl = nodeUsedToExecuteTask.getNodeInformation().getURL(); if (attempts > PASchedulerProperties.SCHEDULER_NODE_PING_ATTEMPTS.getValueAsInt()) { tlogger.error(task.getId(), "node failed " + nodeUrl + ", initiate task restart.", e); runningTask.setRestarting(true); restartTaskOnNodeFailure(task); } else { tlogger.warn(task.getId(), "cannot contact node " + nodeUrl + " - waiting while it comes back, attempt " + attempts, e); } } } }

Target:
private void pingTaskNodeAndInitiateRestart(InternalTask task) { RunningTaskData runningTask = jobs.getRunningTask(task.getId()); if (runningTask != null) { Node nodeUsedToExecuteTask = runningTask.getNodeExecutor(); try { nodeUsedToExecuteTask.getNumberOfActiveObjects(); long taskLauncherFailureTime = runningTask.getTaskLauncherFailurePeriod(); if (taskLauncherFailureTime > PASchedulerProperties.SCHEDULER_TASKLAUNCHER_PING_TIMEOUT.getValueAsLong()) { tlogger.error(task.getId(), "task launcher failed and was not accessible after " + taskLauncherFailureTime + " ms, initiate task restart."); runningTask.setRestarting(); restartTaskOnNodeFailure(task); } } catch (Exception e) { int attempts = runningTask.increaseAndGetPingAttempts(); String nodeUrl = nodeUsedToExecuteTask.getNodeInformation().getURL(); if (attempts > PASchedulerProperties.SCHEDULER_NODE_PING_ATTEMPTS.getValueAsInt()) { tlogger.error(task.getId(), "node failed " + nodeUrl + ", initiate task restart.", e); runningTask.setRestarting(); restartTaskOnNodeFailure(task); } else { tlogger.warn(task.getId(), "cannot contact node " + nodeUrl + " - waiting while it comes back, attempt " + attempts, e); } } } }
Source:
private BooleanExpression comparator(String operator, Object value) { org.neo4j.cypherdsl.query.Query.checkNull( value, "Value" ); return new Value( new Operator( identifier( alias ).property( propertyName ), operator ), literal( value ) ); }

Target:
private BooleanExpression comparator(String operator, Object value) { Contracts.assertNotNull( value, "Value" ); return new Value( new Operator( identifier( alias ).property( propertyName ), operator ), literal( value ) ); }
Source:
public void detachCinderDomainFromPool(final StoragePoolIsoMap mapToRemove) { execute(new Callable<Object>() { @Override public Object call() { DbFacade.getInstance() .getStoragePoolIsoMapDao() .remove(new StoragePoolIsoMapId(mapToRemove.getstorage_id(), mapToRemove.getstorage_pool_id())); return null; } }); }

Target:
public void detachCinderDomainFromPool(final StoragePoolIsoMap mapToRemove) { execute(new Callable<Object>() { @Override public Object call() { getStoragePoolIsoMapDAO().remove(new StoragePoolIsoMapId(mapToRemove.getstorage_id(), mapToRemove.getstorage_pool_id())); return null; } }); }
Source:
public Response commitSnapshot(Action action) { RestoreAllSnapshotsParameters restoreParams = new RestoreAllSnapshotsParameters(guid, SnapshotActionEnum.COMMIT); Response response = doAction(VdcActionType.RestoreAllSnapshots, restoreParams, action); return response; }

Target:
public Response commitSnapshot(Action action) { RestoreAllSnapshotsParameters restoreParams = new RestoreAllSnapshotsParameters(guid, SnapshotActionEnum.COMMIT); Response response = performAction(VdcActionType.RestoreAllSnapshots, restoreParams, action); return response; }
Source:
public DRConsumerDrIdTracker(JSONObject jsObj) throws JSONException { m_map = TreeRangeSet.create(); m_lastSpUniqueId = jsObj.getLong("spUniqueId"); m_lastMpUniqueId = jsObj.getLong("mpUniqueId"); final JSONArray drIdRanges = jsObj.getJSONArray("drIdRanges"); for (int ii = 0; ii < drIdRanges.length(); ii++) { JSONObject obj = drIdRanges.getJSONObject(ii); String startDrIdStr = obj.keys().next(); long start = Long.valueOf(startDrIdStr); long end = obj.getLong(startDrIdStr); if (start > end) { throw new IllegalArgumentException(start + " after " + end); } m_map.add(range(start, end)); } }

Target:
public DRConsumerDrIdTracker(JSONObject jsObj) throws JSONException { m_map = TreeRangeSet.create(); m_lastSpUniqueId = jsObj.getLong("spUniqueId"); m_lastMpUniqueId = jsObj.getLong("mpUniqueId"); final JSONArray drIdRanges = jsObj.getJSONArray("drIdRanges"); for (int ii = 0; ii < drIdRanges.length(); ii++) { JSONObject obj = drIdRanges.getJSONObject(ii); String startDrIdStr = obj.keys().next(); m_map.add(range(Long.valueOf(startDrIdStr), obj.getLong(startDrIdStr))); } }
Source:
private void fetch(Request.Builder requestBuilder, final Movie media, final Callback callback) { enqueue(requestBuilder.build(), new okhttp3.Callback() { @Override public void onFailure(Call call, IOException e) { callback.onFailure(e); } @Override public void onResponse(Call call, Response response) throws IOException { if (response.isSuccessful()) { String responseStr = response.body().string(); YSubsResponse result = mGson.fromJson(responseStr, YSubsResponse.class); callback.onSuccess(result.formatForButte(PREFIX, LANGUAGE_MAPPING).get(media.imdbId)); } } }); }

Target:
private void fetch(Request.Builder requestBuilder, final Movie media, final Callback callback) { enqueue(requestBuilder.build(), new okhttp3.Callback() { @Override public void onFailure(Call call, IOException e) { callback.onFailure(e); } @Override public void onResponse(Call call, Response response) throws IOException { if (response.isSuccessful()) { String responseStr = response.body().string(); YSubsResponse result = mGson.fromJson(responseStr, YSubsResponse.class); callback.onSuccess(result.formatForButter(PREFIX, LANGUAGE_MAPPING).get(media.imdbId)); } } }); }
Source:
public String toString() { return "MeterReads{" + "logTime=" + logTime + ", activeEnergyImport=" + activeEnergyImport + ", activeEnergyExport=" + activeEnergyExport + ", activeEnergyImportTariffOne=" + activeEnergyImportTariffOne + ", activeEnergyImportTariffTwo=" + activeEnergyImportTariffTwo + ", activeEnergyExportTariffOne=" + activeEnergyExportTariffOne + ", activeEnergyExportTariffTwo=" + activeEnergyExportTariffTwo + '}'; }

Target:
public String toString() { return "MeterReads [logTime=" + this.logTime + ", activeEnergyImport=" + this.activeEnergyImport + ", activeEnergyExport=" + this.activeEnergyExport + ", activeEnergyImportTariffOne=" + this.activeEnergyImportTariffOne + ", activeEnergyImportTariffTwo=" + this.activeEnergyImportTariffTwo + ", activeEnergyExportTariffOne=" + this.activeEnergyExportTariffOne + ", activeEnergyExportTariffTwo=" + this.activeEnergyExportTariffTwo + "]"; }
Source:
public CharSequence[][] getHelpItems() { return new CharSequence[][] { { getResources().getString(R.string.help_item_description) }, { "<LINK_0>" } }; }

Target:
public CharSequence[][] getHelpItems() { return new CharSequence[][] { { getString(R.string.help_item_description) }, { "<LINK_0>" } }; }
Source:
public View getView(int position, View convertView, ViewGroup parent) { MonthView monthView = (MonthView) convertView; if (monthView == null) { monthView = MonthView.create(parent, inflater, weekdayNameFormat, listener, today); } monthView.setEvents(this.events); monthView.init(months.get(position), cells.get(position)); return monthView; }

Target:
public View getView(int position, View convertView, ViewGroup parent) { MonthView monthView = (MonthView) convertView; if (monthView == null) { monthView = MonthView.create(parent, inflater, weekdayNameFormat, listener, today); } monthView.init(months.get(position), cells.get(position)); return monthView; }
Source:
protected abstract void startUp() throws Exception; protected abstract void runOneIteration() throws Exception; protected void signal(@Nullable final Thread taskThread) throws Exception { }

Target:
protected abstract void startUp() throws Exception; protected abstract void runOneIteration() throws Exception; protected void signalShutdown(@Nullable final Thread taskThread) throws Exception { }
Source:
public void submit(List<LuceneWork> workList, IndexingMonitor monitor) { Changeset changeset = new Changeset( workList, Thread.currentThread(), monitor ); transferQueue.add( changeset ); wakeUpConsumer(); boolean interrupted = false; while ( ! changeset.isProcessed() ) { LockSupport.park(); if ( Thread.interrupted() ) { interrupted = true; } } if ( interrupted ) { Thread.currentThread().interrupt(); } }

Target:
public void submit(List<LuceneWork> workList, IndexingMonitor monitor) { Changeset changeset = new Changeset( workList, Thread.currentThread(), monitor ); transferQueue.add( changeset ); wakeUpConsumer(); boolean interrupted = false; while ( ! changeset.isProcessed() && ! interrupted ) { LockSupport.park(); if ( Thread.interrupted() ) { interrupted = true; } } if ( interrupted ) { Thread.currentThread().interrupt(); } }
Source:
public void switchOffAdminMode() { info("Switch OFF admin mode"); if (isAdminModeOn()) { info("Admin mode is on. Switching it OFF"); getHeader().switchingAdminMode(); } info("Admin mode is switched OFF"); }

Target:
public void switchOffAdminMode() { info("Switching OFF admin mode..."); if (isAdminModeOn()) { info("Admin mode is on. Switching it OFF"); getHeader().switchingAdminMode(); } else { info("Admin mode was switched off already, doing nothing"); } info("Admin mode is switched OFF"); }
Source:
public void initialize() { super.initialize(); eventBus.register(this); chatService.addChannelsListener(change -> { if (change.wasRemoved() && !change.getValueRemoved().getName().endsWith("'sParty")) { onChannelLeft(change.getValueRemoved()); } if (change.wasAdded() && !change.getValueAdded().getName().endsWith("'sParty")) { onChannelJoined(change.getValueAdded()); } }); JavaFxUtil.addListener(chatService.connectionStateProperty(), (observable, oldValue, newValue) -> onConnectionStateChange(newValue)); onConnectionStateChange(chatService.connectionStateProperty().get()); JavaFxUtil.addListener(tabPane.getTabs(), (ListChangeListener<Tab>) change -> { while (change.next()) { change.getRemoved().forEach(tab -> nameToChatTabController.remove(tab.getId())); } }); }

Target:
public void initialize() { super.initialize(); eventBus.register(this); chatService.addChannelsListener(change -> { if (change.wasRemoved() && !isMatchmakerPartyMessage(change.getValueRemoved().getName())) { onChannelLeft(change.getValueRemoved()); } if (change.wasAdded() && !isMatchmakerPartyMessage(change.getValueAdded().getName())) { onChannelJoined(change.getValueAdded()); } }); JavaFxUtil.addListener(chatService.connectionStateProperty(), (observable, oldValue, newValue) -> onConnectionStateChange(newValue)); onConnectionStateChange(chatService.connectionStateProperty().get()); JavaFxUtil.addListener(tabPane.getTabs(), (ListChangeListener<Tab>) change -> { while (change.next()) { change.getRemoved().forEach(tab -> nameToChatTabController.remove(tab.getId())); } }); }
Source:
public void checkFormatOfShell(String shell, Attribute attribute) throws WrongAttributeValueException { Pattern pattern = Pattern.compile("^(/[-_a-zA-Z0-9]+)+$"); Matcher match = pattern.matcher(shell); if (!match.matches()) { throw new WrongAttributeValueException(attribute, "Bad shell attribute format " + shell); } if(!shell.startsWith("/")) { throw new WrongAttributeValueException(attribute, "Shell " + shell + " doesnt start with /"); } }

Target:
public void checkFormatOfShell(String shell, Attribute attribute) throws WrongAttributeValueException { Pattern pattern = Pattern.compile("^(/[-_a-zA-Z0-9]+)+$"); Matcher match = pattern.matcher(shell); if (!match.matches()) { throw new WrongAttributeValueException(attribute, "Bad shell attribute format " + shell); } }
Source:
private void canDisconnect(IContainerDMContext[] contDmcs, DataRequestMonitor<Boolean> rm) { if (contDmcs.length == 0) { rm.setData(false); rm.done(); return; } IMultiDetach multiDetach = fTracker.getService(IMultiDetach.class); if (multiDetach != null) { multiDetach.canDetachDebuggerFromSomeProcesses(contDmcs, rm); } else { IProcesses procService = fTracker.getService(IProcesses.class); if (procService != null) { procService.canDetachDebuggerFromProcess(contDmcs[0], rm); } else { rm.setData(false);; rm.done(); } } }

Target:
private void canDisconnect(IContainerDMContext[] contDmcs, DataRequestMonitor<Boolean> rm) { if (contDmcs.length == 0) { rm.setData(false); rm.done(); return; } IMultiDetach multiDetach = fTracker.getService(IMultiDetach.class); if (multiDetach != null) { multiDetach.canDetachDebuggerFromSomeProcesses(contDmcs, rm); } else { IProcesses procService = fTracker.getService(IProcesses.class); if (procService != null && contDmcs.length == 1) { procService.canDetachDebuggerFromProcess(contDmcs[0], rm); } else { rm.setData(false); rm.done(); } } }
Source:
public void makesAGetRequestToUri() throws Exception { MockWebServer mockWebServer = mockWebServerTester.startMockWebServer(); mockWebServer.enqueue(new MockResponse()); URI uri = mockWebServer.url("/blah").uri(); subject.executeGetRequest(uri, null, null); assertThat(mockWebServer.getRequestCount(), equalTo(1)); RecordedRequest request = mockWebServer.takeRequest(); assertThat(request.getMethod(), equalTo("GET")); assertThat(request.getRequestUrl().uri(), equalTo(uri)); }

Target:
public void makesAGetRequestToUri() throws Exception { mockWebServer.enqueue(new MockResponse()); URI uri = mockWebServer.url("/blah").uri(); subject.executeGetRequest(uri, null, null); assertThat(mockWebServer.getRequestCount(), equalTo(1)); RecordedRequest request = mockWebServer.takeRequest(); assertThat(request.getMethod(), equalTo("GET")); assertThat(request.getRequestUrl().uri(), equalTo(uri)); }