auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public StepContext getObject() throws Exception { org.springframework.batch.core.scope.context.StepContext stepContext = StepSynchronizationManager.getContext(); String stepName = stepContext.getStepName(); String jobName = stepContext.getStepExecution().getJobExecution().getJobInstance().getJobName(); Properties properties = batchPropertyContext.getStepLevelProperties(jobName + "." + stepName + "." + stepName); return new StepContext(stepContext.getStepExecution(), properties); }

Target:
public StepContext getObject() throws Exception { org.springframework.batch.core.scope.context.StepContext stepContext = StepSynchronizationManager.getContext(); String stepName = stepContext.getStepName(); String jobName = stepContext.getStepExecution().getJobExecution().getJobInstance().getJobName(); Properties properties = batchPropertyContext.getStepLevelProperties(jobName + "." + stepName); return new StepContext(stepContext.getStepExecution(), properties); }
Source:
public TableEto getTable(String id) { LoggerFactory.getLogger(TablemanagementRestServiceImpl.class).trace("impl test"); long idAsLong; if (id == null) { throw new BadRequestException("missing id"); } try { idAsLong = Long.parseLong(id); } catch (NumberFormatException e) { throw new BadRequestException("id is not a number"); } catch (NotFoundException e) { throw new BadRequestException("table not found"); } return this.tableManagement.findTable(idAsLong); }

Target:
public TableEto getTable(String id) { long idAsLong; if (id == null) { throw new BadRequestException("missing id"); } try { idAsLong = Long.parseLong(id); } catch (NumberFormatException e) { throw new BadRequestException("id is not a number"); } catch (NotFoundException e) { throw new BadRequestException("table not found"); } return this.tableManagement.findTable(idAsLong); }
Source:
protected synchronized boolean checkRequiredSettings() { requiredProperties = getRequiredPropertyValues(); if ( requiredProperties.get( RequiredProp.PROVIDER.getName() ).equals( this.getClass().getCanonicalName() ) && requiredProperties.get( RequiredProp.PROVIDER_URL.getName() ) != null && requiredProperties.get( RequiredProp.DIALECT.getName() ) != null ) { return true; } return false; }

Target:
private synchronized Map<String,String> checkRequiredSettings() { requiredProperties = getRequiredPropertyValues(); Map<String, String> unSetRequiredProperties = new HashMap<String, String>(); if ( requiredProperties.get( RequiredProp.PROVIDER_URL.getName() ) == null || requiredProperties.get( RequiredProp.PROVIDER_URL.getName() ).equals( "" ) ) { unSetRequiredProperties.put( RequiredProp.PROVIDER_URL.getName(), null ); } return unSetRequiredProperties; }
Source:
public void sendPassword(String companyId, String emailAddress, Locale locale, boolean fromAngular) throws PortalException, SystemException { emailAddress = emailAddress.trim().toLowerCase(); if (!Validator.isEmailAddress(emailAddress)) { throw new UserEmailAddressException(); } User user = UserUtil.findByC_EA(companyId, emailAddress); String token = RandomStringUtils.randomAlphanumeric( Config.getIntProperty( "RECOVER_PASSWORD_TOKEN_LENGTH", 30 ) ); user.setIcqId(token+":"+new Date().getTime()); UserUtil.update(user); Company company = CompanyUtil.findByPrimaryKey(companyId); String url = null; String urlPrefix = (company.getPortalURL().contains("://") ? "" : "https://") + company.getPortalURL(); if ( !fromAngular ) { url = urlPrefix + "/c/portal_public/login?my_account_cmd=ereset&my_user_id=" + user.getUserId() + "&token=" + token + "&switchLocale=" + locale.getLanguage() + "_" + locale.getCountry(); }else{ url = urlPrefix + "/" + java.text.MessageFormat.format("html/ng?resetPassword=true&userId={0}&token={1}", user.getUserId(), token); } String body = LanguageUtil.format(locale, "reset-password-email-body", url, false); try { Mailer m = new Mailer(); m.setToEmail(emailAddress); m.setToName(user.getFullName()); m.setSubject(LanguageUtil.get(locale, "reset-password-email-subject")); m.setHTMLBody(body.toString()); m.setFromName(company.getName()); m.setFromEmail(company.getEmailAddress()); m.sendMessage(); } catch (Exception ioe) { throw new SystemException(ioe); } }

Target:
public void sendPassword(String companyId, String emailAddress, Locale locale, boolean fromAngular) throws PortalException, SystemException { emailAddress = emailAddress.trim().toLowerCase(); if (!Validator.isEmailAddress(emailAddress)) { throw new UserEmailAddressException(); } User user = UserUtil.findByC_EA(companyId, emailAddress); String token = ResetPasswordTokenUtil.createToken(); user.setIcqId(token+":"+new Date().getTime()); UserUtil.update(user); Company company = CompanyUtil.findByPrimaryKey(companyId); String url = UrlUtil.getAbsoluteResetPasswordURL(company, user, token, locale, fromAngular); String body = LanguageUtil.format(locale, "reset-password-email-body", url, false); String subject = LanguageUtil.get(locale, "reset-password-email-subject"); try { EmailUtils.sendMail(user, company, subject, body); } catch (Exception ioe) { throw new SystemException(ioe); } }
Source:
public Authenticated authenticate(Credentials credentials) throws ContextAuthenticationException { TestUsernameCredentials creds = (TestUsernameCredentials) credentials; User user = getContextDAO().getUserByUsername(creds.getUsername()); return new BasicAuthenticated(user, "test-scheme"); }

Target:
public Authenticated authenticate(Credentials credentials) throws ContextAuthenticationException { User user = getContextDAO().getUserByUsername(credentials.getClientName()); return new BasicAuthenticated(user, "test-scheme"); }
Source:
private <N extends Number> void registerStatistic(String statNameSuffix, StatisticType type, final ValueStatisticDescriptor descriptor) { if (contextObject == null) { return; } Set<TreeNode> result = queryBuilder() .descendants() .filter(context(attributes(Matchers.<Map<String, Object>>allOf( hasAttribute("name", descriptor.getObserverName()), hasAttribute("tags", new Matcher<Set<String>>() { @Override protected boolean matchesSafely(Set<String> object) { return object.containsAll(descriptor.getTags()); } }))))) .filter(context(identifier(subclassOf(ValueStatistic.class)))) .build().execute(Collections.singleton(ContextManager.nodeFor(contextObject))); if (!result.isEmpty()) { for (TreeNode node : result) { String discriminator = null; Map<String, Object> properties = (Map<String, Object>) node.getContext().attributes().get("properties"); if (properties != null && properties.containsKey("discriminator")) { discriminator = properties.get("discriminator").toString(); } String fullStatName = (discriminator == null ? "" : (discriminator + ":")) + statNameSuffix; ValueStatistic<N> statistic = (ValueStatistic<N>) node.getContext().attributes().get("this"); registerStatistic(fullStatName, type, statistic); } } }

Target:
private <N extends Number> void registerStatistic(String statNameSuffix, StatisticType type, final ValueStatisticDescriptor descriptor) { if (contextObject == null) { return; } Set<TreeNode> result = queryBuilder() .descendants() .filter(context(attributes(Matchers.<Map<String, Object>>allOf( hasAttribute("name", descriptor.getObserverName()), hasTags(descriptor.getTags()))))) .filter(context(identifier(subclassOf(ValueStatistic.class)))) .build().execute(Collections.singleton(ContextManager.nodeFor(contextObject))); if (!result.isEmpty()) { for (TreeNode node : result) { String discriminator = null; Map<String, Object> properties = (Map<String, Object>) node.getContext().attributes().get("properties"); if (properties != null && properties.containsKey("discriminator")) { discriminator = properties.get("discriminator").toString(); } String fullStatName = (discriminator == null ? "" : (discriminator + ":")) + statNameSuffix; ValueStatistic<N> statistic = (ValueStatistic<N>) node.getContext().attributes().get("this"); registerStatistic(fullStatName, type, statistic); } } }
Source:
public MVMap.Decision decide(VersionedValue existingValue, VersionedValue providedValue) { assert decision == null; if (existingValue == null) { decision = MVMap.Decision.ABORT; } else { if (existingValue.getOperationId() == undoKey) { if (existingValue.value == null) { decision = MVMap.Decision.REMOVE; } else { decision = MVMap.Decision.PUT; } } else { decision = MVMap.Decision.ABORT; } } return decision; }

Target:
public MVMap.Decision decide(VersionedValue existingValue, VersionedValue providedValue) { assert decision == null; if (existingValue == null || existingValue.getOperationId() != undoKey) { decision = MVMap.Decision.ABORT; } else if (existingValue.value == null) { decision = MVMap.Decision.REMOVE; } else { decision = MVMap.Decision.PUT; } return decision; }
Source:
private List<OSInfluence> getInfluences() { List<OSInfluence> influences = new ArrayList<>(); Set<String> influencesString = OneSignalPrefs.getStringSet( OneSignalPrefs.PREFS_ONESIGNAL, OneSignalPrefs.PREFS_OS_ATTRIBUTED_INFLUENCES, new HashSet<String>() ); for (String influenceJSONString : influencesString) { try { influences.add(new OSInfluence(influenceJSONString)); } catch (JSONException exception) { OneSignal.Log(OneSignal.LOG_LEVEL.ERROR, this.getClass().getSimpleName() + ": error generation OSInfluence from json object: " + exception); } } return influences; }

Target:
private List<OSInfluence> getInfluences() { List<OSInfluence> influences = new ArrayList<>(); Set<String> influenceJSONs = OneSignalPrefs.getStringSet( OneSignalPrefs.PREFS_ONESIGNAL, OneSignalPrefs.PREFS_OS_ATTRIBUTED_INFLUENCES, new HashSet<String>() ); for (String influenceJSON : influenceJSONs) { try { influences.add(new OSInfluence(influenceJSON)); } catch (JSONException exception) { OneSignal.Log(OneSignal.LOG_LEVEL.ERROR, this.getClass().getSimpleName() + ": error generation OSInfluence from json object: " + exception); } } return influences; }
Source:
public int read() throws IOException { if ( closed ) { throw new IOException( "Joint: " + jointIdx + ": Cannot read from closed stream!" ); } synchronized ( JoinableFile.this ) { while ( read == flushed ) { if ( output == null || JoinableFile.this.closed ) { return -1; } try { JoinableFile.this.wait( 100 ); } catch ( final InterruptedException e ) { return -1; } } } if ( buf.position() == buf.limit() ) { buf = channel.map( MapMode.READ_ONLY, read, flushed > MAX_BUFFER_SIZE ? MAX_BUFFER_SIZE : flushed - read ); } if ( buf.position() == buf.limit() ) { return -1; } final int result = buf.get(); read++; return result < 0 ? result + 256 : result; }

Target:
public int read() throws IOException { if ( closed ) { throw new IOException( "Joint: " + jointIdx + ": Cannot read from closed stream!" ); } synchronized ( JoinableFile.this ) { while ( read == flushed ) { if ( output == null || JoinableFile.this.closed ) { return -1; } try { JoinableFile.this.wait( 100 ); } catch ( final InterruptedException e ) { return -1; } } } if ( buf.position() == buf.limit() ) { buf = channel.map( MapMode.READ_ONLY, read, flushed > MAX_BUFFER_SIZE ? MAX_BUFFER_SIZE : flushed - read ); } if ( buf.position() == buf.limit() ) { return -1; } final int result = buf.get(); read++; return result & 0xff; }
Source:
private Transition(final InternalStatus to) { if(to == null) { throw new NullPointerException(); } this.from = InternalStatus.this; this.to = to; }

Target:
private Transition(final InternalStatus to) { if(to == null) { throw new NullPointerException(); } this.to = to; }
Source:
public String getTimeForDisplay() { return TimeHelper.formatTime12H(TimeHelper.convertInstantToLocalDateTime( Instant.ofEpochMilli(emailEntry.getTime()), Const.SystemParams.ADMIN_TIME_ZONE_ID)); }

Target:
public String getTimeForDisplay() { return TimeHelper.formatTime12H(TimeHelper.convertInstantToLocalDateTime( Instant.ofEpochMilli(emailEntry.getTime()), Const.SystemParams.ADMIN_TIME_ZONE)); }
Source:
private void onLightAddedInternal(FullLight light) { ThingUID thingUID = getThingUID(light); ThingTypeUID thingTypeUID = getThingTypeUID(light); String modelId = light.getModelID().replaceAll(HueLightHandler.NORMALIZE_ID_REGEX, "_"); if (thingUID != null && thingTypeUID != null) { ThingUID bridgeUID = hueBridgeHandler.getThing().getUID(); Map<String, Object> properties = new HashMap<>(1); properties.put(LIGHT_ID, light.getId()); properties.put(MODEL_ID, modelId); DiscoveryResult discoveryResult = DiscoveryResultBuilder.create(thingUID).withThingType(thingTypeUID) .withProperties(properties).withBridge(bridgeUID).withLabel(light.getName()).build(); thingDiscovered(discoveryResult); } else { logger.debug("discovered unsupported light of type '{}' with id {}", modelId, light.getId()); } }

Target:
private void onLightAddedInternal(FullLight light) { ThingUID thingUID = getThingUID(light); ThingTypeUID thingTypeUID = getThingTypeUID(light); String modelId = light.getModelID().replaceAll(HueLightHandler.NORMALIZE_ID_REGEX, "_"); if (thingUID != null && thingTypeUID != null) { ThingUID bridgeUID = hueBridgeHandler.getThing().getUID(); Map<String, Object> properties = new HashMap<>(1); properties.put(LIGHT_ID, light.getId()); properties.put(MODEL_ID, modelId); DiscoveryResult discoveryResult = DiscoveryResultBuilder.create(thingUID).withThingType(thingTypeUID) .withProperties(properties).withBridge(bridgeUID).withLabel(light.getName()).build(); thingDiscovered(discoveryResult); } else { logger.debug("discovered unsupported light of type '{}' and model '{}' with id {}", light.getType(), modelId, light.getId()); } }
Source:
protected CommandResult(boolean processed, @Nullable Integer successCount, @Nullable Integer affectedBlocks, @Nullable Integer affectedEntities, @Nullable Integer affectedItems, @Nullable Integer queryResult, @Nullable Map<String, Object> resultInfo) { this.processed = processed; this.successCount = Optional.fromNullable(successCount); this.affectedBlocks = Optional.fromNullable(affectedBlocks); this.affectedEntities = Optional.fromNullable(affectedEntities); this.affectedItems = Optional.fromNullable(affectedItems); this.queryResult = Optional.fromNullable(queryResult); this.resultInfo = resultInfo != null ? Collections.unmodifiableMap(resultInfo) : Collections.<String, Object>emptyMap(); }

Target:
CommandResult(boolean processed, @Nullable Integer successCount, @Nullable Integer affectedBlocks, @Nullable Integer affectedEntities, @Nullable Integer affectedItems, @Nullable Integer queryResult, @Nullable Map<String, Object> resultInfo) { this.processed = processed; this.successCount = Optional.fromNullable(successCount); this.affectedBlocks = Optional.fromNullable(affectedBlocks); this.affectedEntities = Optional.fromNullable(affectedEntities); this.affectedItems = Optional.fromNullable(affectedItems); this.queryResult = Optional.fromNullable(queryResult); this.resultInfo = resultInfo != null ? Collections.unmodifiableMap(resultInfo) : Collections.<String, Object>emptyMap(); }
Source:
private static String getHeaderValue(Header[] headers, String headerName) { if (headers != null) { for (int i = 0; i < headers.length; i++) { if (headerName.equals(headers[i].getName())) { return headers[i].getValue(); } } } return null; }

Target:
private static String getHeaderValue(Header[] headers, String headerName) { if (headers != null) { for (Header header : headers) { if (headerName.equals(header.getName())) { return header.getValue(); } } } return null; }
Source:
public boolean newDue() { return mCol.getDb().queryScalar("SELECT 1 FROM cards WHERE did IN " + _deckLimit() + " AND queue = " + Consts.QUEUE_TYPE_NEW + " LIMIT 1", new Object[] {_deckLimit()}) != 0; }

Target:
public boolean newDue() { return mCol.getDb().queryScalar("SELECT 1 FROM cards WHERE did IN " + _deckLimit() + " AND queue = " + Consts.QUEUE_TYPE_NEW + " LIMIT 1") != 0; }
Source:
public static final byte[] readFully(final File path, final int max) throws FileNotFoundException, IOException { final FileInputStream in = new FileInputStream(path); try { long sz = path.length(); if (sz > max) throw new IOException(MessageFormat.format( JGitText.get().fileIsTooLarge, path)); byte[] buf = new byte[(int) sz]; int valid = 0; for (;;) { if (buf.length == valid) { int nsz = Math.min(max, buf.length * 2); if (nsz > max) throw new IOException(MessageFormat.format( JGitText.get().fileIsTooLarge, path)); byte[] nb = new byte[nsz]; System.arraycopy(buf, 0, nb, 0, valid); buf = nb; } int n = in.read(buf, valid, buf.length - valid); if (n < 0) break; valid += n; } if (valid < buf.length) { byte[] nb = new byte[valid]; System.arraycopy(buf, 0, nb, 0, valid); buf = nb; } return buf; } finally { try { in.close(); } catch (IOException ignored) { } } }

Target:
public static final byte[] readFully(final File path, final int max) throws FileNotFoundException, IOException { final FileInputStream in = new FileInputStream(path); try { long sz = path.length(); if (sz > max) throw new IOException(MessageFormat.format( JGitText.get().fileIsTooLarge, path)); byte[] buf = new byte[(int) sz]; int valid = 0; for (;;) { if (buf.length == valid) { if (buf.length == max) { int next = in.read(); if (next < 0) break; throw new IOException(MessageFormat.format( JGitText.get().fileIsTooLarge, path)); } byte[] nb = new byte[buf.length * 2]; System.arraycopy(buf, 0, nb, 0, valid); buf = nb; } int n = in.read(buf, valid, buf.length - valid); if (n < 0) break; valid += n; } if (valid < buf.length) { byte[] nb = new byte[valid]; System.arraycopy(buf, 0, nb, 0, valid); buf = nb; } return buf; } finally { try { in.close(); } catch (IOException ignored) { } } }
Source:
public void shouldInjectOnlyAttributesWithSameType() throws Exception { Object result = mock(Result.class); when(request.getAttribute("result")).thenReturn(result); when(request.getParameter("result")).thenReturn("buggy"); ControllerMethod method = DefaultControllerMethod.instanceFor(OtherResource.class, OtherResource.class.getDeclaredMethod("logic", String.class)); List<Message> errors = new ArrayList<Message>(); Object[] out = provider.getParametersFor(method, errors); assertThat(out[0], not(is(result))); }

Target:
public void shouldInjectOnlyAttributesWithSameType() throws Exception { Result result = mock(Result.class); when(request.getAttribute("result")).thenReturn(result); when(request.getParameterMap()).thenReturn(singletonMap("result", new String[] { "buggy" })); ControllerMethod method = DefaultControllerMethod.instanceFor(OtherResource.class, OtherResource.class.getDeclaredMethod("logic", String.class)); List<Message> errors = new ArrayList<Message>(); Object[] out = provider.getParametersFor(method, errors); assertThat(out[0], is(not((Object) result))); assertThat(out[0], is((Object) "buggy")); }
Source:
public void reloadConfig() { new GetRequest(mContext, mUrl, GetRequest.URI_CONFIG, mApiKey, null, result -> { Log.v(TAG, "onWebGuiAvailable: " + result); mConfig = new Gson().fromJson(result, Config.class); if (mConfig == null) { throw new RuntimeException("config is null: " + result); } tryIsAvailable(); }); }

Target:
public void reloadConfig() { new GetRequest(mContext, mUrl, GetRequest.URI_CONFIG, mApiKey, null, result -> { Log.v(TAG, "reloadConfig: " + result); mConfig = new Gson().fromJson(result, Config.class); if (mConfig == null) { throw new RuntimeException("config is null: " + result); } }); }
Source:
public void destroy() { for (Component root: this.getRoots()) { getDesktop().getWebApp().getConfiguration().invokeDestroy(root); } super.destroy(); try { if (_ips != null) { final List<Interpreter> ips = new ArrayList<Interpreter>(_ips.values()); _ips.clear(); _ips = null; for (Interpreter ip : ips) { try { ip.destroy(); } catch (Throwable ex) { log.warn("Failed to destroy " + ip, ex); } } } } catch (Throwable ex) { log.warn("Failed to clean up interpreters of " + this, ex); } _desktop = null; _owner = null; _listeners = null; _resolvers = null; _mappers = null; _attrs.getAttributes().clear(); }

Target:
public void destroy() { Configuration config = WebApps.getCurrent().getConfiguration(); for (Component root: this.getRoots()) { config.invokeCallback("destroy", root); } super.destroy(); try { if (_ips != null) { final List<Interpreter> ips = new ArrayList<Interpreter>(_ips.values()); _ips.clear(); _ips = null; for (Interpreter ip : ips) { try { ip.destroy(); } catch (Throwable ex) { log.warn("Failed to destroy " + ip, ex); } } } } catch (Throwable ex) { log.warn("Failed to clean up interpreters of " + this, ex); } _desktop = null; _owner = null; _listeners = null; _resolvers = null; _mappers = null; _attrs.getAttributes().clear(); }
Source:
private void processPaymentDetailEnteredEvent(List<ChargeEventEntity> chargeEventEntities) { chargeEventEntities .stream() .filter(event -> TERMINAL_AUTHENTICATION_STATES.contains(event.getStatus())) .filter(event -> isNotAuthSuccessEventOrAuthSuccessEventWithOut3DSEvent(chargeEventEntities, event)) .map(PaymentDetailsEntered::from) .filter(event -> !emittedEventDao.hasBeenEmittedBefore(event)) .forEach(this::emitAndPersistEvent); }

Target:
private void processPaymentDetailEnteredEvent(List<ChargeEventEntity> chargeEventEntities) { chargeEventEntities .stream() .filter(event -> isValidPaymentDetailsEnteredTransition(chargeEventEntities, event)) .map(PaymentDetailsEntered::from) .filter(event -> !emittedEventDao.hasBeenEmittedBefore(event)) .forEach(this::emitAndPersistEvent); }
Source:
private boolean determineIfUserIsAdminInHierarchy(int userCanvasId, int courseAccountId) { M_log.debug("determineIfUserIsAdminInHierarchy() call"); String url = Utils.urlConstructor("/accounts/", String.valueOf(courseAccountId), "/admins/?user_id[]=", String.valueOf(userCanvasId)); ApiResultWrapper arw = Utils.makeApiCall(new HttpGet(url)); String errMsg = String.format("check user %s is an admin in the course account %s had null response, with status %s, due to:%s" , userCanvasId, courseAccountId, arw.getStatus(), (arw.getApiResp().isEmpty()) ? arw.getMessage() : arw.getApiResp()); if (!Utils.didApiReturnedWithOutErrors(errMsg, arw)) { return false; } JSONArray subAccountAdminsJson = new JSONArray(arw.getApiResp()); if (subAccountAdminsJson.length() > 0) { return true; } int parentAccount = getParentAccount(courseAccountId); if (parentAccount == 0) { return false; } return determineIfUserIsAdminInHierarchy(userCanvasId, parentAccount); }

Target:
private boolean determineIfUserIsAdminInHierarchy(int userCanvasId, int courseAccountId) { M_log.debug("determineIfUserIsAdminInHierarchy() call"); String url = Utils.urlConstructor(Utils.URL_CHUNK_ACCOUNTS, String.valueOf(courseAccountId), URL_CHUNK_ADMINS_USER_ID, String.valueOf(userCanvasId)); ApiResultWrapper arw = Utils.makeApiCall(new HttpGet(url)); String errMsg = String.format("check user %s is an admin in the course account %s had null response, with status %s, due to:%s" , userCanvasId, courseAccountId, arw.getStatus(), (arw.getApiResp().isEmpty()) ? arw.getMessage() : arw.getApiResp()); if (!Utils.didApiReturnedWithOutErrors(errMsg, arw)) { return false; } JSONArray subAccountAdminsJson = new JSONArray(arw.getApiResp()); if (subAccountAdminsJson.length() > 0) { return true; } int parentAccount = getParentAccount(courseAccountId); if (parentAccount == 0) { return false; } return determineIfUserIsAdminInHierarchy(userCanvasId, parentAccount); }
Source:
private List<Cell> doGetCells(Mapper<?, ? extends Cell> mapper, Object actualSource) { if (mapper.getSource() == actualSource) { return Collections.singletonList(mapper.getTarget()); } List<Cell> result = null; for (Synchronizer sync : mapper.synchronizers()) { List<Cell> cells = getCells(sync, actualSource); if (cells != null && !cells.isEmpty()) { if (result == null) { result = new ArrayList<>(cells.size()); } result.addAll(cells); } } return result == null ? Collections.<Cell>emptyList() : result; }

Target:
private List<Cell> doGetCells(Mapper<?, ? extends Cell> mapper, Object actualSource) { if (mapper.getSource() == actualSource) { return Collections.<Cell>singletonList(mapper.getTarget()); } List<Cell> result = null; for (Synchronizer sync : mapper.synchronizers()) { List<Cell> cells = getCells(sync, actualSource); if (cells != null && !cells.isEmpty()) { if (result == null) { result = new ArrayList<>(cells.size()); } result.addAll(cells); } } return result == null ? Collections.<Cell>emptyList() : result; }
Source:
@Override public void run(JsonNode jsonNode) { assert false; }

Target:
@Override public void run(JsonNode jsonNode) { assert false; markInitialized(); markFinished(); }
Source:
public Object executeGeneric(final VirtualFrame frame) { SAbstractObject rcvr = (SAbstractObject) SArguments.rcvr(frame); SObjectWithClass outer; if (rcvr instanceof SObjectWithClass) { outer = (SObjectWithClass) rcvr; } else if (rcvr instanceof SBlock) { outer = (SObjectWithClass) ((SBlock) rcvr).getOuterSelf(); } else { throw new RuntimeException(rcvr + " cannot be the receiver when instantiating an object literal?"); } Object superclassAndMixins = superClassResolver.call(outer); SClass sClass = mixinDef.instantiateClass(outer, superclassAndMixins); sClass.setContext(frame.materialize()); Object[] args = {sClass}; return newMessage.doPreEvaluated(frame, args); }

Target:
public Object executeGeneric(final VirtualFrame frame) { SObjectWithClass outer = (SObjectWithClass) outerRead.executeGeneric(frame); Object superclassAndMixins = superClassResolver.call(outer); SClass sClassObject = instantiation.execute(outer, superclassAndMixins, frame.materialize()); return newMessage.doPreEvaluated(frame, new Object[] {sClassObject}); }
Source:
void testCreateVolumeFromSnapshotInAvailabilityZoneWithOptions() { Volume volume = client.createVolumeInAvailabilityZone(defaultZone, CreateVolumeOptions.Builder.fromSnapshotId(snapshot.getId())); assertNotNull(volume); Predicate<Volume> availabile = retry(new VolumeAvailable(client), 600, 10, SECONDS); assert availabile.apply(volume); Volume result = Iterables.getOnlyElement(client.describeVolumesInRegion(snapshot.getRegion(), volume.getId())); assertEquals(volume.getId(), result.getId()); assertEquals(volume.getSnapshotId(), snapshot.getId()); assertEquals(volume.getAvailabilityZone(), defaultZone); assertEquals(result.getStatus(), Volume.Status.AVAILABLE); client.deleteVolumeInRegion(snapshot.getRegion(), volume.getId()); }

Target:
void testCreateVolumeFromSnapshotInAvailabilityZoneWithOptions() { Volume volume = client.createVolumeInAvailabilityZone(defaultZone, fromSnapshotId(snapshot.getId())); assertNotNull(volume); Predicate<Volume> availabile = retry(new VolumeAvailable(client), 600, 10, SECONDS); assert availabile.apply(volume); Volume result = Iterables.getOnlyElement(client.describeVolumesInRegion(snapshot.getRegion(), volume.getId())); assertEquals(volume.getId(), result.getId()); assertEquals(volume.getSnapshotId(), snapshot.getId()); assertEquals(volume.getAvailabilityZone(), defaultZone); assertEquals(result.getStatus(), Volume.Status.AVAILABLE); client.deleteVolumeInRegion(snapshot.getRegion(), result.getId()); }
Source:
private void runAllParagraphs(final NotebookSocket conn, HashSet<String> userAndRoles, Notebook notebook, final Message fromMessage) throws IOException { final String noteId = (String) fromMessage.get("noteId"); if (StringUtils.isBlank(noteId)) { return; } if (!hasParagraphRunnerPermission(conn, notebook, noteId, userAndRoles, fromMessage.principal, "run all paragraphs")) { return; } final Note note = notebook.getNote(noteId); final List<Map<String, Object>> paragraphs = gson.fromJson(String.valueOf(fromMessage.data.get("paragraphs")), new TypeToken<List<Map<String, Object>>>() {}.getType()); runAllStatusBroadcast(note, true); Thread runAllThread = new Thread(new Runnable() { @Override public void run() { for (Map<String, Object> raw : paragraphs) { String paragraphId = (String) raw.get("id"); if (paragraphId == null) { continue; } String text = (String) raw.get("paragraph"); String title = (String) raw.get("title"); Map<String, Object> params = (Map<String, Object>) raw.get("params"); Map<String, Object> config = (Map<String, Object>) raw.get("config"); Paragraph p = setParagraphUsingMessage(note, fromMessage, paragraphId, text, title, params, config); try { if (!persistAndExecuteSingleParagraph(conn, note, p, true)) { runAllStatusBroadcast(note, false); break; } } catch (Exception e) { LOG.error("Error in runAllParagraphs(). Error: " + e.toString()); runAllStatusBroadcast(note, false); } } runAllStatusBroadcast(note, false); } }); runAllThread.start(); }

Target:
private void runAllParagraphs(final NotebookSocket conn, HashSet<String> userAndRoles, Notebook notebook, final Message fromMessage) throws IOException { final String noteId = (String) fromMessage.get("noteId"); if (StringUtils.isBlank(noteId)) { return; } if (!hasParagraphRunnerPermission(conn, notebook, noteId, userAndRoles, fromMessage.principal, "run all paragraphs")) { return; } final Note note = notebook.getNote(noteId); final List<Map<String, Object>> paragraphs = gson.fromJson(String.valueOf(fromMessage.data.get("paragraphs")), new TypeToken<List<Map<String, Object>>>() {}.getType()); runAllStatusBroadcast(note, true); Thread runAllThread = new Thread(new Runnable() { @Override public void run() { for (Map<String, Object> raw : paragraphs) { String paragraphId = (String) raw.get("id"); if (paragraphId == null) { continue; } String text = (String) raw.get("paragraph"); String title = (String) raw.get("title"); Map<String, Object> params = (Map<String, Object>) raw.get("params"); Map<String, Object> config = (Map<String, Object>) raw.get("config"); Paragraph p = setParagraphUsingMessage(note, fromMessage, paragraphId, text, title, params, config); try { if (p.isEnabled() && !persistAndExecuteSingleParagraph(conn, note, p, true)) { runAllStatusBroadcast(note, false); break; } } catch (Exception e) { LOG.error("Error in runAllParagraphs()", e); runAllStatusBroadcast(note, false); } } runAllStatusBroadcast(note, false); } }); runAllThread.start(); }
Source:
private int calculateK(IntervalDouble delta, IntervalDouble epsilon, IntervalDouble beta) throws IntervalArithmeticException { IntervalDouble gamma = calculateGamma(epsilon, beta); int k = 1; IntervalDouble delta_k = arithmetic.createInterval(Double.MAX_VALUE); for (; !arithmetic.lessThan(delta_k, delta); ++k) { delta_k = calculateDelta(k, epsilon, beta, gamma); } return k; }

Target:
private int calculateK(IntervalDouble delta, IntervalDouble epsilon, IntervalDouble beta) throws IntervalArithmeticException { IntervalDouble gamma = calculateGamma(epsilon, beta); final int CACHE_SIZE = 1000; @SuppressWarnings({ "serial" }) LinkedHashMap<Integer, IntervalDouble> aCache = new LinkedHashMap<Integer, IntervalDouble>(CACHE_SIZE) { @Override protected boolean removeEldestEntry(Map.Entry<Integer, IntervalDouble> eldest) { return size() > CACHE_SIZE; } }; @SuppressWarnings({ "serial" }) LinkedHashMap<Integer, IntervalDouble> cCache = new LinkedHashMap<Integer, IntervalDouble>(CACHE_SIZE) { @Override protected boolean removeEldestEntry(Map.Entry<Integer, IntervalDouble> eldest) { return size() > CACHE_SIZE; } }; int k = 1; IntervalDouble delta_k = arithmetic.createInterval(Double.MAX_VALUE); for (; !arithmetic.lessThan(delta_k, delta); ++k) { delta_k = calculateDelta(k, epsilon, beta, gamma, aCache, cCache); } return k; }
Source:
public Filter rewriteRequiredColumns(Map<String, String> columnRewrites) { if (columnRewrites.get(dimension) == null) { throw new IAE("Received a non-applicable rewrite: %s, filter's dimension: %s", columnRewrites, dimension); } return new InFilter( columnRewrites.get(dimension), values, longPredicateSupplier, floatPredicateSupplier, doublePredicateSupplier, extractionFn, filterTuning ); }

Target:
public Filter rewriteRequiredColumns(Map<String, String> columnRewrites) { String rewriteDimensionTo = columnRewrites.get(dimension); if (rewriteDimensionTo == null) { throw new IAE("Received a non-applicable rewrite: %s, filter's dimension: %s", columnRewrites, dimension); } return new InFilter( rewriteDimensionTo, values, longPredicateSupplier, floatPredicateSupplier, doublePredicateSupplier, extractionFn, filterTuning ); }
Source:
public void testAssignVariable() throws MultipleDefinitionException, MultipleAssignmentException, VariableNotDefinedException { Scope s = new Scope(); try { s.assignVariable(getIdentifier(), getTypeExpression()); fail("assigned to a variable that doesn't exist"); } catch (VariableNotDefinedException vnde) { } s.defineVariable(getIdentifier(), getTypeExpression()); try { s.assignVariable(getIdentifier(), getTypeExpression()); } catch (MultipleAssignmentException mae) { fail("MultipleAssignmentException thrown, but variable only assigned once"); } try { s.assignVariable(getIdentifier(), getTypeExpression()); fail("multiple assignment to a variable was allowed"); } catch (MultipleAssignmentException mae) { } }

Target:
public void testAssignVariable() throws MultipleDefinitionException, VariableNotDefinedException, MultipleAssignmentException, VariableNotAssignedException { Scope s = new Scope(); s.defineVariable(getVariableIdentifier(), getTypeExpression()); s.assignVariable(getVariableIdentifier(), getValueExpression()); assertEquals(s.getVariableValue(getVariableIdentifier()), getValueExpression().evaluate()); }
Source:
private void handlePotentialTimeout(Invocation invocation) { Object identifier = invocation.getIdentifier(); Invocation activeAsyncInvocation = activeAsyncInvocations.get(identifier); if (activeAsyncInvocation.equals(invocation)) { Invocation activeInvocation = activeIdentifiers.get(identifier); if (activeInvocation != null) { invocation.getInvocationHandler().handleTimeout(invocation.getMethod(), activeInvocation); } } }

Target:
private void handlePotentialTimeout(Invocation invocation) { Object identifier = invocation.getIdentifier(); Invocation activeAsyncInvocation = activeAsyncInvocations.get(identifier); if (activeAsyncInvocation == invocation) { Invocation activeInvocation = activeIdentifiers.get(identifier); if (activeInvocation != null) { invocation.getInvocationHandler().handleTimeout(invocation.getMethod(), activeInvocation); } } }
Source:
protected void ExecuteVdsBrokerCommand() { boolean filteringLUNsEnabled = getParameters().getcompatibility_version().compareTo(Version.v3_1) < 0; XmlRpcStruct options = new XmlRpcStruct(); options.add(VdsProperties.includePartitioned, Boolean.toString(filteringLUNsEnabled)); int storageType = (int) getParameters().getStorageType().getValue(); _result = getBroker().getDeviceList(storageType, options); ProceedProxyReturnValue(); setReturnValue(ParseLUNList(_result.lunList)); }

Target:
protected void ExecuteVdsBrokerCommand() { boolean filteringLUNsEnabled = Config.<Boolean> GetValue(ConfigValues.FilteringLUNsEnabled, getParameters().getcompatibility_version().getValue()); XmlRpcStruct options = new XmlRpcStruct(); options.add(VdsProperties.includePartitioned, Boolean.toString(filteringLUNsEnabled)); int storageType = (int) getParameters().getStorageType().getValue(); _result = getBroker().getDeviceList(storageType, options); ProceedProxyReturnValue(); setReturnValue(ParseLUNList(_result.lunList)); }
Source:
public void fluentInterface() { ModuleDeclaration moduleDeclaration = new CompilationUnit() .addModule("org.javacord.api") .addSingleMemberAnnotation(Generated.class, "generator") .addSingleMemberAnnotation(SuppressWarnings.class, "\"module\"") .addDirective("requires transitive java.desktop;") .addDirective("exports org.javacord.api.entity.channel;") .addDirective("exports org.javacord.api.entity.channel.internal to org.javacord.core;") .addDirective("uses org.javacord.api.util.internal.DelegateFactoryDelegate;"); assertEqualsNoEol("@Generated(generator) @SuppressWarnings(\"module\") \n" + "module org.javacord.api {\n" + " requires transitive java.desktop;\n" + " exports org.javacord.api.entity.channel;\n" + " exports org.javacord.api.entity.channel.internal to org.javacord.core;\n" + " uses org.javacord.api.util.internal.DelegateFactoryDelegate;\n" + "}\n", moduleDeclaration.toString()); }

Target:
public void fluentInterface() { ModuleDeclaration moduleDeclaration = new CompilationUnit() .addModule("com.laamella.base") .addSingleMemberAnnotation(SuppressWarnings.class, "\"module\"") .addDirective("requires transitive java.desktop;") .addDirective("exports com.laamella.base.entity.channel;") .addDirective("exports com.laamella.base.entity.channel.internal to com.laamella.core;") .addDirective("uses com.laamella.base.util.internal.FactoryDelegate;"); moduleDeclaration.getModuleStmts() .addLast(new ModuleExportsStmt() .setName("foo.bar") .addModuleName("other.foo") .addModuleName("other.bar") ); moduleDeclaration .addDirective(new ModuleExportsStmt() .setName("foo.bar.x") .addModuleName("other.foo") .addModuleName("other.bar") ); assertEqualsNoEol("@SuppressWarnings(\"module\")\n" + "module com.laamella.base {\n" + " requires transitive java.desktop;\n" + " exports com.laamella.base.entity.channel;\n" + " exports com.laamella.base.entity.channel.internal to com.laamella.core;\n" + " uses com.laamella.base.util.internal.FactoryDelegate;\n" + " exports foo.bar to other.foo, other.bar;\n" + " exports foo.bar.x to other.foo, other.bar;\n" + "}\n", moduleDeclaration.toString()); }
Source:
private void testGracePeriodAccessControlForStudents() { FeedbackSessionAttributes fs = typicalBundle.feedbackSessions.get("gracePeriodSession"); fs.setEndTime(TimeHelper.convertLocalDateTimeToInstant( TimeHelperExtension.now(), TimeHelper.convertToZoneId(fs.getTimeZone()))); typicalBundle.feedbackSessions.put("gracePeriodSession", fs); assertFalse(fs.isOpened()); assertTrue(fs.isInGracePeriod()); assertFalse(fs.isClosed()); FeedbackResponseAttributes fr = typicalBundle.feedbackResponses.get("response1GracePeriodFeedback"); String[] submissionParams = new String[] { Const.ParamsNames.COURSE_ID, fs.getCourseId(), Const.ParamsNames.FEEDBACK_SESSION_NAME, fs.getFeedbackSessionName(), Const.ParamsNames.FEEDBACK_QUESTION_ID + "-1", fr.feedbackQuestionId, Const.ParamsNames.FEEDBACK_RESPONSE_RECIPIENT + "-1-0", fr.recipient, Const.ParamsNames.FEEDBACK_QUESTION_TYPE + "-1", fr.feedbackQuestionType.toString(), Const.ParamsNames.FEEDBACK_RESPONSE_TEXT + "-1-0", fr.getResponseDetails().getAnswerString() }; verifyOnlyStudentsOfTheSameCourseCanAccess(submissionParams); }

Target:
private void testGracePeriodAccessControlForStudents() { FeedbackSessionAttributes fs = typicalBundle.feedbackSessions.get("gracePeriodSession"); fs.setEndTime(Instant.now()); typicalBundle.feedbackSessions.put("gracePeriodSession", fs); assertFalse(fs.isOpened()); assertTrue(fs.isInGracePeriod()); assertFalse(fs.isClosed()); FeedbackResponseAttributes fr = typicalBundle.feedbackResponses.get("response1GracePeriodFeedback"); String[] submissionParams = new String[] { Const.ParamsNames.COURSE_ID, fs.getCourseId(), Const.ParamsNames.FEEDBACK_SESSION_NAME, fs.getFeedbackSessionName(), Const.ParamsNames.FEEDBACK_QUESTION_ID + "-1", fr.feedbackQuestionId, Const.ParamsNames.FEEDBACK_RESPONSE_RECIPIENT + "-1-0", fr.recipient, Const.ParamsNames.FEEDBACK_QUESTION_TYPE + "-1", fr.feedbackQuestionType.toString(), Const.ParamsNames.FEEDBACK_RESPONSE_TEXT + "-1-0", fr.getResponseDetails().getAnswerString() }; verifyOnlyStudentsOfTheSameCourseCanAccess(submissionParams); }
Source:
protected void channelRead0(ChannelHandlerContext ctx, Message msg) throws Exception { seenMessages.incrementAndGet(); byte[] payload = msg.asBytes(); if (encryptionConfig != null) { try { payload = encrypt(payload); } catch (Exception e) { log.error("Fail to encrypt message: ", e); } } boolean sawKtTag = false; for (String tag : msg.getTags()) { if (tag.startsWith("kt:")) { sawKtTag = true; sendOrReportFailure(tag.substring(3), payload); } } if (!sawKtTag) { sendOrReportFailure(defaultTopic, payload); } if (propagate) { msg.retain(); ctx.fireChannelRead(msg); } }

Target:
protected void channelRead0(ChannelHandlerContext ctx, Message msg) throws Exception { seenMessages.incrementAndGet(); byte[] payload = msg.asBytes(); if (encryptionConfig != null) { try { payload = encrypt(payload); } catch (Exception e) { log.error("Fail to encrypt message: ", e.getMessage()); } } boolean sawKtTag = false; for (String tag : msg.getTags()) { if (tag.startsWith("kt:")) { sawKtTag = true; sendOrReportFailure(tag.substring(3), payload); } } if (!sawKtTag) { sendOrReportFailure(defaultTopic, payload); } if (propagate) { msg.retain(); ctx.fireChannelRead(msg); } }
Source:
public ITmfStateValue popAttribute(long t, int attributeQuark) throws TimeRangeException, StateValueTypeException { ITmfStateValue previousSV = transState.getOngoingStateValue(attributeQuark); if (previousSV.isNull()) { return null; } if (previousSV.getType() != Type.INTEGER) { throw new StateValueTypeException(getSSID() + " Quark:" + attributeQuark + ", Type:" + previousSV.getType() + ", Expected:" + Type.INTEGER); } int stackDepth = previousSV.unboxInt(); if (stackDepth <= 0) { throw new StateValueTypeException(getSSID() + " Quark:" + attributeQuark + ", Stack depth:" + stackDepth); } int subAttributeQuark = INVALID_ATTRIBUTE; try { subAttributeQuark = getQuarkRelative(attributeQuark, String.valueOf(stackDepth)); } catch (AttributeNotFoundException e) { String message = " Stack attribute missing sub-attribute for depth:" + stackDepth; throw new IllegalStateException(getSSID() + " Quark:" + attributeQuark + message); } ITmfStateValue poppedValue = queryOngoingState(subAttributeQuark); ITmfStateValue nextSV; if (--stackDepth == 0) { nextSV = TmfStateValue.nullValue(); } else { nextSV = TmfStateValue.newValueInt(stackDepth); } modifyAttribute(t, nextSV, attributeQuark); removeAttribute(t, subAttributeQuark); return poppedValue; }

Target:
public ITmfStateValue popAttribute(long t, int attributeQuark) throws TimeRangeException, StateValueTypeException { ITmfStateValue previousSV = transState.getOngoingStateValue(attributeQuark); if (previousSV.isNull()) { return null; } if (previousSV.getType() != Type.INTEGER) { throw new StateValueTypeException(getSSID() + " Quark:" + attributeQuark + ", Type:" + previousSV.getType() + ", Expected:" + Type.INTEGER); } int stackDepth = previousSV.unboxInt(); if (stackDepth <= 0) { throw new StateValueTypeException(getSSID() + " Quark:" + attributeQuark + ", Stack depth:" + stackDepth); } int subAttributeQuark; try { subAttributeQuark = getQuarkRelative(attributeQuark, String.valueOf(stackDepth)); } catch (AttributeNotFoundException e) { String message = " Stack attribute missing sub-attribute for depth:" + stackDepth; throw new IllegalStateException(getSSID() + " Quark:" + attributeQuark + message); } ITmfStateValue poppedValue = queryOngoingState(subAttributeQuark); ITmfStateValue nextSV; if (--stackDepth == 0) { nextSV = TmfStateValue.nullValue(); } else { nextSV = TmfStateValue.newValueInt(stackDepth); } modifyAttribute(t, nextSV, attributeQuark); removeAttribute(t, subAttributeQuark); return poppedValue; }
Source:
public void handleException(Exception cce, EventLoop el) { logger.error("Exception in the event loop on the attachment {}", el, this, cce); }

Target:
public void handleException(Exception cce, EventLoop el) { logger.error("Exception in the on the {}", el, this, cce); }
Source:
public static String toResolvedType(String type, Importer<?> importer) { requireNonNull(type); requireNonNull(importer); if (Types.isPrimitive(type)) { return type; } String typeToUse; String strippedType = stripGenerics(stripArray(type)); StringBuilder builder = new StringBuilder(); if (isJavaLang(type)) { typeToUse = toSimpleName(strippedType); } else { Import imprt = importer.getImport(type); typeToUse = imprt != null ? imprt.getSimpleName() : strippedType; } builder.append(typeToUse); if (Types.isGeneric(type)) { StringJoiner genericJoiner = new StringJoiner(","); for (String genericPart : splitGenerics(type)) { genericJoiner.add(toResolvedType(genericPart, importer)); } String genericParts = genericJoiner.toString(); genericParts = genericParts.replace("?extends", "? extends "); genericParts = genericParts.replace("?super", "? super "); builder.append("<").append(genericParts).append(">"); } return builder.append(getArraySuffix(type)).toString(); }

Target:
public static String toResolvedType(String type, Importer<?> importer) { requireNonNull(type); requireNonNull(importer); if (Types.isPrimitive(type)) { return type; } String typeToUse; String strippedType = stripGenerics(stripArray(type)); StringBuilder builder = new StringBuilder(); if (isJavaLang(type)) { typeToUse = toSimpleName(strippedType); } else { Import imprt = importer.getImport(type); typeToUse = imprt != null ? imprt.getSimpleName() : strippedType; } builder.append(typeToUse); if (Types.isGeneric(type)) { StringJoiner genericJoiner = new StringJoiner(","); for (String genericPart : splitGenerics(type)) { String resolved = toResolvedType(genericPart, importer); resolved = resolved.replace("?extends", "? extends "); resolved = resolved.replace("?super", "? super "); genericJoiner.add(resolved); } builder.append("<").append(genericJoiner.toString()).append(">"); } return builder.append(getArraySuffix(type)).toString(); }
Source:
public void tearDown() throws Exception { _engine.shutdown(); _engine.awaitTermination(200, TimeUnit.MILLISECONDS); _engine = null; _scheduler.shutdownNow(); _scheduler = null; _asyncExecutor.shutdownNow(); _asyncExecutor = null; _loggerFactory.reset(); _loggerFactory = null; }

Target:
public void tearDown() throws Exception { _engine.shutdown(); _engine.awaitTermination(60, TimeUnit.SECONDS); _engine = null; _scheduler.shutdownNow(); _scheduler = null; _asyncExecutor.shutdownNow(); _asyncExecutor = null; _loggerFactory.reset(); _loggerFactory = null; }
Source:
private void tryFlushQueue() { manager.sendBulk(logQueue); }

Target:
private void tryFlushQueue() { List<String> logEvents = new ArrayList<>(); logQueue.drainTo(logEvents); manager.sendBulk(logEvents); }
Source:
protected HttpClientConnection leaseConnection(Future<CPoolEntry> future, long timeout, TimeUnit tunit) throws InterruptedException, ExecutionException, ConnectionPoolTimeoutException { final Optional<ScheduledFuture<?>> warnFuture; if (warnTimeMs > 0 && warnTimeMs < timeout) { final Runnable warnCommand = () -> lastBlockedAt = Instant.now(); warnFuture = Optional.of(scheduler.schedule(warnCommand, warnTimeMs, TimeUnit.MILLISECONDS)); } else { warnFuture = Optional.empty(); } final Instant start = Instant.now(); final HttpClientConnection result = super.leaseConnection(future, timeout, tunit); final Duration time = Duration.between(start, Instant.now()); if (future.isDone()) { knownRoutes.add(future.get().getRoute()); } warnFuture.ifPresent(f -> f.cancel(false)); Throwable t = null; if (LOG.isTraceEnabled()) { t = new Throwable(); t.fillInStackTrace(); allocationSites.put(result, t); } if (time.toMillis() > warnTimeMs) { LOG.warn("Checkout from pool \"{}\" took {}", clientName, time, t); } return result; }

Target:
protected HttpClientConnection leaseConnection(Future<CPoolEntry> future, long timeout, TimeUnit tunit) throws InterruptedException, ExecutionException, ConnectionPoolTimeoutException { final Optional<ScheduledFuture<?>> warnFuture; if (warnTimeMs > 0 && warnTimeMs < timeout) { final Runnable warnCommand = () -> lastBlockedAt = Instant.now(); warnFuture = Optional.of(scheduler.schedule(warnCommand, warnTimeMs, TimeUnit.MILLISECONDS)); } else { warnFuture = Optional.empty(); } final Instant start = Instant.now(); final HttpClientConnection result = super.leaseConnection(future, timeout, tunit); final Duration time = Duration.between(start, Instant.now()); if (future.isDone()) { knownRoutes.add(future.get().getRoute()); } warnFuture.ifPresent(f -> f.cancel(false)); Throwable t = null; if (LOG.isTraceEnabled()) { t = new Throwable(); t.fillInStackTrace(); allocationSites.put(result, t); } if (warnTimeMs > 0 && time.toMillis() > warnTimeMs) { LOG.warn("Checkout from pool \"{}\" took {}", clientName, time, t); } return result; }