auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { super.onCreateView(inflater, container, savedInstanceState); View root = inflater.inflate(R.layout.all_episodes_fragment, container, false); txtvInformation = root.findViewById(R.id.txtvInformation); recyclerView = root.findViewById(android.R.id.list); recyclerView.setVisibility(View.GONE); recyclerView.setRecycledViewPool(((MainActivity) getActivity()).getRecycledViewPool()); setupLoadMoreScrollListener(); RecyclerView.ItemAnimator animator = recyclerView.getItemAnimator(); if (animator instanceof SimpleItemAnimator) { ((SimpleItemAnimator) animator).setSupportsChangeAnimations(false); } SwipeRefreshLayout swipeRefreshLayout = root.findViewById(R.id.swipeRefresh); swipeRefreshLayout.setOnRefreshListener(() -> { AutoUpdateManager.runImmediate(requireContext()); new Handler().postDelayed(() -> getActivity().runOnUiThread(() -> swipeRefreshLayout.setRefreshing(false)) , 1000); }); progLoading = root.findViewById(R.id.progLoading); progLoading.setVisibility(View.VISIBLE); loadingMoreView = root.findViewById(R.id.loadingMore); emptyView = new EmptyViewHandler(getContext()); emptyView.attachToRecyclerView(recyclerView); emptyView.setIcon(R.attr.feed); emptyView.setTitle(R.string.no_all_episodes_head_label); emptyView.setMessage(R.string.no_all_episodes_label); createRecycleAdapter(recyclerView, emptyView); emptyView.hide(); return root; }

Target:
public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { super.onCreateView(inflater, container, savedInstanceState); View root = inflater.inflate(R.layout.all_episodes_fragment, container, false); txtvInformation = root.findViewById(R.id.txtvInformation); recyclerView = root.findViewById(android.R.id.list); recyclerView.setVisibility(View.GONE); recyclerView.setRecycledViewPool(((MainActivity) getActivity()).getRecycledViewPool()); setupLoadMoreScrollListener(); RecyclerView.ItemAnimator animator = recyclerView.getItemAnimator(); if (animator instanceof SimpleItemAnimator) { ((SimpleItemAnimator) animator).setSupportsChangeAnimations(false); } SwipeRefreshLayout swipeRefreshLayout = root.findViewById(R.id.swipeRefresh); swipeRefreshLayout.setOnRefreshListener(() -> { AutoUpdateManager.runImmediate(requireContext()); new Handler().postDelayed(() -> swipeRefreshLayout.setRefreshing(false), getResources().getInteger(R.integer.swipe_to_refresh_duration_in_ms)); }); progLoading = root.findViewById(R.id.progLoading); progLoading.setVisibility(View.VISIBLE); loadingMoreView = root.findViewById(R.id.loadingMore); emptyView = new EmptyViewHandler(getContext()); emptyView.attachToRecyclerView(recyclerView); emptyView.setIcon(R.attr.feed); emptyView.setTitle(R.string.no_all_episodes_head_label); emptyView.setMessage(R.string.no_all_episodes_label); createRecycleAdapter(recyclerView, emptyView); emptyView.hide(); return root; }
Source:
public void throw_IllegalArgumentException_if_trying_to_update_builtin_rule_description() throws Exception { logInAsQProfileAdministrator(); RuleDefinitionDto templateRule = db.rules().insert( r -> r.setRuleKey(RuleKey.of("java", "S001")), r -> r.setIsTemplate(true), r -> r.setCreatedAt(PAST), r -> r.setDescription("Old description"), r -> r.setUpdatedAt(PAST)); expectedException.expect(IllegalArgumentException.class); expectedException.expectMessage("Not a custom rule"); ws.newRequest().setMethod("POST") .setParam("key", templateRule.getKey().toString()) .setParam("name", "My custom rule") .setParam("markdown_description", "New description") .execute(); }

Target:
public void throw_IllegalArgumentException_if_trying_to_update_builtin_rule_description() throws Exception { logInAsQProfileAdministrator(); RuleDefinitionDto rule = db.rules().insert(); expectedException.expect(IllegalArgumentException.class); expectedException.expectMessage("Not a custom rule"); ws.newRequest().setMethod("POST") .setParam("key", rule.getKey().toString()) .setParam("name", rule.getName()) .setParam("markdown_description", "New description") .execute(); }
Source:
protected void readTimedOut(ChannelHandlerContext ctx) throws Exception { if (!closed) { ctx.fireExceptionCaught(new ReadTimeoutException()); ctx.close(); closed = true; } }

Target:
protected void readTimedOut(ChannelHandlerContext ctx) throws Exception { if (!closed) { ctx.fireExceptionCaught(ReadTimeoutException.INSTANCE); ctx.close(); closed = true; } }
Source:
public Sequence<T> run(final Query<T> query, final Map<String, Object> responseContext) { final ServiceMetricEvent.Builder builder = builderFn.apply(query); for (Map.Entry<String, String> userDimension : userDimensions.entrySet()) { builder.setDimension(userDimension.getKey(), userDimension.getValue()); } return Sequences.wrap( new LazySequence<>(new Supplier<Sequence<T>>() { @Override public Sequence<T> get() { return queryRunner.run(query, responseContext); } }), new SequenceWrapper() { private long startTime; @Override public void before() { startTime = System.currentTimeMillis(); } @Override public void after(boolean isDone, Throwable thrown) { try { long timeTaken = System.currentTimeMillis() - startTime; emitter.emit(builder.build(metricName, timeTaken)); if (creationTime > 0) { emitter.emit(builder.build("query/wait/time", startTime - creationTime)); } } finally { if (thrown != null) { builder.setDimension(DruidMetrics.STATUS, "failed"); } else if (!isDone) { builder.setDimension(DruidMetrics.STATUS, "short"); } } } } ); }

Target:
public Sequence<T> run(final Query<T> query, final Map<String, Object> responseContext) { final ServiceMetricEvent.Builder builder = builderFn.apply(query); for (Map.Entry<String, String> userDimension : userDimensions.entrySet()) { builder.setDimension(userDimension.getKey(), userDimension.getValue()); } return Sequences.wrap( new LazySequence<>(new Supplier<Sequence<T>>() { @Override public Sequence<T> get() { return queryRunner.run(query, responseContext); } }), new SequenceWrapper() { private long startTime; @Override public void before() { startTime = System.currentTimeMillis(); } @Override public void after(boolean isDone, Throwable thrown) { if (thrown != null) { builder.setDimension(DruidMetrics.STATUS, "failed"); } else if (!isDone) { builder.setDimension(DruidMetrics.STATUS, "short"); } long timeTaken = System.currentTimeMillis() - startTime; emitter.emit(builder.build(metricName, timeTaken)); if (creationTime > 0) { emitter.emit(builder.build("query/wait/time", startTime - creationTime)); } } } ); }
Source:
public JobModel getJobModel() { LOG.info("Reading the job model from blob."); JobModelBundle jmBundle = getJobModelBundle(); if (jmBundle == null) { LOG.error("Job Model details don't exist on the blob."); return null; } JobModel jm = jmBundle.getCurrJobModel(); if (jm == null) { LOG.error("Job Model doesn't exist on the blob."); } return jm; }

Target:
public JobModel getJobModel() { LOG.info("Reading the job model from blob."); JobModelBundle jmBundle = getJobModelBundle(); if (jmBundle == null) { LOG.error("Job Model details don't exist on the blob."); return null; } JobModel jm = jmBundle.getCurrJobModel(); return jm; }
Source:
public Response execute() throws IOException { SettableFuture<Response> future = SettableFuture.create(); enqueue(new Callback() { @Override public void onFailure(Call call, IOException exception) { future.setException(exception); } @Override public void onResponse(Call call, Response response) throws IOException { future.set(response); } }); try { return syncCallTimeout.isZero() ? future.get() : future.get(syncCallTimeout.toMillis(), TimeUnit.MILLISECONDS); } catch (InterruptedException e) { getDelegate().cancel(); Thread.currentThread().interrupt(); throw new InterruptedIOException("Call was interrupted during execution"); } catch (ExecutionException e) { getDelegate().cancel(); if (e.getCause() instanceof IoRemoteException) { RemoteException wrappedException = ((IoRemoteException) e.getCause()).getWrappedException(); RemoteException correctStackTrace = new RemoteException( wrappedException.getError(), wrappedException.getStatus()); correctStackTrace.initCause(e); throw correctStackTrace; } else if (e.getCause() instanceof IoUnknownRemoteException) { UnknownRemoteException wrappedException = ((IoUnknownRemoteException) e.getCause()) .getWrappedException(); UnknownRemoteException correctStackTrace = new UnknownRemoteException( wrappedException.getStatus(), wrappedException.getBody()); correctStackTrace.initCause(e); throw correctStackTrace; } else if (e.getCause() instanceof IOException) { throw (IOException) e.getCause(); } else { throw new IOException("Failed to execute call", e); } } catch (TimeoutException e) { getDelegate().cancel(); throw new IOException("Call timed out after: " + syncCallTimeout.toString(), e); } }

Target:
public Response execute() throws IOException { SettableFuture<Response> future = SettableFuture.create(); enqueue(new Callback() { @Override public void onFailure(Call call, IOException exception) { future.setException(exception); } @Override public void onResponse(Call call, Response response) throws IOException { future.set(response); } }); try { return future.get(); } catch (InterruptedException e) { getDelegate().cancel(); Thread.currentThread().interrupt(); throw new InterruptedIOException("Call was interrupted during execution"); } catch (ExecutionException e) { getDelegate().cancel(); if (e.getCause() instanceof IoRemoteException) { RemoteException wrappedException = ((IoRemoteException) e.getCause()).getWrappedException(); RemoteException correctStackTrace = new RemoteException( wrappedException.getError(), wrappedException.getStatus()); correctStackTrace.initCause(e); throw correctStackTrace; } else if (e.getCause() instanceof IoUnknownRemoteException) { UnknownRemoteException wrappedException = ((IoUnknownRemoteException) e.getCause()) .getWrappedException(); UnknownRemoteException correctStackTrace = new UnknownRemoteException( wrappedException.getStatus(), wrappedException.getBody()); correctStackTrace.initCause(e); throw correctStackTrace; } else if (e.getCause() instanceof IOException) { throw (IOException) e.getCause(); } else { throw new IOException("Failed to execute call", e); } } }
Source:
public CompareToBuilder append(final boolean lhs, final boolean rhs) { if (comparison != 0) { return this; } if (lhs == rhs) { return this; } if (lhs) { comparison = +1; } else { comparison = -1; } return this; }

Target:
public CompareToBuilder append(final boolean lhs, final boolean rhs) { if (comparison != 0) { return this; } if (lhs == rhs) { return this; } if (lhs) { comparison = 1; } else { comparison = -1; } return this; }
Source:
private void reset(Reader reader) throws IOException { length = 0; lineOffsets = null; List<Integer> newOffsets = new ArrayList<>(); newOffsets.add(0); int c; while ((c = reader.read()) != -1) { ++length; redo_c: while (true) { switch (c) { case '\r': c = reader.read(); if (c == -1) { newOffsets.add(length); break redo_c; } ++length; if (c == '\n') { newOffsets.add(length); break redo_c; } newOffsets.add(length - 1); continue redo_c; case '\n': newOffsets.add(length); break redo_c; default: } break; } } count = newOffsets.size(); if (newOffsets.get(newOffsets.size() - 1) < length) { newOffsets.add(length); } lineOffsets = new int[newOffsets.size()]; for (int i = 0; i < lineOffsets.length; ++i) { lineOffsets[i] = newOffsets.get(i); } }

Target:
private void reset(Reader reader) throws IOException { length = 0; lineOffsets = null; List<Integer> newOffsets = new ArrayList<>(); LineBreakerScanner scanner = new LineBreakerScanner(reader); scanner.setTarget(newOffsets); scanner.consume(); length = scanner.getLength(); count = newOffsets.size() - 1; lineOffsets = new int[newOffsets.size()]; for (int i = 0; i < lineOffsets.length; ++i) { lineOffsets[i] = newOffsets.get(i); } }
Source:
static int countBitstreamLargerThanMaxSize(Context context, BundleName bundleName, Item item, String mimeList, String prop) { long size = ConfigurationManager.getLongProperty("rest", prop); int count = 0; try { for(Bundle bundle: item.getBundles()){ if (!bundle.getName().equals(bundleName.name())){ continue; } for(Bitstream bit: bundle.getBitstreams()) { for(String mime: mimeList.split(",")) { if (bit.getFormat(context).getMIMEType().equals(mime)) { if (bit.getSize() > size) { count++; } } } } } } catch (SQLException e) { } return count; }

Target:
static int countBitstreamLargerThanMaxSize(Context context, BundleName bundleName, Item item, String mimeList, String prop) { long size = ConfigurationManager.getLongProperty("rest", prop); int count = 0; try { for(Bundle bundle: item.getBundles()){ if (!bundle.getName().equals(bundleName.name())){ continue; } for(Bitstream bit: bundle.getBitstreams()) { for(String mime: mimeList.split(",")) { if (bit.getFormat(context).getMIMEType().equals(mime.trim())) { if (bit.getSize() > size) { count++; } } } } } } catch (SQLException e) { } return count; }
Source:
private File doRemoteCompile(String namespace, String mainComposite, File zippedArchive) throws ClientProtocolException, IOException { String bundleName = namespace + "." + mainComposite + ".sab"; String archiveName = zippedArchive.getName(); HttpClient client = HttpClientBuilder.create().build(); File archiveFile = new File(archiveName); HttpPost postJobWithConfig = new HttpPost(getBuildFarmURL()); postJobWithConfig.addHeader("accept", ContentType.APPLICATION_JSON.getMimeType()); FileBody bundleBody = new FileBody(archiveFile, ContentType.APPLICATION_OCTET_STREAM, archiveName); StringBody configBody = new StringBody(createBuildConfig(namespace, mainComposite), ContentType.TEXT_PLAIN); HttpEntity reqEntity = MultipartEntityBuilder.create() .addPart("inputfile", bundleBody).addPart("buildconfig", configBody) .build(); postJobWithConfig.setEntity(reqEntity); File bundle = doPostAndRetreiveFile((CloseableHttpClient) client, postJobWithConfig, bundleName); return bundle; }

Target:
private File doRemoteCompile(String namespace, String mainComposite, File zippedArchive) throws ClientProtocolException, IOException { String bundleName = namespace + "." + mainComposite + ".sab"; HttpClient client = HttpClientBuilder.create().build(); HttpPost postJobWithConfig = new HttpPost(getBuildFarmURL()); postJobWithConfig.addHeader("accept", ContentType.APPLICATION_JSON.getMimeType()); FileBody bundleBody = new FileBody(zippedArchive, ContentType.APPLICATION_OCTET_STREAM, zippedArchive.getName()); StringBody configBody = new StringBody(createBuildConfig(namespace, mainComposite), ContentType.TEXT_PLAIN); HttpEntity reqEntity = MultipartEntityBuilder.create() .addPart("inputfile", bundleBody).addPart("buildconfig", configBody) .build(); postJobWithConfig.setEntity(reqEntity); File bundle = doPostAndRetreiveFile((CloseableHttpClient) client, postJobWithConfig, bundleName); return bundle; }
Source:
public void canLockAndUnlockMultipleLocks() { LockTokenV2 token = lockSynchronously(REQUEST_1, LOCK_A); assertTrue(service.unlock(token)); assertNotLocked(LOCK_A); }

Target:
public void canLockAndUnlockMultipleLocks() { LockTokenV2 token = lockSynchronously(REQUEST_1, LOCK_A, LOCK_B, LOCK_C); assertTrue(service.unlock(token)); assertNotLocked(LOCK_A); assertNotLocked(LOCK_B); assertNotLocked(LOCK_C); }
Source:
public void focusLost(FocusEvent e) { if (this.handleFocusChanges && !e.widget.isDisposed()) { if (!commit(MoveDirectionEnum.NONE, true)) { if (e.widget instanceof Control && !e.widget.isDisposed()) { ((Control) e.widget).forceFocus(); } } else { if (!AbstractCellEditor.this.parent.isDisposed()) AbstractCellEditor.this.parent.forceFocus(); } } }

Target:
public void focusLost(FocusEvent e) { if (this.handleFocusChanges) { if (!e.widget.isDisposed() && !commit(MoveDirectionEnum.NONE, true)) { if (e.widget instanceof Control && !e.widget.isDisposed()) { ((Control) e.widget).forceFocus(); } } else { if (!AbstractCellEditor.this.parent.isDisposed()) AbstractCellEditor.this.parent.forceFocus(); } } }
Source:
public void generates_removal_after_marker_is_deleted() throws Exception { IMarker marker = this.testFile.createMarker(IMarker.PROBLEM); marker.setAttribute(IMarker.LINE_NUMBER, 1); IMarker marker2 = this.testFile.createMarker(IMarker.PROBLEM); marker2.setAttribute(IMarker.LINE_NUMBER, 2); this.workspace.save(true, null); Job.getJobManager().join(ResourcesPlugin.FAMILY_AUTO_BUILD, null); this.testFile.appendContents(generateFileStreamLines(10), true, true, null); marker.delete(); this.workspace.save(true, null); Job.getJobManager().join(ResourcesPlugin.FAMILY_AUTO_BUILD, null); ArgumentCaptor<StaticAnalysisWarningEvent> captor = ArgumentCaptor.forClass(StaticAnalysisWarningEvent.class); Mockito.verify(this.trackingEventManager, Mockito.times(3)).addEvent(captor.capture()); Assert.assertArrayEquals(captor.getAllValues().stream().map(StaticAnalysisWarningEvent::getType).toArray(), new TrackingEventType[] {TrackingEventType.SA_WARNING_CREATED, TrackingEventType.SA_WARNING_CREATED, TrackingEventType.SA_WARNING_REMOVED}); }

Target:
public void generates_removal_after_marker_is_deleted() throws Exception { IMarker marker = this.testFile.createMarker(IMarker.PROBLEM); marker.setAttribute(IMarker.LINE_NUMBER, 1); IMarker marker2 = this.testFile.createMarker(IMarker.PROBLEM); marker2.setAttribute(IMarker.LINE_NUMBER, 2); this.saveWorkspaceAndWaitForBuild(); this.testFile.appendContents(generateFileStreamLines(10), true, true, null); marker.delete(); this.saveWorkspaceAndWaitForBuild(); Assert.assertArrayEquals(generatedEvents.stream().toArray(), new TrackingEventType[] {TrackingEventType.SA_WARNING_CREATED, TrackingEventType.SA_WARNING_CREATED, TrackingEventType.SA_WARNING_REMOVED}); }
Source:
public static Object[] parseArguments(String args) throws CoreException { List<Object> result= new ArrayList<Object>(); int start= 0; int comma; while ((comma= findNextComma(args, start)) != -1) { result.add(convertArgument(args.substring(start, comma).trim())); start= comma + 1; } result.add(convertArgument(args.substring(start).trim())); return result.toArray(); }

Target:
public static Object[] parseArguments(String args) throws CoreException { List<Object> result= new ArrayList<>(); int start= 0; int comma; while ((comma= findNextComma(args, start)) != -1) { result.add(convertArgument(args.substring(start, comma).trim())); start= comma + 1; } result.add(convertArgument(args.substring(start).trim())); return result.toArray(); }
Source:
public void TopWamWikisWhereIsMyExtension_GeoEdgeFree() { WikiBasePageObject wikiPage = new WikiBasePageObject(driver); wikiPage.logInCookie(credentials.userNameStaff, credentials.passwordStaff, wikiURL); driver.get(wikiURL + URLsContent.specialWhereIsExtension); wikiPage.appendToUrl(extensionURL); wikiPage.verifyNumberOfTop1kWikis(numberOfTop1kWikis); }

Target:
public void TopWamWikisWhereIsMyExtension_GeoEdgeFree() { WikiBasePageObject wikiPage = new WikiBasePageObject(driver); wikiPage.logInCookie(credentials.userNameStaff, credentials.passwordStaff, wikiURL); wikiPage.getUrl(wikiURL + URLsContent.specialWhereIsExtension); wikiPage.appendToUrl(extensionURL); wikiPage.verifyNumberOfTop1kWikis(numberOfTop1kWikis); }
Source:
public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise prm) throws Exception { if (!(msg instanceof HttpResponse)) return; HttpResponse response = (HttpResponse) msg; Span span = ctx.channel().attr(NettyHttpTracing.SPAN_ATTRIBUTE).get(); Throwable error = null; try (SpanInScope ws = tracer.withSpanInScope(span)) { super.write(ctx, msg, prm); } catch (Exception | Error e) { error = e; throw e; } finally { handler.handleSend(response, error, span); } }

Target:
@Override public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise prm) { Span span = ctx.channel().attr(NettyHttpTracing.SPAN_ATTRIBUTE).get(); if (span == null || !(msg instanceof HttpResponse)) { ctx.write(msg, prm); return; } HttpResponse response = (HttpResponse) msg; try (SpanInScope ws = tracer.withSpanInScope(span)) { ctx.write(msg, prm); parser.response(adapter, response, null, span); span.finish(); } }
Source:
public int getDeviceCompletion(String deviceId) { addDevice(deviceId); int folderCount = 0; double sumCompletion = 0; for (String folderId : deviceFolderMap.get(deviceId).keySet()) { sumCompletion += getCompletionInfo(deviceId, folderId).completion; folderCount++; } return (int) Math.floor(sumCompletion / folderCount); }

Target:
public int getDeviceCompletion(String deviceId) { int folderCount = 0; double sumCompletion = 0; HashMap<String, CompletionInfo> folderMap = deviceFolderMap.get(deviceId); if (folderMap != null) { for (Map.Entry<String, CompletionInfo> folder : folderMap.entrySet()) { sumCompletion += folder.getValue().completion; folderCount++; } } if (folderCount == 0) { return 100; } else { return (int) Math.floor(sumCompletion / folderCount); } }
Source:
private XmlListenersConfig(final ListenersType type, final ListenersType... others) { this.parallelismLevel = type.getDispatcherConcurrency().intValue(); String threadPool = type.getDispatcherThreadPool(); Set<Listener> listenerSet = new HashSet<Listener>(); final List<ListenersType.Listener> xmlListeners = type.getListener(); extractListeners(listenerSet, xmlListeners); for (ListenersType other : others) { if (threadPool == null && other.getDispatcherThreadPool() != null) { threadPool = other.getDispatcherThreadPool(); } extractListeners(listenerSet, other.getListener()); } this.threadPool = threadPool; this.listeners = !listenerSet.isEmpty() ? listenerSet : null; }

Target:
private XmlListenersConfig(final ListenersType type, final ListenersType... others) { this.dispatcherConcurrency = type.getDispatcherConcurrency().intValue(); String threadPool = type.getDispatcherThreadPool(); Set<Listener> listenerSet = new HashSet<Listener>(); final List<ListenersType.Listener> xmlListeners = type.getListener(); extractListeners(listenerSet, xmlListeners); for (ListenersType other : others) { if (threadPool == null && other.getDispatcherThreadPool() != null) { threadPool = other.getDispatcherThreadPool(); } extractListeners(listenerSet, other.getListener()); } this.threadPool = threadPool; this.listeners = !listenerSet.isEmpty() ? listenerSet : null; }
Source:
public void pull(PullFilters pullFilters, IPullController.Callback callback, Context context) { Log.d(TAG, "Starting PULL process..."); try { callback.onStep(PullStep.METADATA); mPullController.populateMetadataFromCsvs(pullFilters.isAutoConfig()); OrganisationUnit organisationUnit = null; if (pullFilters.isAutoConfig()) { try { organisationUnit = getOrgUnitByPhone(context, callback); } catch (ApiCallException e) { throw new AutoconfigureException(); } } if (pullFilters.isDemo()) { callback.onComplete(); } else { mPullController.pullMetada(pullFilters, callback); } } catch (Exception ex) { Log.e(TAG, "pull: " + ex.getLocalizedMessage()); ex.printStackTrace(); callback.onError(ex); } }

Target:
public void pull(PullFilters pullFilters, IPullController.Callback callback, Context context) { Log.d(TAG, "Starting PULL process..."); try { callback.onStep(PullStep.METADATA); mPullController.populateMetadataFromCsvs(pullFilters.isAutoConfig()); if (pullFilters.isAutoConfig()) { try { autoConfigureByPhone(context, callback, pullFilters); } catch (ApiCallException e) { throw new AutoconfigureException(); } } else { downloadMetadata(pullFilters, callback); } } catch (Exception ex) { Log.e(TAG, "pull: " + ex.getLocalizedMessage()); ex.printStackTrace(); callback.onError(ex); } }
Source:
protected void acquireRecoveryMemory(KeyExtent extent) { if (!extent.isMeta()) { recoveryLock.lock(); } }

Target:
void acquireRecoveryMemory(KeyExtent extent) { if (!extent.isMeta()) { recoveryLock.lock(); } }
Source:
public void noBodyForHeadTest() { EmbeddedChannel channel = createEmbeddedChannel(); for (Map.Entry<RestServiceErrorCode, HttpResponseStatus> entry : REST_SERVICE_ERROR_CODE_TO_HTTP_RESPONSE_STATUS_MAP .entrySet()) { HttpHeaders httpHeaders = new DefaultHttpHeaders(); httpHeaders.set(MockNettyMessageProcessor.REST_SERVICE_ERROR_CODE_HEADER_NAME, entry.getKey()); channel.writeInbound(RestTestUtils .createRequest(HttpMethod.HEAD, TestingUri.OnResponseCompleteWithRestException.toString(), httpHeaders)); HttpResponse response = (HttpResponse) channel.readOutbound(); assertEquals("Unexpected response status", entry.getValue(), response.getStatus()); if (response instanceof FullHttpResponse) { assertEquals("The response should not contain content", 0, ((FullHttpResponse) response).content().readableBytes()); } else { HttpContent content = (HttpContent) channel.readOutbound(); assertTrue("End marker should be received", content instanceof LastHttpContent); } assertNull("There should be no more data in the channel", channel.readOutbound()); boolean shouldBeAlive = !NettyResponseChannel.CLOSE_CONNECTION_ERROR_STATUSES.contains(entry.getValue()); assertEquals("Channel state (open/close) not as expected", shouldBeAlive, channel.isActive()); assertEquals("Connection header should be consistent with channel state", shouldBeAlive, HttpHeaders.isKeepAlive(response)); if (!shouldBeAlive) { channel = createEmbeddedChannel(); } } channel.close(); }

Target:
public void noBodyForHeadTest() { EmbeddedChannel channel = createEmbeddedChannel(); for (Map.Entry<RestServiceErrorCode, HttpResponseStatus> entry : REST_ERROR_CODE_TO_HTTP_STATUS.entrySet()) { HttpHeaders httpHeaders = new DefaultHttpHeaders(); httpHeaders.set(MockNettyMessageProcessor.REST_SERVICE_ERROR_CODE_HEADER_NAME, entry.getKey()); channel.writeInbound(RestTestUtils .createRequest(HttpMethod.HEAD, TestingUri.OnResponseCompleteWithRestException.toString(), httpHeaders)); HttpResponse response = (HttpResponse) channel.readOutbound(); assertEquals("Unexpected response status", entry.getValue(), response.getStatus()); if (response instanceof FullHttpResponse) { assertEquals("The response should not contain content", 0, ((FullHttpResponse) response).content().readableBytes()); } else { HttpContent content = (HttpContent) channel.readOutbound(); assertTrue("End marker should be received", content instanceof LastHttpContent); } assertNull("There should be no more data in the channel", channel.readOutbound()); boolean shouldBeAlive = !NettyResponseChannel.CLOSE_CONNECTION_ERROR_STATUSES.contains(entry.getValue()); assertEquals("Channel state (open/close) not as expected", shouldBeAlive, channel.isActive()); assertEquals("Connection header should be consistent with channel state", shouldBeAlive, HttpHeaders.isKeepAlive(response)); if (!shouldBeAlive) { channel = createEmbeddedChannel(); } } channel.close(); }
Source:
private void assignPartitionsStates(boolean resetOwners) { Map<String, List<SupplyPartitionInfo>> supplyInfoMap = log.isInfoEnabled() ? new ConcurrentHashMap<>() : null; try { U.doInParallel( cctx.kernalContext().getSystemExecutorService(), nonLocalCacheGroupDescriptors(), grpDesc -> { CacheGroupContext grpCtx = cctx.cache().cacheGroup(grpDesc.groupId()); GridDhtPartitionTopology top = grpCtx != null ? grpCtx.topology() : cctx.exchange().clientTopology(grpDesc.groupId(), events().discoveryCache()); if (CU.isPersistentCache(grpDesc.config(), cctx.gridConfig().getDataStorageConfiguration())) { List<SupplyPartitionInfo> list = assignPartitionStates(top, resetOwners); if (supplyInfoMap != null && !F.isEmpty(list)) supplyInfoMap.put(grpDesc.cacheOrGroupName(), list); } else if (resetOwners) assignPartitionSizes(top); return null; } ); } catch (IgniteCheckedException e) { throw new IgniteException("Failed to assign partition states", e); } if (log.isInfoEnabled() && !F.isEmpty(supplyInfoMap)) printPartitionRebalancingFully(supplyInfoMap); timeBag.finishGlobalStage("Assign partitions states"); }

Target:
private void assignPartitionsStates(boolean resetOwners) { Map<String, List<SupplyPartitionInfo>> supplyInfoMap = log.isInfoEnabled() ? new ConcurrentHashMap<>() : null; try { U.doInParallel( cctx.kernalContext().getSystemExecutorService(), nonLocalCacheGroupDescriptors(), grpDesc -> { CacheGroupContext grpCtx = cctx.cache().cacheGroup(grpDesc.groupId()); GridDhtPartitionTopology top = grpCtx != null ? grpCtx.topology() : cctx.exchange().clientTopology(grpDesc.groupId(), events().discoveryCache()); if (CU.isPersistentCache(grpDesc.config(), cctx.gridConfig().getDataStorageConfiguration())) { List<SupplyPartitionInfo> list = assignPartitionStates(top, resetOwners); if (supplyInfoMap != null && !F.isEmpty(list)) supplyInfoMap.put(grpDesc.cacheOrGroupName(), list); } else if (resetOwners) assignPartitionSizes(top); return null; } ); } catch (IgniteCheckedException e) { throw new IgniteException("Failed to assign partition states", e); } if (!F.isEmpty(supplyInfoMap)) printPartitionRebalancingFully(supplyInfoMap); timeBag.finishGlobalStage("Assign partitions states"); }
Source:
public static String truncate(String index, int shortestLength) { return index.substring(0, shortestLength); }

Target:
private static String truncate(String index, int shortestLength) { return index.substring(0, shortestLength); }
Source:
private void renderCombinedEventScripts() { StringBuilder combinedScript = new StringBuilder(); for (HeaderItem curItem : domReadyItemsToBeRendered) { if (markItemRendered(curItem)) { combinedScript.append('\n'); if (curItem instanceof OnDomReadyHeaderItem) { combinedScript.append(((OnDomReadyHeaderItem)curItem).getJavaScript()); } else if (curItem instanceof OnEventHeaderItem) { combinedScript.append(((OnEventHeaderItem)curItem).getCompleteJavaScript()); } combinedScript.append(';'); } } if (combinedScript.length() > 0) { combinedScript.append("\nWicket.Event.publish(Wicket.Event.Topic.AJAX_HANDLERS_BOUND);"); getRealResponse().render(OnDomReadyHeaderItem.forScript(combinedScript.append('\n'))); } combinedScript.setLength(0); String lastId = null; for (OnLoadHeaderItem curItem : loadItemsToBeRendered) { if (markItemRendered(curItem)) { if (!Strings.isEmpty(curItem.getId())) { lastId = curItem.getId(); } combinedScript.append('\n'); combinedScript.append(curItem.getJavaScript()); combinedScript.append(';'); } } if (combinedScript.length() > 0) { getRealResponse().render(OnLoadHeaderItem.forScript(combinedScript.append('\n'), lastId)); } }

Target:
private void renderCombinedEventScripts() { StringBuilder combinedScript = new StringBuilder(); for (HeaderItem curItem : domReadyItemsToBeRendered) { if (markItemRendered(curItem)) { combinedScript.append('\n'); if (curItem instanceof OnDomReadyHeaderItem) { combinedScript.append(((OnDomReadyHeaderItem)curItem).getJavaScript()); } else if (curItem instanceof OnEventHeaderItem) { combinedScript.append(((OnEventHeaderItem)curItem).getCompleteJavaScript()); } combinedScript.append(';'); } } if (combinedScript.length() > 0) { combinedScript.append("\nWicket.Event.publish(Wicket.Event.Topic.AJAX_HANDLERS_BOUND);"); getRealResponse().render(OnDomReadyHeaderItem.forScript(combinedScript.append('\n'))); } combinedScript.setLength(0); for (OnLoadHeaderItem curItem : loadItemsToBeRendered) { if (markItemRendered(curItem)) { combinedScript.append('\n'); combinedScript.append(curItem.getJavaScript()); combinedScript.append(';'); } } if (combinedScript.length() > 0) { getRealResponse().render(OnLoadHeaderItem.forScript(combinedScript.append('\n'))); } }
Source:
public static Event<WebSocketFrameError> webSocketFrameError(){ return new Event<>(domainName+".webSocketFrameError",map("requestId", WebSocketFrameError.class)); }

Target:
public static Event<WebSocketFrameError> webSocketFrameError() { return new Event<>(DOMAIN_NAME + ".webSocketFrameError", map("requestId", WebSocketFrameError.class)); }
Source:
public void process(KeyFilter keyFilter, CacheLoaderTask cacheLoaderTask, Executor executor, boolean loadValues, boolean loadMetadata) { int batchSize = 100; ExecutorAllCompletionService eacs = new ExecutorAllCompletionService(executor); final TaskContext taskContext = new TaskContextImpl(); Set<Object> allKeys = new HashSet<Object>(batchSize); Set<Object> batch = new HashSet<Object>(); loadAllKeys(state.get(), allKeys, keyFilter, executor); for (Iterator it = allKeys.iterator(); it.hasNext(); ) { batch.add(it.next()); if (batch.size() == batchSize) { final Set<Object> toHandle = batch; batch = new HashSet<Object>(batchSize); submitProcessTask(cacheLoaderTask, eacs, taskContext, toHandle); } } if (!batch.isEmpty()) { submitProcessTask(cacheLoaderTask, eacs, taskContext, batch); } eacs.waitUntilAllCompleted(); if (eacs.isExceptionThrown()) { throw new CacheLoaderException("Execution exception!"); } }

Target:
public void process(KeyFilter keyFilter, CacheLoaderTask cacheLoaderTask, Executor executor, boolean loadValues, boolean loadMetadata) { int batchSize = 100; ExecutorAllCompletionService eacs = new ExecutorAllCompletionService(executor); final TaskContext taskContext = new TaskContextImpl(); Set<Object> allKeys = new HashSet<Object>(batchSize); Set<Object> batch = new HashSet<Object>(); loadAllKeys(state.get(), allKeys, keyFilter, executor); for (Iterator it = allKeys.iterator(); it.hasNext(); ) { batch.add(it.next()); if (batch.size() == batchSize) { final Set<Object> toHandle = batch; batch = new HashSet<Object>(batchSize); submitProcessTask(cacheLoaderTask, eacs, taskContext, toHandle); } } if (!batch.isEmpty()) { submitProcessTask(cacheLoaderTask, eacs, taskContext, batch); } eacs.waitUntilAllCompleted(); if (eacs.isExceptionThrown()) { throw new CacheLoaderException("Execution exception!", eacs.getFirstException()); } }
Source:
public void convert_using_main_title() throws IOException { Result sourceDataset = minimalEntityBuilder(ID, InfoSpaceConstants.SEMANTIC_CLASS_INSTANCE_TYPE_DATASET); addTitle(sourceDataset, OTHER_TITLE, null); addTitle(sourceDataset, TITLE, InfoSpaceConstants.SEMANTIC_CLASS_MAIN_TITLE); DataSetReference metadata = converter.convert(sourceDataset); assertNotNull(metadata); assertEquals(2, metadata.getTitles().size()); assertEquals(OTHER_TITLE, metadata.getTitles().get(0)); assertEquals(TITLE, metadata.getTitles().get(1)); }

Target:
public void convert_using_main_title() { Result sourceDataset = minimalEntityBuilder(ID, InfoSpaceConstants.SEMANTIC_CLASS_INSTANCE_TYPE_DATASET); addTitle(sourceDataset, OTHER_TITLE, null); addTitle(sourceDataset, TITLE, InfoSpaceConstants.SEMANTIC_CLASS_MAIN_TITLE); DataSetReference metadata = converter.convert(sourceDataset); assertNotNull(metadata); assertEquals(2, metadata.getTitles().size()); assertEquals(OTHER_TITLE, metadata.getTitles().get(0)); assertEquals(TITLE, metadata.getTitles().get(1)); }
Source:
public CompletableFuture<Void> closeAsync() { jobManagerRunnerFuture.handle((runner, throwable) -> { if (throwable == null) { CompletableFuture<Void> jobManagerRunnerClose = jobManagerRunnerFuture.thenCompose( AutoCloseableAsync::closeAsync); FutureUtils.forward(jobManagerRunnerClose, terminationFuture); } else { terminationFuture.complete(null); } return null; }); return terminationFuture; }

Target:
public CompletableFuture<Void> closeAsync() { FutureUtils.assertNoException(jobManagerRunnerFuture.handle((runner, throwable) -> { if (throwable == null) { CompletableFuture<Void> jobManagerRunnerClose = jobManagerRunnerFuture.thenCompose( AutoCloseableAsync::closeAsync); FutureUtils.forward(jobManagerRunnerClose, terminationFuture); } else { terminationFuture.complete(null); } return null; })); return terminationFuture; }
Source:
public List<Integer> getRunningFlows(int projectId, String flowId) { ArrayList<Integer> executionIds = new ArrayList<Integer>(); getRunningFlowsHelper(projectId, flowId, executionIds, queuedFlowMap.values()); getRunningFlowsHelper(projectId, flowId, executionIds, runningFlows.values()); return executionIds; }

Target:
public List<Integer> getRunningFlows(int projectId, String flowId) { List<Integer> executionIds = new ArrayList<Integer>(); executionIds.addAll(getRunningFlowsHelper(projectId, flowId, queuedFlows.getAllEntries())); executionIds.addAll(getRunningFlowsHelper(projectId, flowId, runningFlows.values())); return executionIds; }
Source:
public Subject extractSubject(String token) { try { final Claims claims = jwtParser.parseClaimsJws(token).getBody(); final String userId = claims.get(USER_ID_CLAIM, String.class); final String userName = userManager.getById(userId).getName(); final String workspaceId = claims.get(WORKSPACE_ID_CLAIM, String.class); return new MachineTokenAuthorizedSubject( new SubjectImpl(userName, userId, token, false), permissionChecker, workspaceId); } catch (NotFoundException e) { throw new JwtException("User for this token no longer exist."); } catch (ServerException | JwtException e) { throw new JwtException(e.getMessage(), e); } }

Target:
public Subject extractSubject(String token) { try { final Claims claims = jwtParser.parseClaimsJws(token).getBody(); final String userId = claims.get(USER_ID_CLAIM, String.class); final String userName = userManager.getById(userId).getName(); final String workspaceId = claims.get(WORKSPACE_ID_CLAIM, String.class); return new MachineTokenAuthorizedSubject( new SubjectImpl(userName, userId, token, false), permissionChecker, workspaceId); } catch (NotFoundException e) { throw new JwtException("Corresponding user doesn't exist."); } catch (ServerException | JwtException e) { throw new JwtException(e.getMessage(), e); } }
Source:
public void setData(@Nullable LatencyAnalysis analysis) { if (analysis == null) { updateModel(null); return; } ISegmentStore<ISegment> results = analysis.getResults(); if (results != null) { updateModel(new LatencyDataStore(results)); return; } updateModel(null); LatencyViewerUtils.runAnalysis(fListener); }

Target:
public void setData(@Nullable LatencyAnalysis analysis) { if (analysis == null) { updateModel(null); return; } ISegmentStore<ISegment> results = analysis.getResults(); if (results != null) { updateModel(new LatencyDataStore(results)); return; } updateModel(null); analysis.addListener(fListener); analysis.schedule(); }
Source:
public static int numWorkers(CuratorFramework curator) { int numWorkers = 0; try { if (curator.checkExists().forPath(ZookeeperPath.FINDERS) != null) { for (String path : curator.getChildren().forPath(ZookeeperPath.FINDERS)) { if (path.startsWith("f-")) { numWorkers++; } } } } catch (Exception e) { throw new RuntimeException(e); } return numWorkers; }

Target:
public static int numWorkers(CuratorFramework curator) { int numWorkers = 0; try { if (curator.checkExists().forPath(ZookeeperPath.FINDERS) != null) { for (String path : curator.getChildren().forPath(ZookeeperPath.FINDERS)) { if (path.startsWith(PartitionManager.ZK_FINDER_PREFIX)) { numWorkers++; } } } } catch (Exception e) { throw new RuntimeException(e); } return numWorkers; }
Source:
public synchronized String nextNumber(Project project, User user) { Query query = currentSession().createQuery("from SampleNumberPerProjectImpl sn where sn.project = :project"); query.setParameter("project", project); SampleNumberPerProject sampleNumberPerProject = (SampleNumberPerProject) query.uniqueResult(); if (sampleNumberPerProject == null) { sampleNumberPerProject = createSampleNumberPerProject(project, user); } Integer highestSampleNumber = sampleNumberPerProject.getHighestSampleNumber(); highestSampleNumber++; sampleNumberPerProject.setHighestSampleNumber(highestSampleNumber); sampleNumberPerProject.setUpdatedBy(user); sampleNumberPerProject.setLastUpdated(new Date()); addSampleNumberPerProject(sampleNumberPerProject); return padInteger(sampleNumberPerProject.getPadding(), highestSampleNumber); }

Target:
public synchronized String nextNumber(Project project, User user) { Query query = currentSession().createQuery("from SampleNumberPerProjectImpl sn where sn.project = :project"); query.setParameter("project", project); SampleNumberPerProject sampleNumberPerProject = (SampleNumberPerProject) query.uniqueResult(); if (sampleNumberPerProject == null) { sampleNumberPerProject = createSampleNumberPerProject(project, user); } Integer highestSampleNumber = sampleNumberPerProject.getHighestSampleNumber(); highestSampleNumber++; sampleNumberPerProject.setHighestSampleNumber(highestSampleNumber); sampleNumberPerProject.setUpdatedBy(user); update(sampleNumberPerProject); return padInteger(sampleNumberPerProject.getPadding(), highestSampleNumber); }
Source:
public float getVolume(String sinkId) { AudioSink sink = null; if (sinkId == null) { sink = getSink(); } else { sink = audioSinks.get(sinkId); } if (sink != null) { try { return sink.getVolume(); } catch (IOException e) { logger.error("An exception occured while getting the volume of sink : '{}'", sink.getId(), e.getMessage()); } } return 0; }

Target:
public float getVolume(String sinkId) { AudioSink sink = getSink(sinkId); if (sink != null) { try { return sink.getVolume(); } catch (IOException e) { logger.error("An exception occured while getting the volume of sink : '{}'", sink.getId(), e.getMessage()); } } return 0; }
Source:
void deadLetterMessage(MessagingEntityType entityType, boolean isSessionEnabled) { setSenderAndReceiver(entityType, isSessionEnabled); final String messageId = UUID.randomUUID().toString(); final ServiceBusMessage message = getMessage(messageId, isSessionEnabled); sendMessage(message); final IterableStream<ServiceBusReceivedMessage> messageIte = receiver.receive(1, TIMEOUT); Assertions.assertNotNull(messageIte); final List<ServiceBusReceivedMessage> asList = messageIte.stream().collect(Collectors.toList()); ServiceBusReceivedMessage receivedMessage = asList.get(0); assertNotNull(receivedMessage); receiver.deadLetter(receivedMessage); messagesPending.decrementAndGet(); }

Target:
void deadLetterMessage(MessagingEntityType entityType, boolean isSessionEnabled) { setSenderAndReceiver(entityType, isSessionEnabled); final String messageId = UUID.randomUUID().toString(); final ServiceBusMessage message = getMessage(messageId, isSessionEnabled); final int maxMessages = 1; sendMessage(message); final IterableStream<ServiceBusReceivedMessage> messages = receiver.receive(maxMessages, TIMEOUT); Assertions.assertNotNull(messages); final List<ServiceBusReceivedMessage> asList = messages.stream().collect(Collectors.toList()); assertEquals(maxMessages, asList.size()); final ServiceBusReceivedMessage receivedMessage = asList.get(0); assertNotNull(receivedMessage); receiver.deadLetter(receivedMessage); messagesPending.decrementAndGet(); }
Source:
public static String getQualifiedNameLabelWithSufficientDepth(final NamedElement namedElement, final Namespace model) { Assert.isNotNull(namedElement); StringBuffer label = new StringBuffer(); List<Package> importedPackages = null; if (null != model) { importedPackages = new ArrayList<Package>(model.getImportedPackages()); } List<Namespace> visitedNamespaces = new ArrayList<Namespace>(); Namespace currentNamespace = namedElement.getNamespace(); boolean rootFound = false; boolean modelIsTheRoot = false; while (currentNamespace != null && !rootFound) { visitedNamespaces.add(currentNamespace); if (null != importedPackages || null != model) { if (importedPackages.contains(currentNamespace) || currentNamespace == model) { rootFound = true; if (currentNamespace == model) { modelIsTheRoot = true; } } } Element owner = currentNamespace.getOwner(); while (owner != null && !(owner instanceof Namespace)) { owner = owner.getOwner(); } currentNamespace = owner != null ? (Namespace) owner : null; } for (int i = visitedNamespaces.size() - 1 - (modelIsTheRoot ? 1 : 0); i >= 0; i--) { label.append(visitedNamespaces.get(i).getName()); label.append("::"); } label.append(namedElement.getName()); return label.toString(); }

Target:
public static String getQualifiedNameLabelWithSufficientDepth(final NamedElement namedElement, final Namespace model) { Assert.isNotNull(namedElement); StringBuffer label = new StringBuffer(); List<Package> importedPackages = null; if (null != model) { importedPackages = new ArrayList<Package>(model.getImportedPackages()); } List<Namespace> visitedNamespaces = new ArrayList<Namespace>(); Namespace currentNamespace = namedElement.getNamespace(); boolean rootFound = false; boolean modelIsTheRoot = false; while (currentNamespace != null && !rootFound) { visitedNamespaces.add(currentNamespace); if (null != importedPackages || null != model) { if (importedPackages.contains(currentNamespace) || currentNamespace == model) { rootFound = true; if (currentNamespace == model) { modelIsTheRoot = true; } } } Element owner = currentNamespace.getOwner(); while (null != owner && !(owner instanceof Namespace)) { owner = owner.getOwner(); } currentNamespace = owner != null ? (Namespace) owner : null; } int qualifiedNameDepht = visitedNamespaces.size() - 1 - (modelIsTheRoot ? 1 : 0); for (int i = qualifiedNameDepht; i >= 0; i--) { label.append(visitedNamespaces.get(i).getName()); label.append("::"); } label.append(namedElement.getName()); return label.toString(); }
Source:
public DynamicLifespanScheduler( BucketNodeMap bucketNodeMap, List<InternalNode> nodeByTaskId, List<ConnectorPartitionHandle> partitionHandles, OptionalInt concurrentLifespansPerTask) { this.bucketNodeMap = requireNonNull(bucketNodeMap, "bucketNodeMap is null"); if (bucketNodeMap.isDynamic() && bucketNodeMap.getBucketToNode().size() != 0) { this.nodeByTaskId = bucketNodeMap.getBucketToNode(); } else { this.nodeByTaskId = requireNonNull(nodeByTaskId, "nodeByTaskId is null"); } this.partitionHandles = unmodifiableList(new ArrayList<>( requireNonNull(partitionHandles, "partitionHandles is null"))); this.concurrentLifespansPerTask = requireNonNull(concurrentLifespansPerTask, "concurrentLifespansPerTask is null"); concurrentLifespansPerTask.ifPresent(lifespansPerTask -> checkArgument(lifespansPerTask >= 1, "concurrentLifespansPerTask must be great or equal to 1 if present")); int bucketCount = partitionHandles.size(); verify(bucketCount > 0); this.runningDriverGroupIdsByTask = new IntSet[nodeByTaskId.size()]; for (int i = 0; i < nodeByTaskId.size(); i++) { runningDriverGroupIdsByTask[i] = new IntOpenHashSet(); } this.taskByDriverGroup = new int[bucketCount]; this.driverGroupQueue = new IntArrayFIFOQueue(bucketCount); for (int i = 0; i < bucketCount; i++) { taskByDriverGroup[i] = NOT_ASSIGNED; driverGroupQueue.enqueue(i); } this.failedTasks = new IntOpenHashSet(); }

Target:
public DynamicLifespanScheduler( BucketNodeMap bucketNodeMap, List<InternalNode> nodeByTaskId, List<ConnectorPartitionHandle> partitionHandles, OptionalInt concurrentLifespansPerTask) { this.bucketNodeMap = requireNonNull(bucketNodeMap, "bucketNodeMap is null"); this.nodeByTaskId = requireNonNull(nodeByTaskId, "nodeByTaskId is null"); this.partitionHandles = unmodifiableList(new ArrayList<>( requireNonNull(partitionHandles, "partitionHandles is null"))); this.concurrentLifespansPerTask = requireNonNull(concurrentLifespansPerTask, "concurrentLifespansPerTask is null"); concurrentLifespansPerTask.ifPresent(lifespansPerTask -> checkArgument(lifespansPerTask >= 1, "concurrentLifespansPerTask must be great or equal to 1 if present")); int bucketCount = partitionHandles.size(); verify(bucketCount > 0); this.runningDriverGroupIdsByTask = new IntSet[nodeByTaskId.size()]; for (int i = 0; i < nodeByTaskId.size(); i++) { runningDriverGroupIdsByTask[i] = new IntOpenHashSet(); } this.taskByDriverGroup = new int[bucketCount]; this.noPreferenceDriverGroups = new IntArrayFIFOQueue(); this.nodeToPreferredDriverGroups = new HashMap<>(); Set<InternalNode> nodeSet = ImmutableSet.copyOf(nodeByTaskId); for (int i = 0; i < bucketCount; i++) { taskByDriverGroup[i] = NOT_ASSIGNED; if (bucketNodeMap.getAssignedNode(i).isPresent() && nodeSet.contains(bucketNodeMap.getAssignedNode(i).get())) { InternalNode preferredNode = bucketNodeMap.getAssignedNode(i).get(); nodeToPreferredDriverGroups.computeIfAbsent(preferredNode, k -> new IntArrayFIFOQueue()); nodeToPreferredDriverGroups.get(preferredNode).enqueue(i); } else { noPreferenceDriverGroups.enqueue(i); } } this.failedTasks = new IntOpenHashSet(); }