auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public void test_isLeapYear_specific() { assertEquals(InternationalFixedChronology.INSTANCE.isLeapYear(400), true); assertEquals(InternationalFixedChronology.INSTANCE.isLeapYear(100), false); <START> assertEquals(InternationalFixedChronology.INSTANCE.isLeapYear(99), false); <END> assertEquals(InternationalFixedChronology.INSTANCE.isLeapYear(7), false); assertEquals(InternationalFixedChronology.INSTANCE.isLeapYear(6), false); assertEquals(InternationalFixedChronology.INSTANCE.isLeapYear(5), false); assertEquals(InternationalFixedChronology.INSTANCE.isLeapYear(4), true); assertEquals(InternationalFixedChronology.INSTANCE.isLeapYear(3), false); assertEquals(InternationalFixedChronology.INSTANCE.isLeapYear(2), false); assertEquals(InternationalFixedChronology.INSTANCE.isLeapYear(1), false); }</code><technical_language>99 is anomalous now, a special case (unlike in Pax)</technical_language>

Target:
public void test_isLeapYear_specific() { assertTrue(InternationalFixedChronology.INSTANCE.isLeapYear(400)); assertFalse(InternationalFixedChronology.INSTANCE.isLeapYear(100)); assertTrue(InternationalFixedChronology.INSTANCE.isLeapYear(4)); assertFalse(InternationalFixedChronology.INSTANCE.isLeapYear(3)); assertFalse(InternationalFixedChronology.INSTANCE.isLeapYear(2)); assertFalse(InternationalFixedChronology.INSTANCE.isLeapYear(1)); }
Source:
<code>public void getReportAsExcel(long id, EnumSet<ReportInclusion> includes, Integer pageSize, Integer page, OutputStream outputStream) throws SmartsheetException { this.checkParameters(pageSize, page); String path = "/reports"; HashMap<String, String> parameters = new HashMap<String, String>(); parameters.put("include", QueryUtil.generateCommaSeparatedList(includes)); <START> if (pageSize != null) { <END> parameters.put("pageSize", pageSize.toString()); } if (page != null) { parameters.put("page", page.toString()); } path += QueryUtil.generateUrl(null, parameters); getResourceAsFile(path, "application/vnd.ms-excel",outputStream); }</code><technical_language>need for null check, pass page & pageSize calling toString() them</technical_language>

Target:
public void getReportAsExcel(long id, EnumSet<ReportInclusion> includes, Integer pageSize, Integer page, OutputStream outputStream) throws SmartsheetException { String path = "/reports"; HashMap<String, String> parameters = new HashMap<String, String>(); parameters.put("include", QueryUtil.generateCommaSeparatedList(includes)); parameters.put("pageSize", pageSize.toString()); parameters.put("page", page.toString()); path += QueryUtil.generateUrl(null, parameters); getResourceAsFile(path, "application/vnd.ms-excel",outputStream); }
Source:
<code>private boolean validateSubAccountNumber(String chartCode, String accountNumber, String subAccountNumber) { if (StringUtils.isBlank(subAccountNumber)) { <START> return false; <END> } SubAccount subAccount = subAccountService.getByPrimaryId(chartCode, accountNumber, subAccountNumber); if (ObjectUtils.isNull(subAccount)) { String errorMessage = configurationService.getPropertyValueAsString(CuFPKeyConstants.ERROR_SUB_ACCOUNT_NOT_FOUND); LOG.error(String.format(errorMessage, chartCode, accountNumber, subAccountNumber)); return false; } if (!subAccount.isActive()) { String errorMessage = configurationService.getPropertyValueAsString(CuFPKeyConstants.ERROR_SUB_ACCOUNT_INACTIVE); LOG.error(String.format(errorMessage, chartCode, accountNumber, subAccountNumber)); return false; } return true; }</code><technical_language>I empty account is valid, blank. This is true for object, project, org ref ID</technical_language>

Target:
private boolean validateSubAccountNumber(String chartCode, String accountNumber, String subAccountNumber) { if (StringUtils.isBlank(subAccountNumber)) { return true; } SubAccount subAccount = subAccountService.getByPrimaryId(chartCode, accountNumber, subAccountNumber); if (ObjectUtils.isNull(subAccount)) { String errorMessage = configurationService.getPropertyValueAsString(CuFPKeyConstants.ERROR_SUB_ACCOUNT_NOT_FOUND); LOG.error(String.format(errorMessage, chartCode, accountNumber, subAccountNumber)); return false; } if (!subAccount.isActive()) { String errorMessage = configurationService.getPropertyValueAsString(CuFPKeyConstants.ERROR_SUB_ACCOUNT_INACTIVE); LOG.error(String.format(errorMessage, chartCode, accountNumber, subAccountNumber)); return false; } return true; }
Source:
<code>public void rootTestGetVariantsByVariantCoreString() throws URISyntaxException { String url = "/v2/variants/" + CHROMOSOME +":71822:C:G?species=mmusculus&assembly=grcm38"; List<VariantWithSamplesAndAnnotation> variantWithSamplesAndAnnotations = WSTestHelpers .testRestTemplateHelper(url,restTemplate); <START> assertTrue(variantWithSamplesAndAnnotations.size() == 1); <END> assertTrue(variantWithSamplesAndAnnotations.get(0).getSourceEntries().size() == 0); assertNull(variantWithSamplesAndAnnotations.get(0).getAnnotation()); assertTrue(variantWithSamplesAndAnnotations.get(0).getIds().size() > 0); }</code><technical_language>suggestion assertTrue(1, variantWithSamplesAndAnnotations.size());</technical_language>

Target:
public void rootTestGetVariantsByVariantCoreString() throws URISyntaxException { String url = "/v2/variants/" + CHROMOSOME + ":71822:C:G?species=mmusculus&assembly=grcm38"; List<VariantWithSamplesAndAnnotation> variantWithSamplesAndAnnotations = WSTestHelpers .testRestTemplateHelper(url, restTemplate); assertEquals(1, variantWithSamplesAndAnnotations.size()); assertTrue(variantWithSamplesAndAnnotations.get(0).getSourceEntries().size() == 0); assertNull(variantWithSamplesAndAnnotations.get(0).getAnnotation()); assertTrue(variantWithSamplesAndAnnotations.get(0).getIds().size() > 0); }
Source:
<code>Optional<AllureExecutable> provide(AllureGlobalConfig globalConfig, String executableName) { return bambooExecutablesManager.getExecutableByName(executableName) .map(allureHomeDir -> { <START> final Path cmdPath = Paths.get(allureHomeDir, "bin", "allure"); <END> if (!cmdPath.toFile().exists() && globalConfig.isDownloadEnabled()) { final Matcher nameMatcher = EXEC_NAME_PATTERN.matcher(executableName); allureDownloader.downloadAndExtractAllureTo(allureHomeDir, nameMatcher.matches() ? nameMatcher.group(1) : DEFAULT_VERSION); } return (cmdPath.toFile().exists()) ? new AllureExecutable(cmdPath) : null; }); }</code><technical_language>I guess run allure.bat Windows</technical_language>

Target:
Optional<AllureExecutable> provide(AllureGlobalConfig globalConfig, String executableName) { return bambooExecutablesManager.getExecutableByName(executableName) .map(allureHomeDir -> { final Path cmdPath = Paths.get(allureHomeDir, "bin", getAllureExecutableName()); if (!cmdLine.hasCommand(cmdPath.toString()) && globalConfig.isDownloadEnabled()) { final Matcher nameMatcher = EXEC_NAME_PATTERN.matcher(executableName); allureDownloader.downloadAndExtractAllureTo(allureHomeDir, nameMatcher.matches() ? nameMatcher.group(1) : DEFAULT_VERSION); } return (cmdLine.hasCommand(cmdPath.toString())) ? new AllureExecutable(cmdPath, cmdLine) : null; }); }
Source:
<code>public void setParams(Map<?, ?> map) { if (map != null) { if (map.size() == 0) { throw new IllegalArgumentException( "no elements within map for categorical distribution"); } double sum = 0.0; for (Map.Entry<?, ?> entry : map.entrySet()) { Number probNum = (Number) entry.getValue(); double prob = probNum.doubleValue(); if (prob < 0) { throw new IllegalArgumentException("Probability " + prob + " for key " + entry.getKey().toString() + " is negative"); } sum += prob; } if (sum < 1e-9) { throw new IllegalArgumentException( "probabilities sum to approximately zero"); } this.map = new HashMap<Object, Double>(); this.logMap = new HashMap<Object, Double>(); this.objects = new Object[map.size()]; this.cdfObjects = new double[map.size()]; int supportSize = 0; int count = 0; double cdf = 0.0; for (Map.Entry<?, ?> entry : map.entrySet()) { Object key = entry.getKey(); Number num = (Number) entry.getValue(); double value = num.doubleValue(); this.objects[count] = key; double prob = value / sum; cdf += prob; this.cdfObjects[count] = cdf; this.map.put(key, prob); this.logMap.put(key, Math.log(prob)); count += 1; if (!Util.closeToZero(prob)) supportSize++; } int curSupportIndex = 0; <START> this.finiteSupport = new Object[supportSize]; <END> for (Map.Entry<?, ?> entry : map.entrySet()) { Object key = entry.getKey(); Number num = (Number) entry.getValue(); double value = num.doubleValue(); double prob = value / sum; if (!Util.closeToZero(prob)) { this.finiteSupport[curSupportIndex] = key; curSupportIndex++; } } this.hasMap = true; } }</code><technical_language>strange, finiteSupport objects. finiteSupport = objects;</technical_language>

Target:
public void setParams(Map<?, ?> map) { if (map != null) { if (map.size() == 0) { throw new IllegalArgumentException( "no elements within map for categorical distribution"); } double sum = 0.0; for (Map.Entry<?, ?> entry : map.entrySet()) { Number probNum = (Number) entry.getValue(); double prob = probNum.doubleValue(); if (prob < 0) { throw new IllegalArgumentException("Probability " + prob + " for key " + entry.getKey().toString() + " is negative"); } sum += prob; } if (sum < 1e-9) { throw new IllegalArgumentException( "probabilities sum to approximately zero"); } this.map = new HashMap<Object, Double>(); this.logMap = new HashMap<Object, Double>(); this.objects = new Object[map.size()]; this.cdfObjects = new double[map.size()]; int count = 0; double cdf = 0.0; for (Map.Entry<?, ?> entry : map.entrySet()) { Object key = entry.getKey(); Number num = (Number) entry.getValue(); double value = num.doubleValue(); this.objects[count] = key; double prob = value / sum; cdf += prob; this.cdfObjects[count] = cdf; this.map.put(key, prob); this.logMap.put(key, Math.log(prob)); count += 1; } this.hasMap = true; this.finiteSupport = null; } }
Source:
<code><START> public ConnectionMetadata get(String connectionId) { <END> return connections.get(connectionId); }</code><technical_language>This is wrong. Unsynchronized access a map more "stale inconsistent" data. null pointer exceptions other issues. access this synchronization</technical_language>

Target:
public synchronized ConnectionMetadata get(String connectionId) { return connections.get(connectionId); }
Source:
<code>public String generatePassword(int policyLength) { int length = Math.max(32, policyLength); SecureTokenGenerator generator = new SecureTokenGenerator(length); <START> return generator.nextToken() + "Br4%"; <END> }</code><technical_language>increase entropy, choose a random capital letter, insert a random index in string, repeat for lowercase, number, symbol</technical_language>

Target:
public String generatePassword(int policyLength) { return PasswordGenerator.INSTANCE.nextPassword(Math.max(32, policyLength)); }
Source:
<code>private void processQueue() { if (currentHolder != null || queue.isEmpty()) { return; } LockRequest head = queue.poll(); currentHolder = head.requestId; <START> head.result.complete(null); <END> }</code><technical_language>Check if complete returned true here. If not, RuntimeException retry</technical_language>

Target:
private void processQueue() { while (!queue.isEmpty() && currentHolder == null) { LockRequest head = queue.poll(); if (!head.releaseImmediately) { currentHolder = head.requestId; } completeRequest(head); } }
Source:
<code>public Worker createWorker() { final EventLoop eventLoop = eventLoopGroup.next(); return new Worker() { <START> private final SubscriptionList subs = new SubscriptionList(); <END> @Override public Subscription schedule(final Action0 action) { if (isUnsubscribed()) { return Subscriptions.unsubscribed(); } if (eventLoop.inEventLoop()) { action.call(); return Subscriptions.empty(); } else { final Future<?> result = eventLoop.submit(new Runnable() { @Override public void run() { action.call(); } }); Subscription toReturn = fromFuture(result); subs.add(toReturn); return toReturn; } } @Override public Subscription schedule(final Action0 action, long delayTime, TimeUnit unit) { if (delayTime <= 0) { return schedule(action); } if (isUnsubscribed()) { return Subscriptions.unsubscribed(); } final Future<?> result = eventLoop.schedule(new Runnable() { @Override public void run() { action.call(); } }, delayTime, unit); Subscription toReturn = fromFuture(result); subs.add(toReturn); return toReturn; } @Override public void unsubscribe() { subs.unsubscribe(); } @Override public boolean isUnsubscribed() { return subs.isUnsubscribed(); } private Subscription fromFuture(final Future<?> result) { return Subscriptions.create(new Action0() { @Override public void call() { result.cancel(false); } }); } }; }</code><technical_language>of SubscriptionList is problematic delayed scheduling due O(n) removal. A more considerate container a regular CompositeSubscription. If this scheduler is dominated non-delayed tasks, SubscriptionList CompositeSubscription. Non-delayed tasks added list delayed added composite</technical_language>

Target:
public Worker createWorker() { final EventLoop eventLoop = eventLoopGroup.next(); return new EventloopWorker(eventLoop); }
Source:
<code>public Statement apply(final Statement base, final FrameworkMethod method, final Object target) { return new Statement() { @Override public void evaluate() throws Throwable { final List<Throwable> errors = new ArrayList<Throwable>(); adaptor.fireCustomLifecycle( new BeforeRules(target, new TestClass(method.getDeclaringClass()), base, method.getMethod(), LifecycleMethodExecutor.NO_OP)); adaptor.before(target, method.getMethod(), LifecycleMethodExecutor.NO_OP); try { TestResult result = adaptor.test(new TestMethodExecutor() { public void invoke(Object... parameters) throws Throwable { try { base.evaluate(); } catch (Throwable e) { errors.add(e); } } public Method getMethod() { return method.getMethod(); } public Object getInstance() { return target; } }); if (result.getStatus() != Status.PASSED) { <START> throw new RuntimeException("problem: " + result); <END> } } finally { adaptor.after(target, method.getMethod(), LifecycleMethodExecutor.NO_OP); try { adaptor.fireCustomLifecycle( new AfterRules(target, method.getMethod(), LifecycleMethodExecutor.NO_OP)); } catch (Throwable e) { errors.add(e); } } org.junit.runners.model.MultipleFailureException.assertEmpty(errors); } }; }</code><technical_language>a bit more meaningful exception message here</technical_language>

Target:
public Statement apply(final Statement base, final FrameworkMethod method, final Object target) { return new Statement() { @Override public void evaluate() throws Throwable { final List<Throwable> errors = new ArrayList<Throwable>(); adaptor.fireCustomLifecycle( new BeforeRules(target, new TestClass(method.getDeclaringClass()), base, method.getMethod(), LifecycleMethodExecutor.NO_OP)); adaptor.before(target, method.getMethod(), LifecycleMethodExecutor.NO_OP); try { adaptor.test(new TestMethodExecutor() { public void invoke(Object... parameters) throws Throwable { try { base.evaluate(); } catch (Throwable e) { errors.add(e); } } public Method getMethod() { return method.getMethod(); } public Object getInstance() { return target; } }); } finally { adaptor.after(target, method.getMethod(), LifecycleMethodExecutor.NO_OP); try { adaptor.fireCustomLifecycle( new AfterRules(target, method.getMethod(), LifecycleMethodExecutor.NO_OP)); } catch (Throwable e) { errors.add(e); } } org.junit.runners.model.MultipleFailureException.assertEmpty(errors); } }; }
Source:
<code>public CategorizedTimeGroup calc(Config cur, Option<Config> prev) { final ItemKey FPU_KEY = new ItemKey("instrument:fpu"); final double FPU_OVERHEAD = 60.0; final ItemKey FILTER_KEY = new ItemKey("instrument:filter"); final double FILTER_OVERHEAD = 20.0; final ItemKey DISPERSER_KEY = new ItemKey("instrument:disperser"); <START> final double DISPERSER_OVERHEAD = 90.0; <END> final Collection<CategorizedTime> times = new ArrayList<>(); double exposureTime = ExposureCalculator.instance.exposureTimeSec(cur); if (_useNS && isNodAndShuffleableObsType(cur)) { int nOverhead = (_useElectronicOffsetting ? 11 : 25); int numSteps = getPosList().size(); exposureTime = (exposureTime * numSteps * _numNSCycles) + (_numNSCycles * nOverhead); } times.add(CategorizedTime.fromSeconds(Category.EXPOSURE, exposureTime)); if (PlannedTime.isUpdated(cur, prev, FPU_KEY)) { times.add(CategorizedTime.fromSeconds(Category.CONFIG_CHANGE, FPU_OVERHEAD, "FPU")); } if (PlannedTime.isUpdated(cur, prev, FILTER_KEY)) { times.add(CategorizedTime.fromSeconds(Category.CONFIG_CHANGE, FILTER_OVERHEAD, "Filter")); } if (PlannedTime.isUpdated(cur, prev, DISPERSER_KEY)) { times.add(CategorizedTime.fromSeconds(Category.CONFIG_CHANGE, DISPERSER_OVERHEAD, "Disperser")); } double readoutTime = GmosReadoutTime.getReadoutOverhead(cur, getCustomROIs()); times.add(CategorizedTime.fromSeconds(Category.READOUT, readoutTime)); times.add(DHS_WRITE); return CommonStepCalculator.instance.calc(cur, prev).addAll(times); }</code><technical_language>define respective definitions do in Flamingos2. of whacky GMOS enums split north south versions, I this means in interface definitions GmosCommonType.FPUnit etc</technical_language>

Target:
public CategorizedTimeGroup calc(Config cur, Option<Config> prev) { final Collection<CategorizedTime> times = new ArrayList<>(); double exposureTime = ExposureCalculator.instance.exposureTimeSec(cur); if (_useNS && isNodAndShuffleableObsType(cur)) { int nOverhead = (_useElectronicOffsetting ? 11 : 25); int numSteps = getPosList().size(); exposureTime = (exposureTime * numSteps * _numNSCycles) + (_numNSCycles * nOverhead); } times.add(CategorizedTime.fromSeconds(Category.EXPOSURE, exposureTime)); if (PlannedTime.isUpdated(cur, prev, GmosCommonType.FPUnit.KEY)) { times.add(CategorizedTime.fromSeconds( Category.CONFIG_CHANGE, GmosCommonType.FPUnit.CHANGE_OVERHEAD, "FPU") ); } if (PlannedTime.isUpdated(cur, prev, GmosCommonType.Filter.KEY)) { times.add(CategorizedTime.fromSeconds( Category.CONFIG_CHANGE, GmosCommonType.Filter.CHANGE_OVERHEAD, "Filter") ); } if (PlannedTime.isUpdated(cur, prev, GmosCommonType.Disperser.KEY)) { times.add(CategorizedTime.fromSeconds( Category.CONFIG_CHANGE, GmosCommonType.Disperser.CHANGE_OVERHEAD, "Disperser") ); } double readoutTime = GmosReadoutTime.getReadoutOverhead(cur, getCustomROIs()); times.add(CategorizedTime.fromSeconds(Category.READOUT, readoutTime)); times.add(DHS_WRITE); return CommonStepCalculator.instance.calc(cur, prev).addAll(times); }
Source:
<code>public static byte[] createThumbnailFromUri(Context context, Uri imageUri, int maxWidth, String fileExtension, int orientation) { if (context == null || imageUri == null || maxWidth <= 0) return null; ByteArrayOutputStream stream = new ByteArrayOutputStream(); try { <START> boolean res = resizeImageAndWriteToStream(context, imageUri, fileExtension, maxWidth, orientation, 85, stream); <END> if (!res) { AppLog.w(AppLog.T.MEDIA, "Failed to compress the resized image. Use the full picture instead."); return null; } } catch (IOException e) { AppLog.e(AppLog.T.MEDIA, "Failed to create resized image. Use the full picture instead."); return null; } catch (OutOfMemoryError e) { AppLog.e(AppLog.T.MEDIA, "Can't resize the picture due to low memory. Use the full picture instead."); return null; } return stream.toByteArray(); }</code><technical_language>I in research sites compression 75. If case, 75 instead of 85 here</technical_language>

Target:
public static byte[] createThumbnailFromUri(Context context, Uri imageUri, int maxWidth, String fileExtension, int orientation) { if (context == null || imageUri == null || maxWidth <= 0) return null; ByteArrayOutputStream stream = new ByteArrayOutputStream(); try { boolean res = resizeImageAndWriteToStream(context, imageUri, fileExtension, maxWidth, orientation, 75, stream); if (!res) { AppLog.w(AppLog.T.MEDIA, "Failed to compress the resized image. Use the full picture instead."); return null; } } catch (IOException e) { AppLog.e(AppLog.T.MEDIA, "Failed to create resized image. Use the full picture instead."); return null; } catch (OutOfMemoryError e) { AppLog.e(AppLog.T.MEDIA, "Can't resize the picture due to low memory. Use the full picture instead."); return null; } return stream.toByteArray(); }
Source:
<code>private void outputIOPerformanceInfo( HashMap<String,Object> hashMapInstance, IOPerformanceCounter ioPerformance) { <START> HashMap<String,Object> IOPerformanceInfoHash = new HashMap<>(); <END> IOPerformanceInfoHash.put("bitrate", ioPerformance.getMessagesInBytesRate() * 8 / 1000); hashMapInstance.put("IOPerformance", IOPerformanceInfoHash); }</code><technical_language>new HashMap<String,Object>()</technical_language>

Target:
private void outputIOPerformanceInfo( HashMap<String,Object> hashMapInstance, IOPerformanceCounter ioPerformance) { HashMap<String,Object> IOPerformanceInfoHash = new HashMap<String,Object>(); IOPerformanceInfoHash.put("bitrate", ioPerformance.getMessagesInBytesRate() * 8 / 1000); hashMapInstance.put("IOPerformance", IOPerformanceInfoHash); }
Source:
<code><START> public boolean isAnyExceptionExpected() { <END> return matcherBuilder.expectsThrowable(); }</code><technical_language>this final</technical_language>

Target:
public final boolean isAnyExceptionExpected() { return matcherBuilder.expectsThrowable(); }
Source:
<code>public int getTotalResults() { <START> return 0; <END> }</code><technical_language>Needs correct implementation</technical_language>

Target:
public int getTotalResults() { return getMetaDataHandler().getAsInt(ConnectionsFeedXpath.TotalResults); }
Source:
<code><START> public BigtableOptions( <END> InetAddress clusterAdminHost, InetAddress adminHost, InetAddress host, int port, Credentials credential, String projectId, String zone, String cluster, boolean retriesEnabled, String callTimingReportPath, String callStatusReportPath, ScheduledExecutorService rpcRetryExecutorService, EventLoopGroup customEventLoopGroup) { Preconditions.checkArgument( !Strings.isNullOrEmpty(projectId), "ProjectId must not be empty or null."); Preconditions.checkArgument( !Strings.isNullOrEmpty(zone), "Zone must not be empty or null."); Preconditions.checkArgument( !Strings.isNullOrEmpty(cluster), "Cluster must not be empty or null."); this.adminHost = Preconditions.checkNotNull(adminHost); this.clusterAdminHost = clusterAdminHost; this.host = Preconditions.checkNotNull(host); this.port = port; this.credential = credential; this.projectId = projectId; this.retriesEnabled = retriesEnabled; this.callTimingReportPath = callTimingReportPath; this.callStatusReportPath = callStatusReportPath; this.zone = zone; this.cluster = cluster; this.rpcRetryExecutorService = rpcRetryExecutorService; this.customEventLoopGroup = customEventLoopGroup; LOG.info("Connection Configuration: project: %s, cluster: %s, host:port %s:%s, " + "admin host:port %s:%s, using transport %s.", getProjectId(), cluster, host, port, adminHost, 443, TransportOptions.AnviltopTransports.HTTP2_NETTY_TLS); if (clusterAdminHost != null) { LOG.info("Cluster API host: %s" , clusterAdminHost); } }</code><technical_language>Builder, constructor is private</technical_language>

Target:
private BigtableOptions( InetAddress clusterAdminHost, InetAddress adminHost, InetAddress host, int port, Credentials credential, String projectId, String zone, String cluster, boolean retriesEnabled, String callTimingReportPath, String callStatusReportPath, ScheduledExecutorService rpcRetryExecutorService, EventLoopGroup customEventLoopGroup) { Preconditions.checkArgument( !Strings.isNullOrEmpty(projectId), "ProjectId must not be empty or null."); Preconditions.checkArgument( !Strings.isNullOrEmpty(zone), "Zone must not be empty or null."); Preconditions.checkArgument( !Strings.isNullOrEmpty(cluster), "Cluster must not be empty or null."); this.adminHost = Preconditions.checkNotNull(adminHost); this.clusterAdminHost = clusterAdminHost; this.host = Preconditions.checkNotNull(host); this.port = port; this.credential = credential; this.projectId = projectId; this.retriesEnabled = retriesEnabled; this.callTimingReportPath = callTimingReportPath; this.callStatusReportPath = callStatusReportPath; this.zone = zone; this.cluster = cluster; this.rpcRetryExecutorService = rpcRetryExecutorService; this.customEventLoopGroup = customEventLoopGroup; LOG.debug("Connection Configuration: project: %s, cluster: %s, host:port %s:%s, " + "admin host:port %s:%s, using transport %s.", getProjectId(), cluster, host, port, adminHost, port, TransportOptions.AnviltopTransports.HTTP2_NETTY_TLS); if (clusterAdminHost != null) { LOG.debug("Cluster API host: %s" , clusterAdminHost); } }
Source:
<code>private void addLabelSpan(String itemText) { Span labelSpan = new Span(); labelSpan.addStyleName(Styles.LABEL); <START> labelSpan.addStyleName("label-info"); END> labelSpan.setText(itemText); add(labelSpan); }</code><technical_language>PatternflyConstants defines this</technical_language>

Target:
private void addLabelSpan(String itemText) { Span labelSpan = new Span(); labelSpan.addStyleName(Styles.LABEL); labelSpan.addStyleName(PatternflyConstants.PF_LABEL_INFO); labelSpan.setText(itemText); add(labelSpan); }
Source:
<code>public String getTableOrSubselect(Class<?> cls) { Subselect subselectAnnotation = getAnnotation(cls, Subselect.class); if (subselectAnnotation == null) { javax.persistence.Table tableAnnotation = getAnnotation(cls, javax.persistence.Table.class); return (tableAnnotation == null) ? getJsonAliasFor(cls) : tableAnnotation.name(); } else { <START> return "(" + subselectAnnotation.value() + ")"; <END> } }</code><technical_language>I do parenthetic work here. is part of query building. This function return name (minus parenthesis)</technical_language>

Target:
public String getTableOrSubselect(Class<?> cls) { if (isSubselect(cls)) { return getAnnotation(cls, Subselect.class).value(); } else { javax.persistence.Table tableAnnotation = getAnnotation(cls, javax.persistence.Table.class); return (tableAnnotation == null) ? getJsonAliasFor(cls) : tableAnnotation.name(); } }
Source:
<code>default <U extends T> CompletableFuture<T> toCompletableFuture() { <START> CompletableFuture<T> future = new CompletableFuture<>(); <END> onSuccess(future::complete); onFailure(future::completeExceptionally); return future; }</code><technical_language>Please local vars final applicable. I - strange emphasis immutable/functional nature of code. I hope Java get more concise val</technical_language>

Target:
default <U extends T> CompletableFuture<T> toCompletableFuture() { final CompletableFuture<T> future = new CompletableFuture<>(); onSuccess(future::complete); onFailure(future::completeExceptionally); return future; }
Source:
<code>public Node transform(Node node) { List<String> templates = getUriTemplates(((ResourceNode) node).getRelativeUri()); <START> injectImplicitUriParameters(((ResourceNode) node).getValue(), templates); <END> return node; }</code><technical_language>casting node</technical_language>

Target:
public Node transform(Node node) { ResourceNode resourceNode = (ResourceNode) node; List<String> templates = getUriTemplates(resourceNode.getRelativeUri()); injectImplicitUriParameters(resourceNode.getValue(), templates); return node; }
Source:
<code>private String getLooseConfigFileName(MavenProject project) { <START> String name = project.getBuild().getFinalName() + "." + project.getPackaging(); <END> if (stripVersion) { return stripVersionFromName(name, project.getVersion()) + ".xml"; } else { return name + ".xml"; } }</code><technical_language>This feels bug packaging type liberty-assembly war file named wrong</technical_language>

Target:
private String getLooseConfigFileName(MavenProject project) { String name = project.getBuild().getFinalName() + "." + project.getPackaging(); if (project.getPackaging().equals("liberty-assembly")) { name = project.getBuild().getFinalName() + ".war"; } if (stripVersion) { return stripVersionFromName(name, project.getVersion()) + ".xml"; } else { return name + ".xml"; } }
Source:
<code>public BackupClearPushStatusCommand() { <START> super(0); <END> }</code><technical_language>parameter needs 1 backup model node is level cache</technical_language>

Target:
public BackupClearPushStatusCommand() { super(1); }
Source:
<code>public Set<Type> getImportTypes() { <START> return Collections.emptySet(); <END> }</code><technical_language>I create a set types mapperReferences annotations, in GeneratedType#getImportTypes() need call constructor.getImportTypes(). This is OK</technical_language>

Target:
public Set<Type> getImportTypes() { Set<Type> types = new HashSet<Type>(); for ( MapperReference mapperReference : mapperReferences ) { types.addAll( mapperReference.getImportTypes() ); } for ( Annotation annotation : annotations ) { types.addAll( annotation.getImportTypes() ); } return types; }
Source:
<code>public String putBlob(final String containerName, final Blob blob) throws IOException { String blobKey = blob.getMetadata().getName(); Payload payload = blob.getPayload(); filesystemContainerNameValidator.validate(containerName); filesystemBlobKeyValidator.validate(blobKey); File outputFile = getFileForBlobKey(containerName, blobKey); try { Files.createParentDirs(outputFile); if (payload.getRawContent() instanceof File) Files.copy((File) payload.getRawContent(), outputFile); else if (payload.isRepeatable()) Files.copy(payload, outputFile); else { payload = Payloads.newPayload(ByteStreams.toByteArray(payload)); <START> Files.copy(payload, outputFile); <END> } Payloads.calculateMD5(payload); String eTag = base16().lowerCase().encode(payload.getContentMetadata().getContentMD5()); return eTag; } catch (IOException ex) { if (outputFile != null) { if (!outputFile.delete()) { logger.debug("Could not delete %s", outputFile); } } throw ex; } finally { payload.release(); } }</code><technical_language>else { if (!payload.isRepeatable()) { payload = Payloads.newPayload(ByteStreams.toByteArray(payload)); } Files.copy(payload, outputFile); } Avoids some duplication sacrifices some clarify</technical_language>

Target:
public String putBlob(final String containerName, final Blob blob) throws IOException { String blobKey = blob.getMetadata().getName(); Payload payload = blob.getPayload(); filesystemContainerNameValidator.validate(containerName); filesystemBlobKeyValidator.validate(blobKey); File outputFile = getFileForBlobKey(containerName, blobKey); try { Files.createParentDirs(outputFile); if (payload.getRawContent() instanceof File) Files.copy((File) payload.getRawContent(), outputFile); else { if (!payload.isRepeatable()) { payload = Payloads.newPayload(ByteStreams.toByteArray(payload)); } Files.copy(payload, outputFile); } Payloads.calculateMD5(payload); String eTag = base16().lowerCase().encode(payload.getContentMetadata().getContentMD5()); return eTag; } catch (IOException ex) { if (outputFile != null) { if (!outputFile.delete()) { logger.debug("Could not delete %s", outputFile); } } throw ex; } finally { payload.release(); } }
Source:
<code>private String asLocalRepo(String repoLocation) { StringBuffer b = new StringBuffer(repoLocation.length()); b.append(Utils.getPropertyFormat(PROP_FETCH_CACHE_LOCATION)).append('/'); for (int i = 0; i < repoLocation.length(); i++) { char c = repoLocation.charAt(i); <START> if (Character.isLetterOrDigit(c)) { <END> b.append(c); } else { b.append('_'); } } if (b.charAt(b.length() - 1) == '/') return b.substring(0, b.length() - 1); return b.toString(); }</code><technical_language>style nit: braces single line block</technical_language>

Target:
private String asLocalRepo(String repoLocation) { final StringBuffer b = new StringBuffer(repoLocation.length()); b.append(Utils.getPropertyFormat(PROP_FETCH_CACHE_LOCATION)) .append('/'); for (int i = 0; i < repoLocation.length(); i++) { final char c = repoLocation.charAt(i); if (Character.isLetterOrDigit(c)) { b.append(c); } else { b.append('_'); } } if (b.charAt(b.length() - 1) == '/') return b.substring(0, b.length() - 1); return b.toString(); }
Source:
<code>public void testTmpfs() throws Exception { <START> requireDockerApiVersionAtLeast("1.22", "PidsLimit"); <END> sut.pull(BUSYBOX_LATEST); final ImmutableMap<String, String> tmpfs = ImmutableMap.of("/tmp", "rw,noexec,nosuid,size=50m"); final ContainerConfig config = ContainerConfig.builder() .image(BUSYBOX_LATEST) .hostConfig(HostConfig.builder() .tmpfs(tmpfs) .build()) .build(); final ContainerCreation container = sut.createContainer(config, randomName()); final ContainerInfo info = sut.inspectContainer(container.id()); assertThat(info.hostConfig().tmpfs(), is(tmpfs)); }</code><technical_language>param is wrong</technical_language>

Target:
public void testTmpfs() throws Exception { requireDockerApiVersionAtLeast("1.22", "TmpFs"); sut.pull(BUSYBOX_LATEST); final ImmutableMap<String, String> tmpfs = ImmutableMap.of("/tmp", "rw,noexec,nosuid,size=50m"); final ContainerConfig config = ContainerConfig.builder() .image(BUSYBOX_LATEST) .hostConfig(HostConfig.builder() .tmpfs(tmpfs) .build()) .build(); final ContainerCreation container = sut.createContainer(config, randomName()); final ContainerInfo info = sut.inspectContainer(container.id()); assertThat(info.hostConfig().tmpfs(), is(tmpfs)); }
Source:
<code>Itr() { Deque<T> inputBuffer; Deque<T> outputBuffer; int innerQueueSize; Iterator<Deque<T>> queueIterator; fInputLock.lock(); try { inputBuffer = fInputBuffer; innerQueueSize = fInnerQueue.size(); queueIterator = fInnerQueue.descendingIterator(); } finally { fInputLock.unlock(); } <START> fOutputLock.lock(); <END> try { outputBuffer = fOutputBuffer; } finally { fOutputLock.unlock(); } Deque<Deque<T>> queues = new ArrayDeque<>(innerQueueSize + 2); queues.add(inputBuffer); boolean found = false; while (queueIterator.hasNext()) { Deque<T> queue = queueIterator.next(); queues.add(queue); if (queue == outputBuffer) { found = true; } } if (!found) { if (queues.size() <= 1 || !queues.getLast().isEmpty()) { queues.add(outputBuffer); } } fQueueIterator = checkNotNull(queues.iterator()); }</code><technical_language>This block if queue is empty</technical_language>

Target:
Itr() { Deque<T> inputBuffer; @Nullable Deque<T> outputBuffer = null; int innerQueueSize; Iterator<Deque<T>> queueIterator; fInputLock.lock(); try { inputBuffer = fInputBuffer; innerQueueSize = fInnerQueue.size(); queueIterator = fInnerQueue.descendingIterator(); } finally { fInputLock.unlock(); } try { if (fOutputLock.tryLock(1, TimeUnit.SECONDS)) { outputBuffer = fOutputBuffer; fOutputLock.unlock(); } } catch (InterruptedException e) { } Deque<Deque<T>> queues = new ArrayDeque<>(innerQueueSize + 2); queues.add(inputBuffer); boolean found = false; while (queueIterator.hasNext()) { Deque<T> queue = queueIterator.next(); queues.add(queue); if (queue == outputBuffer) { found = true; } } if (!found && outputBuffer != null) { if (queues.size() <= 1 || !queues.getLast().isEmpty()) { queues.add(outputBuffer); } } fQueueIterator = checkNotNull(queues.iterator()); }
Source:
<code>public int compareTo( Profile that ) { <START> int compare = profileFile.compareTo( that.profileFile ); <END> return compare == 0 ? Long.compare( profileCount, that.profileCount ) : compare; }</code><technical_language>want sort lexicographically result in profile1 profile10 profile2 profile3 etc.. If this is case, a test for that</technical_language>

Target:
public int compareTo( Profile that ) { int compare = pagedFile.compareTo( that.pagedFile ); return compare == 0 ? Long.compare( profileSequenceId, that.profileSequenceId ) : compare; }
Source:
<code>public void handleAction(ActionParameters params) throws ActionException { final int layerId = params.getRequiredParamInt(ActionConstants.PARAM_ID); final String srs = params.getRequiredParam(ActionConstants.PARAM_SRS); final int z = params.getRequiredParamInt(PARAM_Z); final int x = params.getRequiredParamInt(PARAM_X); final int y = params.getRequiredParamInt(PARAM_Y); <START> final OskariLayer layer = findLayer(layerId); <END> final WFSTileGrid grid = KNOWN_TILE_GRIDS.get(srs); validateTile(grid, z, x, y); validateScaleDenominator(layer, grid, z); final String cacheKey = getCacheKey(layerId, srs, z, x, y); final byte[] resp; try { resp = tileCache.get(cacheKey, __ -> createTile(layer, srs, grid, z, x, y)); } catch (ServiceRuntimeException e) { throw new ActionException(e.getMessage()); } params.getResponse().addHeader("Access-Control-Allow-Origin", "*"); params.getResponse().addHeader("Content-Encoding", "gzip"); ResponseHelper.writeResponse(params, 200, MVT_CONTENT_TYPE, resp); }</code><technical_language>Add a credentials check if user permission view layer</technical_language>

Target:
public void handleAction(ActionParameters params) throws ActionException { final int layerId = params.getRequiredParamInt(ActionConstants.PARAM_ID); final String srs = params.getRequiredParam(ActionConstants.PARAM_SRS); final int z = params.getRequiredParamInt(PARAM_Z); final int x = params.getRequiredParamInt(PARAM_X); final int y = params.getRequiredParamInt(PARAM_Y); final OskariLayer layer = findLayer(layerId, params.getUser()); final WFSTileGrid grid = KNOWN_TILE_GRIDS.get(srs); validateTile(grid, z, x, y); validateScaleDenominator(layer, grid, z); final String cacheKey = getCacheKey(layerId, srs, z, x, y); final byte[] resp; try { resp = tileCache.get(cacheKey, __ -> createTile(layer, srs, grid, z, x, y)); } catch (ServiceRuntimeException e) { throw new ActionException(e.getMessage()); } params.getResponse().addHeader("Access-Control-Allow-Origin", "*"); params.getResponse().addHeader("Content-Encoding", "gzip"); ResponseHelper.writeResponse(params, 200, MVT_CONTENT_TYPE, resp); }
Source:
<code>private void handleSimpleBlob(BlobData blobData, byte[] userMetadata, ByteBuffer encryptionKey) { totalSize = blobData.getSize(); chunkSize = totalSize; boolean rangeResolutionFailure = false; if (encryptionKey == null) { rangeResolutionFailure = resolveRange(totalSize); } else { } if (!rangeResolutionFailure) { chunkIdIterator = null; dataChunks = null; chunkIndex = 0; numChunksTotal = 1; if (encryptionKey == null) { chunkIndexToBuffer.put(0, filterChunkToRange(blobData.getStream().getByteBuffer())); numChunksRetrieved = 1; } else { logger.trace("Submitting decrypt job for simple blob {}", blobId); long startTimeMs = System.currentTimeMillis(); decryptCallbackResultInfo = new DecryptCallBackResultInfo(); progressTracker.initializeDecryptionTracker(); <START> cryptoJobHandler.submitJob(new DecryptJob(blobId, encryptionKey, blobData.getStream().getByteBuffer(), <END> userMetadata != null ? ByteBuffer.wrap(userMetadata) : null, cryptoService, kms, (DecryptJob.DecryptJobResult result, Exception exception) -> { routerMetrics.contentDecryptTimeMs.update(System.currentTimeMillis() - startTimeMs); logger.trace("Handling decrypt job call back for simple blob to set decrypt callback results", blobId); decryptCallbackResultInfo.setResultAndException(result, exception); routerCallback.onPollReady(); })); } } }</code><technical_language>curious - is DecryptJob() instantiated places in code (I thought - for data chunks for metadata chunk)</technical_language>

Target:
private void handleSimpleBlob(BlobData blobData, byte[] userMetadata, ByteBuffer encryptionKey) { totalSize = blobData.getSize(); chunkSize = totalSize; boolean rangeResolutionFailure = false; if (encryptionKey == null) { rangeResolutionFailure = resolveRange(totalSize); } else { } if (!rangeResolutionFailure) { chunkIdIterator = null; dataChunks = null; chunkIndex = 0; numChunksTotal = 1; if (encryptionKey == null) { chunkIndexToBuffer.put(0, filterChunkToRange(blobData.getStream().getByteBuffer())); numChunksRetrieved = 1; } else { logger.trace("Submitting decrypt job for simple blob {}", blobId); long startTimeMs = System.currentTimeMillis(); decryptCallbackResultInfo = new DecryptCallBackResultInfo(); progressTracker.initializeDecryptionTracker(); cryptoJobHandler.submitJob(new DecryptJob(blobId, encryptionKey, blobData.getStream().getByteBuffer(), userMetadata != null ? ByteBuffer.wrap(userMetadata) : null, cryptoService, kms, (DecryptJob.DecryptJobResult result, Exception exception) -> { routerMetrics.decryptTimeMs.update(System.currentTimeMillis() - startTimeMs); logger.trace("Handling decrypt job call back for simple blob to set decrypt callback results", blobId); decryptCallbackResultInfo.setResultAndException(result, exception); routerCallback.onPollReady(); })); } } }
Source:
<code>public void done() throws CommitFailedException { if (isTimeToUpdate()) { <START> try { long startTime = System.currentTimeMillis(); int docCount = Integer.parseInt(luceneIndexMBean.getDocCount(indexPath)); HistogramStats docCountHistogram = statisticsProvider.getHistogram(indexPath + NO_DOCS, StatsOptions.METRICS_ONLY); docCountHistogram.update(docCount); log.trace("{} stats updated, docCount {}, timeToUpdate {}", indexPath, docCount, System.currentTimeMillis() - startTime); long indexSize = Long.parseLong(luceneIndexMBean.getSize(indexPath)); HistogramStats indexSizeHistogram = statisticsProvider.getHistogram(indexPath + INDEX_SIZE, StatsOptions.METRICS_ONLY); indexSizeHistogram.update(indexSize); long endTime = System.currentTimeMillis(); asyncIndexesSizeStatsUpdate.setLastStatsUpdateTime(indexPath, endTime); log.debug("{} stats updated; docCount {}, size {}, timeToUpdate {}", indexPath, docCount, indexSize, endTime - startTime); } catch (IOException e) { log.debug("could not update no_docs/index_size stats for index at {}", indexPath, e); } <END> } }</code><technical_language>Great</technical_language>

Target:
public void done() { if (shouldUpdateStats()) { try { long startTime = System.currentTimeMillis(); int docCount = Integer.parseInt(luceneIndexMBean.getDocCount(indexPath)); HistogramStats docCountHistogram = statisticsProvider.getHistogram(indexPath + NO_DOCS, StatsOptions.METRICS_ONLY); docCountHistogram.update(docCount); log.trace("{} stats updated, docCount {}, timeToUpdate {}", indexPath, docCount, System.currentTimeMillis() - startTime); long indexSize = Long.parseLong(luceneIndexMBean.getSize(indexPath)); HistogramStats indexSizeHistogram = statisticsProvider.getHistogram(indexPath + INDEX_SIZE, StatsOptions.METRICS_ONLY); indexSizeHistogram.update(indexSize); long endTime = System.currentTimeMillis(); asyncIndexesSizeStatsUpdate.setLastStatsUpdateTime(indexPath, endTime); log.debug("{} stats updated; docCount {}, size {}, timeToUpdate {}", indexPath, docCount, indexSize, endTime - startTime); } catch (IOException e) { log.warn("could not update no_docs/index_size stats for index at {}", indexPath, e); } } }
Source:
<code>public void readParameters(final CgmInputReader inputReader, final int parameterListLength) throws IOException { int data = inputReader.readEnumValue(); switch (data) { case LINE_WIDTH_MODE_ABSOLUTE: <START> mode = CommonSpecificationModeElement.Mode.ABSOLUTE; <END> break; case LINE_WIDTH_MODE_SCALED: mode = CommonSpecificationModeElement.Mode.SCALED; break; case LINE_WIDTH_MODE_FRACTIONAL: mode = CommonSpecificationModeElement.Mode.FRACTIONAL; break; case LINE_WIDTH_MODE_MM: mode = CommonSpecificationModeElement.Mode.MILLIMETRES; break; default: LOG.info(String.format("Unknown %s value: %d", getFriendlyName(), data)); break; } }</code><technical_language>SonarLint unhappy enumeration file name</technical_language>

Target:
public void readParameters(final CgmInputReader inputReader, final int parameterListLength) throws IOException { int data = inputReader.readEnumValue(); switch (data) { case LINE_WIDTH_MODE_ABSOLUTE: mode = Mode.ABSOLUTE; break; case LINE_WIDTH_MODE_SCALED: mode = Mode.SCALED; break; case LINE_WIDTH_MODE_FRACTIONAL: mode = Mode.FRACTIONAL; break; case LINE_WIDTH_MODE_MM: mode = Mode.MILLIMETRES; break; default: LOG.info(String.format("Unknown %s value: %d", getFriendlyName(), data)); break; } }
Source:
<code>private double getIntegrandGivenNoArtifact(final double f, final int nPlus, final int nMinus, final int xPlus, final int xMinus){ <START> final BinomialDistribution binomFwd = new BinomialDistribution(nPlus, f); <END> final BinomialDistribution binomRev = new BinomialDistribution(nMinus, f); return binomFwd.probability(xPlus)*binomRev.probability(xMinus); }</code><technical_language>construct Distribution classes in Apache Commons supplying a RandomGenerator, constructs a default one, is expensive. Instead, construct a new BinomialDistribution(null, nPlus, f) etc</technical_language>

Target:
private double getIntegrandGivenNoArtifact(final double f, final int nPlus, final int nMinus, final int xPlus, final int xMinus){ return MathUtils.binomialProbability(nPlus, xPlus, f) * MathUtils.binomialProbability(nMinus, xMinus, f); }
Source:
<code>public int run() throws IOException { int b; if (in != null) { <START> while ((b = in.read()) != -1) out.write(b); <END> in.close(); } out.close(); return -1; }</code><technical_language>Missing braces</technical_language>

Target:
public int run() throws IOException { int b; if (in != null) { while ((b = in.read()) != -1) { out.write(b); } in.close(); } out.close(); return -1; }
Source:
<code>private BiFunction<CircuitBreakerEvent, CircuitBreaker, String> getCircuitBreakerEventStringFunction() { <START> ObjectMapper jsonMapper = new ObjectMapper(); <END> return (cbEvent, cb) -> { try { return jsonMapper.writeValueAsString( new CircuitBreakerHystrixStreamEventsDTO(cbEvent, cb.getState(), cb.getMetrics(), cb.getCircuitBreakerConfig() ) ); } catch (JsonProcessingException e) { } return ""; }; }</code><technical_language>moved class member variable</technical_language>

Target:
private BiFunction<CircuitBreakerEvent, CircuitBreaker, String> getCircuitBreakerEventStringFunction() { return (cbEvent, cb) -> { try { return jsonMapper.writeValueAsString( new CircuitBreakerHystrixStreamEventsDTO(cbEvent, cb.getState(), cb.getMetrics(), cb.getCircuitBreakerConfig() ) ); } catch (JsonProcessingException e) { } return ""; }; }
Source:
<code>private synchronized void closeAllSessionsExcept(SessionLocal except) { SessionLocal[] all = userSessions.toArray(EMPTY_SESSION_ARRAY); for (SessionLocal s : all) { if (s != except) { s.suspend(); } } int timeout = 2 * getLockTimeout(); long start = System.currentTimeMillis(); <START> long sleep = Math.max(timeout / 20, 50); <END> boolean done = false; while (!done) { try { wait(sleep); } catch (InterruptedException e1) { } if (System.currentTimeMillis() - start > timeout) { for (SessionLocal s : all) { if (s != except && !s.isClosed()) { try { s.close(); } catch (Throwable e) { trace.error(e, "disconnecting session #{0}", s.getId()); } } } break; } done = true; for (SessionLocal s : all) { if (s != except && !s.isClosed()) { done = false; break; } } } }</code><technical_language>Thank for contribution! replace 0 1 here, 50 unreasonably large for systems support small wait values properly</technical_language>

Target:
private synchronized void closeAllSessionsExcept(SessionLocal except) { SessionLocal[] all = userSessions.toArray(EMPTY_SESSION_ARRAY); for (SessionLocal s : all) { if (s != except) { s.suspend(); } } int timeout = 2 * getLockTimeout(); long start = System.currentTimeMillis(); long sleep = Math.max(timeout / 20, 1); boolean done = false; while (!done) { try { wait(sleep); } catch (InterruptedException e1) { } if (System.currentTimeMillis() - start > timeout) { for (SessionLocal s : all) { if (s != except && !s.isClosed()) { try { s.close(); } catch (Throwable e) { trace.error(e, "disconnecting session #{0}", s.getId()); } } } break; } done = true; for (SessionLocal s : all) { if (s != except && !s.isClosed()) { done = false; break; } } } }