auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public AddinsCommandManager(EventBus events, final Session session) { events_ = events; bindings_ = new FileBacked<EditorKeyBindings>( KEYBINDINGS_PATH, false, EditorKeyBindings.create()); events_.addHandler( SessionInitEvent.TYPE, new SessionInitHandler() { @Override public void onSessionInit(SessionInitEvent sie) { MainWindowObject.rAddins().set(session.getSessionInfo().getAddins()); loadBindings(); } }); events_.addHandler( AddinsKeyBindingsChangedEvent.TYPE, new AddinsKeyBindingsChangedEvent.Handler() { @Override public void onAddinsKeyBindingsChanged(AddinsKeyBindingsChangedEvent event) { registerBindings(event.getBindings(), null); } }); events_.addHandler( AddinRegistryUpdatedEvent.TYPE, new AddinRegistryUpdatedEvent.Handler() { @Override public void onAddinRegistryUpdated(AddinRegistryUpdatedEvent event) { MainWindowObject.rAddins().set(event.getData()); loadBindings(); } }); }

Target:
public AddinsCommandManager(EventBus events, final Session session) { events_ = events; bindings_ = new FileBacked<EditorKeyBindings>( KEYBINDINGS_PATH, false, EditorKeyBindings.create()); events_.addHandler( SessionInitEvent.TYPE, new SessionInitHandler() { @Override public void onSessionInit(SessionInitEvent sie) { MainWindowObject.rAddins().set(session.getSessionInfo().getAddins()); loadBindings(); } }); events_.addHandler( AddinsKeyBindingsChangedEvent.TYPE, new AddinsKeyBindingsChangedEvent.Handler() { @Override public void onAddinsKeyBindingsChanged(AddinsKeyBindingsChangedEvent event) { registerBindings(event.getBindings(), null); } }); events_.addHandler( AddinRegistryUpdatedEvent.TYPE, new AddinRegistryUpdatedEvent.Handler() { @Override public void onAddinRegistryUpdated(AddinRegistryUpdatedEvent event) { if (SourceWindowManager.isMainSourceWindow()) MainWindowObject.rAddins().set(event.getData()); loadBindings(); } }); }
Source:
public ForkJoinPoolHierarchicalTestExecutorService(ParallelExecutionConfiguration configuration) { this(new ForkJoinPoolFactory().apply(configuration)); }

Target:
public ForkJoinPoolHierarchicalTestExecutorService(ParallelExecutionConfiguration configuration) { this(ForkJoinPoolFactory.create(configuration)); }
Source:
private boolean updateLeaseInfo(Guid snapshotLeaseDomainId) { if ((getParameters().getSnapshotAction() == SnapshotActionEnum.UNDO && snapshotLeaseDomainId == null) || ( getParameters().getSnapshotAction() == SnapshotActionEnum.COMMIT && snapshotLeaseDomainId == null)) { vmDynamicDao.updateVmLeaseInfo(getParameters().getVmId(), null); return true; } VDSReturnValue retVal = null; try { retVal = runVdsCommand(VDSCommandType.GetVmLeaseInfo, new VmLeaseVDSParameters(getStoragePoolId(), snapshotLeaseDomainId, getParameters().getVmId())); } catch (EngineException e) { log.error("Failure in getting lease info for VM {}, message: {}", getParameters().getVmId(), e.getMessage()); } if (retVal == null || !retVal.getSucceeded()) { log.error("Failed to get info on the lease of VM {}", getParameters().getVmId()); return false; } vmDynamicDao.updateVmLeaseInfo( getParameters().getVmId(), (Map<String, String>) retVal.getReturnValue()); return true; }

Target:
private boolean updateLeaseInfo(Guid snapshotLeaseDomainId) { if (snapshotLeaseDomainId == null) { vmDynamicDao.updateVmLeaseInfo(getParameters().getVmId(), null); return true; } VDSReturnValue retVal = null; try { retVal = runVdsCommand(VDSCommandType.GetVmLeaseInfo, new VmLeaseVDSParameters(getStoragePoolId(), snapshotLeaseDomainId, getParameters().getVmId())); } catch (EngineException e) { log.error("Failure in getting lease info for VM {}, message: {}", getParameters().getVmId(), e.getMessage()); } if (retVal == null || !retVal.getSucceeded()) { log.error("Failed to get info on the lease of VM {}", getParameters().getVmId()); return false; } vmDynamicDao.updateVmLeaseInfo( getParameters().getVmId(), (Map<String, String>) retVal.getReturnValue()); return true; }
Source:
public Float getTIC() { Float tic = MsSpectrumUtil.getTIC(intensityValues, getMzBinaryDataInfo().getArrayLength()); return tic; }

Target:
public Float getTIC() { Float tic = null; try { tic = Float.valueOf(getCVValue(MzMLCV.cvTIC)); } catch (Exception e) { e.printStackTrace(); } if (tic == null) tic = MsSpectrumUtil.getTIC(getIntensityValues(), getMzBinaryDataInfo().getArrayLength()); return tic; }
Source:
public void configure(ServerHttpSecurity http) { ReactiveAuthenticationManager authenticationManager = getAuthenticationManager(); X509PrincipalExtractor principalExtractor = getPrincipalExtractor(); AuthenticationWebFilter filter = new AuthenticationWebFilter(authenticationManager); filter.setServerAuthenticationConverter(new ServerX509AuthenticationConverter(principalExtractor)); http.addFilterAt(filter, SecurityWebFiltersOrder.AUTHENTICATION); }

Target:
protected void configure(ServerHttpSecurity http) { ReactiveAuthenticationManager authenticationManager = getAuthenticationManager(); X509PrincipalExtractor principalExtractor = getPrincipalExtractor(); AuthenticationWebFilter filter = new AuthenticationWebFilter(authenticationManager); filter.setServerAuthenticationConverter(new ServerX509AuthenticationConverter(principalExtractor)); http.addFilterAt(filter, SecurityWebFiltersOrder.AUTHENTICATION); }
Source:
public WatchableOutputStream(@Nonnull OutputStream delegate) { Objects.requireNonNull(delegate, "null pass passed into a WatchableOutputStream"); this.delegate = delegate; this.completionFuture = new Future(); }

Target:
public WatchableOutputStream(@Nonnull OutputStream delegate) { Objects.requireNonNull(delegate, "null was passed into a WatchableOutputStream"); this.delegate = delegate; this.completionFuture = new Future(); }
Source:
public void testGetBytesMiddle() throws CTFReaderException { @NonNull byte[] data = new byte[5]; ByteBuffer bb = ByteBuffer.wrap(new String("hello world").getBytes()); if( bb == null){ throw new IllegalStateException("Failed to allocate memory"); } fixture = new BitBuffer(bb); fixture.position(6 * 8); fixture.get(data); String actual = new String(data); assertEquals("world", actual); }

Target:
public void testGetBytesMiddle() throws CTFReaderException { @NonNull byte[] data = new byte[5]; fixture = new BitBuffer(testMemory(ByteBuffer.wrap(new String("hello world").getBytes()))); fixture.position(6 * 8); fixture.get(data); String actual = new String(data); assertEquals("world", actual); }
Source:
public synchronized void stop(final String reason) { if ( isRunning ) { return; } isRunning = true; new Thread( "Shutdown Thread" ) { @Override @SuppressFBWarnings("DM_EXIT") @SuppressWarnings("TooBroadCatch") public void run() { stopListeners(); getLogger().info( "Closing pending connections" ); connectionLock.readLock().lock(); try { getLogger().log( Level.INFO, "Disconnecting {0} connections", connections.size() ); for ( UserConnection user : connections.values() ) { user.disconnect( reason ); } } finally { connectionLock.readLock().unlock(); } try { Thread.sleep( 500 ); } catch ( InterruptedException ex ) { } if ( reconnectHandler != null ) { getLogger().info( "Saving reconnect locations" ); reconnectHandler.save(); reconnectHandler.close(); } saveThread.cancel(); metricsThread.cancel(); getLogger().info( "Disabling plugins" ); for ( Plugin plugin : Lists.reverse( new ArrayList<>( pluginManager.getPlugins() ) ) ) { try { plugin.onDisable(); for ( Handler handler : plugin.getLogger().getHandlers() ) { handler.close(); } } catch ( Throwable t ) { getLogger().log( Level.SEVERE, "Exception disabling plugin " + plugin.getDescription().getName(), t ); } getScheduler().cancel( plugin ); plugin.getExecutorService().shutdownNow(); } getLogger().info( "Closing IO threads" ); eventLoops.shutdownGracefully(); try { eventLoops.awaitTermination( Long.MAX_VALUE, TimeUnit.NANOSECONDS ); } catch ( InterruptedException ex ) { } getLogger().info( "Thank you and goodbye" ); for ( Handler handler : getLogger().getHandlers() ) { handler.close(); } System.exit( 0 ); } }.start(); }

Target:
public synchronized void stop(final String reason) { if ( !isRunning ) { return; } isRunning = false; new Thread( "Shutdown Thread" ) { @Override @SuppressFBWarnings("DM_EXIT") @SuppressWarnings("TooBroadCatch") public void run() { stopListeners(); getLogger().info( "Closing pending connections" ); connectionLock.readLock().lock(); try { getLogger().log( Level.INFO, "Disconnecting {0} connections", connections.size() ); for ( UserConnection user : connections.values() ) { user.disconnect( reason ); } } finally { connectionLock.readLock().unlock(); } try { Thread.sleep( 500 ); } catch ( InterruptedException ex ) { } if ( reconnectHandler != null ) { getLogger().info( "Saving reconnect locations" ); reconnectHandler.save(); reconnectHandler.close(); } saveThread.cancel(); metricsThread.cancel(); getLogger().info( "Disabling plugins" ); for ( Plugin plugin : Lists.reverse( new ArrayList<>( pluginManager.getPlugins() ) ) ) { try { plugin.onDisable(); for ( Handler handler : plugin.getLogger().getHandlers() ) { handler.close(); } } catch ( Throwable t ) { getLogger().log( Level.SEVERE, "Exception disabling plugin " + plugin.getDescription().getName(), t ); } getScheduler().cancel( plugin ); plugin.getExecutorService().shutdownNow(); } getLogger().info( "Closing IO threads" ); eventLoops.shutdownGracefully(); try { eventLoops.awaitTermination( Long.MAX_VALUE, TimeUnit.NANOSECONDS ); } catch ( InterruptedException ex ) { } getLogger().info( "Thank you and goodbye" ); for ( Handler handler : getLogger().getHandlers() ) { handler.close(); } System.exit( 0 ); } }.start(); }
Source:
public DruidPredicateFactory predicateFactory(final ExtractionFn extractionFn) { return new DruidPredicateFactory() { @Override public Predicate<String> makeStringPredicate() { if (extractionFn != null) { return new Predicate<String>() { @Override public boolean apply(String input) { return matches(extractionFn.apply(input)); } }; } else { return new Predicate<String>() { @Override public boolean apply(String input) { return matches(input); } }; } } @Override public DruidLongPredicate makeLongPredicate() { if (extractionFn != null) { return new DruidLongPredicate() { @Override public boolean applyLong(long input) { return matches(extractionFn.apply(input)); } }; } else { return new DruidLongPredicate() { @Override public boolean applyLong(long input) { return matches(String.valueOf(input)); } }; } } @Override public DruidFloatPredicate makeFloatPredicate() { if (extractionFn != null) { return new DruidFloatPredicate() { @Override public boolean applyFloat(float input) { return matches(extractionFn.apply(input)); } }; } else { return new DruidFloatPredicate() { @Override public boolean applyFloat(float input) { return matches(String.valueOf(input)); } }; } } @Override public DruidDoublePredicate makeDoublePredicate() { return input -> { if (extractionFn != null) { return matches(extractionFn.apply(input)); } return matches(String.valueOf(input)); }; } }; }

Target:
public DruidPredicateFactory predicateFactory(final ExtractionFn extractionFn) { return new DruidPredicateFactory() { @Override public Predicate<String> makeStringPredicate() { if (extractionFn != null) { return new Predicate<String>() { @Override public boolean apply(String input) { return matches(extractionFn.apply(input)); } }; } else { return new Predicate<String>() { @Override public boolean apply(String input) { return matches(input); } }; } } @Override public DruidLongPredicate makeLongPredicate() { if (extractionFn != null) { return input -> matches(extractionFn.apply(input)); } else { return input -> matches(String.valueOf(input)); } } @Override public DruidFloatPredicate makeFloatPredicate() { if (extractionFn != null) { return input -> matches(extractionFn.apply(input)); } else { return input -> matches(String.valueOf(input)); } } @Override public DruidDoublePredicate makeDoublePredicate() { if (extractionFn != null) { return input -> matches(extractionFn.apply(input)); } else { return input -> matches(String.valueOf(input)); } } }; }
Source:
public void cancel(Throwable cause) { Stream .concat( pendingRequests.keySet().stream(), fulfilledRequests.keySet().stream()) .flatMap(group -> executions.get(group).stream()) .forEach(id -> logicalSlotRequestCanceller.accept(id, cause)); }

Target:
public void cancel(Throwable cause) { for (ExecutionSlotSharingGroup group : pendingRequests.keySet()) { for (ExecutionVertexID id : executions.get(group)) { logicalSlotRequestCanceller.accept(id, cause); } } for (ExecutionSlotSharingGroup group : fulfilledRequests.keySet()) { for (ExecutionVertexID id : executions.get(group)) { logicalSlotRequestCanceller.accept(id, cause); } } }
Source:
void propagateCostImprovements(RelNode rel) { RelMetadataQuery mq = rel.getCluster().getMetadataQuery(); Map<RelNode, RelOptCost> propagateRels = new HashMap<>(); PriorityQueue<RelNode> propagateHeap = new PriorityQueue<>((o1, o2) -> { RelOptCost c1 = propagateRels.get(o1); RelOptCost c2 = propagateRels.get(o2); if (c1.equals(c2)) { return 0; } else if (c1.isLt(c2)) { return -1; } return 1; }); propagateRels.put(rel, getCost(rel, mq)); propagateHeap.offer(rel); while (!propagateHeap.isEmpty()) { RelNode relNode = propagateHeap.poll(); RelOptCost cost = propagateRels.get(relNode); for (RelSubset subset : getSet(relNode).subsets) { if (relNode.getTraitSet().satisfies(subset.getTraitSet())) { if (cost.isLt(subset.bestCost)) { subset.timestamp++; LOGGER.trace("Subset cost changed: subset cost was now {}", subset, subset.bestCost, cost); subset.bestCost = cost; subset.best = relNode; mq.clearCache(subset); subset.getParents().forEach(parent -> { mq.clearCache(parent); if (propagateRels.put(parent, getCost(parent, mq)) != null) { propagateHeap.remove(parent); } propagateHeap.offer(parent); }); } } } } }

Target:
void propagateCostImprovements(RelNode rel) { RelMetadataQuery mq = rel.getCluster().getMetadataQuery(); Map<RelNode, RelOptCost> propagateRels = new HashMap<>(); PriorityQueue<RelNode> propagateHeap = new PriorityQueue<>((o1, o2) -> { RelOptCost c1 = propagateRels.get(o1); RelOptCost c2 = propagateRels.get(o2); if (c1.equals(c2)) { return 0; } else if (c1.isLt(c2)) { return -1; } return 1; }); propagateRels.put(rel, getCost(rel, mq)); propagateHeap.offer(rel); while (!propagateHeap.isEmpty()) { RelNode relNode = propagateHeap.poll(); RelOptCost cost = propagateRels.get(relNode); for (RelSubset subset : getSet(relNode).subsets) { if (!relNode.getTraitSet().satisfies(subset.getTraitSet())) { continue; } if (!cost.isLt(subset.bestCost)) { continue; } subset.timestamp++; LOGGER.trace("Subset cost changed: subset cost was now {}", subset, subset.bestCost, cost); subset.bestCost = cost; subset.best = relNode; mq.clearCache(subset); for (RelNode parent : subset.getParents()) { mq.clearCache(parent); RelOptCost newCost = getCost(parent, mq); RelOptCost existingCost = propagateRels.get(parent); if (existingCost == null || newCost.isLt(existingCost)) { propagateRels.put(parent, newCost); if (existingCost != null) { propagateHeap.remove(parent); } propagateHeap.offer(parent); } } } } }
Source:
public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); LayoutInflater layoutInflater = getLayoutInflater(); updateAccountsList(); swipeRefresh = (SwipeRefreshLayout) findViewById(R.id.swipeRefresh); swipeRefresh.setColorSchemeResources(R.color.swipe1, R.color.swipe2, R.color.swipe1, R.color.swipe2); swipeRefresh.setOnRefreshListener(this); mainListView = (ListView) findViewById(R.id.main_app_list); mainListView.addHeaderView(layoutInflater.inflate(R.layout.main_list_header, null), null, false); footer = layoutInflater.inflate(R.layout.main_list_footer, null); footer.setVisibility(View.INVISIBLE); mainListView.addFooterView(footer, null, false); adapter = new MainListAdapter(this, accountName, currentStatsMode); mainListView.setAdapter(adapter); mainViewSwitcher = (ViewSwitcher) findViewById(R.id.main_viewswitcher); statusText = (TextView) findViewById(R.id.main_app_status_line); aniPrevIn = AnimationUtils.loadAnimation(Main.this, R.anim.activity_fade_in); currentStatsMode = Preferences.getStatsMode(this); updateStatsMode(); State lastState = (State) getLastCustomNonConfigurationInstance(); if (lastState != null) { state = lastState; state.attachAll(this); if (state.lastAppList != null) { adapter.setAppInfos(state.lastAppList); setSkipMainReload(true); } } if (isUpdate()) { showChangelog(); } }

Target:
public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); LayoutInflater layoutInflater = getLayoutInflater(); updateAccountsList(); mainListView = (ListView) findViewById(R.id.main_app_list); mainListView.addHeaderView(layoutInflater.inflate(R.layout.main_list_header, null), null, false); footer = layoutInflater.inflate(R.layout.main_list_footer, null); footer.setVisibility(View.INVISIBLE); mainListView.addFooterView(footer, null, false); adapter = new MainListAdapter(this, accountName, currentStatsMode); mainListView.setAdapter(adapter); mainViewSwitcher = (ViewSwitcher) findViewById(R.id.main_viewswitcher); statusText = (TextView) findViewById(R.id.main_app_status_line); aniPrevIn = AnimationUtils.loadAnimation(Main.this, R.anim.activity_fade_in); currentStatsMode = Preferences.getStatsMode(this); updateStatsMode(); State lastState = (State) getLastCustomNonConfigurationInstance(); if (lastState != null) { state = lastState; state.attachAll(this); if (state.lastAppList != null) { adapter.setAppInfos(state.lastAppList); setSkipMainReload(true); } } if (isUpdate()) { showChangelog(); } }
Source:
public void getOutline(@NonNull Outline outline) { if (android.os.Build.VERSION.SDK_INT >= 21) { Path backgroundPath = new Path(); float[] backgroundRadii = { Math.max(0, borderTopLeftRadius), Math.max(0, borderTopLeftRadius), Math.max(0, borderTopRightRadius), Math.max(0, borderTopRightRadius), Math.max(0, borderBottomRightRadius), Math.max(0, borderBottomRightRadius), Math.max(0, borderBottomLeftRadius), Math.max(0, borderBottomLeftRadius) }; backgroundPath.addRoundRect(new RectF(getBounds()), backgroundRadii, Path.Direction.CW); outline.setConvexPath(backgroundPath); } else { super.getOutline(outline); } }

Target:
public void getOutline(@NonNull Outline outline) { if (android.os.Build.VERSION.SDK_INT >= 21) { Path backgroundPath = new Path(); float[] backgroundRadii = { Math.max(0, borderTopLeftRadius), Math.max(0, borderTopLeftRadius), Math.max(0, borderTopRightRadius), Math.max(0, borderTopRightRadius), Math.max(0, borderBottomRightRadius), Math.max(0, borderBottomRightRadius), Math.max(0, borderBottomLeftRadius), Math.max(0, borderBottomLeftRadius) }; backgroundPath.addRoundRect(new RectF(getBounds()), backgroundRadii, Path.Direction.CW); outline.setConvexPath(backgroundPath); } else { throw new IllegalStateException("Method supported on API 21 or higher"); } }
Source:
private SaveablesProvider createSaveablesProvider(NavigatorContentDescriptor descriptor) { NavigatorContentExtension extension = contentService .getExtension(descriptor, true); ITreeContentProvider contentProvider = extension .getContentProvider(); return (SaveablesProvider)Adapters.getAdapter(contentProvider, SaveablesProvider.class, true); }

Target:
private SaveablesProvider createSaveablesProvider(NavigatorContentDescriptor descriptor) { NavigatorContentExtension extension = contentService .getExtension(descriptor, true); ITreeContentProvider contentProvider = extension .getContentProvider(); return Adapters.getAdapter(contentProvider, SaveablesProvider.class, true); }
Source:
public V get(K key, final Callable<? extends V> valueLoader) throws ExecutionException { V value = cache.get(key); if (value != null) return value; try { value = valueLoader.call(); cache.put(key, value); return value; } catch (Exception e) { throw new ISE(e, "got an exception while loading key [%s]", key); } }

Target:
public V get(K key, final Callable<? extends V> valueLoader) throws ExecutionException { synchronized (key) { V value = cache.get(key); if (value != null) { return value; } try { value = valueLoader.call(); cache.put(key, value); return value; } catch (Exception e) { throw new ISE(e, "got an exception while loading key [%s]", key); } } }
Source:
public void destroySession(final HttpServletRequest request) { String logoutMessage; if ("GET".equals(request.getMethod())) { logoutMessage = uncompressLogoutMessage(CommonUtils.safeGetParameter(request, this.frontLogoutParameterName)); } else { logoutMessage = CommonUtils.safeGetParameter(request, this.logoutParameterName, this.safeParameters); } logger.trace("Logout request:\n{}", logoutMessage); final String token = XmlUtils.getTextForElement(logoutMessage, "SessionIndex"); if (CommonUtils.isNotBlank(token)) { final HttpSession session = this.sessionMappingStorage.removeSessionByMappingId(token); if (session != null) { String sessionID = session.getId(); logger.debug("Invalidating session for token [{}]", sessionID, token); try { session.invalidate(); } catch (final IllegalStateException e) { logger.debug("Error invalidating session.", e); } try { request.logout(); } catch (final ServletException e) { logger.debug("Error performing request.logout."); } } } }

Target:
private void destroySession(final HttpServletRequest request) { final String logoutMessage; if (isFrontChannelLogoutRequest(request)) { logoutMessage = uncompressLogoutMessage(CommonUtils.safeGetParameter(request, this.frontLogoutParameterName)); } else { logoutMessage = CommonUtils.safeGetParameter(request, this.logoutParameterName, this.safeParameters); } logger.trace("Logout request:\n{}", logoutMessage); final String token = XmlUtils.getTextForElement(logoutMessage, "SessionIndex"); if (CommonUtils.isNotBlank(token)) { final HttpSession session = this.sessionMappingStorage.removeSessionByMappingId(token); if (session != null) { String sessionID = session.getId(); logger.debug("Invalidating session for token [{}]", sessionID, token); try { session.invalidate(); } catch (final IllegalStateException e) { logger.debug("Error invalidating session.", e); } try { request.logout(); } catch (final ServletException e) { logger.debug("Error performing request.logout."); } } } }
Source:
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) { inflater.inflate(R.menu.card_template_editor, menu); if (mModel.getInt("type") == 1) { Timber.d("Editing cloze model, disabling add/delete card template functionality"); menu.findItem(R.id.action_add).setVisible(false); menu.findItem(R.id.action_delete).setVisible(false); } super.onCreateOptionsMenu(menu, inflater); }

Target:
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) { inflater.inflate(R.menu.card_template_editor, menu); if (mModel.getInt("type") == Consts.MODEL_CLOZE) { Timber.d("Editing cloze model, disabling add/delete card template functionality"); menu.findItem(R.id.action_add).setVisible(false); menu.findItem(R.id.action_delete).setVisible(false); } super.onCreateOptionsMenu(menu, inflater); }
Source:
public void withdrawPatchUnauthorizedTest() throws Exception { context.turnOffAuthorisationSystem(); parentCommunity = CommunityBuilder.createCommunity(context) .withName("Parent Community") .build(); Community child1 = CommunityBuilder.createSubCommunity(context, parentCommunity) .withName("Sub Community") .build(); Collection col1 = CollectionBuilder.createCollection(context, child1) .withName("Collection 1").build(); Item item = ItemBuilder.createItem(context, col1) .withTitle("Public item 1") .withIssueDate("2017-10-17") .withAuthor("Smith, Donald").withAuthor("Doe, John") .withSubject("ExtraEntry") .build(); List<Operation> ops = new ArrayList<Operation>(); ReplaceOperation replaceOperation = new ReplaceOperation("/withdrawn", "true"); ops.add(replaceOperation); String patchBody = getPatchContent(ops); getClient().perform(patch("/api/core/items/" + item.getID()) .content(patchBody) .contentType(MediaType.APPLICATION_JSON_PATCH_JSON)) .andExpect(status().isUnauthorized()); String tokenAdmin = getAuthToken(eperson.getEmail(), password); getClient(tokenAdmin).perform(get("/api/core/items/" + item.getID())) .andExpect(status().isOk()) .andExpect(jsonPath("$.uuid", Matchers.is(item.getID().toString()))) .andExpect(jsonPath("$.withdrawn", Matchers.is(false))) .andExpect(jsonPath("$.inArchive", Matchers.is(true))); }

Target:
public void withdrawPatchUnauthorizedTest() throws Exception { context.turnOffAuthorisationSystem(); parentCommunity = CommunityBuilder.createCommunity(context) .withName("Parent Community") .build(); Community child1 = CommunityBuilder.createSubCommunity(context, parentCommunity) .withName("Sub Community") .build(); Collection col1 = CollectionBuilder.createCollection(context, child1) .withName("Collection 1").build(); Item item = ItemBuilder.createItem(context, col1) .withTitle("Public item 1") .withIssueDate("2017-10-17") .withAuthor("Smith, Donald").withAuthor("Doe, John") .withSubject("ExtraEntry") .build(); List<Operation> ops = new ArrayList<Operation>(); ReplaceOperation replaceOperation = new ReplaceOperation("/withdrawn", true); ops.add(replaceOperation); String patchBody = getPatchContent(ops); getClient().perform(patch("/api/core/items/" + item.getID()) .content(patchBody) .contentType(MediaType.APPLICATION_JSON_PATCH_JSON)) .andExpect(status().isUnauthorized()); String tokenAdmin = getAuthToken(eperson.getEmail(), password); getClient(tokenAdmin).perform(get("/api/core/items/" + item.getID())) .andExpect(status().isOk()) .andExpect(jsonPath("$.uuid", Matchers.is(item.getID().toString()))) .andExpect(jsonPath("$.withdrawn", Matchers.is(false))) .andExpect(jsonPath("$.inArchive", Matchers.is(true))); }
Source:
public Response handle() throws Exception { ServerSideSession session = getDriver().getSession(getRequest().getSession()); JSONObject payload = getRequest().getPayload(); String type = payload.getString("type"); WebDriverLog log = (WebDriverLog) session.getLogManager().getLog(type); List<LogEntry> entries = (log == null ? null : log.getAndClearEntries()); return createResponse(entries); }

Target:
public Response handle() throws Exception { ServerSideSession session = getDriver().getSession(getRequest().getSession()); JSONObject payload = getRequest().getPayload(); String type = payload.getString("type"); List<LogEntry> entries = session.getLogManager().getLog(type); return createResponse(entries); }
Source:
public ConceptName getName(Locale locale, ConceptNameType ofType, ConceptNameTag havingTag) { Collection<ConceptName> namesInLocale = getNames(locale); if (!namesInLocale.isEmpty()) { List<ConceptName> matches = new ArrayList<>(namesInLocale.stream().filter(c->(ofType==null || ofType.equals(c.getConceptNameType()))&&(havingTag==null||c.hasTag(havingTag))).collect(Collectors.toList())); if (matches.size() == 1) { return matches.get(0); } else if (matches.size() > 1) { for (ConceptName match : matches) { if (match.getLocalePreferred()) { return match; } } return matches.get(0); } } Locale parent = new Locale(locale.getLanguage()); if (!parent.equals(locale)) { return getName(parent, ofType, havingTag); } else { return null; } }

Target:
public ConceptName getName(Locale locale, ConceptNameType ofType, ConceptNameTag havingTag) { Collection<ConceptName> namesInLocale = getNames(locale); if (!namesInLocale.isEmpty()) { List<ConceptName> matches = namesInLocale.stream().filter( c->(ofType==null || ofType.equals(c.getConceptNameType())) && (havingTag==null || c.hasTag(havingTag)) ).collect(Collectors.toList()); if (matches.size() == 1) { return matches.get(0); } else if (matches.size() > 1) { for (ConceptName match : matches) { if (match.getLocalePreferred()) { return match; } } return matches.get(0); } } Locale parent = new Locale(locale.getLanguage()); if (!parent.equals(locale)) { return getName(parent, ofType, havingTag); } else { return null; } }
Source:
public DruidQueryGeneratorContext visitProject(ProjectNode node, DruidQueryGeneratorContext contextIn) { DruidQueryGeneratorContext context = node.getSource().accept(this, contextIn); requireNonNull(context, "context is null"); Map<VariableReferenceExpression, Selection> newSelections = new LinkedHashMap<>(); node.getOutputVariables().forEach(variable -> { RowExpression expression = node.getAssignments().get(variable); DruidExpression druidExpression = expression.accept( contextIn.getVariablesInAggregation().contains(variable) ? new DruidAggregationProjectConverter(typeManager, functionMetadataManager, standardFunctionResolution) : druidProjectExpressionConverter, context.getSelections()); newSelections.put( variable, new Selection(druidExpression.getDefinition(), druidExpression.getOrigin())); }); return context.withProject(newSelections); }

Target:
public DruidQueryGeneratorContext visitProject(ProjectNode node, DruidQueryGeneratorContext contextIn) { DruidQueryGeneratorContext context = node.getSource().accept(this, contextIn); requireNonNull(context, "context is null"); Map<VariableReferenceExpression, Selection> newSelections = new LinkedHashMap<>(); node.getOutputVariables().forEach(variable -> { RowExpression expression = node.getAssignments().get(variable); DruidProjectExpressionConverter projectExpressionConverter = druidProjectExpressionConverter; if (contextIn.getVariablesInAggregation().contains(variable)) { projectExpressionConverter = new DruidAggregationProjectConverter(typeManager, functionMetadataManager, standardFunctionResolution); } DruidExpression druidExpression = expression.accept( projectExpressionConverter, context.getSelections()); newSelections.put( variable, new Selection(druidExpression.getDefinition(), druidExpression.getOrigin())); }); return context.withProject(newSelections); }
Source:
public PersistedStats(String baseDir, Context context) { mStatsFile = new File(baseDir, "upload_stats.ini"); mContext = context; }

Target:
public PersistedStats(String baseDir, Context context) { mStatsFile = new File(baseDir, "upload_stats.ini"); mContext = context.getApplicationContext(); }
Source:
void testSshKeyCreation() { String testKey = "ssh-rsa AAAASASFAS3532== banana@apple.com"; AuthenticationDto dto = AuthenticationDto.builder() .withLoginUserName(LOGIN) .withPublicKey(testKey) .withPublicKeyId(PUBLIC_KEY_ID) .withManagedKey(true) .build(); EnvironmentAuthentication environmentAuthentication = underTest.dtoToAuthentication(dto); assertEquals("ssh-rsa AAAASASFAS3532== cloudbreak", environmentAuthentication.getPublicKey()); }

Target:
void testSshKeyCreation() { String testKey = "ssh-rsa AAAASASFAS3532== banana@apple.com"; AuthenticationDto dto = AuthenticationDto.builder() .withLoginUserName(LOGIN) .withPublicKey(testKey) .withPublicKeyId(PUBLIC_KEY_ID) .withManagedKey(true) .build(); EnvironmentAuthentication environmentAuthentication = underTest.dtoToAuthentication(dto); verify(publicKeyValidator, Mockito.times(1)).validatePublicKey(anyString()); assertEquals("ssh-rsa AAAASASFAS3532== login", environmentAuthentication.getPublicKey()); }
Source:
public BlockStroageServicesService services() { return Apis.get(BlockStroageServicesService.class); }

Target:
public BlockStorageServiceService services() { return Apis.get(BlockStorageServiceService.class); }
Source:
protected EntityConfigChangedListener<PipelineConfig> pipelineConfigChangedListener() { final SCMMaterialSource self = this; return new EntityConfigChangedListener<PipelineConfig>() { @Override public void onEntityConfigChange(PipelineConfig pipelineConfig) { self.onConfigChange(goConfigService.getCurrentConfig()); } }; }

Target:
protected EntityConfigChangedListener<PipelineConfig> pipelineConfigChangedListener() { final SCMMaterialSource self = this; return new EntityConfigChangedListener<PipelineConfig>() { @Override public void onEntityConfigChange(PipelineConfig pipelineConfig) { self.onConfigChange(null); } }; }
Source:
public void reward_BigDecimal() { assumeDrools(); TestdataSimpleBigDecimalScoreSolution solution = new TestdataSimpleBigDecimalScoreSolution(); TestdataValue v1 = new TestdataValue("v1"); solution.setValueList(Arrays.asList(v1)); TestdataEntity e1 = new TestdataEntity("e1", v1); TestdataEntity e2 = new TestdataEntity("e2", v1); solution.setEntityList(Arrays.asList(e1, e2)); ConstraintStreamScoreDirectorFactory<TestdataSimpleBigDecimalScoreSolution> scoreDirectorFactory = new ConstraintStreamScoreDirectorFactory<>( TestdataSimpleBigDecimalScoreSolution.buildSolutionDescriptor(), (factory) -> new Constraint[]{ factory.from(TestdataEntity.class) .join(TestdataValue.class, equal(TestdataEntity::getValue, identity())) .join(TestdataValue.class) .reward("myConstraint1", SimpleBigDecimalScore.ONE), factory.from(TestdataEntity.class) .join(TestdataValue.class, equal(TestdataEntity::getValue, identity())) .join(TestdataValue.class) .rewardBigDecimal("myConstraint2", SimpleBigDecimalScore.ONE, (entity, value, extra) -> new BigDecimal("0.2")) }, constraintStreamImplType); InnerScoreDirector<TestdataSimpleBigDecimalScoreSolution> scoreDirector = scoreDirectorFactory.buildScoreDirector(false, constraintMatchEnabled); scoreDirector.setWorkingSolution(solution); assertEquals(SimpleBigDecimalScore.of(new BigDecimal("2.4")), scoreDirector.calculateScore()); }

Target:
public void reward_BigDecimal() { assumeDrools(); TestdataSimpleBigDecimalScoreSolution solution = new TestdataSimpleBigDecimalScoreSolution(); TestdataValue v1 = new TestdataValue("v1"); solution.setValueList(Arrays.asList(v1)); TestdataEntity e1 = new TestdataEntity("e1", v1); TestdataEntity e2 = new TestdataEntity("e2", v1); solution.setEntityList(Arrays.asList(e1, e2)); ConstraintStreamScoreDirectorFactory<TestdataSimpleBigDecimalScoreSolution> scoreDirectorFactory = new ConstraintStreamScoreDirectorFactory<>( TestdataSimpleBigDecimalScoreSolution.buildSolutionDescriptor(), (factory) -> new Constraint[]{ factory.fromUniquePair(TestdataEntity.class) .join(TestdataValue.class, equal((entity1, entity2) -> e1.getValue(), identity())) .join(TestdataValue.class) .reward("myConstraint1", SimpleBigDecimalScore.ONE), factory.fromUniquePair(TestdataEntity.class) .join(TestdataValue.class, equal((entity1, entity2) -> e1.getValue(), identity())) .join(TestdataValue.class) .rewardBigDecimal("myConstraint2", SimpleBigDecimalScore.ONE, (entity1, entity2, value, extra) -> new BigDecimal("0.2")) }, constraintStreamImplType); InnerScoreDirector<TestdataSimpleBigDecimalScoreSolution> scoreDirector = scoreDirectorFactory.buildScoreDirector(false, constraintMatchEnabled); scoreDirector.setWorkingSolution(solution); assertEquals(SimpleBigDecimalScore.of(new BigDecimal("1.2")), scoreDirector.calculateScore()); }
Source:
public void testCreateStatic() throws PendingIntent.CanceledException, InterruptedException { Uri aUri = new Uri.Builder().authority("mine").build(); String something = "something"; int i = 42; sLatch = new CountDownLatch(1); resetState(); RemoteCallback.create(Provider.class, mContext).myCallbackMethod( aUri, something, i, null).toPendingIntent().send(); sLatch.await(2, TimeUnit.SECONDS); assertState(0, aUri, something, i); }

Target:
public void testCreateStatic() throws PendingIntent.CanceledException, InterruptedException { Uri aUri = new Uri.Builder().authority("mine").build(); String something = "something"; int i = 42; resetState(); RemoteCallback.create(Provider.class, mContext).myCallbackMethod( aUri, something, i, null).toPendingIntent().send(); sLatch.await(2, TimeUnit.SECONDS); assertState(0, aUri, something, i); }
Source:
public void process(JSONRequestContext requestContext) { try { OnnistuuClient onnistuuClient = OnnistuuClient.getInstance(); JSONObject jsonObject = onnistuuClient.listSignatureSources(); requestContext.addResponseParameter("sources", jsonObject); } catch (Exception e) { logger.log(Level.SEVERE, "Error loading signature soruces", e); } }

Target:
public void process(JSONRequestContext requestContext) { try { OnnistuuClient onnistuuClient = OnnistuuClient.getInstance(); JSONObject jsonObject = onnistuuClient.listSignatureSources(); requestContext.addResponseParameter("sources", jsonObject); } catch (Exception e) { logger.log(Level.SEVERE, "Error loading signature sources", e); } }
Source:
public HandlerResult handle(ProcessState state, ProcessInstance process) { final Instance instance = (Instance)state.getResource(); Map<String, Object> labels = DataAccessor.fieldMap(instance, InstanceConstants.FIELD_LABELS); List<Volume> volumes = InstanceHelpers.extractVolumesFromMounts(instance, objectManager); for (final Volume v : volumes) { String driver = DataAccessor.fieldString(v, VolumeConstants.FIELD_VOLUME_DRIVER); if (StringUtils.isNotEmpty(driver) && !VolumeConstants.LOCAL_DRIVER.equals(driver)) { List<? extends StoragePool> pools = storagePoolDao.findStoragePoolByDriverName(v.getAccountId(), driver); if (pools.size() == 0) { continue; } StoragePool sp = pools.get(0); final String accessMode = sp.getVolumeAccessMode(); if (StringUtils.isNotEmpty(accessMode) && StringUtils.isEmpty(v.getAccessMode()) && !accessMode.equals(v.getAccessMode())) { lockManager.lock(new InstanceVolumeAccessModeLock(v.getId()), new LockCallbackNoReturn() { @Override public void doWithLockNoResult() { objectManager.setFields(v, VOLUME.ACCESS_MODE, accessMode); } }); } } Map<String, Object> driver_opts = DataAccessor.fieldMap(v, VolumeConstants.FIELD_VOLUME_DRIVER_OPTS); if (driver_opts.containsKey("ec2_az")) { String zone = driver_opts.get("ec2_az").toString(); labels.put(VolumeConstants.SCALE_GROUP_LABEL, String.format("key=ec2.availability_zone;%s=1", zone)); objectManager.setFields(instance, InstanceConstants.FIELD_LABELS, labels); } } return null; }

Target:
public HandlerResult handle(ProcessState state, ProcessInstance process) { final Instance instance = (Instance)state.getResource(); Map<String, Object> labels = DataAccessor.fieldMap(instance, InstanceConstants.FIELD_LABELS); List<Volume> volumes = InstanceHelpers.extractVolumesFromMounts(instance, objectManager); for (final Volume v : volumes) { String driver = DataAccessor.fieldString(v, VolumeConstants.FIELD_VOLUME_DRIVER); if (StringUtils.isNotEmpty(driver) && !VolumeConstants.LOCAL_DRIVER.equals(driver)) { List<? extends StoragePool> pools = storagePoolDao.findStoragePoolByDriverName(v.getAccountId(), driver); if (pools.size() == 0) { continue; } StoragePool sp = pools.get(0); final String accessMode = sp.getVolumeAccessMode(); if (StringUtils.isNotEmpty(accessMode) && StringUtils.isEmpty(v.getAccessMode()) && !accessMode.equals(v.getAccessMode())) { lockManager.lock(new InstanceVolumeAccessModeLock(v.getId()), new LockCallbackNoReturn() { @Override public void doWithLockNoResult() { objectManager.setFields(v, VOLUME.ACCESS_MODE, accessMode); } }); } } Map<String, Object> driver_opts = DataAccessor.fieldMap(v, VolumeConstants.FIELD_VOLUME_DRIVER_OPTS); if (driver_opts.containsKey(VolumeConstants.EC2_AZ)) { String zone = driver_opts.get(VolumeConstants.EC2_AZ).toString(); labels.put(HostAffinityConstraint.LABEL_HEADER_AFFINITY_HOST_LABEL, String.format("%s=%s", VolumeConstants.EC2_AZ_HOST_LABEL_KEY, zone)); objectManager.setFields(instance, InstanceConstants.FIELD_LABELS, labels); } } return null; }
Source:
public Project getProject(int id) { Project fetchedProject = null; try { fetchedProject = projectLoader.fetchProjectById(id); loadAllProjectFlows(fetchedProject); } catch (ProjectManagerException e) { logger.error("Could not load project from store.", e); } return fetchedProject; }

Target:
public Project getProject(int id) { Project fetchedProject = null; try { fetchedProject = projectLoader.fetchProjectById(id); loadAllProjectFlows(fetchedProject); } catch (ProjectManagerException e) { logger.error("Could not load project" + id + " from store.", e); } return fetchedProject; }
Source:
public static Properties loadProperties(String properties) throws IOException { Properties p = new Properties(); try { p.load(new StringReader(properties)); } catch(LinkageError _) { p.load(new StringInputStream(properties)); } return p; }

Target:
public static Properties loadProperties(String properties) throws IOException { Properties p = new Properties(); try { p.load(new StringReader(properties)); } catch(NoSuchMethodError _) { p.load(new StringInputStream(properties)); } return p; }
Source:
public InetSocketAddress getAddressForHost(String host) throws UnknownHostException { if (config.addressTranslation().containsKey(host)) { return config.addressTranslation().get(host); } InetAddress resolvedHost = InetAddress.getByName(host); Set<InetSocketAddress> allKnownHosts = Sets.union(currentPools.keySet(), config.servers()); for (InetSocketAddress address : allKnownHosts) { if (resolvedHost.equals(address.getAddress())) { return address; } } Set<Integer> allKnownPorts = allKnownHosts.stream() .map(InetSocketAddress::getPort) .collect(Collectors.toSet()); if (allKnownPorts.size() == 1) { return new InetSocketAddress(resolvedHost, Iterables.getOnlyElement(allKnownPorts)); } else { throw new UnknownHostException("Couldn't find the provided host in server list or current servers"); } }

Target:
public InetSocketAddress getAddressForHost(String host) throws UnknownHostException { if (config.addressTranslation().containsKey(host)) { return config.addressTranslation().get(host); } InetAddress resolvedHost = InetAddress.getByName(host); Set<InetSocketAddress> allKnownHosts = Sets.union(currentPools.keySet(), config.servers()); for (InetSocketAddress address : allKnownHosts) { if (Objects.equals(address.getAddress(), resolvedHost)) { return address; } } Set<Integer> allKnownPorts = allKnownHosts.stream() .map(InetSocketAddress::getPort) .collect(Collectors.toSet()); if (allKnownPorts.size() == 1) { return new InetSocketAddress(resolvedHost, Iterables.getOnlyElement(allKnownPorts)); } else { throw new UnknownHostException("Couldn't find the provided host in server list or current servers"); } }
Source:
public void onNewUser(User user) { TextInputLayout emailLayout = findViewById(R.id.email_layout); AuthUI.IdpConfig emailConfig; try { emailConfig = ProviderUtils.getConfigFromIdpsOrThrow( getFlowParams().providers, EmailAuthProvider.PROVIDER_ID); } catch (IllegalStateException e) { emailConfig = ProviderUtils.getConfigFromIdpsOrThrow( getFlowParams().providers, EmailAuthProvider.EMAIL_LINK_SIGN_IN_METHOD); } if (emailConfig.getParams().getBoolean(ExtraConstants.ALLOW_NEW_EMAILS, true)) { FragmentTransaction ft = getSupportFragmentManager().beginTransaction(); if (emailConfig.getProviderId().equals(EMAIL_LINK_PROVIDER)) { registerEmailLinkFragment(emailConfig, user.getEmail()); } else { RegisterEmailFragment fragment = RegisterEmailFragment.newInstance(user); ft.replace(R.id.fragment_register_email, fragment, RegisterEmailFragment.TAG); if (emailLayout != null) { String emailFieldName = getString(R.string.fui_email_field_name); ViewCompat.setTransitionName(emailLayout, emailFieldName); ft.addSharedElement(emailLayout, emailFieldName); } ft.disallowAddToBackStack().commit(); } } else { emailLayout.setError(getString(R.string.fui_error_email_does_not_exist)); } }

Target:
public void onNewUser(User user) { TextInputLayout emailLayout = findViewById(R.id.email_layout); AuthUI.IdpConfig emailConfig = ProviderUtils.getConfigFromIdps(getFlowParams().providers, EmailAuthProvider.PROVIDER_ID); if (emailConfig == null) { emailConfig = ProviderUtils.getConfigFromIdps(getFlowParams().providers, EMAIL_LINK_PROVIDER); } if (emailConfig.getParams().getBoolean(ExtraConstants.ALLOW_NEW_EMAILS, true)) { FragmentTransaction ft = getSupportFragmentManager().beginTransaction(); if (emailConfig.getProviderId().equals(EMAIL_LINK_PROVIDER)) { showRegisterEmailLinkFragment(emailConfig, user.getEmail()); } else { RegisterEmailFragment fragment = RegisterEmailFragment.newInstance(user); ft.replace(R.id.fragment_register_email, fragment, RegisterEmailFragment.TAG); if (emailLayout != null) { String emailFieldName = getString(R.string.fui_email_field_name); ViewCompat.setTransitionName(emailLayout, emailFieldName); ft.addSharedElement(emailLayout, emailFieldName); } ft.disallowAddToBackStack().commit(); } } else { emailLayout.setError(getString(R.string.fui_error_email_does_not_exist)); } }
Source:
public void setUp() { final EventTypeCache cache = mock(EventTypeCache.class); final ArgumentCaptor<Consumer<String>> changeCall = new ArgumentCaptor<>(); listener = new EventTypeChangeListener(cache); verify(cache, times(1)).addInvalidationListener(changeCall.capture()); notificationTrigger = changeCall.getValue(); }

Target:
public void setUp() { final EventTypeCache cache = mock(EventTypeCache.class); final ArgumentCaptor<Consumer> changeCall = ArgumentCaptor.forClass(Consumer.class); listener = new EventTypeChangeListener(cache); verify(cache, times(1)).addInvalidationListener(changeCall.capture()); notificationTrigger = changeCall.getValue(); }
Source:
public void createDocumentBuilder() { HtmlSubsetDocumentBuilder builder = newHtmlSubsetLanguage(BlockType.PARAGRAPH) .createDocumentBuilder(new StringWriter(), false); assertNotNull(builder); assertTrue(builder instanceof HtmlSubsetDocumentBuilder); assertEquals(ImmutableSet.of(SpanType.BOLD), builder.getStringSubstitutedSpanTypes()); }

Target:
public void createDocumentBuilder() { StringWriter out = new StringWriter(); HtmlSubsetDocumentBuilder builder = newHtmlSubsetLanguage(BlockType.PARAGRAPH).createDocumentBuilder(out, false); assertNotNull(builder); assertTrue(builder instanceof HtmlSubsetDocumentBuilder); builder = newHtmlSubsetLanguage(SpanType.EMPHASIS).createDocumentBuilder(out, false); builder.beginSpan(SpanType.EMPHASIS, new Attributes()); builder.characters("text"); builder.endSpan(); assertEquals("<new-em>text</new-em>", out.toString()); }
Source:
private <T> LocalRegistrationResult addLocalRegistration(String address, HandlerRegistration<T> registration, boolean replyHandler, boolean localOnly) { Objects.requireNonNull(address, "address"); Context context = Vertx.currentContext(); boolean hasContext = context != null; if (!hasContext) { context = vertx.getOrCreateContext(); } registration.setHandlerContext(context); HandlerHolder<T> holder = new HandlerHolder<>(metrics, registration, replyHandler, localOnly, context); Handlers handlers = new Handlers(holder); Handlers actual = handlerMap.merge(address, handlers, (prev, current) -> prev.add(current.first())); if (hasContext) { HandlerEntry entry = new HandlerEntry<>(address, registration); context.addCloseHook(entry); } boolean newAddress = handlers == actual; return new LocalRegistrationResult<>(holder, newAddress); }

Target:
private <T> LocalRegistrationResult<T> addLocalRegistration(String address, HandlerRegistration<T> registration, boolean replyHandler, boolean localOnly) { Objects.requireNonNull(address, "address"); Context context = Vertx.currentContext(); boolean hasContext = context != null; if (!hasContext) { context = vertx.getOrCreateContext(); } registration.setHandlerContext(context); HandlerHolder<T> holder = new HandlerHolder<>(metrics, registration, replyHandler, localOnly, context); ConcurrentCyclicSequence<HandlerHolder> handlers = new ConcurrentCyclicSequence<HandlerHolder>().add(holder); ConcurrentCyclicSequence<HandlerHolder> actualHandlers = handlerMap.merge( address, handlers, (old, prev) -> old.add(prev.first())); if (hasContext) { HandlerEntry entry = new HandlerEntry<>(address, registration); context.addCloseHook(entry); } boolean newAddress = handlers == actualHandlers; return new LocalRegistrationResult<>(holder, newAddress); }