auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public List<String> getRecommendationsForUser(String user) throws IOException, TasteException { DataModel model = new FileDataModel(new File("Result.csv")); UserSimilarity similarity = new PearsonCorrelationSimilarity(model); UserNeighborhood neighborhood = new ThresholdUserNeighborhood(0.1, similarity, model); UserBasedRecommender recommender = new GenericUserBasedRecommender(model, neighborhood, similarity); int userValue = HashUser.get(user); <START> List RecommendedProducts = new ArrayList<String>(); <END> List<RecommendedItem> recommendations = recommender.recommend(userValue,3); for (RecommendedItem recommendation : recommendations) { RecommendedProducts.add(InvertedHashProduct.get((int)recommendation.getItemID())); } return RecommendedProducts; }</code><technical_language>ArrayList a constructor receives initialCapacity based in recommendations size? answer benefit bring implementing this suggestion</technical_language>

Target:
public List<String> getRecommendationsForUser(String user) throws IOException, TasteException { DataModel model = new FileDataModel(new File("Result.csv")); UserSimilarity similarity = new PearsonCorrelationSimilarity(model); UserNeighborhood neighborhood = new ThresholdUserNeighborhood(0.1, similarity, model); UserBasedRecommender recommender = new GenericUserBasedRecommender(model, neighborhood, similarity); int userValue = HashUser.get(user); List RecommendedProducts = new ArrayList<String>(3); List<RecommendedItem> recommendations = recommender.recommend(userValue,3); for (RecommendedItem recommendation : recommendations) { RecommendedProducts.add(InvertedHashProduct.get((int)recommendation.getItemID())); } return RecommendedProducts; }
Source:
<code>public String toString() { <START> return String.format("%s @ partitionKey=%s partition=%d", _events, _partitionKey.orElse(""), _partition.orElse(-1)); <END> }</code><technical_language>nit: orElse("null") is clearer</technical_language>

Target:
public String toString() { return String.format("%s @ partitionKey=%s partition=%d", _events, _partitionKey.orElse(null), _partition.orElse(-1)); }
Source:
<code>public static <T extends Item> AutoCompletionCandidates ofJobNames(final Class<T> type, final String value, ItemGroup container) { final AutoCompletionCandidates candidates = new AutoCompletionCandidates(); class Visitor extends ItemVisitor { String prefix; Visitor(String prefix) { this.prefix = prefix; } @Override public void onItem(Item i) { String n = contextualNameOf(i); <START> boolean caseInsensitive = UserSearchProperty.isCaseInsensitive(); <END> String hay = n; String needle = value; if(caseInsensitive) { hay = hay.toLowerCase(); needle = needle.toLowerCase(); } if ((hay.startsWith(needle) || needle.startsWith(hay)) && (needle.length()>hay.length() || !hay.substring(needle.length()).contains("/")) && i.hasPermission(Item.READ) ) { if (type.isInstance(i) && hay.startsWith(needle)) candidates.add(n); String oldPrefix = prefix; prefix = n; super.onItem(i); prefix = oldPrefix; } } private String contextualNameOf(Item i) { if (prefix.endsWith("/") || prefix.length()==0) return prefix+i.getName(); else return prefix+'/'+i.getName(); } } if (container==null || container==Jenkins.getInstance()) { new Visitor("").onItemGroup(Jenkins.getInstance()); } else { new Visitor("").onItemGroup(container); if (value.startsWith("/")) new Visitor("/").onItemGroup(Jenkins.getInstance()); for ( String p="../"; value.startsWith(p); p+="../") { container = ((Item)container).getParent(); new Visitor(p).onItemGroup(container); } } return candidates; }</code><technical_language>UserSearchProperty is jobs all, check is confusing. I perform case-insensitive for items</technical_language>

Target:
public static <T extends Item> AutoCompletionCandidates ofJobNames(final Class<T> type, final String value, ItemGroup container) { final AutoCompletionCandidates candidates = new AutoCompletionCandidates(); class Visitor extends ItemVisitor { String prefix; Visitor(String prefix) { this.prefix = prefix; } @Override public void onItem(Item i) { String n = contextualNameOf(i); if ((n.startsWith(value) || value.startsWith(n)) && (value.length()>n.length() || !n.substring(value.length()).contains("/")) && i.hasPermission(Item.READ) ) { if (type.isInstance(i) && n.startsWith(value)) candidates.add(n); String oldPrefix = prefix; prefix = n; super.onItem(i); prefix = oldPrefix; } } private String contextualNameOf(Item i) { if (prefix.endsWith("/") || prefix.length()==0) return prefix+i.getName(); else return prefix+'/'+i.getName(); } } if (container==null || container==Jenkins.getInstance()) { new Visitor("").onItemGroup(Jenkins.getInstance()); } else { new Visitor("").onItemGroup(container); if (value.startsWith("/")) new Visitor("/").onItemGroup(Jenkins.getInstance()); for ( String p="../"; value.startsWith(p); p+="../") { container = ((Item)container).getParent(); new Visitor(p).onItemGroup(container); } } return candidates; }
Source:
<code>public void updateRequiredBundleVersions(Map<String, String> versionsToUpdate) { List<MutableManifestElement> requireBundleElements = parseHeaderForMutation(Constants.REQUIRE_BUNDLE); if (requireBundleElements == null || requireBundleElements.isEmpty()) { return; } boolean somethingChanged = false; for (MutableManifestElement mutableManifestElement : requireBundleElements) { String <START> packageName = <END> mutableManifestElement.getValue(); if (versionsToUpdate.containsKey(packageName)) { somethingChanged |= mutableManifestElement.setAttribute(Constants.BUNDLE_VERSION_ATTRIBUTE, versionsToUpdate.get(packageName)); } } if (somethingChanged) { getAttribute(Constants.REQUIRE_BUNDLE).set(Constants.REQUIRE_BUNDLE, requireBundleElements); } }</code><technical_language>bundleSymbolicName</technical_language>

Target:
public void updateRequiredBundleVersions(Map<String, String> versionsToUpdate) { List<MutableManifestElement> requireBundleElements = parseHeaderForMutation(Constants.REQUIRE_BUNDLE); if (requireBundleElements == null || requireBundleElements.isEmpty()) { return; } boolean somethingChanged = false; for (MutableManifestElement mutableManifestElement : requireBundleElements) { String bundleSymbolicName = mutableManifestElement.getValue(); if (versionsToUpdate.containsKey(bundleSymbolicName)) { somethingChanged |= mutableManifestElement.setAttribute(Constants.BUNDLE_VERSION_ATTRIBUTE, versionsToUpdate.get(bundleSymbolicName)); } } if (somethingChanged) { getAttribute(Constants.REQUIRE_BUNDLE).set(Constants.REQUIRE_BUNDLE, requireBundleElements); } }
Source:
<code>protected HandlerRegistration[] doAddHandler(final ViewEventType type, final ViewHandler<? extends ViewEvent> eventHandler) { if (ViewEventType.MOUSE_CLICK.equals(type)) { return registerClickHandler((ViewHandler<ViewEvent>) eventHandler); } if (ViewEventType.MOUSE_DBL_CLICK.equals(type)) { return registerDoubleClickHandler((ViewHandler<ViewEvent>) eventHandler); } if (ViewEventType.MOUSE_ENTER.equals(type)) { <START> return registerEnterHHandler((ViewHandler<ViewEvent>) eventHandler); <END> } if (ViewEventType.MOUSE_EXIT.equals(type)) { return registerExitHandler((ViewHandler<ViewEvent>) eventHandler); } if (ViewEventType.TOUCH.equals(type)) { return registerTouchHandler((TouchHandler) eventHandler); } if (ViewEventType.GESTURE.equals(type)) { return registerGestureHandler((GestureHandler) eventHandler); } return null; }</code><technical_language>Typo.. ...EnterHHandler (double "H")</technical_language>

Target:
protected HandlerRegistration[] doAddHandler(final ViewEventType type, final ViewHandler<? extends ViewEvent> eventHandler) { if (ViewEventType.MOUSE_CLICK.equals(type)) { return registerClickHandler((ViewHandler<ViewEvent>) eventHandler); } if (ViewEventType.MOUSE_DBL_CLICK.equals(type)) { return registerDoubleClickHandler((ViewHandler<ViewEvent>) eventHandler); } if (ViewEventType.MOUSE_ENTER.equals(type)) { return registerEnterHandler((ViewHandler<ViewEvent>) eventHandler); } if (ViewEventType.MOUSE_EXIT.equals(type)) { return registerExitHandler((ViewHandler<ViewEvent>) eventHandler); } if (ViewEventType.TOUCH.equals(type)) { return registerTouchHandler((TouchHandler) eventHandler); } if (ViewEventType.GESTURE.equals(type)) { return registerGestureHandler((GestureHandler) eventHandler); } return null; }
Source:
<code>public ImmutableScan(Scan scan) throws IOException { <START> this.delegateScan = new Scan(scan); <END> }</code><technical_language>exposing original Scan directly, create a new Scan here? need</technical_language>

Target:
public ImmutableScan(Scan scan) { this.delegateScan = scan; }
Source:
<code>private void visitSuper(Node node, Node parent) { Node exprRoot = node; if (exprRoot.getParent().isGetElem() || exprRoot.getParent().isGetProp()) { exprRoot = exprRoot.getParent(); } Node enclosingMemberDef = NodeUtil.getEnclosingNode( exprRoot, new Predicate<Node>() { @Override public boolean apply(Node n) { switch (n.getToken()) { case MEMBER_FUNCTION_DEF: case GETTER_DEF: case SETTER_DEF: return true; default: return false; } } }); if (exprRoot.getParent().isNew()) { compiler.report(JSError.make(node, INVALID_SUPER_CALL)); <START> } else if (NodeUtil.isCallOrNewTarget(exprRoot) <END> && (exprRoot.isSuper() || exprRoot.getFirstChild().isSuper())) { visitSuperCall(node, exprRoot, enclosingMemberDef); } else { compiler.report(JSError.make(node, CANNOT_CONVERT_YET, "Only calls to super or to a method of super are supported.")); } }</code><technical_language>isCallOrNewTarget() here? redundant previous if</technical_language>

Target:
private void visitSuper(Node node, Node parent) { Preconditions.checkState(node.isSuper()); Node exprRoot = node; if (exprRoot.getParent().isGetElem() || exprRoot.getParent().isGetProp()) { exprRoot = exprRoot.getParent(); } Node enclosingMemberDef = NodeUtil.getEnclosingNode( exprRoot, new Predicate<Node>() { @Override public boolean apply(Node n) { switch (n.getToken()) { case MEMBER_FUNCTION_DEF: case GETTER_DEF: case SETTER_DEF: return true; default: return false; } } }); if (parent.isCall()) { visitSuperCall(node, parent, enclosingMemberDef); } else if (parent.isGetProp()) { if (parent.getFirstChild() == node) { if (parent.getParent().isCall() && NodeUtil.isCallOrNewTarget(parent)) { visitSuperPropertyCall(node, parent, enclosingMemberDef); } else { compiler.report(JSError.make(node, CANNOT_CONVERT_YET, "Only calls to super or to a method of super are supported.")); } } else { compiler.report(JSError.make(node, CANNOT_CONVERT_YET, "Only calls to super or to a method of super are supported.")); } } else if (parent.isGetElem()) { compiler.report(JSError.make(node, CANNOT_CONVERT_YET, "Only calls to super or to a method of super are supported.")); } else if (parent.isNew()) { compiler.report(JSError.make(node, INVALID_SUPER_CALL)); } else { compiler.report(JSError.make(node, CANNOT_CONVERT_YET, "Only calls to super or to a method of super are supported.")); } }
Source:
<code>private List<NameServer> getNameServers(DnsResolverConfiguration dnsResolverConfiguration) { if (dnsResolverConfiguration == null) { return <START> Collections.EMPTY_LIST; <END> } List<NameServer> nameServers = dnsResolverConfiguration.getNameServers(); if (nameServers == null || nameServers.isEmpty()) { return Collections.EMPTY_LIST; } return nameServers; }</code><technical_language>pls Collections.emptyList() - is type safe. EMPTY_LIST is meant directly</technical_language>

Target:
private List<NameServer> getNameServers(DnsResolverConfiguration dnsResolverConfiguration) { if (dnsResolverConfiguration == null) { return Collections.emptyList(); } List<NameServer> nameServers = dnsResolverConfiguration.getNameServers(); if (nameServers == null || nameServers.isEmpty()) { return Collections.emptyList(); } return nameServers; }
Source:
<code>public void removeCache(CacheEntryRemovedEvent<ScopedState, CacheState> event) { String cacheName = event.getKey().getName(); <START> gcm.log.debugf("Remove cache %s", cacheName); <END> gcm.localRemoveCache(cacheName); }</code><technical_language>Do want a message for create well</technical_language>

Target:
public void removeCache(CacheEntryRemovedEvent<ScopedState, CacheState> event) { String cacheName = event.getKey().getName(); gcm.localRemoveCache(cacheName); }
Source:
<code>public AmazonS3 createS3Client(URI name, final String bucket, final AWSCredentialsProvider credentials, final String userAgentSuffix) throws IOException { Configuration conf = getConf(); final ClientConfiguration awsConf = S3AUtils .createAwsConf(conf, bucket, Constants.AWS_SERVICE_IDENTIFIER_S3); awsConf.setUseThrottleRetries( <START> conf.getBoolean(EXPERIMENTAL_AWS_INTERNAL_THROTTLING, true)); <END> if (!StringUtils.isEmpty(userAgentSuffix)) { awsConf.setUserAgentSuffix(userAgentSuffix); } return configureAmazonS3Client( newAmazonS3Client(credentials, awsConf), conf); }</code><technical_language>add a setting for set here</technical_language>

Target:
public AmazonS3 createS3Client(URI name, final String bucket, final AWSCredentialsProvider credentials, final String userAgentSuffix) throws IOException { Configuration conf = getConf(); final ClientConfiguration awsConf = S3AUtils .createAwsConf(conf, bucket, Constants.AWS_SERVICE_IDENTIFIER_S3); awsConf.setUseThrottleRetries( conf.getBoolean(EXPERIMENTAL_AWS_INTERNAL_THROTTLING, EXPERIMENTAL_AWS_INTERNAL_THROTTLING_DEFAULT)); if (!StringUtils.isEmpty(userAgentSuffix)) { awsConf.setUserAgentSuffix(userAgentSuffix); } return configureAmazonS3Client( newAmazonS3Client(credentials, awsConf), conf); }
Source:
<code>private RelDataType inferTypeFromOperands(SqlOperatorBinding opBinding) { final RelDataTypeFactory typeFactory = opBinding.getTypeFactory(); final List<RelDataType> argTypes = opBinding.collectOperandTypes(); assert (argTypes.size() % 2) == 1 : "odd number of arguments expected: " + argTypes.size(); assert argTypes.size() > 1 : "CASE must have more than 1 argument. Given " + argTypes.size() + ", " + argTypes; List<RelDataType> thenTypes = new ArrayList<>(); for (int j = 1; j < (argTypes.size() - 1); j += 2) { RelDataType argType = argTypes.get(j); if (opBinding instanceof RexCallBinding) { RexNode whenNode = ((RexCallBinding) opBinding).getOperands().get(j - 1); RexNode thenNode = ((RexCallBinding) opBinding).getOperands().get(j); if (whenNode.getKind() == SqlKind.IS_NOT_NULL && argType.isNullable()) { <START> if (((RexCall) whenNode).getOperands().get(0).equals(thenNode)) { <END> argType = typeFactory.createTypeWithNullability(argType, false); } } } thenTypes.add(argType); } thenTypes.add(Iterables.getLast(argTypes)); return typeFactory.leastRestrictive(thenTypes); }</code><technical_language>if put if condition out of loop</technical_language>

Target:
private RelDataType inferTypeFromOperands(SqlOperatorBinding opBinding) { final RelDataTypeFactory typeFactory = opBinding.getTypeFactory(); final List<RelDataType> argTypes = opBinding.collectOperandTypes(); assert (argTypes.size() % 2) == 1 : "odd number of arguments expected: " + argTypes.size(); assert argTypes.size() > 1 : "CASE must have more than 1 argument. Given " + argTypes.size() + ", " + argTypes; List<RelDataType> thenTypes = new ArrayList<>(); for (int j = 1; j < (argTypes.size() - 1); j += 2) { RelDataType argType = argTypes.get(j); if (opBinding instanceof RexCallBinding) { final RexCallBinding rexCallBinding = (RexCallBinding) opBinding; final RexNode whenNode = rexCallBinding.operands().get(j - 1); final RexNode thenNode = rexCallBinding.operands().get(j); if (whenNode.getKind() == SqlKind.IS_NOT_NULL && argType.isNullable()) { final RexCall isNotNullCall = (RexCall) whenNode; if (isNotNullCall.getOperands().get(0).equals(thenNode)) { argType = typeFactory.createTypeWithNullability(argType, false); } } } thenTypes.add(argType); } thenTypes.add(Iterables.getLast(argTypes)); return typeFactory.leastRestrictive(thenTypes); }
Source:
<code>public boolean shouldOverrideUrlLoading(WebView view, String url) { Uri responseUri = Uri.parse(url); String schema = responseUri.getScheme(); if (schema == null) { <START> throw new RuntimeException("Invalid schema could not be parsed: " + responseUri.toString()); <END> } String error = responseUri.getQueryParameter("error"); String errorDescription = responseUri.getQueryParameter("error_description"); final String authCode = responseUri.getQueryParameter("code"); if (error != null && !error.isEmpty()) { if (error.equalsIgnoreCase("access_denied") && errorDescription.equalsIgnoreCase("The user denied your request.")) { Toast.makeText(getApplicationContext(), "No credentials provided, failed to load secured resource", Toast.LENGTH_LONG).show(); mOAuthLoginDialog.dismiss(); return true; } } if (authCode != null && !authCode.isEmpty()) { OAuthTokenCredentialRequest request = new OAuthTokenCredentialRequest(mPortal, null, mClientId, mRedirectUri, authCode); final ListenableFuture<OAuthTokenCredential> future = request.executeAsync(); future.addDoneListener(new Runnable() { @Override public void run() { OAuthTokenCredential cred = null; try { cred = future.get(); } catch (Exception e) { } finally { finishOAuthChallenge(cred); } } }); return true; } return (false); }</code><technical_language>throw IllegalArgumentException instead of RuntimeException</technical_language>

Target:
public boolean shouldOverrideUrlLoading(WebView view, String url) { Uri responseUri = Uri.parse(url); String schema = responseUri.getScheme(); if (schema == null) { throw new IllegalArgumentException("Invalid schema could not be parsed: " + responseUri.toString()); } String error = responseUri.getQueryParameter("error"); String errorDescription = responseUri.getQueryParameter("error_description"); final String authCode = responseUri.getQueryParameter("code"); if (error != null && !error.isEmpty()) { if (error.equalsIgnoreCase("access_denied") && errorDescription.equalsIgnoreCase("The user denied your request.")) { Toast.makeText(getApplicationContext(), "No credentials provided, failed to load secured resource", Toast.LENGTH_LONG).show(); finishOAuthChallenge(null); mOAuthLoginDialog.dismiss(); return true; } } if (authCode != null && !authCode.isEmpty()) { OAuthTokenCredentialRequest request = new OAuthTokenCredentialRequest(mPortal, null, mClientId, mRedirectUri, authCode); final ListenableFuture<OAuthTokenCredential> future = request.executeAsync(); future.addDoneListener(new Runnable() { @Override public void run() { OAuthTokenCredential cred = null; try { cred = future.get(); } catch (Exception e) { } finally { finishOAuthChallenge(cred); } } }); return true; } return false; }
Source:
<code>public Path getTargetPath(URI uri) { String relativePath = MavenUrlDecoder.toLocalGradlePath(uri); Path fullPath = getRoot().resolve(relativePath); try { if (fullPath.getParent().toFile().exists()) { Optional<Path> actualPath = Files.list(fullPath.getParent()) <START> .filter(dir -> dir.toFile().isDirectory()) <END> .map(dir -> dir.resolve(fullPath.getFileName())) .filter(path -> path.toFile().exists()) .findAny(); return actualPath.orElse(fullPath); } return fullPath; } catch (IOException e) { throw new HumanReadableException("Failed to list folders in the directory", e); } }</code><technical_language>is hash accommodate case gradle cache versions of artifact present</technical_language>

Target:
public Path getTargetPath(URI uri) { String relativePath = MavenUrlDecoder.toLocalGradlePath(uri); Path fullPath = getRoot().resolve(relativePath); try { if (Files.exists(fullPath.getParent())) { try (Stream<Path> files = Files.list(fullPath.getParent())) { List<Path> actualPaths = files .filter(dir -> Files.isDirectory(dir)) .map(dir -> dir.resolve(fullPath.getFileName())) .filter(path -> Files.exists(path)) .collect(ImmutableList.toImmutableList()); if (actualPaths.size() == 1) { return actualPaths.get(0); } } } return fullPath; } catch (IOException e) { throw new HumanReadableException("Failed to list folders in the directory", e); } }
Source:
<code>public boolean hasRole(Wrapper wrapper, Principal principal, String role) { if (wrapper != null) { String realRole = wrapper.findSecurityReference(role); if (realRole != null) { role = realRole; } } if (getContainer() instanceof Context) { Context context = (Context) getContainer(); <START> String realRole = context.findRoleMapping(role); <END> if (realRole != null) { role = realRole; } } if (principal == null || role == null) { return false; } boolean result = hasRoleInternal(principal, role); if (log.isDebugEnabled()) { String name = principal.getName(); if (result) log.debug(sm.getString("realmBase.hasRoleSuccess", name, role)); else log.debug(sm.getString("realmBase.hasRoleFailure", name, role)); } return result; }</code><technical_language>code is Realm is defined Context level. is required here. role mappings need checked for current Context irrespective of Realm is defined. like: Context context = (Context) wrapper.getParent(); A similar change need UserDatabaseRealm potentially other sub-classes. Consider moving this Wrapper.findSecurityReference. i.e. Wrapper references if try Context</technical_language>

Target:
public boolean hasRole(Wrapper wrapper, Principal principal, String role) { if (wrapper != null) { String realRole = wrapper.findSecurityReference(role); if (realRole != null) { role = realRole; } } if (principal == null || role == null) { return false; } boolean result = hasRoleInternal(principal, role); if (log.isDebugEnabled()) { String name = principal.getName(); if (result) log.debug(sm.getString("realmBase.hasRoleSuccess", name, role)); else log.debug(sm.getString("realmBase.hasRoleFailure", name, role)); } return result; }
Source:
<code>public Writing(ConvertiblePair convertiblePair, Function<? super S, ? extends T> function) { <START> super(convertiblePair, function); <END> }</code><technical_language>Is public visibility modifier required</technical_language>

Target:
Writing(ConvertiblePair convertiblePair, Function<? super S, ? extends T> function) { super(convertiblePair, function); }
Source:
<code>private void removeChildren(Guid snapshot) { List<Guid> children = new ArrayList<>(); getImageChildren(snapshot, children); <START> children.stream().sorted(Collections.reverseOrder()).forEach(child -> diskImageDao.getSnapshotById(child)); <END> }</code><technical_language>I calling removeSnapshot</technical_language>

Target:
private void removeChildren(Guid snapshot) { List<Guid> children = new ArrayList<>(); getImageChildren(snapshot, children); children.stream().sorted(Collections.reverseOrder()).forEach(child -> removeSnapshot(diskImageDao.getSnapshotById(child))); }
Source:
<code>public void setCodeMiningProviders(ICodeMiningProvider[] codeMiningProviders) { <START> if (fCodeMiningProviders != null) { <END> for (ICodeMiningProvider contentMiningProvider : fCodeMiningProviders) { contentMiningProvider.dispose(); } } boolean enable= codeMiningProviders != null && codeMiningProviders.length > 0; fCodeMiningProviders= codeMiningProviders; if (fCodeMiningManager != null) { fCodeMiningManager.uninstall(); } fCodeMiningManager= null; if (enable) { ensureCodeMiningManagerInstalled(); } }</code><technical_language>null interpreted empty array</technical_language>

Target:
public void setCodeMiningProviders(ICodeMiningProvider[] codeMiningProviders) { boolean enable= codeMiningProviders != null && codeMiningProviders.length > 0; fCodeMiningProviders= codeMiningProviders; if (enable) { if (fCodeMiningManager != null) { fCodeMiningManager.setCodeMiningProviders(fCodeMiningProviders); } ensureCodeMiningManagerInstalled(); } else { if (fCodeMiningManager != null) { fCodeMiningManager.uninstall(); } fCodeMiningManager= null; } }
Source:
<code>public static @Nonnull JSONObject getBundle(@Nonnull String baseName, @Nonnull Locale locale) throws MissingResourceException { String bundleKey = baseName + ":" + locale.toString(); JSONObject bundleJSON = bundles.get(bundleKey); if (bundleJSON != null) { return bundleJSON; } ResourceBundle bundle = getBundle(baseName, locale, Jenkins.class.getClassLoader()); if (bundle == null) { <START> Jenkins jenkins = Jenkins.getInstanceOrNull(); <END> if (jenkins != null) { for (PluginWrapper plugin : jenkins.getPluginManager().getPlugins()) { bundle = getBundle(baseName, locale, plugin.classLoader); if (bundle != null) { break; } } } } if (bundle == null) { throw new MissingResourceException("Can't find bundle for base name " + baseName + ", locale " + locale, baseName + "_" + locale, ""); } bundleJSON = toJSONObject(bundle); bundles.put(bundleKey, bundleJSON); return bundleJSON; }</code><technical_language>Guard JenkinsJVM.isJenkinsJVM()</technical_language>

Target:
public static @Nonnull JSONObject getBundle(@Nonnull String baseName, @Nonnull Locale locale) throws MissingResourceException { String bundleKey = baseName + ":" + locale.toString(); JSONObject bundleJSON = bundles.get(bundleKey); if (bundleJSON != null) { return bundleJSON; } ResourceBundle bundle = getBundle(baseName, locale, ResourceBundleUtil.class.getClassLoader()); if (bundle == null && JenkinsJVM.isJenkinsJVM()) { for (PluginWrapper plugin : Jenkins.getInstance().getPluginManager().getPlugins()) { bundle = getBundle(baseName, locale, plugin.classLoader); if (bundle != null) { break; } } } if (bundle == null) { throw new MissingResourceException("Can't find bundle for base name " + baseName + ", locale " + locale, baseName + "_" + locale, ""); } bundleJSON = toJSONObject(bundle); bundles.put(bundleKey, bundleJSON); return bundleJSON; }
Source:
<code>public static <V> CompletableFuture<V> firstCompletedFuture(Iterable<? extends CompletionStage<? extends V>> futures) { requireNonNull(futures, "futures is null"); boolean hasFuture = false; CompletableFuture<V> future = new CompletableFuture<>(); for (CompletionStage<? extends V> stage : futures) { stage.whenComplete((value, exception) -> { if (exception != null) { future.completeExceptionally(exception); } else { future.complete(value); } }); hasFuture = true; } <START> checkArgument(hasFuture, "futures is empty"); <END> return future; }</code><technical_language>do checkArgument(!Iterables.isEmpty(futures), ...) top</technical_language>

Target:
public static <V> CompletableFuture<V> firstCompletedFuture(Iterable<? extends CompletionStage<? extends V>> futures) { requireNonNull(futures, "futures is null"); checkArgument(!isEmpty(futures), "futures is empty"); CompletableFuture<V> future = new CompletableFuture<>(); for (CompletionStage<? extends V> stage : futures) { stage.whenComplete((value, exception) -> { if (exception != null) { future.completeExceptionally(exception); } else { future.complete(value); } }); } return future; }
Source:
<code><START> private void assignUserDirOwnership(final String effectiveUser) throws IOException { <END> final ExecuteAsUser executeAsUser = new ExecuteAsUser( this.sysProps.getString(NATIVE_LIB_FOLDER)); final List<String> changeOwnershipCommand = Arrays .asList(CHOWN, effectiveUser + ":" + GROUP_NAME, getWorkingDirectory()); info("Change current working directory ownership to " + effectiveUser + ":" + GROUP_NAME + "."); final int result = executeAsUser.execute("root", changeOwnershipCommand); if (result != 0) { error("Failed to change current working directory ownership. Error code: " + Integer .toString(result)); } }</code><technical_language>ExecuteAsUser class for this. If is sitting in a package, pull azkaban-common this is precisely wrapper class created for</technical_language>

Target:
private void assignUserDirOwnership(final String effectiveUser) throws IOException { final ExecuteAsUser executeAsUser = new ExecuteAsUser( this.sysProps.getString(AZKABAN_SERVER_NATIVE_LIB_FOLDER)); final String groupName = this.sysProps.getString(AZKABAN_SERVER_GROUP_NAME, "azkaban"); final List<String> changeOwnershipCommand = Arrays .asList(CHOWN, effectiveUser + ":" + groupName, getWorkingDirectory()); info("Change current working directory ownership to " + effectiveUser + ":" + groupName + "."); final int result = executeAsUser.execute("root", changeOwnershipCommand); if (result != 0) { error("Failed to change current working directory ownership. Error code: " + Integer .toString(result)); } }
Source:
<code>private void buildList() { <START> mList = new ExpandableListView(mContext); <END> mList.setId(R.id.snackbar); setListAppearance(); mList.setAdapter(generateAdapter()); mTargetParent.addView(mList); hide(); }</code><technical_language>I advise inflating ExpandableListView a layout apply styling there, instead of hard-coding style values setListAppearance method. Then, get rid of Utils.getPixelFromDips() function too</technical_language>

Target:
private void buildList() { mList = new SnackBarListView(mContext); mList.setId(R.id.snackbar); setListAppearance(); adapter = new SnackBarListAdapter(mContext); mList.setAdapter(adapter); mTargetParent.addView(mList); if (mMessagesList.size() > 0) { show(); } else { hide(); } }
Source:
<code>private Collection<BlackboardArtifact> parseDownloadDictionary(Content dataSource, AbstractFile origFile, NSDictionary entry) throws TskCoreException { Collection<BlackboardArtifact> bbartifacts = new ArrayList<>(); String url = null; String path = null; Long time = null; Long pathID = null; FileManager fileManager = getCurrentCase().getServices().getFileManager(); NSString nsstring = (NSString) entry.get(PLIST_KEY_DOWNLOAD_URL); if (nsstring != null) { url = nsstring.toString(); } nsstring = (NSString) entry.get(PLIST_KEY_DOWNLOAD_PATH); if (nsstring != null) { path = nsstring.toString(); pathID = Util.findID(dataSource, path); } NSDate date = (NSDate) entry.get(PLIST_KEY_DOWNLOAD_DATE); if (date != null) { time = date.getDate().getTime(); } BlackboardArtifact bbart = origFile.newArtifact(BlackboardArtifact.ARTIFACT_TYPE.TSK_WEB_DOWNLOAD); bbart.addAttributes(this.createDownloadAttributes(path, pathID, url, time, NetworkUtils.extractDomain(url), getName())); bbartifacts.add(bbart); <START> for (AbstractFile downloadedFile : fileManager.findFiles(dataSource, FilenameUtils.getName(path), FilenameUtils.getPath(path))) { <END> BlackboardArtifact downloadSourceArt = downloadedFile.newArtifact(BlackboardArtifact.ARTIFACT_TYPE.TSK_DOWNLOAD_SOURCE); if (url != null) { downloadSourceArt.addAttribute(new BlackboardAttribute(BlackboardAttribute.ATTRIBUTE_TYPE.TSK_URL, RecentActivityExtracterModuleFactory.getModuleName(), url)); } bbartifacts.add(downloadSourceArt); break; } return bbartifacts; }</code><technical_language>Is this for browsers? please add this createDownloadAttributes instead of this function? I roll createXXXAttributes out extract subclasses</technical_language>

Target:
private Collection<BlackboardArtifact> parseDownloadDictionary(Content dataSource, AbstractFile origFile, NSDictionary entry) throws TskCoreException { Collection<BlackboardArtifact> bbartifacts = new ArrayList<>(); String url = null; String path = null; Long time = null; Long pathID = null; FileManager fileManager = getCurrentCase().getServices().getFileManager(); NSString nsstring = (NSString) entry.get(PLIST_KEY_DOWNLOAD_URL); if (nsstring != null) { url = nsstring.toString(); } nsstring = (NSString) entry.get(PLIST_KEY_DOWNLOAD_PATH); if (nsstring != null) { path = nsstring.toString(); pathID = Util.findID(dataSource, path); } NSDate date = (NSDate) entry.get(PLIST_KEY_DOWNLOAD_DATE); if (date != null) { time = date.getDate().getTime(); } BlackboardArtifact bbart = origFile.newArtifact(BlackboardArtifact.ARTIFACT_TYPE.TSK_WEB_DOWNLOAD); bbart.addAttributes(this.createDownloadAttributes(path, pathID, url, time, NetworkUtils.extractDomain(url), getName())); bbartifacts.add(bbart); for (AbstractFile downloadedFile : fileManager.findFiles(dataSource, FilenameUtils.getName(path), FilenameUtils.getPath(path))) { BlackboardArtifact downloadSourceArt = downloadedFile.newArtifact(BlackboardArtifact.ARTIFACT_TYPE.TSK_DOWNLOAD_SOURCE); downloadSourceArt.addAttributes(createDownloadSourceAttributes(url)); bbartifacts.add(downloadSourceArt); break; } return bbartifacts; }
Source:
<code>protected String getNodeSecret(String nodeName) throws Failure { computer = (SlaveComputer) Jenkins.getInstance().getComputer(nodeName); if (computer == null) { <START> throw new Failure("Slave trying to register for invalid node: " + nodeName); <END> } return computer.getJnlpMac(); }</code><technical_language>Agent (the rename is in progress - <LINK_0></technical_language>

Target:
protected String getNodeSecret(String nodeName) throws Failure { computer = (SlaveComputer) Jenkins.getInstance().getComputer(nodeName); if (computer == null) { throw new Failure("Agent trying to register for invalid node: " + nodeName); } return computer.getJnlpMac(); }
Source:
<code>public void testInstagramDetection() throws Exception { <START> <END> InputStream testFileStream = DatasiftTwitterActivitySerializerTest.class.getResourceAsStream("/instagram_datasift_json.txt"); Scanner scanner = new Scanner(testFileStream, "UTF-8").useDelimiter(newLinePattern); String line = null; while(scanner.hasNextLine()) { line = scanner.nextLine(); Datasift datasift = MAPPER.readValue(line, Datasift.class); assert(DatasiftEventClassifier.detectClass(datasift) == Instagram.class); assert(DatasiftEventClassifier.bestSerializer(datasift) instanceof DatasiftInstagramActivitySerializer); } }</code><technical_language>This pattern is repeated times, sense abstract out a utility function user pass in resource name get a Scanner object? if needed change encodings for some reason, painful</technical_language>

Target:
public void testInstagramDetection() throws Exception { Scanner scanner = StreamsScannerUtil.getInstance("/instagram_datasift_json.txt"); String line = null; while(scanner.hasNextLine()) { line = scanner.nextLine(); Datasift datasift = MAPPER.readValue(line, Datasift.class); assert(DatasiftEventClassifier.detectClass(datasift) == Instagram.class); assert(DatasiftEventClassifier.bestSerializer(datasift) instanceof DatasiftInstagramActivitySerializer); } }
Source:
<code>public void sendFile( String file1, String file2 ) throws Exception { log.debug(String.format("Sending: '%1$s' '%2$s", file1, file2)); _remoteFileName(file2); MessageDigest localDigest = MessageDigest.getInstance("MD5"); final InputStream in = new DigestInputStream( new FileInputStream(file1), localDigest ); PipedInputStream pin = new PipedInputStream(); final PipedOutputStream pout = new PipedOutputStream(pin); Thread t = new Thread( new Runnable() { public void run() { OutputStream out = null; try { out = new GZIPOutputStream(pout); byte b[] = new byte[8192]; int n; while ((n = in.read(b)) != -1) { out.write(b, 0, n); } } catch (IOException e) { <START> log.debug(e); <END> } finally { if (out != null) { try { out.close(); } catch (IOException e) { log.error(e); } } } } }, "SSHClient.compress " + file1 ); try { t.start(); ByteArrayOutputStream remoteDigest = new ConstraintByteArrayOutputStream(1024); executeCommand( String.format(COMMAND_FILE_SEND, "gunzip -q", file2), pin, new ConstraintByteArrayOutputStream(1024), remoteDigest ); t.join(1000); _validateDigest(localDigest, new String(remoteDigest.toByteArray(), "UTF-8").trim()); } catch(Exception e) { log.debug(e); throw e; } finally { t.interrupt(); try { in.close(); } catch(IOException e) { log.error(e); } } }</code><technical_language>If is error logged ERROR level, DEBUG is enough. A explanatory message help: log.error("Error while sending file ...", e);</technical_language>

Target:
public void sendFile( String file1, String file2 ) throws Exception { log.debug(String.format("Sending: '%1$s' '%2$s", file1, file2)); _remoteFileName(file2); MessageDigest localDigest = MessageDigest.getInstance("MD5"); final InputStream in = new DigestInputStream( new FileInputStream(file1), localDigest ); PipedInputStream pin = new PipedInputStream(STREAM_BUFFER_SIZE); final OutputStream pout = new PipedOutputStream(pin); Thread t = new Thread( new Runnable() { public void run() { OutputStream out = null; try { out = new GZIPOutputStream(pout); byte b[] = new byte[STREAM_BUFFER_SIZE]; int n; while ((n = in.read(b)) != -1) { out.write(b, 0, n); } } catch (IOException e) { log.debug("Exceution during stream processing", e); } finally { if (out != null) { try { out.close(); } catch (IOException e) { log.error("Cannot close stream", e); } } } } }, "SSHClient.compress " + file1 ); try { t.start(); ByteArrayOutputStream remoteDigest = new ConstraintByteArrayOutputStream(CONSTRAINT_BUFFER_SIZE); executeCommand( String.format(COMMAND_FILE_SEND, "gunzip -q", file2), pin, new ConstraintByteArrayOutputStream(CONSTRAINT_BUFFER_SIZE), remoteDigest ); t.join(THREAD_JOIN_WAIT_TIME); if (t.getState() != Thread.State.TERMINATED) { throw new IllegalStateException("Cannot stop SSH stream thead"); } _validateDigest(localDigest, new String(remoteDigest.toByteArray(), "UTF-8").trim()); } catch(Exception e) { log.debug("Send failed", e); throw e; } finally { t.interrupt(); try { in.close(); } catch(IOException e) { log.error("Cannot close stream", e); } } log.debug(String.format("Sent: '%1$s' '%2$s", file1, file2)); }
Source:
<code>public void unLoad(String scriptIdentifier) { HashMap<String, Object> objects = objectCache.remove(scriptIdentifier); if (objects != null) { Object hr = objects.get("AutomationManager"); if (hr != null) { <START> ScriptedAutomationManager handlerRegistry = (ScriptedAutomationManager) hr; <END> handlerRegistry.removeAll(); } } }</code><technical_language>pls correct variable name</technical_language>

Target:
public void unLoad(String scriptIdentifier) { HashMap<String, Object> objects = objectCache.remove(scriptIdentifier); if (objects != null) { Object hr = objects.get(AUTOMATION_MANAGER); if (hr != null) { ScriptedAutomationManager automationManager = (ScriptedAutomationManager) hr; automationManager.removeAll(); } } }
Source:
<code>public void doubleAllocateButton() { WPIFactory factory = injector.getInstance(WPIFactory.class); XXboxController controller = factory.getXboxController(0); <START> thrown.expect(RobotAssertionException.class); <END> controller.getXboxButton(XboxButton.A); controller.getXboxButton(XboxButton.A); }</code><technical_language>Is advantage this opposed annotation</technical_language>

Target:
public void doubleAllocateButton() { WPIFactory factory = injector.getInstance(WPIFactory.class); XXboxController controller = factory.getXboxController(0); controller.getXboxButton(XboxButton.A); controller.getXboxButton(XboxButton.A); }
Source:
<code>@Test public void getWithPathThenUrlThrows() { class Example { @GET Call<Object> method(@Path("hey") String hey, @Url Object url) { return null; } } try { <START> buildRequest(Example.class, "foo/bar"); <END> } catch (IllegalArgumentException e) { assertThat(e).hasMessage("@Path can only be used with relative url on @GET (parameter #1)\n" + " for method Example.method"); } }</code><technical_language>fail</technical_language>

Target:
@Test public void getWithPathThenUrlThrows() { class Example { @GET Call<Object> method(@Path("hey") String hey, @Url Object url) { return null; } } try { buildRequest(Example.class, "foo/bar"); fail(); } catch (IllegalArgumentException e) { assertThat(e).hasMessage("@Path can only be used with relative url on @GET (parameter #1)\n" + " for method Example.method"); } }
Source:
<code>public void onRenderPlayer(RenderPlayerEvent.Pre event) { EntityPlayer p = event.getEntityPlayer(); PlayerSwimData d = getData(p); updateSwimRenderAngles(p); <START> BlockPos bp = new BlockPos((int) p.posX, (int) p.posY + 2, (int) p.posZ); <END> boolean liquidAbove = p.world.getBlockState(bp).getMaterial().isLiquid(); if (p.isInWater()) { if(p.limbSwingAmount <= 0) { } if(p.onGround && !this.isPlayerWearingFlippers(p)) { }else { p.limbSwingAmount = 0.2f+(d.currentSwimSpeed/20); } }else { if(d.currentRotationPitch == 0f && d.currentRotationRoll == 0f) { return; } } GlStateManager.pushMatrix(); GlStateManager.translate(0, 1.5f, 0f); GlStateManager.rotate(d.currentRotationYaw, 0f, -1f, 0f); GlStateManager.rotate(d.currentRotationPitch, 1f, 0f, 0f); GlStateManager.rotate(d.currentRotationRoll, 0f, 0f, -1f); GlStateManager.translate(0, -1.5f, 0f); updateSwimDataAngles(p); clearPlayerRenderAngles(p); }</code><technical_language>do BlockPos bp = p.getPos().up(2)</technical_language>

Target:
public void onRenderPlayer(RenderPlayerEvent.Pre event) { EntityPlayer p = event.getEntityPlayer(); PlayerSwimData d = getData(p); updateSwimRenderAngles(p); if (p.isInWater()) { if (p.onGround && !this.isPlayerWearingFlippers(p)) { } else { p.limbSwingAmount = 0.2f + (d.currentSwimSpeed / 20); } } else { if (d.currentRotationPitch == 0f && d.currentRotationRoll == 0f) { return; } } GlStateManager.pushMatrix(); GlStateManager.translate(0, 1.5f, 0f); GlStateManager.rotate(d.currentRotationYaw, 0f, -1f, 0f); GlStateManager.rotate(d.currentRotationPitch, 1f, 0f, 0f); GlStateManager.rotate(d.currentRotationRoll, 0f, 0f, -1f); GlStateManager.translate(0, -1.5f, 0f); updateSwimDataAngles(p); clearPlayerRenderAngles(p); }
Source:
<code>public void revert(Project project) { synchronized (project) { <START> for (int i = _changes.size() - 1; i >= 0; i--){ <END> _changes.get(i).revert(project); } if (_updateRowContextDependencies) { project.update(); } } }</code><technical_language>Consider Guava's Lists.reverse here. for (Change change : Lists.reverse(_changes)) { Guava (very handy) convenience functions for use</technical_language>

Target:
public void revert(Project project) { synchronized (project) { for (Change change : Lists.reverse(_changes)){ change.revert(project); } if (_updateRowContextDependencies) { project.update(); } } }
Source:
<code>public void addTree(byte[] pathPrefix, int stage, ObjectReader reader, AnyObjectId tree) throws IOException { CanonicalTreeParser p = readTree(pathPrefix, reader, tree); while (!p.eof()) { if (isTree(p)) { p = enterTree(p, reader); continue; } DirCacheEntry first = toEntry(stage, p); beforeAdd(first); fastAdd(first); p = p.next(); break; } while (!p.eof()) { if (isTree(p)) { p = enterTree(p, reader); } else { <START> fastAdd(toEntry(stage, p)); <END> p = p.next(); } } }</code><technical_language>is safe do beforeAdd validation here</technical_language>

Target:
public void addTree(byte[] pathPrefix, int stage, ObjectReader reader, AnyObjectId tree) throws IOException { CanonicalTreeParser p = createTreeParser(pathPrefix, reader, tree); while (!p.eof()) { if (isTree(p)) { p = enterTree(p, reader); continue; } DirCacheEntry first = toEntry(stage, p); beforeAdd(first); fastAdd(first); p = p.next(); break; } while (!p.eof()) { if (isTree(p)) { p = enterTree(p, reader); } else { fastAdd(toEntry(stage, p)); p = p.next(); } } }
Source:
<code>public void run() throws Exception { WebResource webResource = getClient().resource(endpoint + "/v1/version"); <START> ClientResponse clientResponse = webResource.accept(MediaType.APPLICATION_JSON).get(ClientResponse.class); <END> String jsonResponse = clientResponse.getEntity(String.class); String version = getJsonParser().readValue(jsonResponse,String.class); getOut().println("Brooklyn version: "+version); }</code><technical_language>check response code</technical_language>

Target:
public void run() throws Exception { WebResource webResource = getClient().resource(endpoint + "/v1/version"); ClientResponse clientResponse = webResource.accept(MediaType.APPLICATION_JSON).get(ClientResponse.class); if (clientResponse.getStatus() != Response.Status.OK.getStatusCode()) { String err = getErrorMessage(clientResponse); throw new CommandExecutionException(err); } String jsonResponse = clientResponse.getEntity(String.class); String version = getJsonParser().readValue(jsonResponse,String.class); getOut().println("Brooklyn version: "+version); }
Source:
<code>protected String getSqlType(SinkRecordField field) { if (field.schemaName() != null) { switch (field.schemaName()) { case Decimal.LOGICAL_NAME: return "DOUBLE"; case Date.LOGICAL_NAME: return "TIMESTAMP"; case Time.LOGICAL_NAME: return "TIMESTAMP"; case Timestamp.LOGICAL_NAME: return "TIMESTAMP"; default: } } switch (field.schemaType()) { case INT8: return "INTEGER"; case INT16: return "INTEGER"; case INT32: return "INTEGER"; case INT64: return "INTEGER"; case FLOAT32: return "FLOAT"; case FLOAT64: return "FLOAT"; case BOOLEAN: return "BOOLEAN"; case STRING: return "VARCHAR"; case BYTES: <START> return "BYTE"; <END> default: return super.getSqlType(field); } }</code><technical_language>concerned this mapping. CrateDB's BYTE type corresponds a single byte, JDBC BYTES type corresponds array of bytes</technical_language>

Target:
protected String getSqlType(SinkRecordField field) { if (field.schemaName() != null) { switch (field.schemaName()) { case Decimal.LOGICAL_NAME: return "DOUBLE"; case Date.LOGICAL_NAME: return "TIMESTAMP"; case Time.LOGICAL_NAME: return "TIMESTAMP"; case Timestamp.LOGICAL_NAME: return "TIMESTAMP"; default: } } switch (field.schemaType()) { case INT8: return "BYTE"; case INT16: return "SHORT"; case INT32: return "INTEGER"; case INT64: return "LONG"; case FLOAT32: return "FLOAT"; case FLOAT64: return "DOUBLE"; case BOOLEAN: return "BOOLEAN"; case STRING: return "STRING"; case BYTES: return "BYTE"; default: return super.getSqlType(field); } }
Source:
<code>private static void processFailLoadAndGc() throws TestFailed { try { BrokenDexLoader loader; loader = new BrokenDexLoader(ClassLoader.getSystemClassLoader()); loader.findBrokenClass(); System.out.println("ERROR: Inaccessible was accessible"); } catch (InvocationTargetException ite) { Throwable cause = ite.getCause(); if (cause instanceof NullPointerException) { System.out.println("Got expected ITE/NPE"); } else { System.out.println("Got unexpected ITE"); <START> ite.printStackTrace(); <END> } } }</code><technical_language>This is printing System.err OK test is failing in this code path anyway</technical_language>

Target:
private static void processFailLoadAndGc() throws TestFailed { try { BrokenDexLoader loader; loader = new BrokenDexLoader(ClassLoader.getSystemClassLoader()); loader.findBrokenClass(); System.out.println("ERROR: Inaccessible was accessible"); } catch (InvocationTargetException ite) { Throwable cause = ite.getCause(); if (cause instanceof NullPointerException) { System.out.println("Got expected ITE/NPE"); } else { System.out.println("Got unexpected ITE"); ite.printStackTrace(System.out); } } }
Source:
<code>public AsyncFuture<Void> start() { final ResolvableFuture<Void> future = async.future(); final ServerBootstrap s = new ServerBootstrap(); s.channel(NioServerSocketChannel.class); s.group(boss, worker); s.childHandler(new ChannelInitializer<Channel>() { @Override protected void initChannel(final Channel ch) { connected.add(ch); log.info("Connected {}", ch); <START> ch.closeFuture().addListener((ChannelFutureListener) future1 -> { <END> connected.remove(ch); log.info("Disconnected {}", ch); }); } }); s.bind(localAddress).addListener((ChannelFutureListener) f -> { if (!f.isSuccess()) { future.fail(f.cause()); return; } log.info("Bound to {}", localAddress); if (!server.compareAndSet(null, f.channel())) { f.channel().close(); future.fail(new IllegalStateException("server already started")); return; } future.resolve(null); }); return future; }</code><technical_language>call this f future? f below</technical_language>

Target:
public AsyncFuture<Void> start() { final ResolvableFuture<Void> future = async.future(); final ServerBootstrap s = new ServerBootstrap(); s.channel(NioServerSocketChannel.class); s.group(boss, worker); s.childHandler(new ChannelInitializer<Channel>() { @Override protected void initChannel(final Channel ch) { connected.add(ch); log.info("Connected {}", ch); ch.closeFuture().addListener((ChannelFutureListener) f -> { connected.remove(ch); log.info("Disconnected {}", ch); }); } }); s.bind(localAddress).addListener((ChannelFutureListener) f -> { if (!f.isSuccess()) { future.fail(f.cause()); return; } log.info("Bound to {}", localAddress); if (!server.compareAndSet(null, f.channel())) { f.channel().close(); future.fail(new IllegalStateException("server already started")); return; } future.resolve(null); }); return future; }