auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public boolean onOptionsItemSelected(MenuItem item) { int itemId = item.getItemId(); if (itemId == R.id.edit_task) { mCallback.onEditTask(mTaskUri, mContentSet); return true; } else if (itemId == R.id.delete_task) { new AlertDialog.Builder(getActivity()).setTitle(R.string.confirm_delete_title).setCancelable(true) .setNegativeButton(android.R.string.cancel, new OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { } }).setPositiveButton(android.R.string.ok, new OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { if (mContentSet != null) { mContentSet.delete(mAppContext); mCallback.onDelete(mTaskUri); } } }).setMessage(R.string.confirm_delete_message).create().show(); return true; } else if (itemId == R.id.complete_task) { completeTask(); return true; } else if (itemId == R.id.pin_task) { if (TaskFieldAdapters.PINNED.get(mContentSet)) { item.setIcon(R.drawable.ic_pin_white_24dp); TaskNotificationHandler.unpinTask(mAppContext, mContentSet); } else { item.setIcon(R.drawable.ic_pin_off_white_24dp); TaskNotificationHandler.pinTask(mAppContext, mContentSet); } persistTask(); return true; } else if (itemId == R.id.share_task) { shareTaskDescription(); return true; } else { return super.onOptionsItemSelected(item); } }

Target:
public boolean onOptionsItemSelected(MenuItem item) { int itemId = item.getItemId(); if (itemId == R.id.edit_task) { mCallback.onEditTask(mTaskUri, mContentSet); return true; } else if (itemId == R.id.delete_task) { new AlertDialog.Builder(getActivity()).setTitle(R.string.confirm_delete_title).setCancelable(true) .setNegativeButton(android.R.string.cancel, new OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { } }).setPositiveButton(android.R.string.ok, new OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { if (mContentSet != null) { mContentSet.delete(mAppContext); mCallback.onDelete(mTaskUri); } } }).setMessage(R.string.confirm_delete_message).create().show(); return true; } else if (itemId == R.id.complete_task) { completeTask(); return true; } else if (itemId == R.id.pin_task) { if (TaskFieldAdapters.PINNED.get(mContentSet)) { item.setIcon(R.drawable.ic_pin_white_24dp); TaskNotificationHandler.unpinTask(mAppContext, mContentSet); } else { item.setIcon(R.drawable.ic_pin_off_white_24dp); TaskNotificationHandler.pinTask(mAppContext, mContentSet); } persistTask(); return true; } else if (itemId == R.id.opentasks_share_task) { setShareMenuIntent(); return false; } else { return super.onOptionsItemSelected(item); } }
Source:
public void classTearDown() throws IOException { generateResultAnalysis("InstructorStudentEnrollmentLNPTest", 0.2, 60000); deleteTestData(JSON_DATA_PATH); deleteDataFiles(); }

Target:
public void classTearDown() throws IOException { deleteTestData(); deleteDataFiles(); }
Source:
public void setProgressBarVisibility(boolean visibility) { if(visibility) { submitConfirm.setClickable(false); } else { submitConfirm.setClickable(true); } progressBar.setVisibility(visibility ? View.VISIBLE : View.GONE); }

Target:
public void setProgressBarVisibility(boolean visibility) { submitConfirm.setEnabled(!visibility); progressBar.setVisibility(visibility ? View.VISIBLE : View.GONE); }
Source:
private void cleanupWorkflow(String workflow, WorkflowConfig workflowcfg) { LOG.info("Cleaning up workflow: " + workflow); HelixDataAccessor accessor = _manager.getHelixDataAccessor(); for (String job : workflowcfg.getJobDag().getAllNodes()) { cleanupJob(job, workflow); } if (workflowcfg.isTerminable() || workflowcfg.getTargetState() == TargetState.DELETE) { cleanupIdealStateExtView(_manager.getHelixDataAccessor(), workflow); PropertyKey workflowCfgKey = TaskUtil.getWorkflowConfigKey(accessor, workflow); if (accessor.getProperty(workflowCfgKey) != null) { if (!accessor.removeProperty(workflowCfgKey)) { LOG.error(String.format( "Error occurred while trying to clean up workflow %s. Failed to remove node %s from Helix.", workflow, workflowCfgKey)); } } String workflowPropStoreKey = TaskUtil.getWorkflowContextKey(workflow); LOG.info("Removing workflow context: " + workflowPropStoreKey); if (!TaskUtil.removeWorkflowContext(_manager, workflow)) { LOG.error(String.format( "Error occurred while trying to clean up workflow %s. Failed to remove node %s from Helix. Aborting further clean up steps.", workflow, workflowPropStoreKey)); } _scheduledRebalancer.removeScheduledRebalance(workflow); } }

Target:
private void cleanupWorkflow(String workflow, WorkflowConfig workflowcfg) { LOG.info("Cleaning up workflow: " + workflow); HelixDataAccessor accessor = _manager.getHelixDataAccessor(); for (String job : workflowcfg.getJobDag().getAllNodes()) { cleanupJob(job, workflow); } if (workflowcfg.isTerminable() || workflowcfg.getTargetState() == TargetState.DELETE) { cleanupIdealStateExtView(_manager.getHelixDataAccessor(), workflow); PropertyKey workflowCfgKey = TaskUtil.getWorkflowConfigKey(accessor, workflow); if (accessor.getProperty(workflowCfgKey) != null) { if (!accessor.removeProperty(workflowCfgKey)) { LOG.error(String.format( "Error occurred while trying to clean up workflow %s. Failed to remove node %s from Helix.", workflow, workflowCfgKey)); } } LOG.info("Removing workflow context: " + workflow); if (!TaskUtil.removeWorkflowContext(_manager, workflow)) { LOG.error(String.format( "Error occurred while trying to clean up workflow %s. Aborting further clean up steps.", workflow)); } _scheduledRebalancer.removeScheduledRebalance(workflow); } }
Source:
public synchronized void returnConnection(PoolEntry entry) throws IOException { if (entry.isExpired()) { entry.connection.close(); } else { connections.put(entry.getKey(), entry); } }

Target:
public synchronized void returnConnection(PoolEntry entry) throws IOException { if (entry.isExpired()) { closeAsynchronously(entry); } else { connections.put(entry.getKey(), entry); } }
Source:
private void ensureUnequal(CloudFindToken token1, CloudFindToken token2) { assertFalse("Tokens should match", token1.equals(token2)); assertFalse("Tokens should match", token1.hashCode() == token2.hashCode()); }

Target:
private void ensureUnequal(CloudFindToken token1, CloudFindToken token2) { assertFalse("Tokens should match", token1.equals(token2)); }
Source:
protected void performRuntime(OperationContext context, ModelNode operation, ModelNode model) throws OperationFailedException { super.performRuntime(context, operation, model); ServiceName serviceName = TRACER_CAPABILITY.getCapabilityServiceName(context.getCurrentAddressValue()); ServiceBuilder builder = context.getServiceTarget().addService(serviceName); String outboundSocketBindingName = TracerAttributes.SENDER_BINDING.resolveModelAttribute(context, model).asStringOrNull(); Supplier<OutboundSocketBinding> outboundSocketBindingSupplier; if (outboundSocketBindingName != null) { outboundSocketBindingSupplier = builder.requires(OUTBOUND_SOCKET_BINDING_CAPABILITY.getCapabilityServiceName(outboundSocketBindingName)); } else { outboundSocketBindingSupplier = new Supplier<OutboundSocketBinding>() { @Override public OutboundSocketBinding get() { return null; } }; } TracerConfiguration config = new JaegerTracerConfiguration(context, operation, outboundSocketBindingSupplier); OpentracingConfigurationService.installTracerConfigurationService(builder, config, serviceName); }

Target:
protected void performRuntime(OperationContext context, ModelNode operation, ModelNode model) throws OperationFailedException { super.performRuntime(context, operation, model); CapabilityServiceBuilder builder = context.getCapabilityServiceTarget().addCapability(TRACER_CAPABILITY); String outboundSocketBindingName = TracerAttributes.SENDER_BINDING.resolveModelAttribute(context, model).asStringOrNull(); Supplier<OutboundSocketBinding> outboundSocketBindingSupplier; if (outboundSocketBindingName != null) { outboundSocketBindingSupplier = builder.requiresCapability(OUTBOUND_SOCKET_BINDING_CAPABILITY_NAME, OutboundSocketBinding.class, outboundSocketBindingName); } else { outboundSocketBindingSupplier = () -> null; } TracerConfiguration config = new JaegerTracerConfiguration(context, operation, outboundSocketBindingSupplier); Consumer<TracerConfiguration> injector = builder.provides(TRACER_CAPABILITY); builder.setInstance(new Service() { @Override public void start(StartContext context) { injector.accept(config); WildFlyTracerFactory.registerTracer(config.getName()).accept(config); } @Override public void stop(StopContext context) { WildFlyTracerFactory.registerTracer(config.getName()).accept(null); } }); builder.setInitialMode(ON_DEMAND).install(); }
Source:
public AnimatedFactoryV2Impl( PlatformBitmapFactory platformBitmapFactory, ExecutorSupplier executorSupplier, CountingMemoryCache<CacheKey, CloseableImage> backingCache, boolean downscaleFrameToDrawableDimensions, SerialExecutorService serialExecutorServiceForFramePreparing) { mPlatformBitmapFactory = platformBitmapFactory; mExecutorSupplier = executorSupplier; mBackingCache = backingCache; mDownscaleFrameToDrawableDimensions = downscaleFrameToDrawableDimensions; this.mSerialExecutorService = serialExecutorServiceForFramePreparing; }

Target:
public AnimatedFactoryV2Impl( PlatformBitmapFactory platformBitmapFactory, ExecutorSupplier executorSupplier, CountingMemoryCache<CacheKey, CloseableImage> backingCache, boolean downscaleFrameToDrawableDimensions, SerialExecutorService serialExecutorServiceForFramePreparing) { mPlatformBitmapFactory = platformBitmapFactory; mExecutorSupplier = executorSupplier; mBackingCache = backingCache; mDownscaleFrameToDrawableDimensions = downscaleFrameToDrawableDimensions; mSerialExecutorService = serialExecutorServiceForFramePreparing; }
Source:
public Map<String, Object> queryFilterParams(DocumentReference user, NotificationFormat format) { Map<String, Object> params = new ConcurrentHashMap<>(); try { for (NotificationPreferenceScope scope : modelBridge.getNotificationPreferenceScopes(user, format)) { final String suffix = String.format(PREFIX_FORMAT, Integer.toHexString(scope.getEventType().hashCode())); final String wikiParam = "wiki_%s"; switch (scope.getScopeReference().getType()) { case DOCUMENT: params.put(String.format(wikiParam, suffix), scope.getScopeReference().extractReference( EntityType.WIKI).getName()); params.put(String.format("page_%s", suffix), serializer.serialize(scope.getScopeReference())); break; case SPACE: params.put(String.format(wikiParam, suffix), scope.getScopeReference().extractReference( EntityType.WIKI).getName()); params.put(String.format("space_%s", suffix), escape(serializer.serialize(scope.getScopeReference())) + ".%" ); break; case WIKI: params.put(String.format(wikiParam, suffix), scope.getScopeReference().extractReference( EntityType.WIKI).getName()); break; default: break; } } } catch (NotificationException e) { logger.warn(ERROR, e); } return params; }

Target:
public Map<String, Object> queryFilterParams(DocumentReference user, NotificationFormat format) { Map<String, Object> params = new HashMap<>(); try { for (NotificationPreferenceScope scope : modelBridge.getNotificationPreferenceScopes(user, format)) { final String suffix = String.format(PREFIX_FORMAT, Integer.toHexString(scope.getEventType().hashCode())); final String wikiParam = "wiki_%s"; switch (scope.getScopeReference().getType()) { case DOCUMENT: params.put(String.format(wikiParam, suffix), scope.getScopeReference().extractReference( EntityType.WIKI).getName()); params.put(String.format("page_%s", suffix), serializer.serialize(scope.getScopeReference())); break; case SPACE: params.put(String.format(wikiParam, suffix), scope.getScopeReference().extractReference( EntityType.WIKI).getName()); params.put(String.format("space_%s", suffix), escape(serializer.serialize(scope.getScopeReference())) + ".%" ); break; case WIKI: params.put(String.format(wikiParam, suffix), scope.getScopeReference().extractReference( EntityType.WIKI).getName()); break; default: break; } } } catch (NotificationException e) { logger.warn(ERROR, e); } return params; }
Source:
public void initialize(final RequestMonitor rm) { super.initialize(new RequestMonitor(getExecutor(), rm) { @Override protected void handleSuccess() { doInitialize(rm); } }); }

Target:
public void initialize(final RequestMonitor rm) { super.initialize(new ImmediateRequestMonitor(rm) { @Override protected void handleSuccess() { doInitialize(rm); } }); }
Source:
private void subscribeSelectionUpdated(@UIEventTopic(UIEvents.Item.TOPIC_SELECTED) Event event) { if (!(event.getProperty(UIEvents.EventTags.ELEMENT) instanceof MMenuItem)) return; MMenuItem itemModel = (MMenuItem) event.getProperty(UIEvents.EventTags.ELEMENT); IContributionItem ici = getContribution(itemModel); if (ici != null) { ici.update(); } }

Target:
private void subscribeSelectionUpdated(@UIEventTopic(UIEvents.Item.TOPIC_SELECTED) Event event) { Object property = event.getProperty(UIEvents.EventTags.ELEMENT); if (!(property instanceof MMenuItem)) { return; } MMenuItem itemModel = (MMenuItem) property; IContributionItem ici = getContribution(itemModel); if (ici != null) { ici.update(); } }
Source:
public boolean isAtSCCBoundary(final Node node) { final CommunicationGroup ownGroup = this.groupMap.get(node); assert ownGroup != null; for (final Node source : this.dependencyGraph.getSourceNodes(node).keySet()) { final CommunicationGroup otherGroup = this.groupMap.get(source); assert otherGroup != null; if (!ownGroup.equals(otherGroup)) { return true; } } for (final Node target : this.dependencyGraph.getTargetNodes(node).keySet()) { final CommunicationGroup otherGroup = this.groupMap.get(target); assert otherGroup != null; if (!ownGroup.equals(otherGroup)) { return true; } } return false; }

Target:
public boolean isAtSCCBoundary(final Node node) { final CommunicationGroup ownGroup = this.groupMap.get(node); assert ownGroup != null; for (final Node source : this.dependencyGraph.getSourceNodes(node).keySet()) { final CommunicationGroup otherGroup = this.groupMap.get(source); assert otherGroup != null; if (!ownGroup.equals(otherGroup)) { return true; } } return false; }
Source:
private void InitializeHelpers() { try { for (StorageType storageType : StorageType.values()) { Class<?> actionType = null; String formattedClassName = String.format("%1$s.%2$s%3$s", ACTION_TYPE_PACKAGE, storageType.name(), ACTION_TYPE_CLASS); try { actionType = Class.forName(formattedClassName); } catch (ClassNotFoundException cnfe) { log.debug("StorageHelperDirector Error:: the lookup for following class has failed: " + formattedClassName, cnfe); } if (actionType != null) { Constructor<?> info = actionType.getConstructors()[0]; IStorageHelper currentHelper = (IStorageHelper) info.newInstance(null); _helpers.put(storageType, currentHelper); } } } catch (Exception ex) { log.error("StorageHelperDirector Error:: exception was encountered during InitializeHelpers() execution", ex); throw new ApplicationException("JTODO missing exception", ex); } }

Target:
private void InitializeHelpers() { try { for (StorageType storageType : StorageType.values()) { Class<?> actionType = null; String formattedClassName = String.format("%1$s.%2$s%3$s", ACTION_TYPE_PACKAGE, storageType.name(), ACTION_TYPE_CLASS); try { actionType = Class.forName(formattedClassName); } catch (ClassNotFoundException cnfe) { log.debugFormat("StorageHelperDirector Error:: the lookup for following class has failed: " + formattedClassName, cnfe); } if (actionType != null) { Constructor<?> info = actionType.getConstructors()[0]; IStorageHelper currentHelper = (IStorageHelper) info.newInstance(null); _helpers.put(storageType, currentHelper); } } } catch (Exception ex) { log.error("StorageHelperDirector Error:: exception was encountered during InitializeHelpers() execution", ex); throw new ApplicationException("JTODO missing exception", ex); } }
Source:
public SPromise deserialize(final DeserializationBuffer sb) { byte state = sb.get(); assert state >= 0 && state <= 2; if (state > 0) { Object value = sb.getReference(); SPromise p = SPromise.createResolved( EventualMessage.getActorCurrentMessageIsExecutionOn(), value, state == 1 ? Resolution.SUCCESSFUL : Resolution.ERRONEOUS); if (DeserializationBuffer.needsFixup(value)) { sb.installFixup(new PromiseValueFixup(p)); } return p; } else { SPromise promise = SPromise.createPromise( EventualMessage.getActorCurrentMessageIsExecutionOn(), false, false, null); int whenResolvedCnt = sb.getShort(); for (int i = 0; i < whenResolvedCnt; i++) { PromiseMessage pm = (PromiseMessage) sb.getReference(); promise.registerWhenResolvedUnsynced(pm); } int onErrorCnt = sb.getShort(); for (int i = 0; i < onErrorCnt; i++) { PromiseMessage pm = (PromiseMessage) sb.getReference(); promise.registerOnErrorUnsynced(pm); } int chainedPromCnt = sb.getShort(); for (int i = 0; i < chainedPromCnt; i++) { SPromise remote = (SPromise) sb.getReference(); promise.addChainedPromise(remote); } return promise; } }

Target:
public SPromise deserialize(final DeserializationBuffer sb) { byte state = sb.get(); assert state >= 0 && state <= 2; if (state > 0) { return deserializeCompletedPromise(state, sb); } else { return deserializeUnresolvedPromise(sb); } }
Source:
public boolean isCallPermitted() { final boolean callPermitted = semaphore.tryAcquire(); publishBulkheadEvent( () -> callPermitted ? new BulkheadOnCallPermittedEvent(name) : new BulkheadOnCallRejectedEvent(name) ); return callPermitted; }

Target:
public boolean isCallPermitted() { boolean callPermitted = tryEnterBulkhead(); publishBulkheadEvent( () -> callPermitted ? new BulkheadOnCallPermittedEvent(name) : new BulkheadOnCallRejectedEvent(name) ); return callPermitted; }
Source:
public void testWriteAndReadFromPipe() throws IOException, InterruptedException, ExecutionException, TimeoutException { final SAMRecordSetBuilder builder = new SAMRecordSetBuilder(false, SortOrder.unsorted); for (int i=1; i<= 5000; ++i) { builder.addPair("q" + i, 0, i, i); } final File fifo = File.createTempFile("fifo", ""); Assert.assertTrue(fifo.delete()); fifo.deleteOnExit(); final Process exec = new ProcessBuilder("mkfifo", fifo.getAbsolutePath()).start(); exec.waitFor(1, TimeUnit.MINUTES); Assert.assertEquals(exec.exitValue(), 0, "mkfifo failed with exit code " + 0); for (final SamInputResource res : Arrays.asList(SamInputResource.of(fifo), SamInputResource.of(fifo.toPath()))) { ExecutorService executor = null; try { executor = Executors.newSingleThreadExecutor(); final Future<Integer> future = executor.submit(() -> { final SAMFileWriter writer = new SAMFileWriterFactory() .setCreateIndex(false).setCreateMd5File(false).makeBAMWriter(builder.getHeader(), true, fifo); int written = 0; for (SAMRecord read : builder) { writer.addAlignment(read); written += 1; } writer.close(); return written; }); final SamReader in = SamReaderFactory.make().open(res); int count = 0; for (SAMRecord rec : in) { Assert.assertEquals(rec.getReadName(), "q" + rec.getAlignmentStart()); count += 1; } in.close(); Assert.assertEquals(count, builder.size()); Assert.assertEquals(count, future.get().intValue()); } finally { if (executor != null) executor.shutdownNow(); } } }

Target:
public void testWriteAndReadFromPipe() throws IOException, InterruptedException, ExecutionException, TimeoutException { final SAMRecordSetBuilder builder = new SAMRecordSetBuilder(false, SortOrder.unsorted); for (int i = 1; i <= 5000; ++i) { builder.addPair("q" + i, 0, i, i); } for (final boolean usePath : CollectionUtil.makeList(true, false)) { final File fifo = File.createTempFile("fifo", ""); Assert.assertTrue(fifo.delete()); fifo.deleteOnExit(); final Process exec = new ProcessBuilder("mkfifo", fifo.getAbsolutePath()).start(); exec.waitFor(1, TimeUnit.MINUTES); Assert.assertEquals(exec.exitValue(), 0, "mkfifo failed with exit code " + 0); ExecutorService executor = null; try { executor = Executors.newSingleThreadExecutor(); final Future<Integer> future = executor.submit(() -> { try (final SAMFileWriter writer = new SAMFileWriterFactory() .setCreateIndex(false) .setCreateMd5File(false) .makeBAMWriter(builder.getHeader(), true, fifo)) { int written = 0; for (final SAMRecord read : builder) { writer.addAlignment(read); written += 1; } return written; } }); final SamInputResource res = usePath ? SamInputResource.of(fifo.toPath()) : SamInputResource.of(fifo); int count = 0; try (final SamReader in = SamReaderFactory.make().open(res)) { for (final SAMRecord rec : in) { Assert.assertEquals(rec.getReadName(), "q" + rec.getAlignmentStart()); count += 1; } } Assert.assertEquals(count, builder.size()); Assert.assertEquals(count, future.get().intValue()); } finally { if (executor != null) executor.shutdownNow(); } } }
Source:
private void exec(String... command) throws InfrastructureException { LOG.debug( "Executing Pod={} ContainerName={} command={}", kubernetesMachine.getPodName(), kubernetesMachine.getContainerName(), command); namespace .deployments() .exec( kubernetesMachine.getPodName(), kubernetesMachine.getContainerName(), EXEC_TIMEOUT_MIN, command); }

Target:
private void exec(String... command) throws InfrastructureException { namespace .deployments() .exec( kubernetesMachine.getPodName(), kubernetesMachine.getContainerName(), EXEC_TIMEOUT_MIN, command); }
Source:
private void populateReferences() { if (!fReferenceStructs .isEmpty()) { return; } StructDeclaration ref = new StructDeclaration(ALIGN); EnumDeclaration id = new EnumDeclaration(IntegerDeclaration.createDeclaration(5, false, 10, fByteOrder, Encoding.NONE, "", 1)); id.add(0, 30, "compact"); id.add(31, 31, "extended"); ref.addField("id", id); VariantDeclaration v = new VariantDeclaration(); StructDeclaration compact = new StructDeclaration(1); compact.addField("timestamp", IntegerDeclaration.createDeclaration(27, false, 10, fByteOrder, Encoding.NONE, "", 1)); StructDeclaration extended = new StructDeclaration(8); extended.addField("id", IntegerDeclaration.createDeclaration(32, false, 10, fByteOrder, Encoding.NONE, "", 8)); extended.addField("timestamp", IntegerDeclaration.createDeclaration(64, false, 10, fByteOrder, Encoding.NONE, "", 8)); v.addField("compact", compact); v.addField("extended", extended); ref.addField("v", v); fReferenceStructs.add(ref); }

Target:
private void populateReferences() { if (!fReferenceStructs.isEmpty()) { return; } StructDeclaration ref = new StructDeclaration(ALIGN_ON_8); EnumDeclaration id = new EnumDeclaration(IntegerDeclaration.createDeclaration(COMPACT_ID, false, BASE_10, fByteOrder, Encoding.NONE, CLOCK, ALIGN_ON_1)); id.add(0, EXTENDED_VALUE - 1, COMPACT); id.add(EXTENDED_VALUE, EXTENDED_VALUE, EXTENDED); ref.addField(ID, id); VariantDeclaration v = new VariantDeclaration(); StructDeclaration compact = new StructDeclaration(ALIGN_ON_1); compact.addField(TIMESTAMP, IntegerDeclaration.createDeclaration(27, false, BASE_10, fByteOrder, Encoding.NONE, CLOCK, ALIGN_ON_1)); StructDeclaration extended = new StructDeclaration(ALIGN_ON_8); extended.addField(ID, IntegerDeclaration.createDeclaration(32, false, BASE_10, fByteOrder, Encoding.NONE, CLOCK, ALIGN_ON_8)); extended.addField(TIMESTAMP, IntegerDeclaration.createDeclaration(64, false, BASE_10, fByteOrder, Encoding.NONE, CLOCK, ALIGN_ON_8)); v.addField(COMPACT, compact); v.addField(EXTENDED, extended); ref.addField(VARIANT_NAME, v); fReferenceStructs.add(ref); }
Source:
private void validatePersonAddresses(Person person, Errors errors) { int index = 0; for (PersonAddress address : person.getAddresses()) { try { errors.pushNestedPath("addresses[" + index + "]"); personAddressValidator.validate(address, errors); } catch (NullPointerException exception) { continue; } finally { errors.popNestedPath(); index++; } } }

Target:
private void validatePersonAddresses(Person person, Errors errors) { int index = 0; for (PersonAddress address : person.getAddresses()) { try { errors.pushNestedPath("addresses[" + index + "]"); ValidationUtils.invokeValidator(personAddressValidator, address, errors); } finally { errors.popNestedPath(); index++; } } }
Source:
private List<Partition> batchGetPartitions(AWSGlueAsync glueClient, String tableName) throws IOException { List<Partition> partitions = new ArrayList<>(); try { GetPartitionsRequest getPartitionsRequest = new GetPartitionsRequest() .withCatalogId(mGlueConfiguration.get(Property.CATALOG_ID)) .withDatabaseName(mGlueDbName) .withTableName(tableName); if (glueClient.getPartitions(getPartitionsRequest).getPartitions() != null) { partitions = glueClient.getPartitions(getPartitionsRequest).getPartitions(); LOG.debug("Get partitions from Table Database {}.", partitions.size(), tableName, mGlueDbName); partitions.stream().forEach(partition -> LOG.debug("Get partition: {}, from table Database {}.", partition.toString(), tableName, partition.getDatabaseName())); } return partitions; } catch (AWSGlueException e) { throw new IOException("Cannot get partition information for table: " + tableName + " in Database: " + mGlueDbName + "; Catalog ID: " + mGlueConfiguration.get(Property.CATALOG_ID) + ". error: " + e.getMessage(), e); } }

Target:
private List<Partition> batchGetPartitions(AWSGlueAsync glueClient, String tableName) throws IOException { List<Partition> partitions = new ArrayList<>(); try { GetPartitionsRequest getPartitionsRequest = new GetPartitionsRequest() .withCatalogId(mGlueConfiguration.get(Property.CATALOG_ID)) .withDatabaseName(mGlueDbName) .withTableName(tableName); if (glueClient.getPartitions(getPartitionsRequest).getPartitions() != null) { partitions = glueClient.getPartitions(getPartitionsRequest).getPartitions(); LOG.info("Glue table {}.{} has partitions.", mGlueDbName, tableName, partitions.size()); if (LOG.isDebugEnabled()) { partitions.stream().forEach(partition -> LOG.debug("Glue table {}.{} with partition: {}.", partition.getDatabaseName(), tableName, partition.toString())); } } return partitions; } catch (AWSGlueException e) { throw new IOException("Cannot get partition information for table: " + tableName + " in Database: " + mGlueDbName + "; Catalog ID: " + mGlueConfiguration.get(Property.CATALOG_ID) + ". error: " + e.getMessage(), e); } }
Source:
private void closeRAF() { if(!(closed || lockLevel == 0)) throw new IllegalStateException(); if(raf == null) return; try { raf.close(); } catch (IOException e) { Logger.error(this, "Error closing "+this+" : "+e, e); } raf = null; OPEN_FDS--; }

Target:
private void closeRAF() { if(!closed && lockLevel != 0) throw new IllegalStateException(); if(raf == null) return; try { raf.close(); } catch (IOException e) { Logger.error(this, "Error closing "+this+" : "+e, e); } raf = null; OPEN_FDS--; }
Source:
public StreamDefinitionResource instantiateModel(StreamDefinition stream) { final StreamDefinitionResource resource = new StreamDefinitionResource(stream.getName(), new ArgumentSanitizer().sanitizeStream(stream), stream.getOriginalDslText(), stream.getDescription()); DeploymentState deploymentState = streamDeploymentStates.get(stream); if (deploymentState != null) { final DeploymentStateResource deploymentStateResource = ControllerUtils .mapState(deploymentState); resource.setStatus(deploymentStateResource.getKey()); resource.setStatusDescription(deploymentStateResource.getDescription()); } return resource; }

Target:
public StreamDefinitionResource instantiateModel(StreamDefinition stream) { final StreamDefinitionResource resource = new StreamDefinitionResource(stream.getName(), new ArgumentSanitizer().sanitizeStream(stream), new ArgumentSanitizer().sanitizeOriginalStreamDsl(stream), stream.getDescription()); DeploymentState deploymentState = streamDeploymentStates.get(stream); if (deploymentState != null) { final DeploymentStateResource deploymentStateResource = ControllerUtils .mapState(deploymentState); resource.setStatus(deploymentStateResource.getKey()); resource.setStatusDescription(deploymentStateResource.getDescription()); } return resource; }
Source:
public void shouldHaveImmutableSpliterator() { assertThat(of('1', '2', '3').spliterator().hasCharacteristics(Spliterator.IMMUTABLE)); }

Target:
public void shouldHaveImmutableSpliterator() { assertThat(of('1', '2', '3').spliterator().hasCharacteristics(Spliterator.IMMUTABLE)).isTrue(); }
Source:
public void put(K key, V value) { if (service.isRunning()) { try { String target = buildUrl(service.cacheName, key); Invocation put = service.getHttpClient().target(target).request().accept(service.getContentType()) .buildPut(Entity.entity(encodeObject(value), service.getContentType())); Response response = put.invoke(); int status = response.getStatus(); response.close(); if (status != Status.OK.getStatusCode()) { throw new RuntimeException("RESTEasyHTTPOperations.put::Unexpected HttpStatus: " + status + " " + response.getStatusInfo().getReasonPhrase() + " for request " + target); } } catch (IOException e) { throw new RuntimeException(e); } catch (NullPointerException e) { throw new RuntimeException(e); } catch (IllegalArgumentException e) { throw new RuntimeException(e); } } }

Target:
public void put(K key, V value) { putInternal(key, value, null); }
Source:
private String[] extractStateParams(String state) { final String decodedState; try { decodedState = decode(state, "UTF-8"); } catch (UnsupportedEncodingException e) { throw new RuntimeException(e); } return decodedState.split("&"); }

Target:
private String[] extractStateParams(String state) { try { String decodedState = decode(state, "UTF-8"); return decodedState.split("&"); } catch (UnsupportedEncodingException ignored) { } return null; }
Source:
public void execute() throws ResourceUnavailableException, InsufficientCapacityException, ServerApiException, ConcurrentOperationException, ResourceAllocationException, NetworkRuleConflictException { ImageStore result = _storageService.updateImageStoreStatus(getId(), getReadonly()); ImageStoreResponse storeResponse = null; if (result != null) { storeResponse = _responseGenerator.createImageStoreResponse(result); storeResponse.setResponseName(getCommandName()+"response"); storeResponse.setObjectName("imagestore"); setResponseObject(storeResponse); } else { throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to update Image store status"); } }

Target:
public void execute() { ImageStore result = _storageService.updateImageStoreStatus(getId(), getReadonly()); ImageStoreResponse storeResponse = null; if (result != null) { storeResponse = _responseGenerator.createImageStoreResponse(result); storeResponse.setResponseName(getCommandName()+"response"); storeResponse.setObjectName("imagestore"); setResponseObject(storeResponse); } else { throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to update Image store status"); } }
Source:
public MasterBenchTaskResult runLocal() throws Exception { ExecutorService service = ExecutorServiceFactories.fixedThreadPool("bench-thread", mParameters.mThreads).create(); RateLimiter rateLimiter = RateLimiter.create(mParameters.mTargetThroughput); mFiledata = new byte[(int) FormatUtils.parseSpaceSize(mParameters.mCreateFileSize)]; Arrays.fill(mFiledata, (byte) 0x7A); long durationMs = FormatUtils.parseTimeSize(mParameters.mDuration); long warmupMs = FormatUtils.parseTimeSize(mParameters.mWarmup); long startMs = mBaseParameters.mStartMs; if (mBaseParameters.mStartMs == BaseParameters.UNDEFINED_START_MS) { startMs = CommonUtils.getCurrentMs() + 1000; } long endMs = startMs + warmupMs + durationMs; BenchContext context = new BenchContext(rateLimiter, startMs, endMs); for (int i = 0; i < mParameters.mThreads; i++) { service.submit(new BenchThread(context, mCachedFs[i % mCachedFs.length])); } WaitForOptions waitOptions = WaitForOptions.defaults().setInterval(5000) .setTimeoutMs((int) (endMs - CommonUtils.getCurrentMs()) + 60000); if (mParameters.mStopCount != MasterBenchParameters.STOP_COUNT_INVALID) { waitOptions = WaitForOptions.defaults().setInterval(5000).setTimeoutMs(10 * Constants.MINUTE_MS); } CommonUtils.waitFor("Threads to terminate", () -> context.getTerminated().get() == mParameters.mThreads, waitOptions); service.shutdownNow(); service.awaitTermination(30, TimeUnit.SECONDS); return context.getResult(); }

Target:
public MasterBenchTaskResult runLocal() throws Exception { ExecutorService service = ExecutorServiceFactories.fixedThreadPool("bench-thread", mParameters.mThreads).create(); RateLimiter rateLimiter = RateLimiter.create(mParameters.mTargetThroughput); mFiledata = new byte[(int) FormatUtils.parseSpaceSize(mParameters.mCreateFileSize)]; Arrays.fill(mFiledata, (byte) 0x7A); long durationMs = FormatUtils.parseTimeSize(mParameters.mDuration); long warmupMs = FormatUtils.parseTimeSize(mParameters.mWarmup); long startMs = mBaseParameters.mStartMs; if (mBaseParameters.mStartMs == BaseParameters.UNDEFINED_START_MS) { startMs = CommonUtils.getCurrentMs() + 1000; } long endMs = startMs + warmupMs + durationMs; BenchContext context = new BenchContext(rateLimiter, startMs, endMs); List<Callable<Void>> callables = new ArrayList<>(mParameters.mThreads); for (int i = 0; i < mParameters.mThreads; i++) { callables.add(new BenchThread(context, mCachedFs[i % mCachedFs.length])); } service.invokeAll(callables, 10, TimeUnit.MINUTES); service.shutdownNow(); service.awaitTermination(30, TimeUnit.SECONDS); return context.getResult(); }
Source:
private String toString( Object obj ) { String str; if ( obj != null && obj.getClass().isArray() ) { int n = Array.getLength( obj ); StringBuilder buf = new StringBuilder( 256 ); buf.append( '[' ); for ( int i = 0; i < n; i++ ) { if ( i > 0 ) { buf.append( ", " ); } buf.append( String.valueOf( Array.get( obj, i ) ) ); } buf.append( ']' ); str = buf.toString(); } else { str = String.valueOf( obj ); } return str; }

Target:
private String toString( Object obj ) { String str; if ( obj != null && obj.getClass().isArray() ) { int n = Array.getLength( obj ); StringBuilder buf = new StringBuilder( 256 ); StringJoiner sj = new StringJoiner( ", ", "[", "]" ); for ( int i = 0; i < n; i++ ) { sj.add( String.valueOf( Array.get( obj, i ) ) ); } buf.append( sj.toString() ); str = buf.toString(); } else { str = String.valueOf( obj ); } return str; }
Source:
public void testAddFromConfiguration() throws Exception { setUriInfo(setUpGetMatrixConstraintsExpectations(BackendHostResource.REGENERATE_CONSTRAINT, false, "false", setUpBasicUriExpectations(), false)); setUpGetPayloadExpectations(1, 2); setUpGetBallooningExpectations(1, 2); setUpGetCertuficateExpectations(1, 2); setUpGetConsoleExpectations(new int[]{2}); setUpGetVirtioScsiExpectations(new int[]{2}); VM model = createModel(null); org.ovirt.engine.core.common.businessentities.VM returnedVM = getEntity(2); model.setInitialization(new Initialization()); model.getInitialization().setConfiguration(new Configuration()); model.getInitialization().getConfiguration().setData("asdasdasd"); model.getInitialization().getConfiguration().setType("ovf"); setUpGetEntityExpectations(VdcQueryType.GetVmFromConfiguration, GetVmFromConfigurationQueryParameters.class, new String[] { "VmConfiguration", "ConfigurationType" }, new Object[] { model.getInitialization().getConfiguration().getData(), ConfigurationType.OVF}, returnedVM); setUpCreationExpectations(VdcActionType.ImportVmFromConfiguration, ImportVmParameters.class, new String[] { "Vm", "VdsGroupId", "ImportAsNewEntity"}, new Object[] { returnedVM, Guid.createGuidFromString(model.getCluster().getId()), false}, true, true, GUIDS[2], VdcQueryType.GetVmByVmId, IdQueryParameters.class, new String[] { "Id" }, new Object[] { GUIDS[2] }, returnedVM); Response response = collection.add(model); assertEquals(201, response.getStatus()); assertTrue(response.getEntity() instanceof VM); verifyModel((VM) response.getEntity(), 2); }

Target:
public void testAddFromConfiguration() throws Exception { setUriInfo(setUpBasicUriExpectations()); setUpGetPayloadExpectations(1, 2); setUpGetBallooningExpectations(1, 2); setUpGetCertuficateExpectations(1, 2); setUpGetConsoleExpectations(new int[]{2}); setUpGetVmOvfExpectations(new int[]{2}); setUpGetVirtioScsiExpectations(new int[]{2}); VM model = createModel(null); org.ovirt.engine.core.common.businessentities.VM returnedVM = getEntity(2); model.setInitialization(new Initialization()); model.getInitialization().setConfiguration(new Configuration()); model.getInitialization().getConfiguration().setData("asdasdasd"); model.getInitialization().getConfiguration().setType("ovf"); setUpGetEntityExpectations(VdcQueryType.GetVmFromConfiguration, GetVmFromConfigurationQueryParameters.class, new String[] { "VmConfiguration", "ConfigurationType" }, new Object[] { model.getInitialization().getConfiguration().getData(), ConfigurationType.OVF}, returnedVM); setUpCreationExpectations(VdcActionType.ImportVmFromConfiguration, ImportVmParameters.class, new String[] { "Vm", "VdsGroupId", "ImportAsNewEntity"}, new Object[] { returnedVM, Guid.createGuidFromString(model.getCluster().getId()), false}, true, true, GUIDS[2], VdcQueryType.GetVmByVmId, IdQueryParameters.class, new String[] { "Id" }, new Object[] { GUIDS[2] }, returnedVM); Response response = collection.add(model); assertEquals(201, response.getStatus()); assertTrue(response.getEntity() instanceof VM); verifyModel((VM) response.getEntity(), 2); }
Source:
public GenericMessage<?> convert(DBObject source) { return new GenericMessage<Object>(source.get("payload"), (Map<String, Object>) source.get("headers")); }

Target:
public GenericMessage convert(DBObject source) { MessageReadingMongoConverter converter = (MessageReadingMongoConverter) MongoDbMessageStore.this.template.getConverter(); Map<String, Object> headers = converter.normalizeHeaders((Map<String, Object>) source.get("headers")); Object payload = source.get("payload"); Object payloadType = source.get(PAYLOAD_TYPE_KEY); if (payloadType != null && payload instanceof DBObject) { try { Class<?> payloadClass = ClassUtils.forName(payloadType.toString(), classLoader); payload = converter.read(payloadClass, (DBObject) payload); } catch (Exception e) { throw new IllegalStateException("failed to load class: " + payloadType, e); } } GenericMessage message = new GenericMessage(payload, headers); Map innerMap = (Map) new DirectFieldAccessor(message.getHeaders()).getPropertyValue("headers"); innerMap.put(MessageHeaders.ID, headers.get(MessageHeaders.ID)); innerMap.put(MessageHeaders.TIMESTAMP, headers.get(MessageHeaders.TIMESTAMP)); return message; }
Source:
public void getHighestUid_imapConnectionThrowsNegativesResponse_shouldReturnMinus1() throws Exception { ImapFolder folder = createFolder("Folder"); prepareImapFolderForOpen(OPEN_MODE_RW); List<ImapResponse> imapResponses = singletonList(createImapResponse("* SEARCH 42")); when(imapConnection.executeSimpleCommand("UID SEARCH *:*")) .thenThrow(NegativeImapResponseException.class); folder.open(OPEN_MODE_RW); long result = folder.getHighestUid(); assertEquals(-1L, result); }

Target:
public void getHighestUid_imapConnectionThrowsNegativesResponse_shouldReturnMinus1() throws Exception { ImapFolder folder = createFolder("Folder"); prepareImapFolderForOpen(OPEN_MODE_RW); when(imapConnection.executeSimpleCommand("UID SEARCH *:*")) .thenThrow(NegativeImapResponseException.class); folder.open(OPEN_MODE_RW); assertEquals(-1L, folder.getHighestUid()); }
Source:
public int hashCode() { return this.cluster.length() + this.path.length(); }

Target:
public int hashCode() { return new HashCodeBuilder() .append(this.cluster) .append(this.path) .toHashCode(); }
Source:
public void execute(SensorContext context) { if (rules.length == 0) { LOG.info("Skipping execution of eslint-based rules because none of them are activated"); return; } startEslintBridgeServerProcess(); if (process == null) { return; } try { for (InputFile inputFile : getInputFiles(context)) { analyze(inputFile, context); } } finally { clean(); } }

Target:
public void execute(SensorContext context) { if (rules.length == 0) { LOG.debug("Skipping execution of eslint-based rules because none of them are activated"); return; } startEslintBridgeServerProcess(); if (process == null) { return; } try { for (InputFile inputFile : getInputFiles(context)) { analyze(inputFile, context); } } finally { clean(); } }
Source:
private static String quote(String text, char quoteChar) { if (text == null || text.isEmpty()) return emptyQuoted(quoteChar); int nbMatch = 0; int start = -1; do { start = text.indexOf(quoteChar, start + 1); if (start != -1) ++nbMatch; } while (start != -1); int newLength = 2 + text.length() + nbMatch; char[] result = new char[newLength]; result[0] = quoteChar; result[newLength - 1] = quoteChar; int newIdx = 1; for (int i = 0; i < text.length(); i++) { char c = text.charAt(i); if (c == quoteChar) { result[newIdx++] = c; result[newIdx++] = c; } else { result[newIdx++] = c; } } return new String(result); }

Target:
private static String quote(String text, char quoteChar) { if (text == null || text.isEmpty()) return emptyQuoted(quoteChar); int nbMatch = 0; int start = -1; do { start = text.indexOf(quoteChar, start + 1); if (start != -1) ++nbMatch; } while (start != -1); if (nbMatch == 0) return quoteChar + text + quoteChar; int newLength = 2 + text.length() + nbMatch; char[] result = new char[newLength]; result[0] = quoteChar; result[newLength - 1] = quoteChar; int newIdx = 1; for (int i = 0; i < text.length(); i++) { char c = text.charAt(i); if (c == quoteChar) { result[newIdx++] = c; result[newIdx++] = c; } else { result[newIdx++] = c; } } return new String(result); }
Source:
static LedgerMetadataBuilder from(LedgerMetadata other) { LedgerMetadataBuilder builder = new LedgerMetadataBuilder(); builder.ensembleSize = other.getEnsembleSize(); builder.writeQuorumSize = other.getWriteQuorumSize(); builder.ackQuorumSize = other.getAckQuorumSize(); builder.state = other.getState(); long lastEntryId = other.getLastEntryId(); if (lastEntryId != LedgerHandle.INVALID_ENTRY_ID) { builder.lastEntryId = Optional.of(lastEntryId); } builder.ensembles.putAll(other.getEnsembles()); builder.digestType = other.getDigestType(); if (other.hasPassword()) { builder.password = Optional.of(other.getPassword()); } if (other.storeSystemtimeAsLedgerCreationTime) { builder.ctime = Optional.of(other.getCtime()); } builder.customMetadata.putAll(other.getCustomMetadata()); builder.version = other.getVersion(); return builder; }

Target:
static LedgerMetadataBuilder from(LedgerMetadata other) { LedgerMetadataBuilder builder = new LedgerMetadataBuilder(); builder.ensembleSize = other.getEnsembleSize(); builder.writeQuorumSize = other.getWriteQuorumSize(); builder.ackQuorumSize = other.getAckQuorumSize(); builder.state = other.getState(); long lastEntryId = other.getLastEntryId(); if (lastEntryId != LedgerHandle.INVALID_ENTRY_ID) { builder.lastEntryId = Optional.of(lastEntryId); } builder.ensembles.putAll(other.getEnsembles()); builder.digestType = other.getDigestType(); if (other.hasPassword()) { builder.password = Optional.of(other.getPassword()); } if (other.storeSystemtimeAsLedgerCreationTime) { builder.ctime = Optional.of(other.getCtime()); } builder.customMetadata = ImmutableMap.copyOf(other.getCustomMetadata()); builder.version = other.getVersion(); return builder; }
Source:
public void close() throws ItemStreamException { if (!ignoreItemStream && delegate instanceof ItemStream) { ((ItemStream) delegate).close(); } }

Target:
public void close() throws ItemStreamException { if (delegate instanceof ItemStream) { ((ItemStream) delegate).close(); } }
Source:
public static TrackingMode fromString(String trackingMode) { if(trackingMode == null) { return null; } switch(trackingMode){ case "trackingAll": return TRACK_ALL; case "discardedOnly": return TRACK_DISCARDED_ONLY; case "trackingOff": return TRACKING_OFF; default: return TRACKING_OFF; } }

Target:
public static Optional<TrackingMode> fromString(String trackingMode) { if(trackingMode == null) { return Optional.empty(); } switch(trackingMode){ case "trackingAll": return Optional.of(TRACK_ALL); case "discardedOnly": return Optional.of(TRACK_DISCARDED_ONLY); case "trackingOff": default: return Optional.of(TRACKING_OFF); } }
Source:
public boolean getSslEnabledDb() { String ssl = env.get("TWILIO_DISABLE_DB_SSL"); if (ssl != null && ssl.compareToIgnoreCase("true") == 0) { return false; } else { return true; } }

Target:
public boolean getSslEnabledDb() { return !Boolean.parseBoolean(env.get("TWILIO_DISABLE_DB_SSL")); }
Source:
static Checksum forURL(URL url) throws IOException { try { MessageDigest md = MessageDigest.getInstance(JarLoaderImpl.DIGEST_ALGORITHM); try(OutputStream ostream = new DigestOutputStream(new NullOutputStream(), md)) { Util.copy(url.openStream(), ostream); return new Checksum(md.digest(), md.getDigestLength() / 8); } } catch (NoSuchAlgorithmException e) { throw new AssertionError(e); } }

Target:
static Checksum forURL(URL url) throws IOException { try { MessageDigest md = MessageDigest.getInstance(JarLoaderImpl.DIGEST_ALGORITHM); try(InputStream istsream = url.openStream(); OutputStream ostream = new DigestOutputStream(new NullOutputStream(), md)) { Util.copy(istsream, ostream); return new Checksum(md.digest(), md.getDigestLength() / 8); } } catch (NoSuchAlgorithmException e) { throw new AssertionError(e); } }
Source:
public static int getTID(IDMContext context) { IMIExecutionDMContext execContext = DMContexts.getAncestorOfType(context, IMIExecutionDMContext.class); int tid = 0; if (execContext != null) { try { tid = Integer.parseInt(execContext.getThreadId()); } catch (NumberFormatException e) { } } return tid; }

Target:
public static int getTID(IDMContext context) { IMIExecutionDMContext execContext = DMContexts.getAncestorOfType(context, IMIExecutionDMContext.class); int tid = 0; if (execContext != null) { try { tid = Integer.parseInt(execContext.getThreadId()); } catch (NumberFormatException e) { assert false : "The thread id does not convert to an integer: " + execContext.getThreadId(); } } return tid; }
Source:
public void testConsumerRejoinAfterRebalance() throws Exception { long waitTimeout = 5_000; try (ConsumerCoordinator coordinator = prepareCoordinatorForCloseTest(true, true, Optional.of("group-id"))) { coordinator.ensureActiveGroup(); prepareOffsetCommitRequest(singletonMap(t1p, 100L), Errors.REBALANCE_IN_PROGRESS); assertThrows(CommitFailedException.class, () -> coordinator.commitOffsetsSync( singletonMap(t1p, new OffsetAndMetadata(100L)), time.timer(Long.MAX_VALUE))); assertFalse(client.hasPendingResponses()); assertFalse(client.hasInFlightRequests()); AtomicBoolean res = new AtomicBoolean(); Thread th = new Thread(() -> { coordinator.joinGroupIfNeeded(time.timer(Long.MAX_VALUE)); res.set(true); }); th.start(); client.waitForRequests(1, waitTimeout); client.respond(joinGroupFollowerResponse(1, "consumer", "leader", Errors.NONE)); waitForCondition(() -> coordinator.generation.generationId != OffsetCommitRequest.DEFAULT_GENERATION_ID, waitTimeout, "JoinGroup response handled."); client.waitForRequests(1, waitTimeout); client.respond(joinGroupFollowerResponse(1, "consumer", "leader", Errors.NONE)); client.waitForRequests(1, waitTimeout); coordinator.maybeLeaveGroup("Clear generation data."); client.respond(syncGroupResponse(singletonList(t1p), Errors.NONE)); th.join(); assertTrue(res.get()); assertFalse(client.hasPendingResponses()); assertFalse(client.hasInFlightRequests()); } }

Target:
public void testConsumerRejoinAfterRebalance() throws Exception { try (ConsumerCoordinator coordinator = prepareCoordinatorForCloseTest(true, false, Optional.of("group-id"))) { coordinator.ensureActiveGroup(); prepareOffsetCommitRequest(singletonMap(t1p, 100L), Errors.REBALANCE_IN_PROGRESS); assertThrows(CommitFailedException.class, () -> coordinator.commitOffsetsSync( singletonMap(t1p, new OffsetAndMetadata(100L)), time.timer(Long.MAX_VALUE))); assertFalse(client.hasPendingResponses()); assertFalse(client.hasInFlightRequests()); int generationId = 42; String memberId = "consumer-42"; client.prepareResponse(joinGroupFollowerResponse(generationId, memberId, "leader", Errors.NONE)); MockTime time = new MockTime(1); boolean res = coordinator.joinGroupIfNeeded(time.timer(2)); assertFalse(res); assertFalse(client.hasPendingResponses()); assertEquals(1, client.inFlightRequestCount()); assertEquals(generationId, coordinator.generation().generationId); assertEquals(memberId, coordinator.generation().memberId); coordinator.maybeLeaveGroup("Clear generation data."); assertEquals(AbstractCoordinator.Generation.NO_GENERATION, coordinator.generation()); client.respond(syncGroupResponse(singletonList(t1p), Errors.NONE)); res = coordinator.joinGroupIfNeeded(time.timer(1)); assertFalse(res); assertFalse(client.hasPendingResponses()); assertFalse(client.hasInFlightRequests()); } }