auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>private void guaranteeHasAllSubnets(Collection<String> subnetIds, LoadBalancer loadBalancer) { Collection<String> subnetsOnLoadBalancer = getSubnetsFromLoadBalancer(loadBalancer); Collection<String> subnetsToAdd = new HashSet<>(); for (String subnetId : subnetIds) { if (! subnetsOnLoadBalancer.contains(subnetId)) { subnetsToAdd.add(subnetId); } } try { <START> SetSubnetsRequest subnetsRequest = new SetSubnetsRequest() <END> .withLoadBalancerArn(loadBalancer.getLoadBalancerArn()) .withSubnets(subnetsToAdd); elbClient.setSubnets(subnetsRequest); } catch (AmazonClientException acexn) { LOG.error("Could not attach subnets to load balancer due to error", subnetsToAdd, loadBalancer.getLoadBalancerName(), acexn); exceptionNotifier.notify(acexn, ImmutableMap.of( "elb", loadBalancer.getLoadBalancerName(), "subnets", subnetsToAdd.toString())); } }</code><technical_language>SetSubnets override current ones? If want this list includes currently active removing needed (i.e. subnetsOnLoadBalancer + subnetIds here)</technical_language>

Target:
private void guaranteeHasAllSubnets(Collection<String> subnetIds, LoadBalancer loadBalancer) { Collection<String> subnetsOnLoadBalancer = getSubnetsFromLoadBalancer(loadBalancer); Set<String> subnetsToAdd = new HashSet<>(); for (String subnetId : subnetIds) { if (! subnetsOnLoadBalancer.contains(subnetId)) { subnetsToAdd.add(subnetId); } } subnetsToAdd = Sets.union(new HashSet<>(subnetsOnLoadBalancer), subnetsToAdd); try { SetSubnetsRequest subnetsRequest = new SetSubnetsRequest() .withLoadBalancerArn(loadBalancer.getLoadBalancerArn()) .withSubnets(subnetsToAdd); elbClient.setSubnets(subnetsRequest); } catch (AmazonClientException acexn) { LOG.error("Could not attach subnets to load balancer due to error", subnetsToAdd, loadBalancer.getLoadBalancerName(), acexn); exceptionNotifier.notify(acexn, ImmutableMap.of( "elb", loadBalancer.getLoadBalancerName(), "subnets", subnetsToAdd.toString())); } }
Source:
<code>public Mono<AccessToken> getToken(TokenRequestContext request) { final StringBuilder errorMsg = new StringBuilder(); <START> return Flux.fromIterable(credentials).flatMap(p -> p.getToken(request).onErrorResume(t -> { <END> if (t.getMessage() != null && !t.getMessage().contains("authentication unavailable")) { throw new RuntimeException(UnavailableError+p.getClass().getSimpleName()+"authentication failed.",t); } errorMsg.append(" ").append(t.getMessage()); return Mono.empty(); }), 1) .next() .switchIfEmpty(Mono.defer(() -> Mono.error(new RuntimeException(FailedError+errorMsg.toString()+" )")))); }</code><technical_language>code indentation needs fixed</technical_language>

Target:
public Mono<AccessToken> getToken(TokenRequestContext request) { List<CredentialUnavailableException> exceptions = new ArrayList<>(4); return Flux.fromIterable(credentials) .flatMap(p -> p.getToken(request).onErrorResume(Exception.class, t -> { if (!t.getClass().getSimpleName().equals("CredentialUnavailableException")) { return Mono.error(new ClientAuthenticationException( unavailableError + p.getClass().getSimpleName() + " authentication failed. Error Details: " + t.getMessage(), null, t)); } exceptions.add((CredentialUnavailableException) t); return Mono.empty(); }), 1) .next() .switchIfEmpty(Mono.defer(() -> { CredentialUnavailableException last = exceptions.get(exceptions.size() - 1); for (int z = exceptions.size() - 2; z >= 0; z--) { CredentialUnavailableException current = exceptions.get(z); last = new CredentialUnavailableException(current.getMessage() + "\r\n" + last.getMessage(), last.getCause()); } return Mono.error(last); })); }
Source:
<code>public Task execute(Context cntxt) { TaskContext context = (TaskContext) cntxt; Task task = context.getTaskQueryService().getTaskInstanceById(taskId); if (task == null) { throw new IllegalStateException("Unable to find task with id " + taskId); } if (!isPotentialOwner(userId, task, context)) { <START> throw new PermissionDeniedException("User " + userId + " isn't allowed to see thask " + taskId); <END> } return task; }</code><technical_language>type - "thask"</technical_language>

Target:
public Task execute(Context cntxt) { TaskContext context = (TaskContext) cntxt; Task task = context.getTaskQueryService().getTaskInstanceById(taskId); if (task == null) { throw new IllegalStateException("Unable to find task with id " + taskId); } if (!checkUserPermissions(userId, task, context)) { throw new PermissionDeniedException("User " + userId + " isn't allowed to see the task " + taskId); } return task; }
Source:
<code>synchronized PgPool getPool() { PgPool ret = pool.get(); if(ret == null) { <START> ret = pgClientFactory.sqlClient(4); <END> pool.set(ret); } return ret; }</code><technical_language>nice for 4 a constant for readability</technical_language>

Target:
synchronized PgPool getPool() { PgPool ret = pool.get(); if(ret == null) { ret = pgClientFactory.sqlClient(POOL_SIZE); pool.set(ret); } return ret; }
Source:
<code>public void isToSkip() { FactMapping otherFactMapping = new FactMapping(FactIdentifier.DESCRIPTION, ExpressionIdentifier.create("value", FactMappingType.OTHER)); assertTrue(AbstractScenarioValidation.isToSkip(otherFactMapping)); FactMapping descriptionFactMapping = new FactMapping(FactIdentifier.DESCRIPTION, ExpressionIdentifier.create("value", FactMappingType.OTHER)); assertTrue(AbstractScenarioValidation.isToSkip(descriptionFactMapping)); FactMapping emptyFactMapping = new FactMapping(FactIdentifier.EMPTY, ExpressionIdentifier.create("value", FactMappingType.GIVEN)); assertTrue(AbstractScenarioValidation.isToSkip(emptyFactMapping)); FactMapping expressionFactMapping = new FactMapping(FactIdentifier.create("myType", "anyClass"), <START> ExpressionIdentifier.create("expression", FactMappingType.GIVEN)); <END> assertTrue(AbstractScenarioValidation.isToSkip(expressionFactMapping)); }</code><technical_language>@yesamer Please replace this "expression" a global static constant, choose actual string serialized stuff (xml/json) change</technical_language>

Target:
public void isToSkip() { FactMapping otherFactMapping = new FactMapping(FactIdentifier.INDEX, ExpressionIdentifier.create("value", FactMappingType.OTHER)); assertTrue(AbstractScenarioValidation.isToSkip(otherFactMapping)); FactMapping descriptionFactMapping = new FactMapping(FactIdentifier.DESCRIPTION, ExpressionIdentifier.create("value", FactMappingType.OTHER)); assertTrue(AbstractScenarioValidation.isToSkip(descriptionFactMapping)); FactMapping emptyFactMapping = new FactMapping(FactIdentifier.EMPTY, ExpressionIdentifier.create("value", FactMappingType.GIVEN)); assertTrue(AbstractScenarioValidation.isToSkip(emptyFactMapping)); FactMapping expressionFactMapping = new FactMapping(FactIdentifier.create("myType", "anyClass"), ExpressionIdentifier.create(ConstantsHolder.EXPRESSION_CLASSNAME, FactMappingType.GIVEN)); assertTrue(AbstractScenarioValidation.isToSkip(expressionFactMapping)); FactMapping simpleTypeFactMapping = new FactMapping(FactIdentifier.create("mySimpleType", "com.mySimpleType"), ExpressionIdentifier.create("value", FactMappingType.GIVEN)); assertTrue(AbstractScenarioValidation.isToSkip(simpleTypeFactMapping)); FactMapping complexTypeFactMapping = new FactMapping(FactIdentifier.create("myComplexType", "com.myComplexType"), ExpressionIdentifier.create("value", FactMappingType.GIVEN)); complexTypeFactMapping.addExpressionElement("name", "com.lang.String"); assertFalse(AbstractScenarioValidation.isToSkip(complexTypeFactMapping)); }
Source:
<code>public void deleteStoreFiles() throws StoreException, IOException { if (started) { throw new IllegalStateException("Store is still started. Deleting store files is not allowed."); } String[] swapSegmentsInUse = compactor.getSwapSegmentsInUse(); if (swapSegmentsInUse.length > 0) { for (String fileName : swapSegmentsInUse) { <START> logger.trace("Returning swap segment to reserve pool", fileName); <END> File swapSegmentTempFile = new File(dataDir, fileName); diskSpaceAllocator.free(swapSegmentTempFile, config.storeSegmentSizeInBytes, storeId, true); } } logger.info("Deleting store directory", storeId); File storeDir = new File(dataDir); try { Files.walk(storeDir.toPath()).sorted(Comparator.reverseOrder()).map(Path::toFile).forEach(File::delete); } catch (Exception e) { throw new IOException("Couldn't delete store directory " + dataDir); } logger.info("All files of store deleted", storeId); }</code><technical_language>log this info level is rare</technical_language>

Target:
public void deleteStoreFiles() throws StoreException, IOException { if (started) { throw new IllegalStateException("Store is still started. Deleting store files is not allowed."); } String[] swapSegmentsInUse = compactor.getSwapSegmentsInUse(); for (String fileName : swapSegmentsInUse) { logger.info("Returning swap segment to reserve pool", fileName); File swapSegmentTempFile = new File(dataDir, fileName); diskSpaceAllocator.free(swapSegmentTempFile, config.storeSegmentSizeInBytes, storeId, true); } logger.info("Deleting store directory", storeId); File storeDir = new File(dataDir); try { Utils.deleteFileOrDirectory(storeDir); } catch (Exception e) { throw new IOException("Couldn't delete store directory " + dataDir, e); } logger.info("All files of store deleted", storeId); }
Source:
<code>public Map<Capability, CapReqBuilder> from(Resource bundle) { Map<Capability, CapReqBuilder> mapping = new HashMap<>(); addRequirements(bundle.getRequirements(null)); for (Capability c : bundle.getCapabilities(null)) { CapReqBuilder clone = CapReqBuilder.clone(c); <START> addCapability0(clone); <END> mapping.put(c, clone); } return mapping; }</code><technical_language>This change is source compatible</technical_language>

Target:
public Map<Capability, Capability> from(Resource bundle) { Map<Capability, Capability> mapping = new HashMap<>(); addRequirements(bundle.getRequirements(null)); for (Capability c : bundle.getCapabilities(null)) { CapReqBuilder clone = CapReqBuilder.clone(c); Capability addedCapability = addCapability0(clone); mapping.put(c, addedCapability); } return mapping; }
Source:
<code>public void setUp() throws NoSuchFieldException, NoSuchMethodException { configMap = new HashMap<>(); configMap.put("job.name", "test-job"); configMap.put("job.coordinator.system", "kafka"); configMap.put("task.inputs", "kafka.topic1"); configMap.put("systems.kafka.samza.factory", "org.apache.samza.system.MockSystemFactory"); configMap.put("samza.cluster-manager.factory", "org.apache.samza.clustermanager.MockClusterResourceManagerFactory"); MockSystemFactory.MSG_QUEUES.put(new SystemStreamPartition("kafka", "topic1", new Partition(0)), new ArrayList<>()); this.monitorField = ClusterBasedJobCoordinator.class.getDeclaredField("partitionMonitor"); this.monitorField.setAccessible(true); this.appStateField = ClusterBasedJobCoordinator.class.getDeclaredField("state"); this.appStateField.setAccessible(true); <START> this.updatePartitionCountMethod = StreamPartitionCountMonitor.class.getDeclaredMethod("updatePartitionCountMetric"); <END> this.updatePartitionCountMethod.setAccessible(true); }</code><technical_language>Minor: FWIW, personally a huge fan of setting methods / fields accessible Reflection in tests A couple of ways get this: (in decreasing order of preference) - ClusterBasedJC implement StreamPartitionMonitor.Callback - invoke callback method, assert sets status right? === - Alternately, a StreamPartitionCountMonitor in constructor of ClusterBasedJC class, JC invoke a setter StreamPartitionCountMonitor register callback. - inject a mock StreamPartitionCountMonitor invoke registered callback. think</technical_language>

Target:
public void setUp() throws NoSuchFieldException, NoSuchMethodException { configMap = new HashMap<>(); configMap.put("job.name", "test-job"); configMap.put("job.coordinator.system", "kafka"); configMap.put("task.inputs", "kafka.topic1"); configMap.put("systems.kafka.samza.factory", "org.apache.samza.system.MockSystemFactory"); configMap.put("samza.cluster-manager.factory", "org.apache.samza.clustermanager.MockClusterResourceManagerFactory"); configMap.put("job.coordinator.monitor-partition-change.frequency.ms", "1"); MockSystemFactory.MSG_QUEUES.put(new SystemStreamPartition("kafka", "topic1", new Partition(0)), new ArrayList<>()); }
Source:
<code>private void testFailureCases() { <START> FeedbackResponseCommentAttributes feedbackResponseComment = getCommentFromInstructor1(); <END> assertNotNull("response comment not found", feedbackResponseComment); InstructorAttributes instructor = dataBundle.instructors.get("instructor1InCourse1"); gaeSimulation.loginAsInstructor(instructor.googleId); ______TS("Unsuccessful case: not enough parameters"); verifyAssumptionFailure(); String[] submissionParams = new String[] { Const.ParamsNames.COURSE_ID, feedbackResponseComment.courseId, Const.ParamsNames.FEEDBACK_SESSION_NAME, feedbackResponseComment.feedbackSessionName, Const.ParamsNames.FEEDBACK_RESPONSE_COMMENT_TEXT, "Comment to first response", Const.ParamsNames.USER_ID, instructor.googleId }; verifyAssumptionFailure(submissionParams); ______TS("Non-existent feedback response comment: fails silently"); submissionParams = new String[] { Const.ParamsNames.COURSE_ID, feedbackResponseComment.courseId, Const.ParamsNames.FEEDBACK_SESSION_NAME, feedbackResponseComment.feedbackSessionName, Const.ParamsNames.FEEDBACK_RESPONSE_ID, feedbackResponseComment.feedbackResponseId, Const.ParamsNames.FEEDBACK_RESPONSE_COMMENT_ID, "123123123123123", }; AjaxResult result = getAjaxResult(getAction(submissionParams)); FeedbackResponseCommentAjaxPageData data = (FeedbackResponseCommentAjaxPageData) result.data; assertFalse(data.isError); assertEquals("", result.getStatusMessage()); }</code><technical_language>separate @Test methods big @Test. do independent. I remember, order of tests guaranteed order listed in file; means tests able run in order</technical_language>

Target:
public void testFailureCases() { FeedbackResponseCommentAttributes feedbackResponseComment = getCommentFromInstructor1AsFeedbackParticipant(); assertNotNull("response comment not found", feedbackResponseComment); InstructorAttributes instructor = dataBundle.instructors.get("instructor1InCourse1"); gaeSimulation.loginAsInstructor(instructor.googleId); ______TS("Unsuccessful case: not enough parameters"); String[] submissionParams = new String[] { Const.ParamsNames.COURSE_ID, feedbackResponseComment.courseId, Const.ParamsNames.FEEDBACK_SESSION_NAME, feedbackResponseComment.feedbackSessionName, }; verifyAssumptionFailure(); verifyAssumptionFailure(submissionParams); ______TS("Non-existent feedback response comment: fails silently"); submissionParams = new String[] { Const.ParamsNames.COURSE_ID, feedbackResponseComment.courseId, Const.ParamsNames.FEEDBACK_SESSION_NAME, feedbackResponseComment.feedbackSessionName, Const.ParamsNames.FEEDBACK_RESPONSE_ID, feedbackResponseComment.feedbackResponseId, Const.ParamsNames.FEEDBACK_RESPONSE_COMMENT_ID, "123123123123123", }; AjaxResult result = getAjaxResult(getAction(submissionParams)); FeedbackResponseCommentAjaxPageData data = (FeedbackResponseCommentAjaxPageData) result.data; assertFalse(data.isError); assertEquals("", result.getStatusMessage()); }
Source:
<code>public void onReceive(final Context context, final Intent intent) { final Intent redirect; Log.i(LOGTAG, "Got intent " + intent.getAction()); if (intent.getAction().equals(ACTION_LAUNCH_BROWSER)) { redirect = buildRedirectIntent(Intent.ACTION_MAIN, AppConstants.ANDROID_PACKAGE_NAME, AppConstants.BROWSER_INTENT_CLASS_NAME, intent); Telemetry.sendUIEvent(TelemetryContract.Event.LAUNCH, TelemetryContract.Method.WIDGET, "launch-browser"); } else if (intent.getAction().equals(ACTION_LAUNCH_NEW_TAB)) { redirect = buildRedirectIntent(Intent.ACTION_VIEW, AppConstants.ANDROID_PACKAGE_NAME, AppConstants.BROWSER_INTENT_CLASS_NAME, intent); Telemetry.sendUIEvent(TelemetryContract.Event.LAUNCH, TelemetryContract.Method.WIDGET, "launch-new-tab"); } else if (intent.getAction().equals(ACTION_LAUNCH_SEARCH)) { redirect = buildRedirectIntent(Intent.ACTION_VIEW, AppConstants.SEARCH_PACKAGE_NAME, AppConstants.SEARCH_INTENT_CLASS_NAME, intent); <START> Telemetry.sendUIEvent(TelemetryContract.Event.SEARCH, <END> TelemetryContract.Method.WIDGET, "launch-search"); } else { redirect = null; } if (redirect != null) { try { context.startActivity(redirect); } catch(Exception ex) { Intent redirect2 = buildRedirectIntent(Intent.ACTION_VIEW, null, null, intent); context.startActivity(redirect2); } } super.onReceive(context, intent); }</code><technical_language>I this a LAUNCH event, launching search activity. reserve SEARCH event for user performing a search. I remove "launch-" prefix extras, LAUNCH events</technical_language>

Target:
public void onReceive(final Context context, final Intent intent) { final Intent redirect; Log.i(LOGTAG, "Got intent " + intent.getAction()); if (intent.getAction().equals(ACTION_LAUNCH_BROWSER)) { redirect = buildRedirectIntent(Intent.ACTION_MAIN, AppConstants.ANDROID_PACKAGE_NAME, AppConstants.BROWSER_INTENT_CLASS_NAME, intent); Telemetry.sendUIEvent(TelemetryContract.Event.LAUNCH, TelemetryContract.Method.WIDGET, "browser"); } else if (intent.getAction().equals(ACTION_LAUNCH_NEW_TAB)) { redirect = buildRedirectIntent(Intent.ACTION_VIEW, AppConstants.ANDROID_PACKAGE_NAME, AppConstants.BROWSER_INTENT_CLASS_NAME, intent); Telemetry.sendUIEvent(TelemetryContract.Event.LAUNCH, TelemetryContract.Method.WIDGET, "new-tab"); } else if (intent.getAction().equals(ACTION_LAUNCH_SEARCH)) { redirect = buildRedirectIntent(Intent.ACTION_VIEW, AppConstants.SEARCH_PACKAGE_NAME, AppConstants.SEARCH_INTENT_CLASS_NAME, intent); Telemetry.sendUIEvent(TelemetryContract.Event.LAUNCH, TelemetryContract.Method.WIDGET, "search"); } else { redirect = null; } if (redirect != null) { try { context.startActivity(redirect); } catch(Exception ex) { Intent redirect2 = buildRedirectIntent(Intent.ACTION_VIEW, null, null, intent); context.startActivity(redirect2); } } super.onReceive(context, intent); }
Source:
<code>protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); initWhatsNew(); <START> configureDrawer(); <END> }</code><technical_language>configuring drawer in this activity. This activity it</technical_language>

Target:
protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); initWhatsNew(); addClickListenerOnProfileButton(); }
Source:
<code>private int compareTo( ServerVersion o ) { if ( !product.equals( o.product ) ) { <START> throw new IllegalArgumentException("Comparing different products"); <END> } int c = compare( major, o.major ); if (c == 0) { c = compare( minor, o.minor ); if (c == 0) { c = compare( patch, o.patch ); } } return c; }</code><technical_language>nice include product names in error message</technical_language>

Target:
private int compareTo( ServerVersion o ) { if ( !product.equals( o.product ) ) { throw new IllegalArgumentException( "Comparing different products '" + product + "' with '" + o.product + "'" ); } int c = compare( major, o.major ); if (c == 0) { c = compare( minor, o.minor ); if (c == 0) { c = compare( patch, o.patch ); } } return c; }
Source:
<code>public static List<ItemStack> modifyLoot(List<ItemStack> list, LootContext context) { LootModifierManager man = LootModifierManager.getInstance(); <START> for(IGlobalLootModifier mod : man.getAllLootMods()) { <END> list = mod.apply(list, context); } return list; }</code><technical_language>This address re-processing new list entries added modifiers. re-running a smelting modifier modifier converts gravel sand. Is want care all</technical_language>

Target:
public static List<ItemStack> modifyLoot(List<ItemStack> list, LootContext context) { LootModifierManager man = context.getWorld().getServer().getLootModifierManager(); for(IGlobalLootModifier mod : man.getAllLootMods()) { list = mod.apply(list, context); } return list; }
Source:
<code>public Tenor visitCouponIborAverageDefinition(CouponIborAverageIndexDefinition payment) { <START> return null; <END> }</code><technical_language>discussed, return empty collection instead of null</technical_language>

Target:
public Set<Tenor> visitCouponIborAverageDefinition(CouponIborAverageIndexDefinition payment) { return Sets.newHashSet(Tenor.of(payment.getIndex1().getTenor()), Tenor.of(payment.getIndex2().getTenor())); }
Source:
<code>public void mergeInventory(final List<Trackable> newTrackables) { if (inventory != null) { for (final Iterator<Trackable> iterator = inventory.iterator(); iterator.hasNext(); ) { final Trackable trackable = iterator.next(); <START> Boolean removeTrackable = true; <END> Boolean hasBrand = false; for (final Trackable newTrackable : newTrackables) { if (trackable.getBrand() == newTrackable.getBrand()) { hasBrand = true; if (trackable.getUniqueID().equals(newTrackable.getUniqueID())) { removeTrackable = false; break; } } } if (hasBrand && removeTrackable) { iterator.remove(); } } } for (final Trackable newTrackable : newTrackables) { addInventoryItem(newTrackable); } inventoryItems = inventory != null ? inventory.size() : 0; }</code><technical_language>2 lines</technical_language>

Target:
public void mergeInventory(final List<Trackable> newTrackables) { if (inventory != null) { final Iterator<Trackable> iterator = inventory.iterator(); while (iterator.hasNext()) { final Trackable trackable = iterator.next(); Boolean removeTrackable = true; Boolean hasBrand = false; for (final Trackable newTrackable : newTrackables) { if (trackable.getBrand() == newTrackable.getBrand()) { hasBrand = true; if (trackable.getUniqueID().equals(newTrackable.getUniqueID())) { removeTrackable = false; break; } } } if (hasBrand && removeTrackable) { iterator.remove(); } } } for (final Trackable newTrackable : newTrackables) { addInventoryItem(newTrackable); } inventoryItems = CollectionUtils.size(inventory); }
Source:
<code>public Map<Cell, byte[]> get(TableReference tableRef, Set<Cell> cells) { try { return super.getAsync(tableRef, cells).get(); } catch (InterruptedException | ExecutionException e) { <START> throw Throwables.rewrapAndThrowUncheckedException(e.getCause()); <END> } }</code><technical_language>If e is InterruptedException want throw e.getCause(), I in case want throw e. if rewrapping reset interruption flag (whereas throwing e work there)</technical_language>

Target:
public Map<Cell, byte[]> get(TableReference tableRef, Set<Cell> cells) { try { return super.getAsync(tableRef, cells).get(); } catch (InterruptedException e) { throw Throwables.rewrapAndThrowUncheckedException(e); } catch (ExecutionException e) { throw Throwables.rewrapAndThrowUncheckedException(e.getCause()); } }
Source:
<code>public static Dictionary<String, Object> configureMetacardValidityFilterPlugin( <START> List<String> securityAttributeMappings, <END> boolean filterErrors, boolean filterWarnings, AdminConfig configAdmin) throws IOException { Dictionary<String, Object> properties = new DictionaryMap<>(); properties.put("attributeMap", securityAttributeMappings); properties.put("filterErrors", String.valueOf(filterErrors)); properties.put("filterWarnings", String.valueOf(filterWarnings)); return configureMetacardValidityFilterPlugin(properties, configAdmin); }</code><technical_language>If field is passed in, others in config nulled out right? Do want allow this happen passing in a dictionary, force callers configure field other methods? a case case basis for config</technical_language>

Target:
public static Dictionary<String, Object> configureMetacardValidityFilterPlugin( List<String> securityAttributeMappings, boolean filterErrors, boolean filterWarnings, AdminConfig configAdmin) throws IOException { Dictionary<String, Object> properties = new DictionaryMap<>(); properties.put("attributeMap", securityAttributeMappings); properties.put("filterErrors", filterErrors); properties.put("filterWarnings", filterWarnings); return configureMetacardValidityFilterPlugin(properties, configAdmin); }
Source:
<code>public void fileOpened(@NotNull FileEditorManager source, @NotNull VirtualFile file) { if (!globalSettings.isAutoTrigger()) { return; } Module m = ModuleUtil.findModuleForFile(file, myProject); if (m == null || !SonarLintUtils.shouldAnalyzeAutomatically(file, m)) { return; } analyzer.submitAsync(m, Collections.singleton(file), TriggerType.EDITOR_OPEN); <START> serverIssueUpdater.trackServerIssues(Collections.singleton(file)); <END> }</code><technical_language>synchronize tasks end (only do server issue tracking local analysis completes) share a CountDownLatch</technical_language>

Target:
public void fileOpened(@NotNull FileEditorManager source, @NotNull VirtualFile file) { if (!globalSettings.isAutoTrigger()) { return; } Module m = ModuleUtil.findModuleForFile(file, myProject); if (m == null || !SonarLintUtils.shouldAnalyzeAutomatically(file, m)) { return; } analyzer.submitAsync(m, Collections.singleton(file), TriggerType.EDITOR_OPEN); }
Source:
<code>private void runPlugins(BPMN4ToscaPlan plan, AbstractActivity abstractActivity) { if (abstractActivity instanceof ANodeTemplateActivity) { AbstractNodeTemplate nodeTemplate = ((ANodeTemplateActivity) abstractActivity).getNodeTemplate(); LOGGER.debug("Trying to handle NodeTemplate " + nodeTemplate.getId()); IPlanBuilderTypePlugin plugin = this.findTypePlugin(nodeTemplate); if (plugin == null) { <START> <END> } else { LOGGER.info("Handling NodeTemplate with generic plugin", nodeTemplate.getId()); plugin.handle(plan.getElements(), nodeTemplate); } for (IPlanBuilderPostPhasePlugin postPhasePlugin : PluginRegistry.getPostPlugins()) { if (postPhasePlugin.canHandle(nodeTemplate)) { } } } else { } }</code><technical_language>empty conditional block? Consider inverting condition</technical_language>

Target:
private void runPlugins(BPMN4ToscaPlan plan, AbstractActivity abstractActivity) { if (abstractActivity instanceof ANodeTemplateActivity) { AbstractNodeTemplate nodeTemplate = ((ANodeTemplateActivity) abstractActivity).getNodeTemplate(); LOGGER.debug("Trying to handle NodeTemplate " + nodeTemplate.getId()); IPlanBuilderTypePlugin plugin = this.findTypePlugin(nodeTemplate); if (plugin != null) { LOGGER.info("Handling NodeTemplate with plugin {}", nodeTemplate.getId(), plugin.getID()); plugin.handle(plan.getElements(), nodeTemplate); } else { LOGGER.warn("No Plugins for NodeTemplate {}", nodeTemplate.getId()); } for (IPlanBuilderPostPhasePlugin postPhasePlugin : PluginRegistry.getPostPlugins()) { if (postPhasePlugin.canHandle(nodeTemplate)) { } } } else { } }
Source:
<code>public static NodeList getNodeList(Node contextNode, String xPath) throws Exception { XPathFactory factory = XPathFactory.newInstance(); factory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true); XPath xpath = factory.newXPath(); XPathExpression expr = xpath.compile(xPath); <START> NodeList result = (NodeList) expr.evaluate(contextNode, XPathConstants.NODESET); return result; <END> }</code><technical_language>return here: return (NodeList) expr.evaluate(contextNode, XPathConstants.NODESET);</technical_language>

Target:
public static NodeList getNodeList(Node contextNode, String xPath) throws Exception { XPathFactory factory = XPathFactory.newInstance(); factory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true); XPath xpath = factory.newXPath(); XPathExpression expr = xpath.compile(xPath); return (NodeList) expr.evaluate(contextNode, XPathConstants.NODESET); }
Source:
<code>public FrameDesc findFrameDesc(byte[] buf, int off, int len) { RawPacket pkt = new RawPacket(buf, off, len); <START> return findFrameDesc(pkt.getSSRCAsLong(), pkt.getTimestamp()); <END> }</code><technical_language>static versions of getSSRCAsLong getTimestamp</technical_language>

Target:
public FrameDesc findFrameDesc(byte[] buf, int off, int len) { return findFrameDesc( RawPacket.getSSRCAsLong(buf, off, len), RawPacket.getTimestamp(buf, off, len)); }
Source:
<code>private void assertBlobIdFieldValues(BlobId blobId, BlobId.BlobIdType type, byte datacenterId, short accountId, short containerId, PartitionId partitionId, boolean isEncrypted) throws IOException { assertEquals("Wrong partition id in blobId: " + blobId, partitionId, blobId.getPartition()); assertEquals("Wrong type in blobId: " + blobId, type, blobId.getType()); assertEquals("Wrong datacenter id in blobId: " + blobId, datacenterId, blobId.getDatacenterId()); assertEquals("Wrong account id in blobId: " + blobId, accountId, blobId.getAccountId()); assertEquals("Wrong container id in blobId: " + blobId, containerId, blobId.getContainerId()); assertEquals("Wrong isEncrypted value in blobId: " + blobId, isEncrypted, blobId.isEncrypted()); <START> Pair<Short, Short> accountAndContainer = BlobId.getAccountAndContainerIds(blobId.getID()); <END> assertEquals("Account id from the id string should be the same as the associated account id", blobId.getAccountId(), (short) accountAndContainer.getFirst()); assertEquals("Container id from the id string should be the same as the associated container id", blobId.getContainerId(), (short) accountAndContainer.getSecond()); }</code><technical_language>this part is required. This tested in BlobId (if is not, transfer this piece of code there)</technical_language>

Target:
private void assertBlobIdFieldValues(BlobId blobId, BlobId.BlobIdType type, byte datacenterId, short accountId, short containerId, PartitionId partitionId, boolean isEncrypted) throws IOException { assertEquals("Wrong partition id in blobId: " + blobId, partitionId, blobId.getPartition()); assertEquals("Wrong type in blobId: " + blobId, type, blobId.getType()); assertEquals("Wrong datacenter id in blobId: " + blobId, datacenterId, blobId.getDatacenterId()); assertEquals("Wrong account id in blobId: " + blobId, accountId, blobId.getAccountId()); assertEquals("Wrong container id in blobId: " + blobId, containerId, blobId.getContainerId()); assertEquals("Wrong isEncrypted value in blobId: " + blobId, isEncrypted, blobId.isEncrypted()); }
Source:
<code>public static long greatestCommonDivisor(long a, long b) { while (b != 0) { <START> a = b; <END> b = a % b; } return a; }</code><technical_language>me, this calculation wrong, assign a = b, b = a % b 0, a = b. be: long c = b; b = a % b; a = c;</technical_language>

Target:
public static long greatestCommonDivisor(long a, long b) { while (b != 0) { long c = b; b = a % b; a = c; } return a; }
Source:
<code>public static String getTag(Class<?> clazz) { <START> return clazz.getSimpleName().substring(0, 23); <END> }</code><technical_language>need substring() Class.getSimpleName() return class' name package? Please remove</technical_language>

Target:
public static String getTag(Class<?> clazz) { String className = clazz.getSimpleName(); return className.substring(0, Math.min(23, className.length())); }
Source:
<code>default void setMateUnmapped(final boolean mateUnmapped) { addFlag(SAMFlag.MATE_UNMAPPED, mateUnmapped); <START> } <END></code><technical_language>add isMateMapped</technical_language>

Target:
default void setMateUnmapped(final boolean mateUnmapped) { setFlag(SAMFlag.MATE_UNMAPPED, mateUnmapped); }
Source:
<code>public List<String> getMasters(TajoConf conf) throws ServiceTrackerException { <START> return null; <END> }</code><technical_language>change empty list</technical_language>

Target:
public List<String> getMasters(TajoConf conf) throws ServiceTrackerException { return new ArrayList<String>(); }
Source:
<code>@FromJson public AnInterface read(JsonReader jsonReader) throws IOException { jsonReader.beginObject(); String name = null; <START> while (jsonReader.peek() != JsonReader.Token.END_OBJECT) { <END> switch (jsonReader.nextName()) { case "name": name = jsonReader.nextString(); break; } } jsonReader.endObject(); return new AnImplementation(name); }</code><technical_language>while (jsonReader.hasNext()) ... for symmetry other libraries</technical_language>

Target:
@FromJson public AnInterface read(JsonReader jsonReader) throws IOException { jsonReader.beginObject(); String name = null; while (jsonReader.hasNext()) { switch (jsonReader.nextName()) { case "name": name = jsonReader.nextString(); break; } } jsonReader.endObject(); return new AnImplementation(name); }
Source:
<code>public synchronized RegisteredProject removeType(String wsPath, String type) throws ConflictException, NotFoundException, ServerException, BadRequestException, ForbiddenException { <START> RegisteredProject project = projectConfigRegistry.getOrNull(wsPath); <END> if (project == null) throw new NotFoundException("Can't find project"); List<String> mixins = project.getMixins(); if (mixins.contains(type)) { mixins.remove(type); NewProjectConfigImpl projectConfig = new NewProjectConfigImpl( project.getPath(), project.getType(), mixins, project.getName(), project.getDescription(), project.getAttributes(), null, project.getSource()); projectConfigRegistry.put(projectConfig, true, false); return projectConfigRegistry.getOrNull(wsPath); } if (project.getType().equals(type) && !project.isDetected()) { NewProjectConfigImpl projectConfig = new NewProjectConfigImpl( project.getPath(), BaseProjectType.ID, project.getMixins(), project.getName(), project.getDescription(), project.getAttributes(), null, project.getSource()); projectConfigRegistry.put(projectConfig, true, false); return projectConfigRegistry.getOrNull(wsPath); } if (project.getType().equals(type) && project.isDetected()) { return projectConfigRegistry.removeOrNull(project.getPath()); } return project; }</code><technical_language>I guess simply java RegisteredProject project = projectConfigRegistry.get(wsPath).orElseThrow(() -> new NotFoundException("Can't find project")); java RegisteredProject project = projectConfigRegistry.getOrNull(wsPath); if (project == null) { throw new NotFoundException("Can't find project"); }</technical_language>

Target:
public synchronized RegisteredProject removeType(String wsPath, String type) throws ConflictException, NotFoundException, ServerException, BadRequestException, ForbiddenException { RegisteredProject project = projectConfigRegistry .get(wsPath) .orElseThrow(() -> new NotFoundException("Can't find project")); List<String> mixins = project.getMixins(); if (mixins.contains(type)) { mixins.remove(type); NewProjectConfigImpl projectConfig = new NewProjectConfigImpl( project.getPath(), project.getType(), mixins, project.getName(), project.getDescription(), project.getAttributes(), null, project.getSource()); projectConfigRegistry.put(projectConfig, true, false); return projectConfigRegistry.getOrNull(wsPath); } if (project.getType().equals(type) && !project.isDetected()) { NewProjectConfigImpl projectConfig = new NewProjectConfigImpl( project.getPath(), BaseProjectType.ID, project.getMixins(), project.getName(), project.getDescription(), project.getAttributes(), null, project.getSource()); projectConfigRegistry.put(projectConfig, true, false); return projectConfigRegistry.getOrNull(wsPath); } if (project.getType().equals(type) && project.isDetected()) { return projectConfigRegistry.removeOrNull(project.getPath()); } return project; }
Source:
<code>private double getRequiredSizeForMerge(SubchainInfo subchain) { DiskImage baseSnapshot = subchain.getBaseImage(); DiskImage topSnapshot = subchain.getTopImage(); if (baseSnapshot.getVolumeFormat() == VolumeFormat.RAW) { if (storageDomain.getStorageType().isBlockDomain()) { return 0; } else { return Math.min(topSnapshot.getActualSizeInBytes() / StorageConstants.QCOW_OVERHEAD_FACTOR, baseSnapshot.getSize() - baseSnapshot.getActualSizeInBytes()); } } return <START> Math.min(topSnapshot.getSize() * StorageConstants.QCOW_OVERHEAD_FACTOR - baseSnapshot.getActualSizeInBytes(), <END> topSnapshot.getActualSizeInBytes()); }</code><technical_language>create a variable a meaningful (requiredExtendSize) name for this expression? explain extend size is limited virtual size, Min</technical_language>

Target:
private double getRequiredSizeForMerge(SubchainInfo subchain) { DiskImage baseSnapshot = subchain.getBaseImage(); DiskImage topSnapshot = subchain.getTopImage(); if (baseSnapshot.getVolumeFormat() == VolumeFormat.RAW) { if (storageDomain.getStorageType().isBlockDomain()) { return 0; } else { return Math.min(topSnapshot.getActualSizeInBytes() / StorageConstants.QCOW_OVERHEAD_FACTOR, baseSnapshot.getSize() - baseSnapshot.getActualSizeInBytes()); } } double requiredExtendSize = Math.min(topSnapshot.getSize() * StorageConstants.QCOW_OVERHEAD_FACTOR - baseSnapshot.getActualSizeInBytes(), topSnapshot.getActualSizeInBytes()); return requiredExtendSize; }
Source:
<code>protected void onRestoreInstanceState(@NonNull Bundle savedState) { super.onRestoreInstanceState(savedState); Serializable serializable = savedState.getSerializable(INFO_KEY); if (serializable instanceof ChannelInfo) { currentInfo = (ChannelInfo) serializable; InfoCache.getInstance().putInfo(serviceId, url, currentInfo, InfoItem.InfoType.CHANNEL); <START> } <END> serializable = savedState.getSerializable(STACK_KEY); if (serializable instanceof Collection) { stack.addAll((Collection<? extends StackItem>) serializable); } }</code><technical_language>Remove this if needed</technical_language>

Target:
protected void onRestoreInstanceState(@NonNull Bundle savedState) { super.onRestoreInstanceState(savedState); Serializable serializable = savedState.getSerializable(INFO_KEY); if (serializable instanceof ChannelInfo) { currentInfo = (ChannelInfo) serializable; InfoCache.getInstance().putInfo(serviceId, url, currentInfo, InfoItem.InfoType.CHANNEL); } }
Source:
<code>boolean isConnectionSuccessful(HttpURLConnection conn) { try { int responseCode = conn.getResponseCode(); boolean success = isConnectionSuccessful(responseCode); if (!success && LOG.isDebugEnabled()) { String response; try { InputStream in = conn.getErrorStream(); if (in == null) { in = conn.getInputStream(); } try (Reader reader = new InputStreamReader(in)) { response = CharStreams.toString(reader); } } catch (Exception e) { <START> response = "failed to ready response: " + e.getMessage(); <END> } LOG.debug( "Server check for '{}' request failed with code {}. Response: {}", serverRef, responseCode, response); } return success; } catch (IOException e) { LOG.debug( "Failed to establish http connection to check server '{}'. Cause: {}", serverRef, e.getMessage()); return false; } }</code><technical_language>do need re-throw Exception</technical_language>

Target:
boolean isConnectionSuccessful(HttpURLConnection conn) { try { int responseCode = conn.getResponseCode(); boolean success = isConnectionSuccessful(responseCode); if (!success && LOG.isDebugEnabled()) { String response; try { InputStream in = conn.getErrorStream(); if (in == null) { in = conn.getInputStream(); } try (Reader reader = new InputStreamReader(in)) { response = CharStreams.toString(reader); } } catch (Exception e) { response = "failed to ready response: " + e.getMessage(); } LOG.debug( "Server check for '{}:{}' request failed with code {}. Response: {}", serverRef, url, responseCode, response); } return success; } catch (IOException e) { LOG.debug( "Failed to establish http connection to check server '{}:{}'. Cause: {}", serverRef, url, e.getMessage()); return false; } }
Source:
<code>protected String[] getIndexNames() { List<String> repositoryNames = getElasticSearchAdmin().getRepositoryNames(); String indices[] = new String[repositoryNames.size()]; int i = 0; for (String repo : repositoryNames) { indices[i++] = getElasticSearchAdmin().getIndexNameForRepository(repo); } <START> return indices; <END> }</code><technical_language>arrays intermediate data structures. Convert array need it. ElasticSearchAdmin esa = Framework.getService(ElasticSearchAdmin.class); esa.getRepositoryNames().stream().map(repositoryName -> esa::getIndexNameForRepository).toArray(String[]::new);</technical_language>

Target:
protected String[] getIndexNames() { ElasticSearchAdmin esa = Framework.getService(ElasticSearchAdmin.class); List<String> repositoryNames = Framework.getService(ElasticSearchAdmin.class).getRepositoryNames(); String indices[] = new String[repositoryNames.size()]; int i = 0; for (String repo : repositoryNames) { indices[i++] = esa.getIndexNameForRepository(repo); } return indices; }
Source:
<code>public synchronized void send(String command) throws NodeJsDebuggerException { LOG.debug("Execute: {}", command); if (!process.isAlive()) { throw new NodeJsDebuggerTerminatedException("NodeJs process is terminated."); } try { processWriter.write(command); processWriter.newLine(); processWriter.flush(); } catch (IOException e) { LOG.error(String.format("Command execution <%s> failed", command), e); } <START> try { <END> sleep(100); } catch (InterruptedException ignored) { } }</code><technical_language>do sleep instruction</technical_language>

Target:
public synchronized void send(String command) throws NodeJsDebuggerException { LOG.debug("Execute: {}", command); if (!process.isAlive()) { throw new NodeJsDebuggerTerminatedException("NodeJs process is terminated."); } try { processWriter.write(command); processWriter.newLine(); processWriter.flush(); } catch (IOException e) { LOG.error(String.format("Command execution <%s> failed", command), e); } }
Source:
<code>public RedisTokenEntry fetchTokenEntry(String processorName, int segment, String owner, Instant currentTimestamp, Instant expirationFromTimestamp) { String redisOutput = (String) tryEvalSha1(FETCH_TOKEN_SCRIPT, FETCH_TOKEN_SHA1, getHashKeyList(processorName, segment), Arrays.asList( processorName, Integer.toString(segment), owner, Long.toString(currentTimestamp.toEpochMilli()), Long.toString(expirationFromTimestamp.toEpochMilli()))); if (redisOutput != null) { JSONObject tokenEntry = new JSONObject(redisOutput); String tokenEntryProcessorName = null; int tokenEntrySegment = 0; String tokenEntryOwner = null; String tokenEntryTimestamp = null; byte[] tokenEntryToken = null; String tokenEntryTokenType = null; <START> if (tokenEntry.has("processorName")) { <END> tokenEntryProcessorName = tokenEntry.getString("processorName"); } if (tokenEntry.has("segment")) { tokenEntrySegment = Integer.parseInt(tokenEntry.getString("segment")); } if (tokenEntry.has("owner")) { tokenEntryOwner = tokenEntry.getString("owner"); } if (tokenEntry.has("timestamp")) { tokenEntryTimestamp = Instant.ofEpochMilli(Long.parseLong(tokenEntry.getString("timestamp"))).toString(); } if (tokenEntry.has("token")) { tokenEntryToken = Base64.getDecoder().decode(tokenEntry.getString("token")); } if (tokenEntry.has("tokenType")) { tokenEntryTokenType = tokenEntry.getString("tokenType"); } return new RedisTokenEntry(tokenEntryToken, tokenEntryTokenType, tokenEntryTimestamp, tokenEntryOwner, tokenEntryProcessorName, tokenEntrySegment); } else { return null; } }</code><technical_language>Small adjustment, nice change Strings (e.g. processorName/segment/...) private constants</technical_language>

Target:
public RedisTokenEntry fetchTokenEntry(String processorName, int segment, String owner, Instant currentTimestamp, Instant expirationFromTimestamp) { String redisOutput = (String) tryEvalSha1( FETCH_TOKEN_SCRIPT, FETCH_TOKEN_SHA1, getHashKeyList(processorName, segment), Arrays.asList( processorName, Integer.toString(segment), owner, Long.toString(currentTimestamp.toEpochMilli()), Long.toString(expirationFromTimestamp.toEpochMilli()))); return mapRedisTokenEntry(redisOutput); }
Source:
<code>public Response getRefund(@PathParam("accountId") Long accountId, @PathParam("chargeId") String chargeId, @PathParam("refundId") String refundId, @Context UriInfo uriInfo) { return chargeService.findCharge(chargeId, accountId) <START> .map(chargeEntity -> getRefundResponse(chargeEntity, refundId, accountId, uriInfo)) <END> .orElseGet(() -> responseWithChargeNotFound(chargeId)); }</code><technical_language>suggestion .map(charge -> getRefundResponse(charge, refundId, accountId, uriInfo))</technical_language>

Target:
public Response getRefund(@PathParam("accountId") Long accountId, @PathParam("chargeId") String chargeId, @PathParam("refundId") String refundId, @Context UriInfo uriInfo) { return chargeService.findCharge(chargeId, accountId) .map(charge -> getRefundResponse(charge, refundId, accountId, uriInfo)) .orElseGet(() -> responseWithChargeNotFound(chargeId)); }
Source:
<code>protected void finalize() throws Throwable { super.finalize(); <START> if(channel!=null) { <END> channel.send(new Unexport(channel.newIoId(),oid)); oid = -1; } }</code><technical_language>null assignment preventing a double export..</technical_language>

Target:
protected void finalize() throws Throwable { super.finalize(); if(channel != null && oid != -1) { channel.send(new Unexport(channel.newIoId(),oid)); oid = -1; } }
Source:
<code>public boolean steady(final List<ServerHolder> serverHolders) { double totalCost = 0; double maxCost = Double.MIN_VALUE; double minCost = Double.MAX_VALUE; for (ServerHolder server : serverHolders) { double serverCost = calculateServerCost(server); totalCost += serverCost; maxCost = Math.max(maxCost, serverCost); minCost = Math.min(minCost, serverCost); } double average = (double) totalCost / serverHolders.size(); <START> double floor = (double) Math.floor(average * (1 - balancerSlop)); <END> double ceiling = (double) Math.ceil(average * (1 + balancerSlop)); if (maxCost < ceiling && minCost > floor) { return true; } return false; }</code><technical_language>reason rounding up/down nearest integer</technical_language>

Target:
public boolean steady(final List<ServerHolder> serverHolders) { if (balancerSlope <= BalancerStrategy.DEFAULT_BALANCER_SLOPE) { return false; } double totalCost = 0; double maxCost = Double.MIN_VALUE; double minCost = Double.MAX_VALUE; for (ServerHolder server : serverHolders) { double serverCost = calculateServerCost(server); totalCost += serverCost; maxCost = Math.max(maxCost, serverCost); minCost = Math.min(minCost, serverCost); } double average = totalCost / serverHolders.size(); double floor = average * (1 - balancerSlope); double ceiling = average * (1 + balancerSlope); if (maxCost < ceiling && minCost > floor) { return true; } return false; }
Source:
<code><START> public static synchronized void closeAll() { <END> FullTextSettings.closeAll(); }</code><technical_language>FullTextSettings.closeAll appears handle synch needs, need mark this method synch</technical_language>

Target:
public static void closeAll() { FullTextSettings.closeAll(); }
Source:
<code>private ContentSummary getContentSummary() { if( contentSummary != null ) return contentSummary; try { if (fileStatus.isFile()) { long length = fileStatus.getLen(); contentSummary = new ContentSummary.Builder().length(length). fileCount(1).directoryCount(0).spaceConsumed(length).build(); } else { <START> long[] summary = {0, 0, 1}; <END> for (FileStatus s : listRoot()) { long length = s.getLen(); ContentSummary c = s.isDirectory() ? fs.getContentSummary(s.getPath()) : new ContentSummary.Builder().length(length). fileCount(1).directoryCount(0).spaceConsumed(length).build(); summary[0] += c.getLength(); summary[1] += c.getFileCount(); summary[2] += c.getDirectoryCount(); } contentSummary = new ContentSummary.Builder().length(summary[0]). fileCount(summary[1]).directoryCount(summary[2]). spaceConsumed(summary[0]).build(); } } catch (IOException ioe) { LOG.error("Unexpected error getting content summary. We ignore it for now, but you should probably check it out:", ioe); contentSummary = new ContentSummary(0L, 0L, 0L); } return contentSummary; }</code><technical_language>Nitpick: explicit variables IMHO (e.g. length / fileCount / dirCount)</technical_language>

Target:
private ContentSummary getContentSummary() { if( contentSummary != null ) return contentSummary; try { if (fileStatus.isFile()) { long length = fileStatus.getLen(); contentSummary = new ContentSummary.Builder().length(length). fileCount(1).directoryCount(0).spaceConsumed(length).build(); } else { long length = 0, fileCount = 0, dirCount = 1; for (FileStatus s : listRoot()) { if( s.isDirectory() ) { ContentSummary c = fs.getContentSummary(s.getPath()); length += c.getLength(); fileCount += c.getFileCount(); dirCount += c.getDirectoryCount(); } else { length += s.getLen(); fileCount++; } } contentSummary = new ContentSummary.Builder().length(length). fileCount(fileCount).directoryCount(dirCount). spaceConsumed(length).build(); } } catch (IOException ioe) { LOG.error("Unexpected error getting content summary. We ignore it for now, but you should probably check it out:", ioe); contentSummary = new ContentSummary(0L, 0L, 0L); } return contentSummary; }