auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public boolean addNetwork(V1NetworkAttachmentDefinition network, Guid clusterId) { String networkName = network.getMetadata().getName(); if (networkDao.getByNameAndCluster(networkName, clusterId) != null) { return false; } StoragePool dataCenter = storagePoolDao.getForCluster(clusterId); List<Network> dcNetworks = networkDao.getAllForDataCenter(dataCenter.getId()); Network dcNetwork = dcNetworks.stream().filter(n -> n.getName().equals(networkName)).findFirst().orElse(null); Guid dcNetworkId = dcNetwork == null ? null : dcNetwork.getId(); if (dcNetworkId == null) { dcNetwork = new Network(); dcNetwork.setName(networkName); dcNetwork.setDataCenterId(dataCenter.getId()); AddNetworkStoragePoolParameters params = new AddNetworkStoragePoolParameters(dataCenter.getId(), dcNetwork); params.setVnicProfilePublicUse(true); NetworkCluster networkCluster = new NetworkCluster(); networkCluster.setClusterId(clusterId); networkCluster.setRequired(false); params.setNetworkClusterList(List.of(networkCluster)); ActionReturnValue returnValue = backend.get().runInternalAction(ActionType.AddNetwork, params); dcNetworkId = returnValue.getActionReturnValue(); dcNetwork.setId(dcNetworkId); return returnValue.getSucceeded(); } ActionReturnValue returnValue = backend.get() .runInternalAction(ActionType.AttachNetworkToCluster, new AttachNetworkToClusterParameter(clusterId, dcNetwork)); return returnValue.getSucceeded(); }

Target:
public boolean addNetwork(V1NetworkAttachmentDefinition network, Guid clusterId) { String networkName = getNetworkName(network); if (networkDao.getByNameAndCluster(networkName, clusterId) != null) { return false; } StoragePool dataCenter = storagePoolDao.getForCluster(clusterId); List<Network> dcNetworks = networkDao.getAllForDataCenter(dataCenter.getId()); Network dcNetwork = dcNetworks.stream().filter(n -> n.getName().equals(networkName)).findFirst().orElse(null); Guid dcNetworkId = dcNetwork == null ? null : dcNetwork.getId(); if (dcNetworkId == null) { dcNetwork = new Network(); dcNetwork.setName(networkName); dcNetwork.setDataCenterId(dataCenter.getId()); AddNetworkStoragePoolParameters params = new AddNetworkStoragePoolParameters(dataCenter.getId(), dcNetwork); params.setVnicProfilePublicUse(true); NetworkCluster networkCluster = new NetworkCluster(); networkCluster.setClusterId(clusterId); networkCluster.setRequired(false); params.setNetworkClusterList(List.of(networkCluster)); ActionReturnValue returnValue = backend.get().runInternalAction(ActionType.AddNetwork, params); dcNetworkId = returnValue.getActionReturnValue(); dcNetwork.setId(dcNetworkId); return returnValue.getSucceeded(); } ActionReturnValue returnValue = backend.get() .runInternalAction(ActionType.AttachNetworkToCluster, new AttachNetworkToClusterParameter(clusterId, dcNetwork)); return returnValue.getSucceeded(); }
Source:
public boolean isVideoVisible() { driver.switchTo().frame(commentIFrame); try { wait.forElementVisible(By.cssSelector("img")); return true; } catch(NoSuchElementException e) { PageObjectLogging.logInfo("Video element is not visible", e); return false; } }

Target:
public boolean isVideoVisible() { driver.switchTo().frame(commentIFrame); try { wait.forElementVisible(By.cssSelector("img")); return true; } catch(TimeoutException e) { PageObjectLogging.logInfo("Video element is not visible", e); return false; } }
Source:
protected Object parseValue(CommandSource source, CommandArgs args) throws ArgumentParseException { if (!args.hasNext() && this.self) { if (source instanceof Player) { return ((Player) source).getConnection().getAddress().getAddress(); } else { throw args.createError(Text.of("No IP address was specified!")); } } Object state = args.getState(); String s = args.next(); try { return InetAddress.getByName(s); } catch (UnknownHostException e) { if (this.self) { if (source instanceof RemoteSource) { args.setState(state); return ((RemoteSource) source).getConnection().getAddress().getAddress(); } else { throw args.createError(Text.of("Invalid IP address, and source was not a player!")); } } throw args.createError(Text.of("Invalid IP address!")); } }

Target:
protected Object parseValue(CommandSource source, CommandArgs args) throws ArgumentParseException { if (!args.hasNext() && this.self) { if (source instanceof RemoteSource) { return ((RemoteSource) source).getConnection().getAddress().getAddress(); } else { throw args.createError(Text.of("No IP address was specified!")); } } Object state = args.getState(); String s = args.next(); try { return InetAddress.getByName(s); } catch (UnknownHostException e) { try { return ((Player) this.possiblePlayer.parseValue(source, args)).getConnection().getAddress().getAddress(); } catch (ArgumentParseException ex) { if (this.self && source instanceof RemoteSource) { args.setState(state); return ((RemoteSource) source).getConnection().getAddress().getAddress(); } throw args.createError(Text.of("Invalid IP address!")); } } }
Source:
protected boolean bootProtocolDhcp() { String bootProtocol = (String) this.entry.get("BOOTPROTO"); return bootProtocol != null && "dhcp".equalsIgnoreCase(bootProtocol); }

Target:
protected boolean bootProtocolDhcp() { return "dhcp".equalsIgnoreCase((String) entry.get("BOOTPROTO")); }
Source:
public <T> void delete(DeleteQuery deleteQuery, Class<T> clazz) { String indexName = hasText(deleteQuery.getIndex()) ? deleteQuery.getIndex() : getPersistentEntityFor(clazz).getIndexName(); String typeName = hasText(deleteQuery.getType()) ? deleteQuery.getType() : getPersistentEntityFor(clazz).getIndexType(); DeleteByQueryRequest deleteByQueryRequest = new DeleteByQueryRequest(indexName) .setDocTypes(typeName) .setQuery(deleteQuery.getQuery()) .setAbortOnVersionConflict(false) .setRefresh(true); if (deleteQuery.getPageSize() != null) deleteByQueryRequest.setBatchSize(deleteQuery.getPageSize()); if (deleteQuery.getScrollTimeInMillis() != null) deleteByQueryRequest.setScroll(TimeValue.timeValueMillis(deleteQuery.getScrollTimeInMillis())); try { client.deleteByQuery(deleteByQueryRequest, RequestOptions.DEFAULT); } catch (IOException e) { throw new ElasticsearchException("Error for search request with scroll: " + deleteByQueryRequest.toString(), e); } }

Target:
public <T> void delete(DeleteQuery deleteQuery, Class<T> clazz) { String indexName = hasText(deleteQuery.getIndex()) ? deleteQuery.getIndex() : getPersistentEntityFor(clazz).getIndexName(); String typeName = hasText(deleteQuery.getType()) ? deleteQuery.getType() : getPersistentEntityFor(clazz).getIndexType(); DeleteByQueryRequest deleteByQueryRequest = new DeleteByQueryRequest(indexName) .setDocTypes(typeName) .setQuery(deleteQuery.getQuery()) .setAbortOnVersionConflict(false) .setRefresh(true); if (deleteQuery.getPageSize() != null) deleteByQueryRequest.setBatchSize(deleteQuery.getPageSize()); if (deleteQuery.getScrollTimeInMillis() != null) deleteByQueryRequest.setScroll(TimeValue.timeValueMillis(deleteQuery.getScrollTimeInMillis())); try { client.deleteByQuery(deleteByQueryRequest, RequestOptions.DEFAULT); } catch (IOException e) { throw new ElasticsearchException("Error for delete request: " + deleteByQueryRequest.toString(), e); } }
Source:
public boolean handleError(@NotNull List<String> message, @NotNull ExternalSystemException error, @NotNull NotificationData notification, @NotNull Project project) { String firstLine = message.get(0); if (firstLine != null && firstLine.startsWith(ProjectImportErrorHandler.CONNECTION_PERMISSION_DENIED_PREFIX)) { NotificationHyperlink quickFix = new OpenUrlHyperlink("<LINK_1>", "More details (and potential fix)"); updateNotification(notification, project, firstLine, quickFix); return true; } return false; }

Target:
public boolean handleError(@NotNull List<String> message, @NotNull ExternalSystemException error, @NotNull NotificationData notification, @NotNull Project project) { String firstLine = message.get(0); if (firstLine != null && firstLine.startsWith(ProjectImportErrorHandler.CONNECTION_PERMISSION_DENIED_PREFIX)) { NotificationHyperlink quickFix = new OpenUrlHyperlink("<LINK_0>", "More details (and potential fix)"); updateNotification(notification, project, firstLine, quickFix); return true; } return false; }
Source:
public void onClusterAdded(String updatedClusterName) { if (_sourceClusterName.equals(updatedClusterName)) { try { DarkClusterConfigMap potentialDarkConfigMap = _facilities.getClusterInfoProvider().getDarkClusterConfigMap(updatedClusterName); for (Map.Entry<String, DarkClusterConfig> entry : potentialDarkConfigMap.entrySet()) { String darkClusterName = entry.getKey(); DarkClusterConfig darkClusterConfig = entry.getValue(); _darkStrategyMap.put(darkClusterName, createStrategy(darkClusterName, darkClusterConfig)); } } catch (ServiceUnavailableException e) { _notifier.notify(() -> new RuntimeException("PEGA_0019 unable to refresh DarkClusterConfigMap for source cluster: " + _sourceClusterName)); } return; } }

Target:
public void onClusterAdded(String updatedClusterName) { if (_sourceClusterName.equals(updatedClusterName)) { try { DarkClusterConfigMap updatedDarkConfigMap = _facilities.getClusterInfoProvider().getDarkClusterConfigMap(_sourceClusterName); Set<String> oldDarkStrategySet = _darkStrategyMap.keySet(); Set<String> updatedDarkClusterConfigKeySet = updatedDarkConfigMap.keySet(); oldDarkStrategySet.removeAll(updatedDarkClusterConfigKeySet); for (String darkClusterToRemove : oldDarkStrategySet) { _darkStrategyMap.remove(darkClusterToRemove); } for (Map.Entry<String, DarkClusterConfig> entry : updatedDarkConfigMap.entrySet()) { _darkStrategyMap.put(entry.getKey(), createStrategy(entry.getKey(), entry.getValue())); } } catch (ServiceUnavailableException e) { _notifier.notify(() -> new RuntimeException("PEGA_0019 unable to refresh DarkClusterConfigMap for source cluster: " + _sourceClusterName)); } } }
Source:
private String getPercentagesLabelPortion(double[] percentages, int i) { StringBuilder sb = new StringBuilder(); if (percentages != null) { sb.append(" (").append(percentages[i]).append(")"); } return sb.toString(); }

Target:
private String getPercentagesLabelPortion(double[] percentages, int i) { if (percentages == null) return ""; else return " (" + percentages[i] + "%)"; }
Source:
public Path resolve(String other) { if (".".equals(other)) { return this; } if (Strings.isFilled(other) && other.startsWith("/")) { return new BridgePath(vfs.resolve(other), fs); } return new BridgePath(virtualFile.resolve(other), fs); }

Target:
public Path resolve(String other) { if (".".equals(other)) { return this; } if (Strings.isFilled(other) && other.startsWith("/")) { return new BridgePath(vfs.resolve(other), fileSystem); } return new BridgePath(virtualFile.resolve(other), fileSystem); }
Source:
public void close() { try (Closer closer = Closer.create()) { closer.register(userAggregateMemoryContext::close); closer.register(revocableAggregateMemoryContext::close); closer.register(systemAggregateMemoryContext::close); userLocalMemoryContext.setBytes(0); revocableLocalMemoryContext.setBytes(0); systemLocalMemoryContext.setBytes(0); } catch (IOException e) { throw new RuntimeException("Exception closing memory tracking context", e); } }

Target:
public void close() { try (Closer closer = Closer.create()) { closer.register(userAggregateMemoryContext::close); closer.register(revocableAggregateMemoryContext::close); closer.register(systemAggregateMemoryContext::close); userLocalMemoryContext.close(); revocableLocalMemoryContext.close(); systemLocalMemoryContext.close(); } catch (IOException e) { throw new RuntimeException("Exception closing memory tracking context", e); } }
Source:
public JumpRule( Condition condition, UUID jumpToChainID, String jumpToChainName) { super(condition, Action.JUMP); this.jumpToChainID = jumpToChainID; this.jumpToChainName = jumpToChainName; }

Target:
public JumpRule( Condition condition, UUID jumpToChainID, String jumpToChainName) { super(condition, null); this.jumpToChainID = jumpToChainID; this.jumpToChainName = jumpToChainName; }
Source:
private HostVO getHost(long zoneId, boolean computeClusterMustSupportResign) { List<? extends Cluster> clusters = _mgr.searchForClusters(zoneId, 0L, Long.MAX_VALUE, HypervisorType.XenServer.toString()); if (clusters == null) { clusters = new ArrayList<>(); } Collections.shuffle(clusters, new Random(System.nanoTime())); clusters: for (Cluster cluster : clusters) { if (cluster.getAllocationState() == AllocationState.Enabled) { List<HostVO> hosts = _hostDao.findByClusterId(cluster.getId()); if (hosts != null) { Collections.shuffle(hosts, new Random(System.nanoTime())); for (HostVO host : hosts) { if (host.getResourceState() == ResourceState.Enabled) { if (computeClusterMustSupportResign) { if (computeClusterSupportsResign(cluster.getId())) { return host; } else { continue clusters; } } else { return host; } } } } } } return null; }

Target:
private Optional<HostVO> getHost(long zoneId, boolean computeClusterMustSupportResign) { List<? extends Cluster> clusters = mgr.searchForClusters(zoneId, 0L, Long.MAX_VALUE, HypervisorType.XenServer.toString()); if (clusters == null) { clusters = new ArrayList<>(); } Collections.shuffle(clusters, new Random(System.nanoTime())); clusters: for (Cluster cluster : clusters) { if (cluster.getAllocationState() == AllocationState.Enabled) { List<HostVO> hosts = hostDao.findByClusterId(cluster.getId()); if (hosts != null) { Collections.shuffle(hosts, new Random(System.nanoTime())); for (HostVO host : hosts) { if (host.getResourceState() == ResourceState.Enabled) { if (computeClusterMustSupportResign) { if (clusterDao.getSupportsResigning(cluster.getId())) { return Optional.of(host); } else { continue clusters; } } else { return Optional.of(host); } } } } } } return Optional.absent(); }
Source:
private void showFilterDialog() { Context context = getContext(); final String[] items = context.getResources().getStringArray(R.array.episode_filter_options); final String[] values = context.getResources().getStringArray(R.array.episode_filter_values); final boolean[] checkedItems = new boolean[items.length]; final Set<String> filter = new HashSet<>(Arrays.asList(feedItemFilter.getValues())); Iterator<String> it = filter.iterator(); while(it.hasNext()) { if(TextUtils.isEmpty(it.next())) { it.remove(); } } for(int i=0; i < values.length; i++) { String value = values[i]; if(filter.contains(value)) { checkedItems[i] = true; } } AlertDialog.Builder builder = new AlertDialog.Builder(context); builder.setTitle(R.string.filter); builder.setMultiChoiceItems(items, checkedItems, (dialog, which, isChecked) -> { if (isChecked) { filter.add(values[which]); } else { filter.remove(values[which]); } }); builder.setPositiveButton(R.string.confirm_label, (dialog, which) -> { feedItemFilter = new FeedItemFilter(filter.toArray(new String[filter.size()])); displayedEpisodes = feedItemFilter.filter(allEpisodes); onFragmentLoaded(displayedEpisodes); }); builder.setNegativeButton(R.string.cancel_label, null); builder.create().show(); }

Target:
private void showFilterDialog() { FilterDialog filterDialog = new FilterDialog(getContext(), feedItemFilter) { @Override protected void updateFilter(Set<String> filterValues) { feedItemFilter = new FeedItemFilter(filterValues.toArray(new String[filterValues.size()])); loadItems(); } }; filterDialog.openDialog(); }
Source:
long firstAddress() { if (cacheEntries.peek() == null) return Address.NOT_FOUND;; return cacheEntries.peek().txVersion; }

Target:
public long firstAddress() { if (cacheEntries.isEmpty()) { return Address.NOT_FOUND; } return cacheEntries.peek().txVersion; }
Source:
public static void createCluster() { UnitTestConnectionService.add(CLUSTER_URI, new PassthroughServerBuilder() .serverEntityService(new ClusterTierManagerServerEntityService()) .clientEntityService(new ClusterTierManagerClientEntityService()) .serverEntityService(OBSERVABLE_CLUSTER_TIER_SERVICE = new ObservableClusterTierServerEntityService()) .clientEntityService(new ClusterTierClientEntityService()) .serverEntityService(new VoltronReadWriteLockServerEntityService()) .clientEntityService(new VoltronReadWriteLockEntityClientService()) .resource("defaultResource", 128, MemoryUnit.MB).build()); }

Target:
public static void createCluster() { UnitTestConnectionService.add(CLUSTER_URI, new PassthroughServerBuilder() .serverEntityService(new ClusterTierManagerServerEntityService()) .clientEntityService(new ClusterTierManagerClientEntityService()) .serverEntityService(observableClusterTierService = new ObservableClusterTierServerEntityService()) .clientEntityService(new ClusterTierClientEntityService()) .serverEntityService(new VoltronReadWriteLockServerEntityService()) .clientEntityService(new VoltronReadWriteLockEntityClientService()) .resource("defaultResource", 128, MemoryUnit.MB).build()); }
Source:
public void customAttributes() { UnifiedMessage unifiedMessage = new UnifiedMessage.Builder() .message().customProperty("foo-key", "foo-value") .customProperty("bar-key", "bar-value").build() .build(); assertEquals("foo-value", ((Map) unifiedMessage.getMessage().getAttributes().get("payload")).get("foo-key")); assertEquals("bar-value", ((Map) unifiedMessage.getMessage().getAttributes().get("payload")).get("bar-key")); }

Target:
public void customAttributes() { UnifiedMessage unifiedMessage = new UnifiedMessage.Builder() .message().userData("foo-key", "foo-value") .userData("bar-key", "bar-value").build() .build(); assertEquals("foo-value", ((Map) unifiedMessage.getMessage().getAttributes().get("user-data")).get("foo-key")); assertEquals("bar-value", ((Map) unifiedMessage.getMessage().getAttributes().get("user-data")).get("bar-key")); }
Source:
protected void runStreamProcessor(SamzaResourceRequest request, String preferredHost) { CommandBuilder builder = getCommandBuilder(request.getProcessorId()); SamzaResource resource = peekAllocatedResource(preferredHost); if (resource == null) { throw new SamzaException("Expected resource for Processor ID: " + request.getProcessorId() + " was unavailable on host: " + preferredHost); } if(clusterResourceManager.isResourceExpired(resource)) { LOG.info("Lease for the resource has been expired for resource: request: {}", resource, request); resourceRequestState.releaseUnstartableContainer(resource, preferredHost); resourceRequestState.cancelResourceRequest(request); this.requestResource(request.getProcessorId(), request.getPreferredHost()); return; } resourceRequestState.updateStateAfterAssignment(request, preferredHost, resource); String processorId = request.getProcessorId(); LOG.info("Found Container ID: for Processor ID: on host: for request creation time: {}.", resource.getContainerId(), processorId, preferredHost, request.getRequestTimestamp()); state.pendingProcessors.put(processorId, resource); clusterResourceManager.launchStreamProcessor(resource, builder); }

Target:
protected void runStreamProcessor(SamzaResourceRequest request, String preferredHost) { CommandBuilder builder = getCommandBuilder(request.getProcessorId()); SamzaResource resource = peekAllocatedResource(preferredHost); if (resource == null) { throw new SamzaException("Expected resource for Processor ID: " + request.getProcessorId() + " was unavailable on host: " + preferredHost); } if (clusterResourceManager.isResourceExpired(resource)) { containerManager.handleExpiredResource(request, resource, preferredHost, resourceRequestState, this); return; } resourceRequestState.updateStateAfterAssignment(request, preferredHost, resource); String processorId = request.getProcessorId(); LOG.info("Found Container ID: for Processor ID: on host: for request creation time: {}.", resource.getContainerId(), processorId, preferredHost, request.getRequestTimestamp()); state.pendingProcessors.put(processorId, resource); clusterResourceManager.launchStreamProcessor(resource, builder); }
Source:
public void testUpsertSelectDoesntSeeUpsertedData() throws Exception { Properties props = PropertiesUtil.deepCopy(TEST_PROPERTIES); props.setProperty(QueryServices.MUTATE_BATCH_SIZE_ATTRIB, Integer.toString(3)); props.setProperty(QueryServices.SCAN_CACHE_SIZE_ATTRIB, Integer.toString(3)); props.setProperty(QueryServices.SCAN_RESULT_CHUNK_SIZE, Integer.toString(3)); Connection conn = DriverManager.getConnection(getUrl(), props); conn.setAutoCommit(true); conn.createStatement().execute("CREATE SEQUENCE "+seqName); BaseTest.createSchema(getUrl(), fullTableName, null); conn.createStatement().execute("CREATE TABLE " + fullTableName + "(pk INTEGER PRIMARY KEY, val INTEGER)"+(!mutable? " IMMUTABLE_ROWS=true" : "")); conn.createStatement().execute("CREATE "+(localIndex? "LOCAL " : "")+"INDEX " + indexName + " ON " + fullTableName + "(val)"); conn.createStatement().execute("UPSERT INTO " + fullTableName + " VALUES (NEXT VALUE FOR " + seqName + ",1)"); for (int i=0; i<6; i++) { Statement stmt = conn.createStatement(); int upsertCount = stmt.executeUpdate("UPSERT INTO " + fullTableName + " SELECT NEXT VALUE FOR " + seqName + ", val FROM " + fullTableName); assertEquals((int)Math.pow(2, i), upsertCount); } conn.close(); }

Target:
public void testUpsertSelectDoesntSeeUpsertedData() throws Exception { Properties props = PropertiesUtil.deepCopy(TEST_PROPERTIES); props.setProperty(QueryServices.MUTATE_BATCH_SIZE_ATTRIB, Integer.toString(3)); props.setProperty(QueryServices.SCAN_CACHE_SIZE_ATTRIB, Integer.toString(3)); props.setProperty(QueryServices.SCAN_RESULT_CHUNK_SIZE, Integer.toString(3)); Connection conn = DriverManager.getConnection(getUrl(), props); conn.setAutoCommit(true); conn.createStatement().execute("CREATE SEQUENCE "+seqName); conn.createStatement().execute("CREATE TABLE " + fullTableName + "(pk INTEGER PRIMARY KEY, val INTEGER)"+(!mutable? " IMMUTABLE_ROWS=true" : "")); conn.createStatement().execute("CREATE "+(localIndex? "LOCAL " : "")+"INDEX " + indexName + " ON " + fullTableName + "(val)"); conn.createStatement().execute("UPSERT INTO " + fullTableName + " VALUES (NEXT VALUE FOR " + seqName + ",1)"); for (int i=0; i<6; i++) { Statement stmt = conn.createStatement(); int upsertCount = stmt.executeUpdate("UPSERT INTO " + fullTableName + " SELECT NEXT VALUE FOR " + seqName + ", val FROM " + fullTableName); assertEquals((int)Math.pow(2, i), upsertCount); } conn.close(); }
Source:
private ActionEventRequest buildCreateObservationJSON(String configName) { SortedSet<ActionParameterRequest> actionParameters = new TreeSet<>(); int order = 0; String serviceMethod = "createObservationJSON"; actionParameters.add(prepareParameter(Keys.CONFIG_NAME, DisplayNames.CONFIG_NAME, configName, true, true, order++)); actionParameters.add(prepareParameter(Keys.OBSERVATION_JSON, DisplayNames.OBSERVATION_JSON, TEXTAREA, "{}", true, order++)); actionParameters.add(prepareParameter(Keys.ENCOUNTER_UUID, DisplayNames.ENCOUNTER_UUID, false, order++)); actionParameters.add(prepareParameter(Keys.CONCEPT_UUID, DisplayNames.CONCEPT_UUID, false, order++)); actionParameters.add(prepareParameter(Keys.OBSERVATION_DATETIME, DisplayNames.OBSERVATION_DATETIME, DATE, false, order++)); actionParameters.add(prepareParameter(Keys.COMMENT, DisplayNames.COMMENT, false, order)); return new ActionEventRequestBuilder() .setDisplayName(getDisplayName(CREATE_OBSERVATION_JSON, configName)) .setServiceInterface(OPENMRS_ACTION_PROXY_SERVICE) .setServiceMethod(serviceMethod) .setSubject(getSubject(serviceMethod, configName)) .setActionParameters(actionParameters) .createActionEventRequest(); }

Target:
private ActionEventRequest buildCreateObservationJSON(String configName) { SortedSet<ActionParameterRequest> actionParameters = new TreeSet<>(); int order = 0; String serviceMethod = "createObservationJSON"; String defaultValueForJsonField = "{}"; actionParameters.add(prepareParameter(Keys.CONFIG_NAME, DisplayNames.CONFIG_NAME, configName, true, true, order++)); actionParameters.add(prepareParameter(Keys.OBSERVATION_JSON, DisplayNames.OBSERVATION_JSON, TEXTAREA, defaultValueForJsonField, true, order++)); actionParameters.add(prepareParameter(Keys.ENCOUNTER_UUID, DisplayNames.ENCOUNTER_UUID, false, order++)); actionParameters.add(prepareParameter(Keys.CONCEPT_UUID, DisplayNames.CONCEPT_UUID, false, order++)); actionParameters.add(prepareParameter(Keys.OBSERVATION_DATETIME, DisplayNames.OBSERVATION_DATETIME, DATE, false, order++)); actionParameters.add(prepareParameter(Keys.COMMENT, DisplayNames.COMMENT, false, order)); return new ActionEventRequestBuilder() .setDisplayName(getDisplayName(CREATE_OBSERVATION_JSON, configName)) .setServiceInterface(OPENMRS_ACTION_PROXY_SERVICE) .setServiceMethod(serviceMethod) .setSubject(getSubject(serviceMethod, configName)) .setActionParameters(actionParameters) .createActionEventRequest(); }
Source:
public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null || getClass() != obj.getClass()) { return false; } BenchmarkQuery other = (BenchmarkQuery) obj; return Objects.equals(this.querySet, other.querySet) && Objects.equals(this.name, other.name) && Objects.equals(this.query, other.query) && Objects.equals(this.catalog, other.catalog) && Objects.equals(this.schema, other.schema); }

Target:
public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null || getClass() != obj.getClass()) { return false; } BenchmarkQuery o = (BenchmarkQuery) obj; return Objects.equals(querySet, o.querySet) && Objects.equals(name, o.name) && Objects.equals(query, o.query) && Objects.equals(catalog, o.catalog) && Objects.equals(schema, o.schema); }
Source:
public Opt<Identity> enter(final Request request) throws IOException { final Iterator<String> headers = new RqHeaders.Smart( new RqHeaders.Base(request) ).header("authorization").iterator(); if (!headers.hasNext()) { throw new RsForward( new RsWithHeader( String.format( "WWW-Authenticate: Basic ream=\"%s\" ", this.realm ) ), HttpURLConnection.HTTP_UNAUTHORIZED, new RqHref.Base(request).href() ); } final String decoded = new Utf8String( DatatypeConverter.parseBase64Binary( PsBasic.AUTH.split(headers.next())[1] ) ).asString().trim(); final String user = decoded.split(":")[0]; final Opt<Identity> identity = this.entry.enter( user, decoded.substring(user.length() + 1) ); if (!identity.has()) { throw new RsForward( new RsWithHeader( new RsFlash("access denied", Level.WARNING), String.format( "WWW-Authenticate: Basic ream=\"%s\"", this.realm ) ), HttpURLConnection.HTTP_UNAUTHORIZED, new RqHref.Base(request).href() ); } return identity; }

Target:
public Opt<Identity> enter(final Request request) throws IOException { final Iterator<String> headers = new RqHeaders.Smart( new RqHeaders.Base(request) ).header("authorization").iterator(); if (!headers.hasNext()) { throw new RsForward( new RsWithHeader( String.format( "WWW-Authenticate: Basic ream=\"%s\" ", this.realm ) ), HttpURLConnection.HTTP_UNAUTHORIZED, new RqHref.Base(request).href() ); } final String decoded = new UncheckedText( new TrimmedText( new Utf8String( DatatypeConverter.parseBase64Binary( PsBasic.AUTH.split(headers.next())[1] ) ) ) ).asString(); final String user = decoded.split(":")[0]; final Opt<Identity> identity = this.entry.enter( user, decoded.substring(user.length() + 1) ); if (!identity.has()) { throw new RsForward( new RsWithHeader( new RsFlash("access denied", Level.WARNING), String.format( "WWW-Authenticate: Basic ream=\"%s\"", this.realm ) ), HttpURLConnection.HTTP_UNAUTHORIZED, new RqHref.Base(request).href() ); } return identity; }
Source:
private void checkObjectCollision(AnyObjectId obj, int type, byte[] data) throws IOException { try { final ObjectLoader ldr = readCurs.open(obj, type); final byte[] existingData = ldr.getCachedBytes(data.length); if (!Arrays.equals(data, existingData)) { throw new IOException(MessageFormat.format( JGitText.get().collisionOn, obj.name())); } } catch (MissingObjectException notLocal) { } }

Target:
private void checkObjectCollision(AnyObjectId obj, int type, byte[] data) throws IOException { try { final ObjectLoader ldr = readCurs.open(obj, type); final byte[] existingData = ldr.getCachedBytes(data.length); if (!Arrays.equals(data, existingData)) { throw new IOException(MessageFormat.format( JGitText.get().collisionOn, obj.name())); } stats.increaseNumBytesDuplicated(data.length()); stats.incrementObjectsDuplicated(); } catch (MissingObjectException notLocal) { } }
Source:
public static String formatTimeAbs(long time, Resolution res) { StringBuilder str = new StringBuilder(); String stime = TIME_FORMAT.format(new Date(time / MILLISEC_IN_NS)); str.append(stime); String ns = formatNs(time, res); if (!ns.isEmpty()) { str.append('.'); str.append(ns); } return str.toString(); }

Target:
public static String formatTimeAbs(long time, Resolution res) { String stime = TIME_FORMAT.format(new Date(time / MILLISEC_IN_NS)); StringBuilder str = new StringBuilder(stime); String ns = formatNs(time, res); if (!ns.isEmpty()) { str.append('.'); str.append(ns); } return str.toString(); }
Source:
public String toString() { return file + ": " + contig.toString() + ", locus size = " + sizeInLoci(); }

Target:
public String toString() { String str = file + ": " + contig.toString() + ", locus size = " + sizeInLoci(); if (cachedSizeInBytes >= 0) { str += ", span size = " + cachedSizeInBytes; } return str; }
Source:
private <T> Message<O> toMessage(T value, Message<I> originalMessage) { logger.debug("Converting result back to message using the original message: " + originalMessage); if (value instanceof Message) { value = (T) ((Message<?>)value).getPayload(); } Message<O> result = (Message<O>) this.messageConverter.toMessage(value, originalMessage.getHeaders()); return result; }

Target:
private <T> Message<O> toMessage(T value, Message<I> originalMessage) { if (logger.isDebugEnabled()) { logger.debug("Converting result back to message using the original message: " + originalMessage); } Message<O> result = value instanceof Message ? result = (Message<O>) value : (Message<O>) this.messageConverter.toMessage(value, originalMessage.getHeaders()); return result; }
Source:
static ClassPathElement getClassPathElement(File file) throws ZipException, IOException { if (file.isDirectory()) { return new FolderPathElement(file); } else if (file.isFile()) { return new ArchivePathElement(new ZipFile(file)); } else if (file.exists()) { throw new IOException(file.getAbsolutePath() + " is not a directory neither a zip file"); } else { throw new FileNotFoundException(file.getAbsolutePath()); } }

Target:
static ClassPathElement getClassPathElement(File file) throws ZipException, IOException { if (file.isDirectory()) { return new FolderPathElement(file); } else if (file.isFile()) { return new ArchivePathElement(new ZipFile(file)); } else if (file.exists()) { throw new IOException("\"" + file.getPath() + "\" is not a directory neither a zip file"); } else { throw new FileNotFoundException("File \"" + file.getPath() + "\" not found"); } }
Source:
public void finished(boolean successful, Operation operation) { statistics.record(this, operation); this.successful = successful; }

Target:
public void finished(boolean successful, Operation operation) { this.successful = successful; statistics.record(this, operation); }
Source:
public boolean install(Resource r, ResourceLocation location, Reference ref, ResourceTable table, AndroidCommCarePlatform platform, boolean upgrade, boolean recovery) throws UnresolvedResourceException, UnfullfilledRequirementsException { super.install(r, location, ref, table, platform, upgrade, recovery); storeReleasedTime(platform, ref); InputStream inputStream = null; try { Reference local = ReferenceManager.instance().DeriveReference(localLocation); inputStream = local.getStream(); ProfileParser parser = new ProfileParser(inputStream, platform, table, r.getRecordGuid(), Resource.RESOURCE_STATUS_UNINITIALIZED, false); Profile p = parser.parse(); if (recovery) { validateRecovery(platform, p); } if (!upgrade) { initProperties(p); if (!recovery) { checkDuplicate(p); checkAppTarget(); } } table.commitCompoundResource(r, upgrade ? Resource.RESOURCE_STATUS_UPGRADE : Resource.RESOURCE_STATUS_INSTALLED, p.getVersion()); return true; } catch (XmlPullParserException | InvalidReferenceException | IOException e) { e.printStackTrace(); } catch (InvalidStructureException e) { throw new UnresolvedResourceException(r, "Invalid content in the Profile Definition: " + e.getMessage(), true); } finally { try { if (inputStream != null) { inputStream.close(); } } catch (IOException e) { e.printStackTrace(); } } return false; }

Target:
public boolean install(Resource r, ResourceLocation location, Reference ref, ResourceTable table, AndroidCommCarePlatform platform, boolean upgrade, boolean recovery) throws UnresolvedResourceException, UnfullfilledRequirementsException { super.install(r, location, ref, table, platform, upgrade, recovery); try { storeReleasedTime(platform, ref); } catch (ParseException e) { Logger.exception("Error on parsing x-commcarehq-appreleasedon header", e); throw new InvalidResourceException(r.getDescriptor(), e.getMessage()); } InputStream inputStream = null; try { Reference local = ReferenceManager.instance().DeriveReference(localLocation); inputStream = local.getStream(); ProfileParser parser = new ProfileParser(inputStream, platform, table, r.getRecordGuid(), Resource.RESOURCE_STATUS_UNINITIALIZED, false); Profile p = parser.parse(); if (recovery) { validateRecovery(platform, p); } if (!upgrade) { initProperties(p); if (!recovery) { checkDuplicate(p); checkAppTarget(); } } table.commitCompoundResource(r, upgrade ? Resource.RESOURCE_STATUS_UPGRADE : Resource.RESOURCE_STATUS_INSTALLED, p.getVersion()); return true; } catch (XmlPullParserException | InvalidReferenceException | IOException e) { e.printStackTrace(); } catch (InvalidStructureException e) { throw new UnresolvedResourceException(r, "Invalid content in the Profile Definition: " + e.getMessage(), true); } finally { try { if (inputStream != null) { inputStream.close(); } } catch (IOException e) { e.printStackTrace(); } } return false; }
Source:
public void prepare(Map stormConf, TopologyContext context, final OutputCollector collector) { Object maxPending = stormConf.get(Config.TOPOLOGY_SHELLBOLT_MAX_PENDING); if (maxPending != null && maxPending instanceof Number) { this._pendingWrites = new LinkedBlockingQueue(((Number)maxPending).intValue()); } _rand = new Random(); _process = new ShellProcess(_command); _collector = collector; try { Number subpid = _process.launch(stormConf, context); LOG.info("Launched subprocess with pid " + subpid); } catch (IOException e) { throw new RuntimeException("Error when launching multilang subprocess\n" + _process.getErrorsString(), e); } _readerThread = new Thread(new Runnable() { public void run() { while (_running) { try { JSONObject action = _process.readMessage(); if (action == null) { } String command = (String) action.get("command"); if(command.equals("ack")) { handleAck(action); } else if (command.equals("fail")) { handleFail(action); } else if (command.equals("error")) { handleError(action); } else if (command.equals("log")) { String msg = (String) action.get("msg"); LOG.info("Shell msg: " + msg); } else if (command.equals("emit")) { handleEmit(action); } } catch (InterruptedException e) { } catch (Throwable t) { die(t); } } } }); _readerThread.start(); _writerThread = new Thread(new Runnable() { public void run() { while (_running) { try { Object write = _pendingWrites.poll(1, SECONDS); if (write != null) { _process.writeMessage(write); } _process.drainErrorStream(); } catch (InterruptedException e) { } catch (Throwable t) { die(t); } } } }); _writerThread.start(); }

Target:
public void prepare(Map stormConf, TopologyContext context, final OutputCollector collector) { Object maxPending = stormConf.get(Config.TOPOLOGY_SHELLBOLT_MAX_PENDING); if (maxPending != null) { this._pendingWrites = new LinkedBlockingQueue(((Number)maxPending).intValue()); } _rand = new Random(); _process = new ShellProcess(_command); _collector = collector; try { Number subpid = _process.launch(stormConf, context); LOG.info("Launched subprocess with pid " + subpid); } catch (IOException e) { throw new RuntimeException("Error when launching multilang subprocess\n" + _process.getErrorsString(), e); } _readerThread = new Thread(new Runnable() { public void run() { while (_running) { try { JSONObject action = _process.readMessage(); if (action == null) { } String command = (String) action.get("command"); if(command.equals("ack")) { handleAck(action); } else if (command.equals("fail")) { handleFail(action); } else if (command.equals("error")) { handleError(action); } else if (command.equals("log")) { String msg = (String) action.get("msg"); LOG.info("Shell msg: " + msg); } else if (command.equals("emit")) { handleEmit(action); } } catch (InterruptedException e) { } catch (Throwable t) { die(t); } } } }); _readerThread.start(); _writerThread = new Thread(new Runnable() { public void run() { while (_running) { try { Object write = _pendingWrites.poll(1, SECONDS); if (write != null) { _process.writeMessage(write); } _process.drainErrorStream(); } catch (InterruptedException e) { } catch (Throwable t) { die(t); } } } }); _writerThread.start(); }
Source:
private EntityDamageHandler getEntityDamageHandler() { return (e, entity, item1) -> { if (entity instanceof Skeleton || entity instanceof SkeletonHorse) { ((Creature) entity).damage(e.getFinalDamage() + 4D); e.setCancelled(true); } }; }

Target:
private EntityDamageHandler getEntityDamageHandler() { return (e, entity, item1) -> { if (entity instanceof Skeleton || entity instanceof SkeletonHorse) { e.setDamage(e.getFinalDamage() + 4); } }; }
Source:
public void testAggregationPushdownThroughOuterJoinNotFiringInCorrelatedAggregatesRightSide() { assertQuery("SELECT max(y) from (SELECT * from (VALUES 1) t(x) LEFT JOIN (VALUES 1) t2(y) ON t.x = t2.y) GROUP BY y", "VALUES 1"); }

Target:
public void testAggregationPushdownThroughOuterJoinNotFiringInCorrelatedAggregatesRightSide() { assertQuery("SELECT max(y) FROM" + "(SELECT * from (VALUES 1) t(x) LEFT JOIN (VALUES 1) t2(y) ON t.x = t2.y)" + "GROUP BY y", "VALUES 1"); }
Source:
private void setTitleSpan(Editable editable) { for (RelativeSizeSpan span : editable.getSpans(0, editable.length(), RelativeSizeSpan.class)) { editable.removeSpan(span); } for (StyleSpan span : editable.getSpans(0, editable.length(), StyleSpan.class)) { editable.removeSpan(span); } int newLinePosition = getNoteContentString().indexOf("\n"); if (newLinePosition == 0) { return; } int titleEndPosition = (newLinePosition > 0) ? newLinePosition : editable.length(); editable.setSpan(new RelativeSizeSpan(1.3f), 0, titleEndPosition, Spanned.SPAN_INCLUSIVE_EXCLUSIVE); editable.setSpan(new StyleSpan(Typeface.BOLD), 0, titleEndPosition, Spanned.SPAN_INCLUSIVE_EXCLUSIVE); }

Target:
private void setTitleSpan(Editable editable) { for (MetricAffectingSpan span : editable.getSpans(0, editable.length(), MetricAffectingSpan.class)) { editable.removeSpan(span); } int newLinePosition = getNoteContentString().indexOf("\n"); if (newLinePosition == 0) { return; } int titleEndPosition = (newLinePosition > 0) ? newLinePosition : editable.length(); editable.setSpan(new RelativeSizeSpan(1.3f), 0, titleEndPosition, Spanned.SPAN_INCLUSIVE_EXCLUSIVE); editable.setSpan(new StyleSpan(Typeface.BOLD), 0, titleEndPosition, Spanned.SPAN_INCLUSIVE_EXCLUSIVE); }
Source:
private void setTaskOffsetSumDataFromTaskOffsetSumMap(final Map<TaskId, Long> taskOffsetSums) { final Map<Integer, List<SubscriptionInfoData.PartitionToOffsetSum>> topicGroupIdToPartitionOffsetSum = new HashMap<>(); for (final Map.Entry<TaskId, Long> taskEntry : taskOffsetSums.entrySet()) { final TaskId task = taskEntry.getKey(); topicGroupIdToPartitionOffsetSum.putIfAbsent(task.topicGroupId, new ArrayList<>()); topicGroupIdToPartitionOffsetSum.get(task.topicGroupId).add( new SubscriptionInfoData.PartitionToOffsetSum() .setPartition(task.partition) .setOffsetSum(taskEntry.getValue())); } data.setTaskOffsetSums(topicGroupIdToPartitionOffsetSum.entrySet().stream().map(t -> { final SubscriptionInfoData.TaskOffsetSum taskOffsetSum = new SubscriptionInfoData.TaskOffsetSum(); taskOffsetSum.setTopicGroupId(t.getKey()); taskOffsetSum.setPartitionToOffsetSum(t.getValue()); return taskOffsetSum; }).collect(Collectors.toList())); }

Target:
private void setTaskOffsetSumDataFromTaskOffsetSumMap(final Map<TaskId, Long> taskOffsetSums) { final Map<Integer, List<SubscriptionInfoData.PartitionToOffsetSum>> topicGroupIdToPartitionOffsetSum = new HashMap<>(); for (final Map.Entry<TaskId, Long> taskEntry : taskOffsetSums.entrySet()) { final TaskId task = taskEntry.getKey(); topicGroupIdToPartitionOffsetSum.computeIfAbsent(task.topicGroupId, t -> new ArrayList<>()).add( new SubscriptionInfoData.PartitionToOffsetSum() .setPartition(task.partition) .setOffsetSum(taskEntry.getValue())); } data.setTaskOffsetSums(topicGroupIdToPartitionOffsetSum.entrySet().stream().map(t -> { final SubscriptionInfoData.TaskOffsetSum taskOffsetSum = new SubscriptionInfoData.TaskOffsetSum(); taskOffsetSum.setTopicGroupId(t.getKey()); taskOffsetSum.setPartitionToOffsetSum(t.getValue()); return taskOffsetSum; }).collect(Collectors.toList())); }
Source:
public IssueColumn(UI ui, Stage mainStage, Model model, ColumnControl parentColumnControl, int columnIndex, TurboCommandExecutor dragAndDropExecutor) { super(mainStage, model, parentColumnControl, columnIndex, dragAndDropExecutor); this.ui = ui; getChildren().add(createFilterBox()); setupIssueColumnDragEvents(model, columnIndex); this.setOnMouseClicked(e-> { ui.triggerEvent(new ColumnClickedEvent(columnIndex)); getParent().requestFocus(); }); focusedProperty().addListener(new ChangeListener<Boolean>() { @Override public void changed(ObservableValue<? extends Boolean> unused, Boolean wasFocused, Boolean isFocused) { if (!isFocused) { if (getStyleClass().contains("issue-panel-focused")) getStyleClass().remove("issue-panel-focused"); return; } getStyleClass().add("issue-panel-focused"); } }); }

Target:
public IssueColumn(UI ui, Stage mainStage, Model model, ColumnControl parentColumnControl, int columnIndex, TurboCommandExecutor dragAndDropExecutor) { super(mainStage, model, parentColumnControl, columnIndex, dragAndDropExecutor); this.ui = ui; getChildren().add(createFilterBox()); setupIssueColumnDragEvents(model, columnIndex); this.setOnMouseClicked(e-> { ui.triggerEvent(new ColumnClickedEvent(columnIndex)); getParent().requestFocus(); }); focusedProperty().addListener(new ChangeListener<Boolean>() { @Override public void changed(ObservableValue<? extends Boolean> unused, Boolean wasFocused, Boolean isFocused) { if (isFocused) { getStyleClass().add("issue-panel-focused"); } else { getStyleClass().remove("issue-panel-focused"); } } }); }
Source:
public static List<InetSocketAddress> getRMAddresses(Configuration conf) { List<InetSocketAddress> rmAddresses = new ArrayList<>(); String rmWebAppAddress = conf.get(YarnConfiguration.RM_WEBAPP_ADDRESS); if (rmWebAppAddress != null) { if (ConfigUtils.isRMHAEnabled(conf)) { for (String rmId : ConfigUtils.getRMHAIds(conf)) { InetSocketAddress socketAddress = getRMWebAddress(conf, rmId); rmAddresses.add(socketAddress); } } else { InetSocketAddress socketAddress = getRMWebAddress(conf, null); rmAddresses.add(socketAddress); } } return rmAddresses; }

Target:
public static List<InetSocketAddress> getRMAddresses(Configuration conf) { List<InetSocketAddress> rmAddresses = new ArrayList<>(); if (ConfigUtils.isRMHAEnabled(conf)) { for (String rmId : ConfigUtils.getRMHAIds(conf)) { InetSocketAddress socketAddress = getRMWebAddress(conf, rmId); rmAddresses.add(socketAddress); } } else { InetSocketAddress socketAddress = getRMWebAddress(conf, null); rmAddresses.add(socketAddress); } return rmAddresses; }
Source:
public static final List<ConsumableInArrearDetail> fromJson(String itemDetails){ List<ConsumableInArrearDetail> toBeBilledConsumableInArrearDetails = null; if (itemDetails != null){ ObjectMapper objectMapper = new ObjectMapper(); try { toBeBilledConsumableInArrearDetails = objectMapper.reader() .forType(new TypeReference<List<ConsumableInArrearDetail>>() {}) .readValue(itemDetails); } catch (IOException e) { Preconditions.checkState(false, e.getMessage()); } } return toBeBilledConsumableInArrearDetails; }

Target:
private static final List<UsageInArrearDetail> fromJson(String itemDetails){ List<UsageInArrearDetail> toBeBilledUsageInArrearDetails = null; if (itemDetails != null){ try { toBeBilledUsageInArrearDetails = objectMapper.readValue(itemDetails, new TypeReference<List<UsageInArrearDetail>>() {}); } catch (IOException e) { Preconditions.checkState(false, e.getMessage()); } } return toBeBilledUsageInArrearDetails; }
Source:
Mono<Response<SearchDocument>> getDocumentWithResponse(String key, List<String> selectedFields, RequestOptions requestOptions, Context context) { try { return restClient.documents() .getWithRestResponseAsync(key, selectedFields, RequestOptionsConverter.map(requestOptions), context) .onErrorMap(DocumentResponseConversions::exceptionMapper) .map(res -> { ObjectMapper mapper = new ObjectMapper(); SerializationUtil.configureMapper(mapper); SearchDocument document = mapper.convertValue(res.getValue(), SearchDocument.class); return new SimpleResponse<>(res, document); }) .map(Function.identity()); } catch (RuntimeException ex) { return monoError(logger, ex); } }

Target:
Mono<Response<SearchDocument>> getDocumentWithResponse(String key, List<String> selectedFields, RequestOptions requestOptions, Context context) { try { return restClient.documents() .getWithRestResponseAsync(key, selectedFields, RequestOptionsConverter.map(requestOptions), context) .onErrorMap(DocumentResponseConversions::exceptionMapper) .map(res -> { SearchDocument document = MAPPER.convertValue(res.getValue(), SearchDocument.class); return new SimpleResponse<>(res, document); }) .map(Function.identity()); } catch (RuntimeException ex) { return monoError(logger, ex); } }
Source:
public void testFirstBlockedThenSucceed() throws Exception { final int size = 1024; final long capacity = 1024; final long maxBlockTimeInMs = 200; SimpleByteBufferPool pool = new SimpleByteBufferPool(capacity); CountDownLatch[] allocated = new CountDownLatch[2]; CountDownLatch[] used = new CountDownLatch[2]; BufferConsumer[] consumers = new BufferConsumer[2]; Thread[] consumerThreads = new Thread[2]; for (int i = 0; i < 2; i++) { allocated[i] = new CountDownLatch(1); used[i] = new CountDownLatch(1); consumers[i] = new BufferConsumer(size, maxBlockTimeInMs, pool, allocated[i], used[i]); consumerThreads[i] = new Thread(consumers[i]); } consumerThreads[0].start(); if (!allocated[0].await(100, TimeUnit.MILLISECONDS)) { fail("SimpleByteBufferPool takes too long time to allocate a buffer to BufferConsumer[0]."); } assertEquals(0, pool.availableMemory()); consumerThreads[1].start(); used[0].countDown(); consumerThreads[0].join(); used[1].countDown(); consumerThreads[1].join(); for (int i = 0; i < 2; i++) { if (consumers[i].exception != null) { throw consumers[i].exception; } } assertEquals(capacity, pool.availableMemory()); }

Target:
public void testFirstBlockedThenSucceed() throws Exception { final int size = 1024; final long capacity = 1024; final long maxBlockTimeInMs = 200; SimpleByteBufferPool pool = new SimpleByteBufferPool(capacity); CountDownLatch[] allocated = new CountDownLatch[2]; CountDownLatch[] used = new CountDownLatch[2]; BufferConsumer[] consumers = new BufferConsumer[2]; Thread[] consumerThreads = new Thread[2]; for (int i = 0; i < 2; i++) { allocated[i] = new CountDownLatch(1); used[i] = new CountDownLatch(1); consumers[i] = new BufferConsumer(size, maxBlockTimeInMs, pool, allocated[i], used[i]); consumerThreads[i] = new Thread(consumers[i]); } consumerThreads[0].start(); if (!allocated[0].await(100, TimeUnit.MILLISECONDS)) { fail("SimpleByteBufferPool takes too long time to allocate a buffer to BufferConsumer[0]."); } assertEquals(0, pool.availableMemory()); consumerThreads[1].start(); assertEquals("BufferConsumer-1 should not have got buffer from the buffer pool.", 1, allocated[1].getCount()); used[0].countDown(); consumerThreads[0].join(); used[1].countDown(); consumerThreads[1].join(); for (int i = 0; i < 2; i++) { if (consumers[i].exception != null) { throw consumers[i].exception; } } assertEquals(capacity, pool.availableMemory()); }
Source:
public void sleep(long millis) { try { Thread.sleep(millis); } catch (InterruptedException e) { logger.warn(e.getMessage()); Thread.currentThread().interrupt(); } }

Target:
public void sleep(long millis) { try { Thread.sleep(millis); } catch (InterruptedException e) { logger.trace(e.getMessage()); Thread.currentThread().interrupt(); } }