auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public void testInterruptsNotCached() throws Exception { final NettyTestUtil.NettyServerAndClient nettyServerAndClient = createNettyServerAndClient(); ConnectionID connectionId = new ConnectionID(new InetSocketAddress( nettyServerAndClient.server().getConfig().getServerAddress(), nettyServerAndClient.server().getConfig().getServerPort()), 0); try { AwaitingNettyClient nettyClient = new AwaitingNettyClient(nettyServerAndClient.client()); PartitionRequestClientFactory factory = new PartitionRequestClientFactory(nettyClient, 0); nettyClient.awaitForInterrupts = true; connectAndInterrupt(factory, connectionId); nettyClient.awaitForInterrupts = false; factory.createPartitionRequestClient(connectionId); } finally { nettyServerAndClient.client().shutdown(); nettyServerAndClient.server().shutdown(); } }

Target:
public void testInterruptsNotCached() throws Exception { NettyTestUtil.NettyServerAndClient nettyServerAndClient = createNettyServerAndClient(); try { AwaitingNettyClient nettyClient = new AwaitingNettyClient(nettyServerAndClient.client()); PartitionRequestClientFactory factory = new PartitionRequestClientFactory(nettyClient, 0); nettyClient.awaitForInterrupts = true; connectAndInterrupt(factory, nettyServerAndClient.getConnectionID(0)); nettyClient.awaitForInterrupts = false; factory.createPartitionRequestClient(nettyServerAndClient.getConnectionID(0)); } finally { nettyServerAndClient.client().shutdown(); nettyServerAndClient.server().shutdown(); } }
Source:
public AdvancedCache<String, V> getCache(String name, MediaType requestedMediaType) { if (requestedMediaType == null) { throw new IllegalArgumentException("requestedMediaType cannot be null"); } checkCacheAvailable(name); boolean matchesAll = requestedMediaType.matchesAll(); String cacheKey = matchesAll ? name : name + requestedMediaType.getTypeSubtype(); AdvancedCache<String, V> registered = knownCaches.get(cacheKey); if (registered != null) return registered; if (name.equals(PROTOBUF_METADATA_CACHE_NAME)) { return (AdvancedCache<String, V>) instance.getCache(PROTOBUF_METADATA_CACHE_NAME).getAdvancedCache() .withEncoding(UTF8CompatEncoder.class); } AdvancedCache<?, ?> encodedCache = getCache(name).getAdvancedCache(); Configuration cacheConfiguration = encodedCache.getCacheConfiguration(); if (cacheConfiguration.memory().storageType() == StorageType.OFF_HEAP) { encodedCache = encodedCache.withKeyEncoding(UTF8Encoder.class); } encodedCache = encodedCache.withMediaType(TEXT_PLAIN_TYPE, requestedMediaType.toString()); AdvancedCache<String, V> decoratedCache = (AdvancedCache<String, V>) encodedCache; knownCaches.putIfAbsent(cacheKey, decoratedCache); return decoratedCache; }

Target:
public AdvancedCache<String, V> getCache(String name, MediaType requestedMediaType) { if (requestedMediaType == null) { throw new NullPointerException("requestedMediaType cannot be null"); } checkCacheAvailable(name); boolean matchesAll = requestedMediaType.matchesAll(); String cacheKey = matchesAll ? name : name + requestedMediaType.getTypeSubtype(); AdvancedCache<String, V> registered = knownCaches.get(cacheKey); if (registered != null) return registered; if (name.equals(PROTOBUF_METADATA_CACHE_NAME)) { return (AdvancedCache<String, V>) instance.getCache(PROTOBUF_METADATA_CACHE_NAME).getAdvancedCache() .withEncoding(UTF8CompatEncoder.class); } AdvancedCache<?, ?> encodedCache = getCache(name).getAdvancedCache(); Configuration cacheConfiguration = encodedCache.getCacheConfiguration(); if (cacheConfiguration.memory().storageType() == StorageType.OFF_HEAP) { encodedCache = encodedCache.withKeyEncoding(UTF8Encoder.class); } encodedCache = encodedCache.withMediaType(TEXT_PLAIN_TYPE, requestedMediaType.toString()); AdvancedCache<String, V> decoratedCache = (AdvancedCache<String, V>) encodedCache; knownCaches.putIfAbsent(cacheKey, decoratedCache); return decoratedCache; }
Source:
public void canBeSubmitted(PerunSession session, Map<String, String> params) throws PerunException { User user = session.getPerunPrincipal().getUser(); AttributesManager am = session.getPerun().getAttributesManager(); Attribute affiliations = am.getAttribute(session, user, A_U_D_userEduPersonScopedAffiliations); if (affiliations.getValue() != null) { LinkedHashMap<String, String> val = affiliations.valueAsMap(); for (String key: val.keySet()) { if (key.startsWith("faculty@")) { return; } } } Attribute rems = am.getAttribute(session, user, A_U_D_userBonaFideStatusRems); if (rems.getValue() != null) { return; } throw new CantBeSubmittedException("User does not meet the criteria for applying for Bona Fide Status"); }

Target:
public void canBeSubmitted(PerunSession session, Map<String, String> params) throws PerunException { User user = session.getPerunPrincipal().getUser(); if (user == null) { throw new CantBeSubmittedException("This module can be set only for registration to Group."); } AttributesManager am = session.getPerun().getAttributesManager(); Attribute affiliations = am.getAttribute(session, user, A_U_D_userEduPersonScopedAffiliations); if (affiliations.getValue() != null) { LinkedHashMap<String, String> val = affiliations.valueAsMap(); for (String key: val.keySet()) { if (key.startsWith("faculty@")) { return; } } } Attribute rems = am.getAttribute(session, user, A_U_D_userBonaFideStatusRems); if (rems.getValue() != null) { return; } throw new CantBeSubmittedException("User does not meet the criteria for applying for Bona Fide Status"); }
Source:
public void updateAuthorization(Authorization authorization, String groupName, HttpLocalizedOperationResult result, Username validUser) { UpdateAuthorizationCommand command = new UpdateAuthorizationCommand(groupName, authorization); try{ PipelineConfigsUpdateCommand updateCommand = new PipelineConfigsUpdateCommand(goConfigService, command, result, validUser, groupName); goConfigService.updateConfig(updateCommand, validUser); } catch (Exception e) { if (e instanceof GoConfigInvalidException) { result.unprocessableEntity(LocalizedMessage.string("ENTITY_CONFIG_VALIDATION_FAILED")); } else { result.internalServerError(LocalizedMessage.string("INTERNAL_SERVER_ERROR")); } } }

Target:
public void updateAuthorization(Authorization authorization, String groupName, HttpLocalizedOperationResult result, Username validUser) { UpdateAuthorizationCommand command = new UpdateAuthorizationCommand(groupName, authorization); try{ PipelineConfigsUpdateCommand updateCommand = new PipelineConfigsUpdateCommand(goConfigService, command, result, validUser, groupName); goConfigService.updateConfig(updateCommand, validUser); } catch (Exception e) { if (e instanceof GoConfigInvalidException) { result.unprocessableEntity(LocalizedMessage.string("ENTITY_CONFIG_VALIDATION_FAILED")); } else if(e instanceof ConfigUpdateCheckFailedException) { return; } else { result.internalServerError(LocalizedMessage.string("INTERNAL_SERVER_ERROR")); } } }
Source:
SingleItemModel(String blogId, long date, String itemID, String title, int totals, String url, String icon) { this.mBlogID = blogId; this.mItemID = itemID; this.mTitle = title; this.mTotals = totals; if (url == null || "null".equals(url) || "false".equals(url)) { this.mUrl = ""; } else { this.mUrl = url; } this.mDate = date; this.mIcon = icon; }

Target:
SingleItemModel(String blogId, long date, String itemID, String title, int totals, String url, String icon) { this.mBlogID = blogId; this.mItemID = itemID; this.mTitle = title; this.mTotals = totals; if (!URLUtil.isValidUrl(url)) { this.mUrl = ""; } else { this.mUrl = url; } this.mDate = date; this.mIcon = icon; }
Source:
public static Collection<Object[]> data() { List<Object[]> values = new ArrayList<>(); values.add(new Object[] {Collections.singletonList("TLSv1.2"), Collections.singletonList("TLSv1.2")}); if (Java.IS_JAVA11_COMPATIBLE) { values.add(new Object[] {Arrays.asList("TLSv1.2", "TLSv1.3"), Collections.singletonList("TLSv1.3")}); values.add(new Object[] {Arrays.asList("TLSv1.2", "TLSv1.3"), Collections.singletonList("TLSv1.2")}); values.add(new Object[] {Arrays.asList("TLSv1.2", "TLSv1.3"), Arrays.asList("TLSv1.2", "TLSv1.3")}); values.add(new Object[] {Arrays.asList("TLSv1.2", "TLSv1.3"), Arrays.asList("TLSv1.3", "TLSv1.2")}); values.add(new Object[] {Arrays.asList("TLSv1.3", "TLSv1.2"), Collections.singletonList("TLSv1.3")}); values.add(new Object[] {Arrays.asList("TLSv1.3", "TLSv1.2"), Collections.singletonList("TLSv1.2")}); values.add(new Object[] {Arrays.asList("TLSv1.3", "TLSv1.2"), Arrays.asList("TLSv1.2", "TLSv1.3")}); values.add(new Object[] {Arrays.asList("TLSv1.3", "TLSv1.2"), Arrays.asList("TLSv1.3", "TLSv1.2")}); } return values; }

Target:
public static Collection<Object[]> data() { List<Object[]> values = new ArrayList<>(); values.add(new Object[] {Collections.singletonList("TLSv1.2"), Collections.singletonList("TLSv1.2")}); if (Java.IS_JAVA11_COMPATIBLE) { values.add(new Object[] {Collections.singletonList("TLSv1.2"), Collections.singletonList("TLSv1.3")}); values.add(new Object[] {Collections.singletonList("TLSv1.3"), Collections.singletonList("TLSv1.2")}); values.add(new Object[] {Collections.singletonList("TLSv1.3"), Collections.singletonList("TLSv1.3")}); values.add(new Object[] {Collections.singletonList("TLSv1.2"), Arrays.asList("TLSv1.2", "TLSv1.3")}); values.add(new Object[] {Collections.singletonList("TLSv1.2"), Arrays.asList("TLSv1.3", "TLSv1.2")}); values.add(new Object[] {Collections.singletonList("TLSv1.3"), Arrays.asList("TLSv1.2", "TLSv1.3")}); values.add(new Object[] {Collections.singletonList("TLSv1.3"), Arrays.asList("TLSv1.3", "TLSv1.2")}); values.add(new Object[] {Arrays.asList("TLSv1.3", "TLSv1.2"), Collections.singletonList("TLSv1.3")}); values.add(new Object[] {Arrays.asList("TLSv1.3", "TLSv1.2"), Collections.singletonList("TLSv1.2")}); values.add(new Object[] {Arrays.asList("TLSv1.3", "TLSv1.2"), Arrays.asList("TLSv1.2", "TLSv1.3")}); values.add(new Object[] {Arrays.asList("TLSv1.3", "TLSv1.2"), Arrays.asList("TLSv1.3", "TLSv1.2")}); values.add(new Object[] {Arrays.asList("TLSv1.2", "TLSv1.3"), Collections.singletonList("TLSv1.3")}); values.add(new Object[] {Arrays.asList("TLSv1.2", "TLSv1.3"), Collections.singletonList("TLSv1.2")}); values.add(new Object[] {Arrays.asList("TLSv1.2", "TLSv1.3"), Arrays.asList("TLSv1.2", "TLSv1.3")}); values.add(new Object[] {Arrays.asList("TLSv1.2", "TLSv1.3"), Arrays.asList("TLSv1.3", "TLSv1.2")}); } return values; }
Source:
public static Region[] values() { Collection<Region> valuesCollection = VALUES_BY_NAME.values(); return valuesCollection.toArray(new Region[valuesCollection.size()]); }

Target:
public static Collection<Region> values() { return VALUES_BY_NAME.values(); }
Source:
public void testNonAtomicPushWithOptions() throws Exception { PushResult r; server.setPerformsAtomicTransactions(false); List<String> pushOptions = Arrays.asList("Hello", "World!"); try (Transport tn = testProtocol.open(uri, client, "server")) { tn.setPushAtomic(false); tn.setCapablePushOptions(true); tn.setPushOptions(pushOptions); r = tn.push(NullProgressMonitor.INSTANCE, commands()); } RemoteRefUpdate one = r.getRemoteUpdate("refs/heads/one"); RemoteRefUpdate two = r.getRemoteUpdate("refs/heads/two"); System.out.println("PushOptionsTest: receivePack.getPushOptions() = " + receivePack.getPushOptions()); assertSame(pushOptions, receivePack.getPushOptions()); assertSame(RemoteRefUpdate.Status.OK, one.getStatus()); assertSame(RemoteRefUpdate.Status.REJECTED_REMOTE_CHANGED, two.getStatus()); }

Target:
public void testNonAtomicPushWithOptions() throws Exception { PushResult r; server.setPerformsAtomicTransactions(false); List<String> pushOptions = Arrays.asList("Hello", "World!"); try (Transport tn = testProtocol.open(uri, client, "server")) { tn.setPushAtomic(false); tn.setPushOptions(pushOptions); Map<String, RemoteRefUpdate> updates = new HashMap<>(); for (RemoteRefUpdate rru : commands()) { updates.put(rru.getRemoteName(), rru); } r = tn.push(NullProgressMonitor.INSTANCE, commands()); } RemoteRefUpdate one = r.getRemoteUpdate("refs/heads/one"); RemoteRefUpdate two = r.getRemoteUpdate("refs/heads/two"); assertSame(RemoteRefUpdate.Status.OK, one.getStatus()); assertSame(RemoteRefUpdate.Status.REJECTED_REMOTE_CHANGED, two.getStatus()); assertEquals(pushOptions, baseReceivePack.getPushOptions()); }
Source:
protected void containerExists() throws Exception { Assert.assertTrue(this.blobStore.containerExists(this.container), "Container SHOULD exist"); Assert.assertTrue(!this.blobStore.containerExists(String.valueOf(Calendar.getInstance().getTimeInMillis())), "Container SHOULD NOT exist"); }

Target:
protected void containerExists() throws Exception { Assert.assertTrue(this.blobStore.containerExists(this.container), "Container SHOULD exist"); Assert.assertFalse(this.blobStore.containerExists(String.valueOf(Calendar.getInstance().getTimeInMillis())), "Container SHOULD NOT exist"); }
Source:
public RsXslt(final Response rsp, final URIResolver resolver) { super( new RsOf( rsp::head, () -> RsXslt.transform(rsp.body(), resolver) ) ); }

Target:
public RsXslt(final Response rsp, final URIResolver resolver) { super( new ResponseOf( rsp::head, () -> RsXslt.transform(rsp.body(), resolver) ) ); }
Source:
protected void onFilterConfigSet() throws Exception { super.onFilterConfigSet(); try { keys = getPlexusContainer().lookupMap( NexusApiKey.class ).keySet(); } catch ( final Exception ignore ) { } }

Target:
protected void onFilterConfigSet() throws Exception { super.onFilterConfigSet(); if ( null == apiKeys ) { apiKeys = getPlexusContainer().lookupMap( NexusApiKey.class ).keySet(); } }
Source:
public String generateDoc(PsiElement element, PsiElement originalElement) { if (element instanceof GoImportSpec) { element = ((GoImportSpec)element).getImportString().resolve(); } if (element instanceof GoNamedElement) { GoTopLevelDeclaration topLevel = PsiTreeUtil.getParentOfType(element, GoTopLevelDeclaration.class); Collection<PsiElement> children = PsiTreeUtil.findChildrenOfType(topLevel, element.getClass()); boolean alone = children.size() == 1 && children.iterator().next().equals(element); String result = getSignature(element); if (result != "") { result = "<p><b>"+result+"</b></p>\n"; } List<PsiComment> comments = getPreviousNonWsComment(alone ? topLevel : element); if (!comments.isEmpty()) result += getCommentText(comments); return result; } else if (element instanceof PsiDirectory) { String comments = getPackageComment(((PsiDirectory)element).findFile("doc.go")); if (comments != null) return comments; return getPackageComment(((PsiDirectory)element).findFile(((PsiDirectory)element).getName() + ".go")); } return null; }

Target:
public String generateDoc(PsiElement element, PsiElement originalElement) { if (element instanceof GoImportSpec) { element = ((GoImportSpec)element).getImportString().resolve(); } if (element instanceof GoNamedElement) { GoTopLevelDeclaration topLevel = PsiTreeUtil.getParentOfType(element, GoTopLevelDeclaration.class); Collection<PsiElement> children = PsiTreeUtil.findChildrenOfType(topLevel, element.getClass()); boolean alone = children.size() == 1 && children.iterator().next().equals(element); String result = getSignature(element); if (!result.isEmpty()) { result = "<p><b>" + result + "</b></p>\n"; } List<PsiComment> comments = getPreviousNonWsComment(alone ? topLevel : element); if (!comments.isEmpty()) result += getCommentText(comments); return result; } else if (element instanceof PsiDirectory) { String comments = getPackageComment(((PsiDirectory)element).findFile("doc.go")); if (comments != null) return comments; return getPackageComment(((PsiDirectory)element).findFile(((PsiDirectory)element).getName() + ".go")); } return null; }
Source:
public Void call() throws Exception { List<Change> openChanges; ReviewDb db = schemaFactory.open(); try { openChanges = db.changes().byBranchOpenAll(new Branch.NameKey(project, ref)).toList(); } finally { db.close(); } for (Change change : openChanges) { updateAsync(change); } return null; }

Target:
public Void call() throws Exception { List<Change> openChanges; ReviewDb db = schemaFactory.open(); try { openChanges = db.changes().byBranchOpenAll(new Branch.NameKey(project, ref)).toList(); } finally { db.close(); } for (Change change : mergeabilityCheckQueue.addAll(openChanges)) { updateAsync(change); } return null; }
Source:
public static Cache<String, CachableResponse> getMediatorCache() { if (mediatorCacheInit.get()) { return Caching.getCacheManagerFactory().getCacheManager(CachingConstants.CACHE_MANAGER) .getCache(CachingConstants.MEDIATOR_CACHE); } else { CacheManager cacheManager = Caching.getCacheManagerFactory().getCacheManager(CachingConstants.CACHE_MANAGER); mediatorCacheInit.set(true); return cacheManager.<String, CachableResponse>createCacheBuilder(CachingConstants.MEDIATOR_CACHE). setExpiry(CacheConfiguration.ExpiryType.MODIFIED, new CacheConfiguration.Duration(TimeUnit.SECONDS, CachingConstants.CACHE_INVALIDATION_TIME)).setExpiry(CacheConfiguration.ExpiryType.ACCESSED, new CacheConfiguration.Duration(TimeUnit.SECONDS,CachingConstants.CACHE_INVALIDATION_TIME)) .setStoreByValue(false).build(); } }

Target:
public static Cache<String, CachableResponse> getMediatorCache() { if (mediatorCacheInit.get()) { return Caching.getCacheManagerFactory().getCacheManager(CachingConstants.CACHE_MANAGER) .getCache(CachingConstants.MEDIATOR_CACHE); } else { CacheManager cacheManager = Caching.getCacheManagerFactory().getCacheManager(CachingConstants.CACHE_MANAGER); mediatorCacheInit.getAndSet(true); return cacheManager.<String, CachableResponse>createCacheBuilder(CachingConstants.MEDIATOR_CACHE). setExpiry(CacheConfiguration.ExpiryType.MODIFIED, new CacheConfiguration.Duration(TimeUnit.SECONDS, CachingConstants.CACHE_INVALIDATION_TIME)).setExpiry(CacheConfiguration.ExpiryType.ACCESSED, new CacheConfiguration.Duration(TimeUnit.SECONDS,CachingConstants.CACHE_INVALIDATION_TIME)) .setStoreByValue(false).build(); } }
Source:
void returnsNopLockWithoutExclusiveResources() { Collection<ExclusiveResource> resources = emptySet(); List<Lock> locks = getLocks(lockManager, resources); assertThat(locks).isEmpty(); }

Target:
void returnsNopLockWithoutExclusiveResources() { Collection<ExclusiveResource> resources = emptySet(); List<Lock> locks = getLocks(resources, NopLock.class); assertThat(locks).isEmpty(); }
Source:
private static Method[] populateSetters(Class<?> cls, String propertyName) { String setterName = ""; if(propertyName != null && propertyName.length()>0){ setterName = new StringBuilder("set").append(propertyName.substring(0, 1).toUpperCase(Locale.ENGLISH)) .append(propertyName.substring(1)).toString(); } List<Method> resultList = null; for (Method method: cls.getMethods()) { if (method.getName().equals(setterName)) { Class<?>[] clazzes = method.getParameterTypes(); if (clazzes.length != 1) { continue; } if (resultList == null) { resultList = new ArrayList<Method>(); } resultList.add(method); } } Method[] result = EMPTY_METHOD_ARRAY; if (resultList != null && !resultList.isEmpty()) { result = resultList.toArray(new Method[resultList.size()]); } Map<String, Method[]> classMap = SETTERS_METHODS_CACHE.get(cls); if (classMap == null) { classMap = new ConcurrentHashMap<String, Method[]>(); SETTERS_METHODS_CACHE.put(cls, classMap); } classMap.put(propertyName, result); return result; }

Target:
private static Method[] populateSetters(Class<?> cls, String propertyName) { String setterName = ""; if (propertyName != null && propertyName.length() > 0){ setterName = new StringBuilder("set").append(propertyName.substring(0, 1).toUpperCase(Locale.ENGLISH)) .append(propertyName.substring(1)).toString(); } List<Method> resultList = null; for (Method method : cls.getMethods()) { if (method.getName().equals(setterName)) { Class<?>[] clazzes = method.getParameterTypes(); if (clazzes.length != 1) continue; if (resultList == null) resultList = new ArrayList<Method>(); resultList.add(method); } } Method[] result = EMPTY_METHOD_ARRAY; if (resultList != null && !resultList.isEmpty()) result = resultList.toArray(new Method[resultList.size()]); Map<String, Method[]> classMap = SETTERS_METHODS_CACHE.get(cls); if (classMap == null) { classMap = new ConcurrentHashMap<String, Method[]>(); SETTERS_METHODS_CACHE.put(cls, classMap); } classMap.put(propertyName, result); return result; }
Source:
public static TempFileSpace with(final Path baseDir, final String prefix) throws IOException { if (baseDir == null || prefix == null) { throw new IllegalArgumentException("TempFileSpace is created with null."); } if (!baseDir.isAbsolute()) { throw new IllegalArgumentException("TempFileSpace is created under a relative path."); } if (!Files.isDirectory(baseDir)) { throw new IOException("TempFileSpace is created under non-directory."); } return new TempFileSpace(true, baseDir, prefix, null); }

Target:
public static TempFileSpace with(final Path baseDir, final String prefix) throws IOException { if (baseDir == null || prefix == null) { throw new IllegalArgumentException("TempFileSpace cannot be created with null."); } if (!baseDir.isAbsolute()) { throw new IllegalArgumentException("TempFileSpace cannot be created under a relative path."); } if (!Files.isDirectory(baseDir)) { throw new IOException("TempFileSpace cannot be created under non-directory."); } return new TempFileSpace(true, baseDir, prefix, null); }
Source:
static Map<Aggregate, Object> getAggregates(String attributeName, FeatureCollection featureCollection, Aggregate... aggregates) { Map<Aggregate, Object> result = new HashMap<>(); PropertyName property = FF.property(attributeName); for (Aggregate aggregate : aggregates) { FeatureCalc featureCalc = aggregate.create(property); try { featureCollection.accepts(featureCalc, null); Object value = featureCalc.getResult().getValue(); result.put(aggregate, value); } catch (IOException e) { throw new RuntimeException(e); } } return result; }

Target:
static Map<Aggregate, Object> getAggregates(String attributeName, FeatureCollection featureCollection, Aggregate... aggregates) { Map<Aggregate, Object> result = new HashMap<>(); PropertyName property = FF.property(attributeName); for (Aggregate aggregate : aggregates) { FeatureCalc featureCalc = aggregate.create(property); try { featureCollection.accepts(featureCalc, null); Object value = featureCalc.getResult().getValue(); result.put(aggregate, value); } catch (IOException e) { throw new RuntimeException("Failed to collect summary aggregates on attribute " + attributeName, e); } } return result; }
Source:
PaxosQuorumCheckingCoalescingFunction<REQ, RESP, F> wrapWithRemotes( List<SERVICE> services, Map<SERVICE, ExecutorService> executors, int quorumSize, Function<SERVICE, F> functionFactory) { List<FunctionAndExecutor<F>> functionsAndExecutors = KeyedStream.of(services) .map(executors::get) .mapKeys(functionFactory) .entries() .<FunctionAndExecutor<F>>map(entry -> ImmutableFunctionAndExecutor.of(entry.getKey(), entry.getValue())) .collect(Collectors.toList()); return new PaxosQuorumCheckingCoalescingFunction<>(functionsAndExecutors, quorumSize); }

Target:
PaxosQuorumCheckingCoalescingFunction<REQ, RESP, F> wrapWithRemotes( List<SERVICE> services, Map<SERVICE, ExecutorService> executors, int quorumSize, Function<SERVICE, F> functionFactory) { List<FunctionAndExecutor<F>> functionsAndExecutors = KeyedStream.of(services) .map(executors::get) .mapKeys(functionFactory) .entries() .<FunctionAndExecutor<F>>map(entry -> ImmutableFunctionAndExecutor.of(entry.getKey(), entry.getValue())) .collect(Collectors.toList()); List<F> functions = new ArrayList<>(services.size()); Map<F, ExecutorService> executorMap = new HashMap<>(services.size()); for (SERVICE service: services) { F function = functionFactory.apply(service); functions.add(function); executorMap.put(function, executors.get(service)); } return new PaxosQuorumCheckingCoalescingFunction<>(functions, executorMap, quorumSize); }
Source:
public void testAbortTransaction() { Map<String, Object> configs = new HashMap<>(); configs.put(ProducerConfig.TRANSACTIONAL_ID_CONFIG, "some.id"); configs.put(ProducerConfig.MAX_BLOCK_MS_CONFIG, 10000); configs.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, "localhost:9000"); Time time = new MockTime(1); MetadataResponse initialUpdateResponse = TestUtils.metadataUpdateWith(1, singletonMap("topic", 1)); ProducerMetadata metadata = newMetadata(0, Long.MAX_VALUE); MockClient client = new MockClient(time, metadata); client.updateMetadata(initialUpdateResponse); client.prepareResponse(FindCoordinatorResponse.prepareResponse(Errors.NONE, host1)); client.prepareResponse(initProducerIdResponse(1L, (short) 5, Errors.NONE)); client.prepareResponse(endTxnResponse(Errors.NONE)); try (Producer<String, String> producer = new KafkaProducer<>(configs, new StringSerializer(), new StringSerializer(), metadata, client, null, time)) { producer.initTransactions(); producer.beginTransaction(); producer.abortTransaction(); } }

Target:
public void testAbortTransaction() { Map<String, Object> configs = new HashMap<>(); configs.put(ProducerConfig.TRANSACTIONAL_ID_CONFIG, "some.id"); configs.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, "localhost:9000"); Time time = new MockTime(1); MetadataResponse initialUpdateResponse = TestUtils.metadataUpdateWith(1, singletonMap("topic", 1)); ProducerMetadata metadata = newMetadata(0, Long.MAX_VALUE); MockClient client = new MockClient(time, metadata); client.updateMetadata(initialUpdateResponse); client.prepareResponse(FindCoordinatorResponse.prepareResponse(Errors.NONE, host1)); client.prepareResponse(initProducerIdResponse(1L, (short) 5, Errors.NONE)); client.prepareResponse(endTxnResponse(Errors.NONE)); try (Producer<String, String> producer = new KafkaProducer<>(configs, new StringSerializer(), new StringSerializer(), metadata, client, null, time)) { producer.initTransactions(); producer.beginTransaction(); producer.abortTransaction(); } }
Source:
public void requestResults(String query, Searcher searcher) { Matcher m = p.matcher(query); if (m.find()) { SearchPojo pojo = new SearchPojo(); pojo.id = "calculator://"; pojo.type = SearchPojo.CALCULATOR_QUERY; String operator = m.group(2); String result = ""; float lhs = Float.parseFloat(m.group(1)); float rhs = Float.parseFloat(m.group(3)); float floatResult = 0; if (operator.equals("+")) { floatResult = lhs + rhs; } if (operator.equals("-")) { floatResult = lhs - rhs; } if (operator.equals("*") || operator.equals("×")) { floatResult = lhs * rhs; } if (operator.equals("/") || operator.equals("÷")) { floatResult = lhs / rhs; } pojo.query = floatToString(lhs) + " " + operator + " " + floatToString(rhs) + " = " + floatToString(floatResult); pojo.relevance = 100; searcher.addResult(pojo); } }

Target:
public void requestResults(String query, Searcher searcher) { Matcher m = p.matcher(query); if (m.find()) { SearchPojo pojo = new SearchPojo(); pojo.id = "calculator://"; pojo.type = SearchPojo.CALCULATOR_QUERY; String operator = m.group(2); float lhs = Float.parseFloat(m.group(1)); float rhs = Float.parseFloat(m.group(3)); float floatResult = 0; switch (operator) { case "+": floatResult = lhs + rhs; break; case "-": floatResult = lhs - rhs; break; case "*": case "×": floatResult = lhs * rhs; break; case "/": case "÷": floatResult = lhs / rhs; break; default: floatResult = Float.POSITIVE_INFINITY; } pojo.query = floatToString(lhs) + " " + operator + " " + floatToString(rhs) + " = " + floatToString(floatResult); pojo.relevance = 100; searcher.addResult(pojo); } }
Source:
public void handleRemoveEvent(CatalogRemoveEvent event) throws CatalogException { String resourceWorkSpaceName = null; CatalogInfo resourceInfo = event.getSource(); String resourceName = null; if (resourceInfo instanceof LayerInfo) { resourceWorkSpaceName = ((LayerInfo) resourceInfo).getResource().getStore().getWorkspace().getName(); resourceName = ((LayerInfo) resourceInfo).getName(); } else if (event.getSource() instanceof LayerGroupInfo) { resourceWorkSpaceName = ((LayerGroupInfo) resourceInfo).getWorkspace().getName(); resourceName = ((LayerGroupInfo) resourceInfo).getName(); } if (resourceWorkSpaceName != null && resourceInfo != null) { if (layerHasSecurityRule(resourceWorkSpaceName, resourceName)) { LOGGER.info( String.format( "Removing Security Rules for removed layer: %s", resourceName)); List<DataAccessRule> rulesToRemove = getDataAccessRule(resourceInfo, resourceName); for (DataAccessRule r : rulesToRemove) { dao.removeRule(r); } try { dao.storeRules(); } catch (IOException e) { LOGGER.log(Level.SEVERE, e.getMessage(), e); } } } }

Target:
public void handleRemoveEvent(CatalogRemoveEvent event) throws CatalogException { String resourceWorkSpaceName = null; CatalogInfo resourceInfo = event.getSource(); String resourceName = null; if (resourceInfo instanceof LayerInfo) { resourceWorkSpaceName = ((LayerInfo) resourceInfo).getResource().getStore().getWorkspace().getName(); resourceName = ((LayerInfo) resourceInfo).getName(); } else if (event.getSource() instanceof LayerGroupInfo) { resourceWorkSpaceName = ((LayerGroupInfo) resourceInfo).getWorkspace().getName(); resourceName = ((LayerGroupInfo) resourceInfo).getName(); } if (resourceWorkSpaceName != null && resourceInfo != null) { if (layerHasSecurityRule(resourceWorkSpaceName, resourceName)) { LOGGER.info( String.format( "Removing Security Rules for removed layer: %s", resourceName)); List<DataAccessRule> rulesToRemove = getDataAccessRule(resourceInfo, resourceName); for (DataAccessRule r : rulesToRemove) { dao.removeRule(r); } try { dao.storeRules(); } catch (IOException e) { LOGGER.log(Level.SEVERE, e.getMessage(), e); throw new CatalogException(e); } } } }
Source:
public void setAttribute(String key, String value) { if (key.equals(attributeKeyString)) { String command[] = value.split(" "); if (command.length == 3 && command[0].equals("add")) { while (command[1].charAt(command[1].length() - 1) == '/') { command[1] = command[1].substring(0, command[1].length() - 1); } this.prefixToOSDMap.put(command[1], command[2]); } else if (command.length >= 2 && command[0].equals("remove")) { this.prefixToOSDMap.remove(command[1]); } else if (command.length == 1 && command[0].equals("clear")) { this.prefixToOSDMap.clear(); } } }

Target:
public void setAttribute(String key, String value) { if (key.equals(attributeKeyString)) { String command[] = value.split(" "); if (command.length == 3 && command[0].equals("add")) { if (!(command[1].length() == 0 || command[2].length() == 0)) { this.prefixToOSDMap.put(removeLeadingTrailingSlashes(command[1]), command[2]); } } else if (command.length >= 2 && command[0].equals("remove")) { this.prefixToOSDMap.remove(removeLeadingTrailingSlashes (command[1])); } else if (command.length == 1 && command[0].equals("clear")) { this.prefixToOSDMap.clear(); } } }
Source:
public void testToStringDefault() { DateFormat df = new SimpleDateFormat("HH:mm:ss.SSS"); Date d0 = new Date(0); Date d1 = new Date(12345000L); Date d2 = new Date(1234500L); Date d3 = new Date(1234500000L); assertEquals("toString", df.format(d0) + " 000 000", ts0.toString()); assertEquals("toString", df.format(d1) + " 000 000", ts1.toString()); assertEquals("toString", df.format(d2) + " 000 000", ts2.toString()); assertEquals("toString", df.format(d3) + " 000 000", ts3.toString()); }

Target:
public void testToStringDefault() { DateFormat df = new SimpleDateFormat("HH:mm:ss.SSS"); Date d0 = new Date(ts0.getValue() * (long) Math.pow(10, ts0.getScale() + 3)); Date d1 = new Date(ts1.getValue() * (long) Math.pow(10, ts1.getScale() + 3)); Date d2 = new Date(ts2.getValue() * (long) Math.pow(10, ts2.getScale() + 3)); Date d3 = new Date(ts3.getValue() * (long) Math.pow(10, ts3.getScale() + 3)); assertEquals("toString", df.format(d0) + " 000 000", ts0.toString()); assertEquals("toString", df.format(d1) + " 000 000", ts1.toString()); assertEquals("toString", df.format(d2) + " 000 000", ts2.toString()); assertEquals("toString", df.format(d3) + " 000 000", ts3.toString()); }
Source:
public int getSerializedSize() { int size = memoizedSerializedSize; if (size != -1) { return size; } size = 0; if (((bitField0_ & 0x00000001) == 0x00000001)) { size += com.google.protobuf.CodedOutputStream .computeEnumSize(1, continent_.getNumber()); } if (((bitField0_ & 0x00000002) == 0x00000002)) { size += com.google.protobuf.CodedOutputStream .computeBytesSize(2, getCityBytes()); } size += getUnknownFields().getSerializedSize(); memoizedSerializedSize = size; return size; }

Target:
public int getSerializedSize() { int size = memoizedSerializedSize; if (size != -1) return size; size = 0; if (((bitField0_ & 0x00000001) == 0x00000001)) { size += com.google.protobuf.CodedOutputStream .computeEnumSize(1, continent_.getNumber()); } if (((bitField0_ & 0x00000002) == 0x00000002)) { size += com.google.protobuf.CodedOutputStream .computeBytesSize(2, getCityBytes()); } size += getUnknownFields().getSerializedSize(); memoizedSerializedSize = size; return size; }
Source:
private void proposeLeadershipAfter(Optional<PaxosValue> value) { lock.lock(); try { if (!isLatestRound(value)) { return; } long seq = value.map(val -> val.getRound() + 1).orElse(0L); eventRecorder.recordProposalAttempt(seq); proposer.propose(seq, null); } catch (PaxosRoundFailureException e) { eventRecorder.recordProposalFailure(e); return; } finally { lock.unlock(); } }

Target:
private void proposeLeadershipAfter(Optional<PaxosValue> value) { lock.lock(); try { if (!isLatestRound(value)) { return; } long seq = value.map(val -> val.getRound()).orElse(PaxosAcceptor.NO_LOG_ENTRY) + 1; eventRecorder.recordProposalAttempt(seq); proposer.propose(seq, null); } catch (PaxosRoundFailureException e) { eventRecorder.recordProposalFailure(e); return; } finally { lock.unlock(); } }
Source:
public int hashCode() { int result = bucket != null ? bucket.hashCode() : 0; result = 31 * result + (id != null ? id.hashCode() : 0); result = 31 * result + (latest ? 1 : 0); result = 31 * result + (int) (length ^ (length >>> 32)); result = 31 * result + (name != null ? name.hashCode() : 0); result = 31 * result + (int) (offset ^ (offset >>> 32)); result = 31 * result + (physicalPlacement != null ? physicalPlacement.hashCode() : 0); result = 31 * result + (int) (version ^ (version >>> 32)); return result; }

Target:
public int hashCode() { return java.util.Objects.hash(bucket, id, latest, length, name, offset, physicalPlacement, version); }
Source:
void testGenerateMsgId() { GelfMessage gelfMessage = new GelfMessage() { @Override long getRandomLong() { return 0x8040201008040201L; } @Override short getCurrentTimeMillis() { return 0x0603; } }; byte[] expectedBytes = { (byte) 0x80, 0x40, 0x20, 0x10, 0x08, 0x04, 0x06, 0x03 }; byte[] msgId = gelfMessage.generateMsgId(); assertEquals(8, msgId.length); assertArrayEquals(expectedBytes, msgId); }

Target:
void testGenerateMsgId() { GelfMessage gelfMessage = new GelfMessage() { @Override long getRandomLong() { return 0x804020100804A201L; } @Override long getCurrentTimeMillis() { return 0x90C06030090C1683L; } }; assertThat(gelfMessage.generateMsgId()).isEqualTo(0x804020100804B683L); }
Source:
public AgentInfo approve(Long id, boolean approve) { Optional<AgentInfo> found = agentManagerRepository.findOne(idEqual(id)); AgentInfo agentInfo = null; if (found.isPresent()) { agentInfo = found.get(); agentInfo.setApproved(approve); agentManagerRepository.save(agentInfo); expireLocalCache(); } return agentInfo; }

Target:
public AgentInfo approve(Long id, boolean approve) { Optional<AgentInfo> found = agentManagerRepository.findOne(idEqual(id)); AgentInfo agentInfo = null; if (found.isPresent()) { agentInfo = found.get(); agentInfo.setApproved(approve); expireLocalCache(); } return agentInfo; }
Source:
public static synchronized String nextGlobal() { return StandardCharsets.US_ASCII.decode(getInstance().next()).toString(); }

Target:
public static synchronized String nextGlobal() { return getInstance().next(); }
Source:
public Optional<DecorrelationResult> visitLimit(LimitNode node, Void context) { Optional<DecorrelationResult> childDecorrelationResultOptional = lookup.resolve(node.getSource()).accept(this, null); if (!childDecorrelationResultOptional.isPresent() || node.getCount() == 0) { return Optional.empty(); } DecorrelationResult childDecorrelationResult = childDecorrelationResultOptional.get(); if (childDecorrelationResult.atMostSingleRow) { return childDecorrelationResultOptional; } if (correlation.isEmpty() || !childDecorrelationResult.getConstantSymbols().containsAll(node.getOutputSymbols())) { return Optional.empty(); } childDecorrelationResultOptional = new AggregationNode( idAllocator.getNextId(), node.getSource(), ImmutableMap.of(), ImmutableList.of(ImmutableList.<Symbol>builder() .addAll(correlation) .addAll(node.getOutputSymbols()) .build()), AggregationNode.Step.SINGLE, Optional.empty(), Optional.empty()).accept(this, null); if (!childDecorrelationResultOptional.isPresent() || !childDecorrelationResultOptional.get().atMostSingleRow) { return Optional.empty(); } return childDecorrelationResultOptional; }

Target:
public Optional<DecorrelationResult> visitLimit(LimitNode node, Void context) { Optional<DecorrelationResult> childDecorrelationResultOptional = lookup.resolve(node.getSource()).accept(this, null); if (!childDecorrelationResultOptional.isPresent() || node.getCount() == 0) { return Optional.empty(); } DecorrelationResult childDecorrelationResult = childDecorrelationResultOptional.get(); if (childDecorrelationResult.atMostSingleRow) { return childDecorrelationResultOptional; } if (node.getCount() != 1) { return Optional.empty(); } Set<Symbol> constantSymbols = childDecorrelationResult.getConstantSymbols(); PlanNode decorrelatedChildNode = childDecorrelationResult.node; if (constantSymbols.isEmpty() || !constantSymbols.containsAll(decorrelatedChildNode.getOutputSymbols())) { return Optional.empty(); } AggregationNode aggregationNode = new AggregationNode( idAllocator.getNextId(), decorrelatedChildNode, ImmutableMap.of(), ImmutableList.of(ImmutableList.<Symbol>builder() .addAll(decorrelatedChildNode.getOutputSymbols()) .build()), AggregationNode.Step.SINGLE, Optional.empty(), Optional.empty()); return Optional.of(new DecorrelationResult( aggregationNode, childDecorrelationResult.symbolsToPropagate, childDecorrelationResult.correlatedPredicates, childDecorrelationResult.correlatedSymbolsMapping, true)); }
Source:
public PlanNode visitApply(ApplyNode node, RewriteContext<Set<Symbol>> context) { ImmutableSet.Builder<Symbol> subqueryAssignmentsSymbolsBuilder = ImmutableSet.builder(); Assignments.Builder subqueryAssignments = Assignments.builder(); for (Map.Entry<Symbol, Expression> entry : node.getSubqueryAssignments().getMap().entrySet()) { Symbol output = entry.getKey(); Expression expression = entry.getValue(); if (context.get().contains(output)) { subqueryAssignmentsSymbolsBuilder.addAll(SymbolsExtractor.extractUnique(expression)); subqueryAssignments.put(output, expression); } } Set<Symbol> subqueryAssignmentsSymbols = subqueryAssignmentsSymbolsBuilder.build(); PlanNode subquery = context.rewrite(node.getSubquery(), subqueryAssignmentsSymbols); Set<Symbol> subquerySymbols = SymbolsExtractor.extractUnique(subquery); List<Symbol> newCorrelation = node.getCorrelation().stream() .filter(subquerySymbols::contains) .collect(toImmutableList()); Set<Symbol> inputContext = ImmutableSet.<Symbol>builder() .addAll(context.get()) .addAll(newCorrelation) .addAll(subqueryAssignmentsSymbols) .build(); PlanNode input = context.rewrite(node.getInput(), inputContext); return new ApplyNode(node.getId(), input, subquery, subqueryAssignments.build(), newCorrelation); }

Target:
public PlanNode visitApply(ApplyNode node, RewriteContext<Set<Symbol>> context) { if (intersection(node.getSubqueryAssignments().getSymbols(), context.get()).isEmpty()) { return context.rewrite(node.getInput(), context.get()); } ImmutableSet.Builder<Symbol> subqueryAssignmentsSymbolsBuilder = ImmutableSet.builder(); Assignments.Builder subqueryAssignments = Assignments.builder(); for (Map.Entry<Symbol, Expression> entry : node.getSubqueryAssignments().getMap().entrySet()) { Symbol output = entry.getKey(); Expression expression = entry.getValue(); if (context.get().contains(output)) { subqueryAssignmentsSymbolsBuilder.addAll(SymbolsExtractor.extractUnique(expression)); subqueryAssignments.put(output, expression); } } Set<Symbol> subqueryAssignmentsSymbols = subqueryAssignmentsSymbolsBuilder.build(); PlanNode subquery = context.rewrite(node.getSubquery(), subqueryAssignmentsSymbols); Set<Symbol> subquerySymbols = SymbolsExtractor.extractUnique(subquery); List<Symbol> newCorrelation = node.getCorrelation().stream() .filter(subquerySymbols::contains) .collect(toImmutableList()); Set<Symbol> inputContext = ImmutableSet.<Symbol>builder() .addAll(context.get()) .addAll(newCorrelation) .addAll(subqueryAssignmentsSymbols) .build(); PlanNode input = context.rewrite(node.getInput(), inputContext); return new ApplyNode(node.getId(), input, subquery, subqueryAssignments.build(), newCorrelation); }
Source:
public FileSystemStorage(ZeppelinConfiguration zConf, String path) throws IOException { this.zConf = zConf; this.hadoopConf = new Configuration(); URI zepConfigURI; URI defaultFSURI; zepConfigURI = getURI(path, "Failed to get URI path"); this.hadoopConf.setBoolean("fs.file.impl.disable.cache", true); String defaultFS = this.hadoopConf.get(FS_DEFAULTFS); defaultFSURI = getURI(defaultFS, "Failed to get defaultFS URI"); if (isS3AFileSystem(defaultFSURI, zepConfigURI)) { this.hadoopConf.set("fs.s3a.impl", S3AFileSystem.class.getName()); LOGGER.info("Setting fs.s3a.impl to S3AFileSystem"); } else { this.hadoopConf.set("fs.file.impl", RawLocalFileSystem.class.getName()); LOGGER.info("Overriding fs.file.impl to RawLocalFileSystem"); } this.isSecurityEnabled = UserGroupInformation.isSecurityEnabled(); this.fs = FileSystem.get(zepConfigURI, this.hadoopConf); }

Target:
public FileSystemStorage(ZeppelinConfiguration zConf, String path) throws IOException { this.zConf = zConf; this.hadoopConf = new Configuration(); URI zepConfigURI; URI defaultFSURI; try { zepConfigURI = new URI(path); } catch (URISyntaxException e) { LOGGER.error("Failed to get Zeppelin config URI"); throw new IOException(e); } this.hadoopConf.setBoolean("fs.file.impl.disable.cache", true); String defaultFS = this.hadoopConf.get(FS_DEFAULTFS); try { defaultFSURI = new URI(defaultFS); } catch (URISyntaxException e) { LOGGER.error("Failed to get defaultFS URI"); throw new IOException(e); } if (!isS3AFileSystem(defaultFSURI, zepConfigURI)) { this.hadoopConf.set("fs.file.impl", RawLocalFileSystem.class.getName()); } this.isSecurityEnabled = UserGroupInformation.isSecurityEnabled(); this.fs = FileSystem.get(zepConfigURI, this.hadoopConf); }
Source:
public void stop() { try { LOGGER.log(Level.CONFIG, "Stopping rest server"); webManager.stop(); LOGGER.log(Level.INFO, "Rest server stopped"); } catch (Exception e) { LOGGER.log(Level.SEVERE, "Error occurred when stopping VXQuery", e); throw new VXQueryRuntimeException("Error occurred when stopping rest server", e); } }

Target:
public void stop() { try { LOGGER.log(Level.FINE, "Stopping rest server"); webManager.stop(); } catch (Exception e) { LOGGER.log(Level.SEVERE, "Error occurred when stopping VXQueryService", e); throw new VXQueryRuntimeException("Error occurred when stopping rest server", e); } LOGGER.log(Level.INFO, "Rest server stopped"); }
Source:
private void calcParallelismAndResource(Transformation<?> transform) { int currentParallelism = transform.getParallelism(); if (parallelism < 0) { parallelism = currentParallelism; } else { checkState( currentParallelism < 0 || parallelism == currentParallelism, "Parallelism of a transformation in MultipleInputNode is different from others. This is a bug."); } int currentMaxParallelism = transform.getMaxParallelism(); if (maxParallelism < 0) { maxParallelism = currentMaxParallelism; } else { checkState( currentMaxParallelism < 0 || maxParallelism == currentMaxParallelism, "Max parallelism of a transformation in MultipleInputNode is different from others. This is a bug."); } if (minResources == null) { minResources = transform.getMinResources(); preferredResources = transform.getPreferredResources(); managedMemoryWeight = transform.getManagedMemoryOperatorScopeUseCaseWeights() .getOrDefault(ManagedMemoryUseCase.BATCH_OP, 0); } else { minResources = minResources.merge(transform.getMinResources()); preferredResources = preferredResources.merge(transform.getPreferredResources()); managedMemoryWeight += transform.getManagedMemoryOperatorScopeUseCaseWeights() .getOrDefault(ManagedMemoryUseCase.BATCH_OP, 0); } }

Target:
private void calcParallelismAndResource(Transformation<?> transform) { parallelism = Math.max(parallelism, transform.getParallelism()); int currentMaxParallelism = transform.getMaxParallelism(); if (maxParallelism < 0) { maxParallelism = currentMaxParallelism; } else { checkState( currentMaxParallelism < 0 || maxParallelism == currentMaxParallelism, "Max parallelism of a transformation in MultipleInputNode is different from others. This is a bug."); } if (minResources == null) { minResources = transform.getMinResources(); preferredResources = transform.getPreferredResources(); managedMemoryWeight = transform.getManagedMemoryOperatorScopeUseCaseWeights() .getOrDefault(ManagedMemoryUseCase.BATCH_OP, 0); } else { minResources = minResources.merge(transform.getMinResources()); preferredResources = preferredResources.merge(transform.getPreferredResources()); managedMemoryWeight += transform.getManagedMemoryOperatorScopeUseCaseWeights() .getOrDefault(ManagedMemoryUseCase.BATCH_OP, 0); } }
Source:
public void testCloseAbort() throws Exception { byte[] cf1 = Bytes.toBytes("CF1"); byte[][] families = { cf1 }; Configuration conf = new Configuration(CONF); conf.setBoolean(HRegion.CLOSE_WAIT_ABORT, true); conf.setInt(HRegion.CLOSE_WAIT_TIME, 5*1000); region = initHRegion(tableName, method, conf, families); RegionServerServices rsServices = mock(RegionServerServices.class); region.rsServices = rsServices; final CountDownLatch latch = new CountDownLatch(1); Thread holder = new Thread(new Runnable() { @Override public void run() { try { LOG.info("Starting region operation holder"); region.startRegionOperation(Operation.SCAN); latch.countDown(); int timeRemaining = 10 * 1000; while (timeRemaining > 0) { long start = EnvironmentEdgeManager.currentTime(); try { Thread.sleep(timeRemaining); } catch (InterruptedException e) { LOG.info("Interrupted"); } long end = EnvironmentEdgeManager.currentTime(); timeRemaining -= end - start; LOG.info("Sleeping again, remaining time " + timeRemaining + " ms"); } } catch (Exception e) { throw new RuntimeException(e); } finally { try { region.closeRegionOperation(); } catch (IOException e) { } LOG.info("Stopped region operation holder"); } } }); holder.start(); latch.await(); try { region.close(); } catch (IOException e) { LOG.info("Caught expected exception", e); } holder.join(); region = null; verify(rsServices, atLeast(1)).abort(anyString(),any()); }

Target:
public void testCloseAbort() throws Exception { byte[] cf1 = Bytes.toBytes("CF1"); byte[][] families = { cf1 }; final int SLEEP_TIME = 10 * 1000; Configuration conf = new Configuration(CONF); conf.setBoolean(HRegion.CLOSE_WAIT_ABORT, true); conf.setInt(HRegion.CLOSE_WAIT_TIME, SLEEP_TIME / 2); conf.setInt(HRegion.CLOSE_WAIT_INTERVAL, SLEEP_TIME / 4); region = initHRegion(tableName, method, conf, families); RegionServerServices rsServices = mock(RegionServerServices.class); when(rsServices.getServerName()).thenReturn(ServerName.valueOf("localhost", 1000, 1000)); region.rsServices = rsServices; final CountDownLatch latch = new CountDownLatch(1); Thread holder = new Thread(new Runnable() { @Override public void run() { try { LOG.info("Starting region operation holder"); region.startRegionOperation(Operation.SCAN); latch.countDown(); int timeRemaining = SLEEP_TIME; while (timeRemaining > 0) { long start = EnvironmentEdgeManager.currentTime(); try { Thread.sleep(timeRemaining); } catch (InterruptedException e) { LOG.info("Interrupted"); } long end = EnvironmentEdgeManager.currentTime(); timeRemaining -= end - start; if (timeRemaining < 0) { timeRemaining = 0; } if (timeRemaining > 0) { LOG.info("Sleeping again, remaining time " + timeRemaining + " ms"); } } } catch (Exception e) { throw new RuntimeException(e); } finally { try { region.closeRegionOperation(); } catch (IOException e) { } LOG.info("Stopped region operation holder"); } } }); holder.start(); latch.await(); try { region.close(); } catch (IOException e) { LOG.info("Caught expected exception", e); } region = null; holder.join(); verify(rsServices, atLeast(1)).abort(anyString(),any()); }