auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public HeartbeatDispatcher( ISarosSession sarosSession, UISynchronizer uiSynchronizer, ConcurrentDocumentClient cdClient) { this.sarosSession = sarosSession; this.uiSynchronizer = uiSynchronizer; <START> this.clientDocs = cdClient.getJupiterClient().getClientDocs(); <END> }</code><technical_language>Holding this map of another class instance variable strange me. hard understand map is modified externally. I prefer hold jupiter client instead request map locally in dispatchHeartbeats() time needed. this is worse performance-wise request object multiple times (periodically), I is worth code easier understand</technical_language>

Target:
public HeartbeatDispatcher( ISarosSession sarosSession, UISynchronizer uiSynchronizer, ConcurrentDocumentClient cdClient) { this.sarosSession = sarosSession; this.uiSynchronizer = uiSynchronizer; this.jupiter = cdClient.getJupiterClient(); }
Source:
<code><START> public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { <END> log.debug("Entered SsoPostLoginFilter"); HttpServletRequest req = (HttpServletRequest) request; try { String engineSessionId = (String) req.getAttribute(SessionConstants.HTTP_SESSION_ENGINE_SESSION_ID_KEY); if (StringUtils.isEmpty(engineSessionId) && req.getSession(false) != null) { engineSessionId = (String) req.getSession(false).getAttribute(SessionConstants.HTTP_SESSION_ENGINE_SESSION_ID_KEY); } if (StringUtils.isNotEmpty(engineSessionId)) { InitialContext ctx = new InitialContext(); try { String ssoToken = (String) runQuery(VdcQueryType.GetEngineSessionIdToken, engineSessionId, ctx); log.debug("Adding userInfo to session"); DbUser loggedInUser = (DbUser) runQuery(VdcQueryType.GetUserBySessionId, engineSessionId, ctx); req.getSession(true).setAttribute(ATTR_USER_INFO, getUserInfoObject(loggedInUser, ssoToken)); chain.doFilter(request, response); } finally { ctx.close(); } } else { log.info("No sessionId in request or session"); } } catch (Exception ex) { log.error("Unable to get token for engine session {}", ex.getMessage()); } log.debug("Exiting SsoPostLoginFilter"); }</code><technical_language>Please reformat, line exceeds 120 chars</technical_language>

Target:
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { log.debug("Entered SsoPostLoginFilter"); HttpServletRequest req = (HttpServletRequest) request; try { String engineSessionId = (String) req.getAttribute(SessionConstants.HTTP_SESSION_ENGINE_SESSION_ID_KEY); if (StringUtils.isEmpty(engineSessionId) && req.getSession(false) != null) { engineSessionId = (String) req.getSession(false). getAttribute(SessionConstants.HTTP_SESSION_ENGINE_SESSION_ID_KEY); } if (StringUtils.isNotEmpty(engineSessionId)) { InitialContext ctx = new InitialContext(); try { String ssoToken = (String) runQuery(VdcQueryType.GetEngineSessionIdToken, engineSessionId, ctx); log.debug("Adding userInfo to session"); DbUser loggedInUser = (DbUser) runQuery(VdcQueryType.GetUserBySessionId, engineSessionId, ctx); req.getSession(true).setAttribute(ATTR_USER_INFO, getUserInfoObject(loggedInUser, ssoToken)); chain.doFilter(request, response); } finally { ctx.close(); } } else { log.info("Missing sessionId in either request or session scope. " + "Please configure SSO properly with SsoPostLoginServlet."); } } catch (Exception ex) { log.error("Unable to get token for engine session {}", ex.getMessage()); } log.debug("Exiting SsoPostLoginFilter"); }
Source:
<code>@Nullable @Override public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { super.onCreateView(inflater, container, savedInstanceState); View view = inflater.inflate(R.layout.fragment_feed, container, false); unbinder = ButterKnife.bind(this, view); feedView.set(coordinator.getCards()); <START> ((AppCompatActivity) getActivity()).setSupportActionBar((Toolbar) view.findViewById(R.id.feed_toolbar)); <END> ((AppCompatActivity) getActivity()).getSupportActionBar().setDisplayHomeAsUpEnabled(true); coordinator.setFeedUpdateListener(new FeedCoordinator.FeedUpdateListener() { @Override public void update(List<Card> cards) { feedView.update(); } }); coordinator.more(app.getSite()); return view; }</code><technical_language>this live in FeedActivity? If signalling is necessary, a callback interface. I ultimately discarding FeedActivity easier Activity dependencies FeedFragment if live in FeedActivity</technical_language>

Target:
@Nullable @Override public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { super.onCreateView(inflater, container, savedInstanceState); View view = inflater.inflate(R.layout.fragment_feed, container, false); unbinder = ButterKnife.bind(this, view); feedView.set(coordinator.getCards()); if (getCallback() != null) { getCallback().onAddToolbar(toolbar); } coordinator.setFeedUpdateListener(new FeedCoordinator.FeedUpdateListener() { @Override public void update(List<Card> cards) { if (isAdded()) { feedView.update(); } } }); coordinator.more(app.getSite()); return view; }
Source:
<code>private Iterable<HostAndPort> getNodesHostAndPort() { Group group = Iterables.getFirst(getEntity().getGroups(), null); if (group == null) return Lists.newArrayList(); return Iterables.transform(group.getAttribute(CouchbaseCluster.COUCHBASE_CLUSTER_UP_NODES), new Function<Entity, HostAndPort>() { @Nullable @Override <START> public HostAndPort apply(@Nullable Entity input) { <END> return BrooklynAccessUtils.getBrooklynAccessibleAddress(input, input.getAttribute(CouchbaseNode.COUCHBASE_WEB_ADMIN_PORT)); } }); }</code><technical_language>@Nullable remove annotation</technical_language>

Target:
private Iterable<HostAndPort> getNodesHostAndPort() { Group group = Iterables.getFirst(getEntity().getGroups(), null); if (group == null) return Lists.newArrayList(); return Iterables.transform(group.getAttribute(CouchbaseCluster.COUCHBASE_CLUSTER_UP_NODES), new Function<Entity, HostAndPort>() { @Override public HostAndPort apply(Entity input) { return BrooklynAccessUtils.getBrooklynAccessibleAddress(input, input.getAttribute(CouchbaseNode.COUCHBASE_WEB_ADMIN_PORT)); } }); }
Source:
<code>public void removeTokenForOwnerStats(TokenIdent id) { String realOwner = getTokenRealOwner(id); if (tokenOwnerStats.containsKey(realOwner)) { <START> if (tokenOwnerStats.get(realOwner) <= 1) { <END> tokenOwnerStats.remove(realOwner); } else { tokenOwnerStats.put(realOwner, tokenOwnerStats.get(realOwner)-1); } } }</code><technical_language>tokenOwnerStats is a concurrent map, run race conditions if multiple threads operate this method time. potentially method synchronized avoid that. care this is for metrics</technical_language>

Target:
private void removeTokenForOwnerStats(TokenIdent id) { String realOwner = getTokenRealOwner(id); if (tokenOwnerStats.containsKey(realOwner)) { if (tokenOwnerStats.get(realOwner) <= 1) { tokenOwnerStats.remove(realOwner); } else { tokenOwnerStats.put(realOwner, tokenOwnerStats.get(realOwner)-1); } } }
Source:
<code>public static long skipLines( LogChannelInterface log, InputStreamReader reader, EncodingType encodingType, int fileFormatType, StringBuilder line, int nrLinesToSkip, String regex, long lineNumberInFile ) throws KettleFileException { String[] oGetline = getLine( log, reader, encodingType, fileFormatType, line, regex, lineNumberInFile ); int skipped = 1; while ( oGetline[0] != null && skipped < nrLinesToSkip ) { oGetline = getLine( log, reader, encodingType, fileFormatType, line, regex, Long.parseLong( oGetline[ 1 ] ) ); skipped++; } <START> return Long.parseLong( oGetline[ 1 ] ); <END> }</code><technical_language>hack propagates ? More unnecessary type conversion</technical_language>

Target:
public static long skipLines( LogChannelInterface log, InputStreamReader reader, EncodingType encodingType, int fileFormatType, StringBuilder line, int nrLinesToSkip, String regex, long lineNumberInFile ) throws KettleFileException { TextFileLine textFileLine = getLine( log, reader, encodingType, fileFormatType, line, regex, lineNumberInFile ); int skipped = 1; while ( textFileLine.line != null && skipped < nrLinesToSkip ) { textFileLine = getLine( log, reader, encodingType, fileFormatType, line, regex, textFileLine.lineNumber ); skipped++; } return textFileLine.lineNumber; }
Source:
<code>protected void prepare(List<? extends Modification> mods, GlobalTransaction tx) throws CacheLoaderException { if (trace) log.tracef("preparing transaction %s", tx); try { transactionRunner.prepare(new ModificationsTransactionWorker(this, mods)); Transaction txn = currentTransaction.getTransaction(); if (trace) log.tracef("transaction %s == sleepycat transaction %s", tx, txn); txnMap.put(tx, txn); try { ThreadLocal<Object> tl = (ThreadLocal<Object>) ReflectionUtil.getValue(currentTransaction, "localTrans"); tl.remove(); } catch (Exception e) { <START> log.warn("Unable to clean up BerkeleyDB thread locals."); <END> } } catch (Exception e) { throw convertToCacheLoaderException("Problem preparing transaction", e); } }</code><technical_language>If exception re-throw before: e.g. if "localTrans" is renamed this code do hacky cleanup longer.</technical_language>

Target:
protected void prepare(List<? extends Modification> mods, GlobalTransaction tx) throws CacheLoaderException { if (trace) log.tracef("preparing transaction %s", tx); try { transactionRunner.prepare(new ModificationsTransactionWorker(this, mods)); Transaction txn = currentTransaction.getTransaction(); if (trace) log.tracef("transaction %s == sleepycat transaction %s", tx, txn); txnMap.put(tx, txn); try { ThreadLocal<Object> tl = (ThreadLocal<Object>) ReflectionUtil.getValue(currentTransaction, "localTrans"); tl.remove(); } catch (Exception e) { log.warn("Unable to clean up BDBJE transaction thread locals."); throw convertToCacheLoaderException("Unable to clean up BDBJE transaction", e); } } catch (Exception e) { throw convertToCacheLoaderException("Problem preparing transaction", e); } }
Source:
<code>public void handleShutdownSignal(String consumerTag, ShutdownSignalException sig) { <START> log.info("consumer has been shutdown unexpectedly: " + consumerTag); <END> if ((this.shutdownHandler != null) && !queue.isCancelled()) { shutdownHandler.handle(sig); } }</code><technical_language>debug</technical_language>

Target:
public void handleShutdownSignal(String consumerTag, ShutdownSignalException sig) { log.debug("consumer has been shutdown unexpectedly: " + consumerTag); if ((this.shutdownHandler != null) && !queue.isCancelled()) { shutdownHandler.handle(sig); } }
Source:
<code>public String getUuid(AutoGenerationOption autoGenerationOption) { <START> return autoGenerationOption.getIdentifierType().getUuid(); <END> }</code><technical_language>This is correct for reason i above</technical_language>

Target:
public String getUuid(AutoGenerationOption autoGenerationOption) { return autoGenerationOption.getUuid(); }
Source:
<code>public MultiChannelMessageReceiver(Connector connector, FlowConstruct flowConstruct, InboundEndpoint endpoint) throws CreateException { super(connector, flowConstruct, endpoint); <START> asyncConsumersStartup = toBoolean(getProperty(MULE_ASYNC_CONSUMERS_STARTUP, "false")); <END> this.amqpConnector = (AmqpConnector) connector; declarator = new AmqpDeclarer(); numberOfChannels = new AmqpEndpointUtil().getNumberOfChannels(endpoint); }</code><technical_language>java.lang.Boolean#getBoolean get property false default do conversion too</technical_language>

Target:
public MultiChannelMessageReceiver(Connector connector, FlowConstruct flowConstruct, InboundEndpoint endpoint) throws CreateException { super(connector, flowConstruct, endpoint); asyncConsumersStartup = getBoolean(MULE_ASYNC_CONSUMERS_STARTUP); this.amqpConnector = (AmqpConnector) connector; declarator = new AmqpDeclarer(); numberOfChannels = new AmqpEndpointUtil().getNumberOfChannels(endpoint); }
Source:
<code>private void validateTargetedSequencing(LibraryDilution dilution) { if (!isTargetedSequencingInLibrary(dilution)) { <START> throw new IllegalArgumentException("Dilution Targeted Sequencing not contained in parent library"); <END> } }</code><technical_language>issue is chosen kit descriptor library se, do changing this Selected targeted sequencing is for kit parent library ? For everyone: this is a rare case (and more happen legacy dilutions opposed newly-created ones), do want append suggestions for fix it? If this is error, please contact MISO administrator targeted sequencing ${targetedSequencingName} for kit ${kitName}</technical_language>

Target:
private void validateTargetedSequencing(LibraryDilution dilution) { TargetedSequencing ts = dilution.getTargetedSequencing(); Library library = dilution.getLibrary(); if (ts == null) { if (isTargetedSequencingRequired(library)) { throw new IllegalArgumentException("Targeted sequencing value is required"); } } else { if (!isTargetedSequencingCompatible(ts, library)) { throwTargetedSequencingIncompatible(ts, library.getKitDescriptor()); } } }
Source:
<code><START> public int getValue() { <END> return intValue; }</code><technical_language>s/getValue/getId</technical_language>

Target:
public int getValue() { return id; }
Source:
<code>PartitionId getRandomWritablePartition(String partitionClass, List<PartitionId> partitionsToExclude) { PartitionId selectedPartition = null; PartitionId anyWritablePartition = null; List<PartitionId> partitionsInClass = getPartitionsInClass(partitionClass, true); int workingSize = partitionsInClass.size(); <START> while(true) { <END> if(workingSize == 0) break; int randomIndex = ThreadLocalRandom.current().nextInt(workingSize); PartitionId selected = partitionsInClass.get(randomIndex); if(partitionsToExclude == null || partitionsToExclude.size() == 0 || !partitionsToExclude.contains(selected)) { if (selected.getPartitionState() == PartitionState.READ_WRITE) { anyWritablePartition = selected; if(areAllReplicasForPartitionUp(selected)) { selectedPartition = selected; break; } } } if (randomIndex != workingSize - 1) { partitionsInClass.set(randomIndex, partitionsInClass.get(workingSize - 1)); } workingSize--; } return (selectedPartition == null) ? anyWritablePartition : selectedPartition; }</code><technical_language>changing this while (workingSize > 0) remove if-statement line 424</technical_language>

Target:
PartitionId getRandomWritablePartition(String partitionClass, List<PartitionId> partitionsToExclude) { PartitionId anyWritablePartition = null; List<PartitionId> partitionsInClass = getPartitionsInClass(partitionClass, true); int workingSize = partitionsInClass.size(); while (workingSize > 0) { int randomIndex = ThreadLocalRandom.current().nextInt(workingSize); PartitionId selected = partitionsInClass.get(randomIndex); if (partitionsToExclude == null || partitionsToExclude.size() == 0 || !partitionsToExclude.contains(selected)) { if (selected.getPartitionState() == PartitionState.READ_WRITE) { anyWritablePartition = selected; if(areEnoughReplicasForPartitionUp(selected)) { return selected; } } } if (randomIndex != workingSize - 1) { partitionsInClass.set(randomIndex, partitionsInClass.get(workingSize - 1)); } workingSize--; } return anyWritablePartition; }
Source:
<code>public T produce(CreationalContext<T> ctx) { T context; <START> if (getDelegate() instanceof ContextCreateStrategyInjectionTarget) { <END> context = super.produce(ctx); } else { ContextCreateStrategy contextCreateStrategy = getReference(manager, ContextCreateStrategy.class, extension.getContextCreateStrategy()); ContextCreateAction action = new ContextCreateAction(() -> super.produce(ctx), getAnnotatedClassLoader(annotated)); context = (T) contextCreateStrategy.createCamelContext(action); } if (context.getNameStrategy() instanceof DefaultCamelContextNameStrategy) { context.setNameStrategy(nameStrategy(annotated)); } if (context instanceof DefaultCamelContext) { DefaultCamelContext adapted = context.adapt(DefaultCamelContext.class); adapted.setRegistry(new CdiCamelRegistry(manager)); adapted.setInjector(new CdiCamelInjector(context.getInjector(), manager)); } else { throw new InjectionException("Camel CDI requires Camel context [" + context.getName() + "] to be a subtype of DefaultCamelContext"); } Set<Annotation> qualifiers = annotated.getAnnotations().stream() .filter(isAnnotationType(Named.class).negate() .and(q -> manager.isQualifier(q.annotationType()))) .collect(toSet()); qualifiers.add(ANY); if (qualifiers.size() == 1) { qualifiers.add(DEFAULT); } qualifiers.retainAll(extension.getObserverEvents()); if (!qualifiers.isEmpty()) { context.getManagementStrategy().addEventNotifier(new CdiEventNotifier(manager, qualifiers)); } return context; }</code><technical_language>if statement reveals asymmetrical design. ContextCreateStrategyInjectionTarget is composed everywhere, removed logic applied in CamelContextProducer</technical_language>

Target:
public T produce(CreationalContext<T> ctx) { T context = createCamelContextWithTCCL(() -> super.produce(ctx), annotated); if (context.getNameStrategy() instanceof DefaultCamelContextNameStrategy) { context.setNameStrategy(nameStrategy(annotated)); } if (context instanceof DefaultCamelContext) { DefaultCamelContext adapted = context.adapt(DefaultCamelContext.class); adapted.setRegistry(new CdiCamelRegistry(manager)); adapted.setInjector(new CdiCamelInjector(context.getInjector(), manager)); } else { throw new InjectionException("Camel CDI requires Camel context [" + context.getName() + "] to be a subtype of DefaultCamelContext"); } Set<Annotation> qualifiers = annotated.getAnnotations().stream() .filter(isAnnotationType(Named.class).negate() .and(q -> manager.isQualifier(q.annotationType()))) .collect(toSet()); qualifiers.add(ANY); if (qualifiers.size() == 1) { qualifiers.add(DEFAULT); } qualifiers.retainAll(extension.getObserverEvents()); if (!qualifiers.isEmpty()) { context.getManagementStrategy().addEventNotifier(new CdiEventNotifier(manager, qualifiers)); } return context; }
Source:
<code>public void execute(BasicMessageWithExtraData<ResourcePathDestination> message, WsCommandContext context) throws Exception { ResourcePathDestination request = message.getBasicMessage(); String rawResourcePath = request.getResourcePath(); if (rawResourcePath == null) { throw new IllegalStateException(request.getClass().getName() + ".resourcePath must not be null"); } log.tracef("%s is about to execute the request [%s] ", getClass().getName(), request); CanonicalPath resourcePath = CanonicalPath.fromString(rawResourcePath); String feedId = resourcePath.ids().getFeedId(); try (ConnectionContextFactory ccf = new ConnectionContextFactory(context.getConnectionFactory())) { <START> Endpoint topic = Constants.FEED_COMMAND_QUEUE; <END> ProducerConnectionContext pcc = ccf.createProducerConnectionContext(topic); MessageId mid = new MessageProcessor().send(pcc, message, Collections.singletonMap(Constants.HEADER_FEEDID, feedId)); log.debugf("Message [%s] forwarded to bus endpoint [%s]", request.getClass().getName(), topic.getName()); GenericSuccessResponse response = new GenericSuccessResponse(); response.setMessage("The request has been forwarded to feed [" + feedId + "] (MessageId=" + mid + ")"); BasicMessageWithExtraData<GenericSuccessResponse> result = new BasicMessageWithExtraData<>(response, null); new WebSocketHelper().sendSync(context.getSession(), result); } }</code><technical_language>variable name "topic" renamed</technical_language>

Target:
public void execute(BasicMessageWithExtraData<ResourcePathDestination> message, WsCommandContext context) throws Exception { ResourcePathDestination request = message.getBasicMessage(); String rawResourcePath = request.getResourcePath(); if (rawResourcePath == null) { throw new IllegalStateException(request.getClass().getName() + ".resourcePath must not be null"); } log.tracef("%s is about to execute the request [%s] ", getClass().getName(), request); CanonicalPath resourcePath = CanonicalPath.fromString(rawResourcePath); String feedId = resourcePath.ids().getFeedId(); try (ConnectionContextFactory ccf = new ConnectionContextFactory(context.getConnectionFactory())) { Endpoint endpoint = Constants.FEED_COMMAND_QUEUE; ProducerConnectionContext pcc = ccf.createProducerConnectionContext(endpoint); MessageId mid = new MessageProcessor().send(pcc, message, Collections.singletonMap(Constants.HEADER_FEEDID, feedId)); log.debugf("Message [%s] forwarded to bus endpoint [%s]", request.getClass().getName(), endpoint.getName()); GenericSuccessResponse response = new GenericSuccessResponse(); response.setMessage("The request has been forwarded to feed [" + feedId + "] (MessageId=" + mid + ")"); BasicMessageWithExtraData<GenericSuccessResponse> result = new BasicMessageWithExtraData<>(response, null); new WebSocketHelper().sendSync(context.getSession(), result); } }
Source:
<code>public String getVendorThingID() throws ThingIFException { <START> return thingIfApi.getVendorThingID(); <END> }</code><technical_language>Adding this a field is good manner</technical_language>

Target:
public String getVendorThingID() throws ThingIFException { return this.thingIfApi.getVendorThingID(); }
Source:
<code>public static void checkAnyPermission(AccessControlled ac, Permission[] permissions) { if (permissions == null) { return; } boolean failed = true; for (Permission permission : permissions) { if (ac.hasPermission(permission)) { failed = false; } } if (failed) { <START> ac.checkPermission(permissions[0]); <END> } }</code><technical_language>ArrayIndexOutOfBOundsException if passed in a zero length array</technical_language>

Target:
public static void checkAnyPermission(AccessControlled ac, Permission[] permissions) { if (permissions == null || permissions.length == 0) { return; } ac.checkAnyPermission(permissions); }
Source:
<code>public void testAllDomainsHaveSpaceForNewDisksSuccess() { setUpGeneralValidations(); setUpDiskValidations(); List disksList = getNonEmptyDiskList(); doReturn(disksList).when(cmd).getDisksList(); doReturn(ValidationResult.VALID).when(multipleStorageDomainsValidator).allDomainsHaveSpaceForNewDisks(disksList); <START> assertTrue(cmd.canDoAction()); <END> verify(multipleStorageDomainsValidator).allDomainsHaveSpaceForNewDisks(disksList); }</code><technical_language>Please replace this assert a CanDoActionTestUtils call</technical_language>

Target:
public void testAllDomainsHaveSpaceForNewDisksSuccess() { setUpGeneralValidations(); setUpDiskValidations(); List<DiskImage> disksList = getNonEmptyDiskList(); doReturn(disksList).when(cmd).getDisksList(); doReturn(ValidationResult.VALID).when(multipleStorageDomainsValidator).allDomainsHaveSpaceForNewDisks(disksList); CanDoActionTestUtils.runAndAssertCanDoActionSuccess(cmd); verify(multipleStorageDomainsValidator).allDomainsHaveSpaceForNewDisks(disksList); }
Source:
<code>public List<Integer> getTransferAbortedOkStatusCodes(final FileSystemOptions opts) { @SuppressWarnings("unchecked") List<Integer> statusCodes = (List<Integer>) getParam(opts, TRANSFER_ABORTED_OK_STATUS_CODES); <START> return statusCodes != null ? statusCodes : Arrays.asList(FTPReply.TRANSFER_ABORTED, FTPReply.FILE_UNAVAILABLE); <END> }</code><technical_language>@boris-petrov, more detail. I create a protected method called getDefault... returns Arrays.asList(FTPReply.TRANSFER_ABORTED, FTPReply.FILE_UNAVAILABLE) clear defaults possibility of easy override subclassing. Gary</technical_language>

Target:
public List<Integer> getTransferAbortedOkStatusCodes(final FileSystemOptions opts) { return (List<Integer>) getParam(opts, TRANSFER_ABORTED_OK_STATUS_CODES); }
Source:
<code>public void populateViewCache(View rowView, ListRowViewCache viewCache, SectionListItem<H, I> value) { if (value.isSectionHeader()) { headerRenderer.populateViewCache(rowView, viewCache, value.getSectionHeader()); <START> return; <END> } itemRenderer.populateViewCache(rowView, viewCache, value.getData()); }</code><technical_language>if else</technical_language>

Target:
public void populateViewCache(View rowView, ListRowViewCache viewCache, SectionListItem<H, I> value) { if (value.isSectionHeader()) { headerRenderer.populateViewCache(rowView, viewCache, value.getSectionHeader()); } else { itemRenderer.populateViewCache(rowView, viewCache, value.getData()); } }
Source:
<code>public void testYieldProjection() throws Exception { int rows = 128; int columns = 20; DriverYieldSignal yieldSignal = new DriverYieldSignal(); PageProcessor pageProcessor = new PageProcessor( Optional.empty(), Collections.nCopies(columns, new YieldPageProjection(new InputPageProjection(0, VARCHAR)))); Slice[] slices = new Slice[rows]; Arrays.fill(slices, Slices.allocate(rows)); Page inputPage = new Page(new SliceArrayBlock(slices.length, slices)); PageProcessorOutput output = pageProcessor.process(SESSION, yieldSignal, inputPage); <START> for (int i = 0; i < columns * 2 - 1; i++) { <END> assertTrue(output.hasNext()); assertNull(output.next().orElse(null)); if (yieldSignal.isSet()) { yieldSignal.reset(); } } assertTrue(output.hasNext()); Page actualPage = output.next().orElse(null); assertNotNull(actualPage); Block[] blocks = new Block[columns]; Arrays.fill(blocks, new SliceArrayBlock(rows, slices)); Page expectedPage = new Page(blocks); assertPageEquals(Collections.nCopies(columns, VARCHAR), actualPage, expectedPage); assertFalse(output.hasNext()); }</code><technical_language>I understand this</technical_language>

Target:
public void testYieldProjection() throws Exception { int rows = 128; int columns = 20; DriverYieldSignal yieldSignal = new DriverYieldSignal(); PageProcessor pageProcessor = new PageProcessor( Optional.empty(), Collections.nCopies(columns, new YieldPageProjection(new InputPageProjection(0, VARCHAR)))); Slice[] slices = new Slice[rows]; Arrays.fill(slices, Slices.allocate(rows)); Page inputPage = new Page(new SliceArrayBlock(slices.length, slices)); PageProcessorOutput output = pageProcessor.process(SESSION, yieldSignal, inputPage); for (int i = 0; i < columns - 1; i++) { assertTrue(output.hasNext()); assertNull(output.next().orElse(null)); assertTrue(yieldSignal.isSet()); yieldSignal.reset(); } assertTrue(output.hasNext()); Page actualPage = output.next().orElse(null); assertNotNull(actualPage); assertTrue(yieldSignal.isSet()); yieldSignal.reset(); Block[] blocks = new Block[columns]; Arrays.fill(blocks, new SliceArrayBlock(rows, slices)); Page expectedPage = new Page(blocks); assertPageEquals(Collections.nCopies(columns, VARCHAR), actualPage, expectedPage); assertFalse(output.hasNext()); }
Source:
<code>protected Command getResizeChildrenCommand(ChangeBoundsRequest request) { CompoundCommand result = new CompoundCommand(); result.add(super.getResizeChildrenCommand(request)); TransactionalEditingDomain editingDomain = ((IGraphicalEditPart) getHost()).getEditingDomain(); ShiftEdgeIdentityAnchorOperation operation = new ShiftEdgeIdentityAnchorOperation(request); ICommand command = CommandFactory.createICommand(editingDomain, operation); result.add(new ICommandProxy(command)); <START> return result; <END> }</code><technical_language>for example: org.eclipse.sirius.diagram.sequence.ui.tool.internal.edit.policy.ExecutionSelectionEditPolicy.getMoveCommand(ChangeBoundsRequest) I create a new CompositeTransactionalCommand, avoid ly transaction</technical_language>

Target:
protected Command getResizeChildrenCommand(ChangeBoundsRequest request) { Command superCommand = super.getResizeChildrenCommand(request); EditPart host = getHost(); if (host instanceof IGraphicalEditPart) { TransactionalEditingDomain editingDomain = ((IGraphicalEditPart) host).getEditingDomain(); CompositeTransactionalCommand ctc = new CompositeTransactionalCommand(editingDomain, "Resize Children"); ctc.add(new CommandProxy(superCommand)); ShiftEdgeIdentityAnchorOperation operation = new ShiftEdgeIdentityAnchorOperation(request); ICommand command = CommandFactory.createICommand(editingDomain, operation); ctc.add(command); } return superCommand; }
Source:
<code>public void test_fetch_upload_id_finds_file() throws IOException { val dir = new File(getClass().getClassLoader().getResource("fixtures/upload/placeholder-upload-file.txt").getFile()); Optional<String> result = UploadStateStore.fetchUploadId(dir, "valid-upload-id"); if (result.isPresent()) { <START> System.out.println(result.get()); <END> } else { System.out.println("not there"); } assertEquals("this-is-my-uploadId", result.get()); }</code><technical_language>assertions</technical_language>

Target:
public void test_fetch_upload_id_finds_file() throws IOException { val dir = getTestResourceRoot(); Optional<String> result = UploadStateStore.fetchUploadId(dir, "valid-upload-id"); assertThat(result.get()).isEqualTo("this-is-my-uploadId"); }
Source:
<code>private boolean validateImageAvailability(DiskImage image, Guid imageGroupId) { boolean imageAvailable = false; for (Guid storageDomainId : image.getStorageIds()) { DiskImage fromIrs = null; try { <START> log.debug("Validating <END> that image '{}/{}' is available in storage domain {}.", imageGroupId, image.getImageId(), storageDomainId); fromIrs = (DiskImage) runVdsCommand(VDSCommandType.GetImageInfo, new GetImageInfoVDSCommandParameters(getStoragePoolId(), storageDomainId, imageGroupId, image.getImageId())).getReturnValue(); } catch (Exception e) { log.debug("Unable to get image info from storage", e); } if (fromIrs == null) { log.warn("Disk image '{}/{}' doesn't exist on storage domain '{}'", imageGroupId, image.getImageId(), storageDomainId); } else { imageAvailable = true; } } return imageAvailable; }</code><technical_language>info here, better. This work registering a Template</technical_language>

Target:
private boolean validateImageAvailability(DiskImage image, Guid imageGroupId) { boolean imageAvailable = false; for (Guid storageDomainId : image.getStorageIds()) { DiskImage fromIrs = null; try { log.info("Validating that image '{}/{}' is available in storage domain {}.", imageGroupId, image.getImageId(), storageDomainId); fromIrs = (DiskImage) runVdsCommand(VDSCommandType.GetImageInfo, new GetImageInfoVDSCommandParameters(getStoragePoolId(), storageDomainId, imageGroupId, image.getImageId())).getReturnValue(); } catch (Exception e) { log.debug("Unable to get image info from storage", e); } if (fromIrs == null) { log.warn("Disk image '{}/{}' doesn't exist on storage domain '{}'", imageGroupId, image.getImageId(), storageDomainId); } else if (!imageAvailable) { imageAvailable = true; } } return imageAvailable; }
Source:
<code>UmiAwareMarkDuplicatesWithMateCigarTester(final boolean allowMissingUmis) { this.allowMissingUmis = allowMissingUmis; <START> if(allowMissingUmis) { <END> addArg("ALLOW_MISSING_UMIS=" + allowMissingUmis); } }</code><technical_language>space b/w if (</technical_language>

Target:
UmiAwareMarkDuplicatesWithMateCigarTester(final boolean allowMissingUmis) { if (allowMissingUmis) { addArg("ALLOW_MISSING_UMIS=" + true); } }
Source:
<code>private void openFileInEditor(FileDiff d) { RevCommit commit; ObjectId blob; ObjectId[] blobs = d.getBlobs(); if (d.getChange().equals(ChangeType.DELETE)) { commit = d.getCommit().getParent(0); blob = blobs[0]; } else { commit = d.getCommit(); blob = blobs[blobs.length - 1]; } try { IFileRevision rev = CompareUtils.getFileRevision(d.getNewPath(), commit, getRepository(), blob); if (rev != null) { IWorkbenchWindow window = PlatformUI.getWorkbench() .getActiveWorkbenchWindow(); IWorkbenchPage page = window.getActivePage(); EgitUiEditorUtils.openEditor(page, rev, new NullProgressMonitor()); } else { String message = NLS.bind( UIText.CommitFileDiffViewer_notContainedInCommit, d <START> .getNewPath(), d.getCommit().getId().getName()); <END> Activator.showError(message, null); } } catch (IOException e) { Activator.logError(UIText.GitHistoryPage_openFailed, e); Activator.showError(UIText.GitHistoryPage_openFailed, null); } catch (CoreException e) { Activator.logError(UIText.GitHistoryPage_openFailed, e); Activator.showError(UIText.GitHistoryPage_openFailed, null); } }</code><technical_language>commit.getName()</technical_language>

Target:
private void openFileInEditor(FileDiff d) { RevCommit commit; ObjectId blob; ObjectId[] blobs = d.getBlobs(); if (d.getChange().equals(ChangeType.DELETE)) { commit = d.getCommit().getParent(0); blob = blobs[0]; } else { commit = d.getCommit(); blob = blobs[blobs.length - 1]; } try { IFileRevision rev = CompareUtils.getFileRevision(d.getNewPath(), commit, getRepository(), blob); if (rev != null) { IWorkbenchWindow window = PlatformUI.getWorkbench() .getActiveWorkbenchWindow(); IWorkbenchPage page = window.getActivePage(); EgitUiEditorUtils.openEditor(page, rev, new NullProgressMonitor()); } else { String message = NLS.bind( UIText.CommitFileDiffViewer_notContainedInCommit, d .getNewPath(), commit.getName()); Activator.showError(message, null); } } catch (IOException e) { Activator.logError(UIText.GitHistoryPage_openFailed, e); Activator.showError(UIText.GitHistoryPage_openFailed, null); } catch (CoreException e) { Activator.logError(UIText.GitHistoryPage_openFailed, e); Activator.showError(UIText.GitHistoryPage_openFailed, null); } }
Source:
<code>public void requireTestSkip(ThrowingRunnable run, String msgPart) { try { run.run(); <START> } catch (Throwable throwable) { <END> if (throwable instanceof SkipException) { if (throwable.getMessage().contains(msgPart)) { return; } else { throw new RuntimeException( String.format("Expected TCK to skip this test with '... %s ...', yet it skipped with (%s) instead!", msgPart, throwable.getMessage()), throwable); } } else { throw new RuntimeException( String.format("Expected TCK to skip this test, yet it threw %s(%s) instead!", throwable.getClass().getName(), throwable.getMessage()), throwable); } } throw new RuntimeException(String.format("Expected TCK to SKIP this test, instead if PASSed!")); }</code><technical_language>Catch SkipException in separate catch clause</technical_language>

Target:
public void requireTestSkip(ThrowingRunnable run, String msgPart) { try { run.run(); } catch (SkipException skip) { if (skip.getMessage().contains(msgPart)) { return; } else { throw new RuntimeException( String.format("Expected TCK to skip this test with '... %s ...', yet it skipped with (%s) instead!", msgPart, skip.getMessage()), skip); } } catch (Throwable throwable) { throw new RuntimeException( String.format("Expected TCK to skip this test, yet it threw %s(%s) instead!", throwable.getClass().getName(), throwable.getMessage()), throwable); } throw new RuntimeException("Expected TCK to SKIP this test, instead if PASSed!"); }
Source:
<code><START> private String generateColumnReference(Path path) { <END> Path.PathElement last = path.lastElement().get(); Class<?> lastClass = last.getType(); String fieldName = last.getFieldName(); JoinTo joinTo = dictionary.getAttributeOrRelationAnnotation(lastClass, JoinTo.class, fieldName); if (joinTo == null) { return getClassAlias(lastClass) + "." + dictionary.getColumnName(lastClass, last.getFieldName()); } else { return generateColumnReference(new Path(lastClass, dictionary, joinTo.path())); } }</code><technical_language>In general, I preferred function names helper functions untouched possible. code inspected</technical_language>

Target:
private String generateColumnReference(Path path) { Path.PathElement last = path.lastElement().get(); Class<?> lastClass = last.getType(); String fieldName = last.getFieldName(); JoinTo joinTo = dictionary.getAttributeOrRelationAnnotation(lastClass, JoinTo.class, fieldName); if (joinTo == null) { return getClassAlias(lastClass) + "." + dictionary.getAnnotatedColumnName(lastClass, last.getFieldName()); } else { return generateColumnReference(new Path(lastClass, dictionary, joinTo.path())); } }
Source:
<code>List<String> restoreNegativeNumberOptions(List<String> nonOptionArgs) { if (!negativeNumberParams.isEmpty()) { List<String> nonOptionArgsClone = new ArrayList<>(nonOptionArgs); negativeNumberParams.forEach((k, v) -> { int idx = k; <START> nonOptionArgsClone.remove(idx); nonOptionArgsClone.add(idx, v); <END> }); return Collections.unmodifiableList(nonOptionArgsClone); } else { return nonOptionArgs; } }</code><technical_language>nonOptionArgsClone.set(idx, v);</technical_language>

Target:
List<String> restoreNegativeNumberOptions(List<String> nonOptionArgs) { if (!negativeNumberParams.isEmpty()) { List<String> nonOptionArgsClone = new ArrayList<>(nonOptionArgs); negativeNumberParams.forEach((k, v) -> { int idx = k; nonOptionArgsClone.set(idx, v); }); return Collections.unmodifiableList(nonOptionArgsClone); } else { return nonOptionArgs; } }
Source:
<code>protected IValidator createDefaultValueAlreadyDefinedValidator() { return new IValidator() { @Override public IStatus validate(final Object value) { if (value instanceof Document) { final Document document = (Document) value; <START> if (document.getDocumentType().equals(DocumentType.NONE)) { <END> return Status.OK_STATUS; } else { return ValidationStatus.warning(Messages.bind(Messages.defaultValueAlreadyDefinedWarning, document.getName())); } } return Status.OK_STATUS; } }; }</code><technical_language>invert equals</technical_language>

Target:
protected IValidator createDefaultValueAlreadyDefinedValidator() { return new IValidator() { @Override public IStatus validate(final Object value) { if (value instanceof Document && contract.eContainer() instanceof Pool) { final Document document = (Document) value; return DocumentType.NONE.equals(document.getDocumentType()) ? Status.OK_STATUS : ValidationStatus.warning(Messages.bind(Messages.defaultValueAlreadyDefinedWarning, document.getName())); } return Status.OK_STATUS; } }; }
Source:
<code>public void fetchesProperties() throws Exception { final Fork fork = Mockito.mock(Fork.class); Mockito.doReturn( Json.createObjectBuilder() .add("organization", "OrganizationName") .add("name", "ForkName") .build() ).when(fork).json(); final Fork.Smart smart = new Fork.Smart(fork); MatcherAssert.assertThat( <START> smart.name(), <END> Matchers.notNullValue() ); }</code><technical_language>created fork attributes (name organization), check of them. approach is create tests - attribute check actual matches expected</technical_language>

Target:
public void fetchesProperties() throws Exception { final Fork fork = Mockito.mock(Fork.class); Mockito.doReturn( Json.createObjectBuilder() .add("organization", "OrganizationName") .build() ).when(fork).json(); final Fork.Smart smart = new Fork.Smart(fork); MatcherAssert.assertThat( smart.organization(), Matchers.equalTo("OrganizationName") ); }
Source:
<code>protected static <R> R runAndCleanupTransactionContext(Supplier<R> supplier) { try { return supplier.get(); } finally { if (!TransactionHelper.isNoTransaction()) { try { <START> TransactionHelper.commitOrRollbackTransaction(); <END> } catch (TransactionRuntimeException e) { log.error("Failed to commit/rollback", e); } } } }</code><technical_language>call method TransactionHelper right</technical_language>

Target:
protected static <R> R runAndCleanupTransactionContext(Supplier<R> supplier) { try { return supplier.get(); } finally { if (!isNoTransaction()) { try { commitOrRollbackTransaction(); } catch (TransactionRuntimeException e) { log.error("Failed to commit/rollback", e); } } } }
Source:
<code>public NamespaceNameTree namespaceName(List<Tuple<InternalSyntaxToken, InternalSyntaxToken>> tuples) { <START> NameIdentifierTree lastPart = new NameIdentifierTreeImpl(tuples.get(0).second()); <END> return namespaceName(lastPart, tuples.get(0).first(), tuples.subList(1, tuples.size())); }</code><technical_language>@vilchik-elena "firstPart"</technical_language>

Target:
public NamespaceNameTree namespaceName(List<Tuple<InternalSyntaxToken, InternalSyntaxToken>> tuples) { NameIdentifierTree lastPartIfOneTuple = new NameIdentifierTreeImpl(tuples.get(0).second()); return namespaceName(lastPartIfOneTuple, tuples.get(0).first(), tuples.subList(1, tuples.size())); }
Source:
<code>public void getSegmentFiles(final DataSegment segment, final File outDir) throws SegmentLoadingException { <START> Map<String, Object> loadSpec = segment.getLoadSpec(); <END> String region = MapUtils.getString(loadSpec, "region"); String container = MapUtils.getString(loadSpec, "container"); String path = MapUtils.getString(loadSpec, "path"); log.info("Pulling index at path[%s] to outDir[%s]", path, outDir); prepareOutDir(outDir); getSegmentFiles(region, container, path, outDir); }</code><technical_language>this is typically done a LoadSpec implementation wires json config puller (see io.druid.storage.azure.AzureLoadSpec for a good example)</technical_language>

Target:
public void getSegmentFiles(final DataSegment segment, final File outDir) throws SegmentLoadingException { final Map<String, Object> loadSpec = segment.getLoadSpec(); final String region = MapUtils.getString(loadSpec, "region"); final String container = MapUtils.getString(loadSpec, "container"); final String path = MapUtils.getString(loadSpec, "path"); log.info("Pulling index at path[%s] to outDir[%s]", path, outDir); prepareOutDir(outDir); getSegmentFiles(region, container, path, outDir); }
Source:
<code>public boolean hasConflicts() { <START> return this.conflictStatus > 0; <END> }</code><technical_language>I guess need a null check well</technical_language>

Target:
public boolean hasConflicts() { return conflictStatus != null && conflictStatus > 0; }
Source:
<code>public void drawString(String s, float x, float y, float scale, TextAlignment align, boolean centered, Color tint) { <START> drawer.drawString(s, x, y, scale * FONT_SIZE * FONT_SIZE_MULTIPLIER / displayDimensions.getHeight(), align, centered, tint); <END> }</code><technical_language>*definitely* computing true of fontSize call drawString. Remove FONT_SIZE FONT_SIZE_MULTIPLIER, addd new variables - FONT_SIZE_IN_PX = 20 fontSize = someCalculation;</technical_language>

Target:
public void drawString(String s, float x, float y, float scale, TextAlignment align, boolean centered, Color tint) { drawer.drawString(s, x, y, scale * fontSize, align, centered, tint); }
Source:
<code>public int calculateTransactionAmount(double price, ArrayList<Order> sellOrders, ArrayList<Order> buyOrders) { int sellers = 0; int buyers = 0; int transactions = 0; <START> for (Order o : sellOrders) { if (o.getPrice() <= price || o.isMarketOrder) sellers += o.getSize(); } <END> for (Order o : buyOrders) { if (o.getPrice() >= price || o.isMarketOrder) buyers += o.getSize(); } transactions = buyers > sellers ? sellers : buyers; return transactions; }</code><technical_language>Extract this method getTotalSellAmount. refactoring tool do automatically. Code smell Overly long function</technical_language>

Target:
public int calculateTransactionAmount(double price, ArrayList<Order> sellOrders, ArrayList<Order> buyOrders) { int buyers = 0; int sellers = 0; buyers = getTotalSellAmount(sellOrders); sellers = getTotalBuyAmount(buyOrders); return getTransaction(buyers, sellers); }
Source:
<code>public void initialize() { <START> move.initialize(); <END> }</code><technical_language>initialize() schedule()</technical_language>

Target:
public void initialize() { move.schedule(); }
Source:
<code>private JButton getBtnOk() { if (btnOk == null) { btnOk = new JButton(); btnOk.setText(Constant.messages.getString("alert.add.button.save")); btnOk.addActionListener(new java.awt.event.ActionListener() { @Override public void actionPerformed(java.awt.event.ActionEvent e) { Alert alert = alertViewPanel.getAlert(); try { ExtensionAlert extAlert = (ExtensionAlert) Control.getSingleton().getExtensionLoader().getExtension(ExtensionAlert.NAME); if (alert.getAlertId() >= 0) { if (extAlert != null) { extAlert.updateAlert(alert); <START> extAlert.displayAlert(alert); <END> } else if (historyRef != null) { historyRef.updateAlert(alert); extension.notifyHistoryItemChanged(historyRef); } } else { if (httpMessage != null) { historyRef = new HistoryReference(Model.getSingleton().getSession(), historyType, httpMessage); } alert.setSource(Alert.Source.MANUAL); if (extAlert != null) { extAlert.alertFound(alert, historyRef); } else { historyRef.addAlert(alert); extension.notifyHistoryItemChanged(historyRef); } } } catch (Exception ex) { logger.error(ex.getMessage(), ex); } clearAndCloseDialog(); } }); } return btnOk; }</code><technical_language>This deleted, selection displays alert</technical_language>

Target:
private JButton getBtnOk() { if (btnOk == null) { btnOk = new JButton(); btnOk.setText(Constant.messages.getString("alert.add.button.save")); btnOk.addActionListener(new java.awt.event.ActionListener() { @Override public void actionPerformed(java.awt.event.ActionEvent e) { Alert alert = alertViewPanel.getAlert(); try { ExtensionAlert extAlert = (ExtensionAlert) Control.getSingleton().getExtensionLoader().getExtension(ExtensionAlert.NAME); if (alert.getAlertId() >= 0) { if (extAlert != null) { extAlert.updateAlert(alert); } else if (historyRef != null) { historyRef.updateAlert(alert); extension.notifyHistoryItemChanged(historyRef); } } else { if (httpMessage != null) { historyRef = new HistoryReference(Model.getSingleton().getSession(), historyType, httpMessage); } alert.setSource(Alert.Source.MANUAL); if (extAlert != null) { extAlert.alertFound(alert, historyRef); } else { historyRef.addAlert(alert); extension.notifyHistoryItemChanged(historyRef); } } } catch (Exception ex) { logger.error(ex.getMessage(), ex); } clearAndCloseDialog(); } }); } return btnOk; }
Source:
<code>public void catch_class_cast_exception() throws Exception { Map<Symbol.MethodSymbol, MethodBehavior> behaviorCache = createSymbolicExecutionVisitor("src/test/files/se/XProcCatchClassCastException.java").behaviorCache; assertThat(behaviorCache.values()).hasSize(1); MethodBehavior methodBehavior = behaviorCache.values().iterator().next(); assertThat(methodBehavior.yields()).hasSize(2); MethodYield[] expected = new MethodYield[] { <START> buildMethodYield(0, null, (Constraint) null), <END> buildMethodYield(-1, new ObjectConstraint(true, false, null), (Constraint) null)}; assertThat(methodBehavior.yields()).contains((Object[]) expected); }</code><technical_language>i this method a varargs a single null constraint. remove parameter hardcode array in buildMethodYield</technical_language>

Target:
public void catch_class_cast_exception() throws Exception { Map<Symbol.MethodSymbol, MethodBehavior> behaviorCache = createSymbolicExecutionVisitor("src/test/files/se/XProcCatchClassCastException.java").behaviorCache; assertThat(behaviorCache.values()).hasSize(1); MethodBehavior methodBehavior = behaviorCache.values().iterator().next(); assertThat(methodBehavior.yields()).hasSize(2); MethodYield[] expected = new MethodYield[] { buildMethodYield(0, null), buildMethodYield(-1, ObjectConstraint.nullConstraint())}; assertThat(methodBehavior.yields()).contains((Object[]) expected); }
Source:
<code>private static void replacePing(JGroupsProtocolCfg jgroupsCfg) { if (!jgroupsCfg.containsProtocol(LOCAL_PING)) { <START> ProtocolType[] pingProtocols = new ProtocolType[]{MPING}; <END> boolean found = false; for (ProtocolType protocol : pingProtocols) { found = jgroupsCfg.containsProtocol(MPING); if (found) { break; } } if (!found) { throw new IllegalStateException(String.format( "You should one of %s protocol configured.", Arrays.toString(pingProtocols))); } jgroupsCfg.replaceProtocol(MPING, new ProtocolConfiguration(LOCAL_PING.name(), new HashMap<>())); } }</code><technical_language>replacing MPING (from default-jgroups-tcp.xml) PING (from default-jgroups-udp.xml)</technical_language>

Target:
private static void replacePing(JGroupsProtocolCfg jgroupsCfg) { if (!jgroupsCfg.containsProtocol(LOCAL_PING)) { ProtocolType[] pingProtocols = new ProtocolType[]{MPING, PING}; ProtocolType pingProtocolToBeReplaced = null; for (ProtocolType protocol : pingProtocols) { if (jgroupsCfg.containsProtocol(protocol)) { pingProtocolToBeReplaced = protocol; break; } } if (pingProtocolToBeReplaced == null) { throw new IllegalStateException("Can't replace the ping protocol with LOCAL_PING"); } jgroupsCfg.replaceProtocol(pingProtocolToBeReplaced, new ProtocolConfiguration(LOCAL_PING.name(), new HashMap<>())); } }