auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>private GlusterVolumeRemoveBricksParameters toParameters(Action action) { GlusterVolumeRemoveBricksParameters params = new GlusterVolumeRemoveBricksParameters(); List<GlusterBrickEntity> entityBricks = new ArrayList<GlusterBrickEntity>(); for (GlusterBrick brick : action.getBricks().getGlusterBricks()) { GlusterBrickEntity entity = new GlusterBrickEntity(); entity.setBrickDirectory(brick.getBrickDir()); entity.setVolumeId(new Guid(getVolumeId())); <START> if (brick.getId() != null) { <END> entity.setId(new Guid(brick.getId())); } else { entity.setId(null); } if (brick.getName() != null) { String arr = brick.getName().split("\\:"); if (arr.length > 1) { entity.setServerName(arr[0]); entity.setBrickDirectory(arr[1]); } } entityBricks.add(entity); } params.setVolumeId(new Guid(getVolumeId())); params.setBricks(entityBricks); params.setCommandType(VdcActionType.StartRemoveGlusterVolumeBricks); return params; }</code><technical_language>please asGuid() (it throws response id is convertible UUID)</technical_language>

Target:
private GlusterVolumeRemoveBricksParameters toParameters(Action action) { GlusterVolumeRemoveBricksParameters params = new GlusterVolumeRemoveBricksParameters(); List<GlusterBrickEntity> entityBricks = new ArrayList<GlusterBrickEntity>(); for (GlusterBrick brick : action.getBricks().getGlusterBricks()) { GlusterBrickEntity entity = new GlusterBrickEntity(); entity.setBrickDirectory(brick.getBrickDir()); entity.setVolumeId(new Guid(getVolumeId())); if (brick.getName() != null) { String arr = brick.getName().split("\\:"); if (arr.length > 1) { entity.setServerName(arr[0]); entity.setBrickDirectory(arr[1]); } else { continue; } } entityBricks.add(entity); } params.setVolumeId(asGuid(getVolumeId())); params.setBricks(entityBricks); params.setCommandType(VdcActionType.StartRemoveGlusterVolumeBricks); return params; }
Source:
<code>public QueryHistoryMetricsKey key() { if (key == null) <START> key = new QueryHistoryMetricsKey(qry, schema, loc); <END> return key; }</code><technical_language>initialize key eagerly? method key() is called right creating new instance of QueryHistoryMetrics</technical_language>

Target:
public QueryHistoryMetricsKey key() { return key; }
Source:
<code>private void runEvictionStrategies() { final ILogger logger = this.logger(); final int forcedEvictionRetryCount = getRetryCount(); <START> final Eviction[] evictions = new Eviction[] { <END> new RecordStoreForcedEviction(forcedEvictionRetryCount, logger, this), new PartitionRecordStoreForcedEviction(forcedEvictionRetryCount, logger, this), new AllEntriesEviction(logger, this), new PartitionAllEntriesEviction(logger, this) }; for (Eviction eviction : evictions) { eviction.execute(); if (eviction.isSuccessful()) { return; } } }</code><technical_language>This code hot path some conditions, is create new objects for run</technical_language>

Target:
private void runEvictionStrategies() { for (ForcedEviction eviction : WithForcedEviction.EVICTIONS) { if (eviction.execute(getRetryCount(), this, logger())) { return; } } }
Source:
<code>private PrivateKey getPrivateKey(String alias, String password) { try { <START> return (PrivateKey) keyStore.getKey(alias, password.toCharArray()); <END> } catch (KeyStoreException | NoSuchAlgorithmException | UnrecoverableKeyException e) { LOGGER.debug("Unable to retrieve private key from key store", e); } return null; }</code><technical_language>Do for this return a PrivateKey</technical_language>

Target:
private PrivateKey getPrivateKey(String alias, String password) { try { Key key = keyStore.getKey(alias, password.toCharArray()); if (key instanceof PrivateKey) { return (PrivateKey) key; } } catch (KeyStoreException | NoSuchAlgorithmException | UnrecoverableKeyException e) { LOGGER.debug("Unable to retrieve private key from key store", e); } return null; }
Source:
<code>private ProjectType resolveProjectType(String artifactId, String owa) { if (artifactId != null) { return ProjectType.MODULE; } else if (owa != null) { return ProjectType.OWA; } List<String> options = new ArrayList<>(Arrays.asList( FETCH_MODULE_OPTION, FETCH_OWA_OPTION )); if (projectType == null) { String choice = wizard.promptForMissingValueWithOptions("What would you like to fetch?%s", null, "", options); switch (choice) { case FETCH_MODULE_OPTION: <START> return ProjectType.MODULE; <END> case FETCH_OWA_OPTION: return ProjectType.OWA; } } return null; }</code><technical_language>I consider assigning ProjectType returning end</technical_language>

Target:
private ProjectType resolveProjectType(String artifactId, String owa) { ProjectType result = null; if (StringUtils.isNotBlank(artifactId)) { result = ProjectType.MODULE; } else if (StringUtils.isNotBlank(owa)) { result = ProjectType.OWA; } if (result == null) { List<String> options = new ArrayList<>(Arrays.asList( FETCH_MODULE_OPTION, FETCH_OWA_OPTION )); String choice = wizard.promptForMissingValueWithOptions("What would you like to fetch?%s", null, "", options); switch (choice) { case FETCH_MODULE_OPTION: result = ProjectType.MODULE; break; case FETCH_OWA_OPTION: result = ProjectType.OWA; break; } } return result; }
Source:
<code>public boolean matches(final URL url) { <START> return url.getProtocol().equals("file"); <END> }</code><technical_language>objects.equals please</technical_language>

Target:
public boolean matches(final URL url) { return Objects.equals(url.getProtocol(), "file"); }
Source:
<code>public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view; if (IS_COURSEWARE_ACCESSIBLE) { view = inflater.inflate(R.layout.fragment_course_dashboard, container, false); courseTextName = (TextView) view.findViewById(R.id.course_detail_name); courseTextDetails = (TextView) view.findViewById(R.id.course_detail_extras); headerImageView = (ImageView) view.findViewById(R.id.header_image_view); parent = (LinearLayout) view.findViewById(R.id.dashboard_detail); } <START> else { <END> view = inflater.inflate(R.layout.fragment_course_dashboard_disabled, container, false); errorText = (TextView) view.findViewById(R.id.error_msg); } return view; }</code><technical_language>else moved line block ending. Avoids wasting space :wink:</technical_language>

Target:
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view; if (isCoursewareAccessible) { view = inflater.inflate(R.layout.fragment_course_dashboard, container, false); courseTextName = (TextView) view.findViewById(R.id.course_detail_name); courseTextDetails = (TextView) view.findViewById(R.id.course_detail_extras); headerImageView = (ImageView) view.findViewById(R.id.header_image_view); parent = (LinearLayout) view.findViewById(R.id.dashboard_detail); } else { view = inflater.inflate(R.layout.fragment_course_dashboard_disabled, container, false); errorText = (TextView) view.findViewById(R.id.error_msg); } return view; }
Source:
<code>private void parseUpwardsStepCount() throws ParseException { if (!isDigit(curr())) { fail(); } if (pos == input.length()) { return; } for (char current = curr(); isDigit(current) && pos < input.length() - 1; current = curr()) ; <START> pos--; <END> }</code><technical_language>work for values consists of positive-integer more digits e.g. '123'? In case I of step other parsing (parseJsonPointer) try process digit. This prevented like: if (!(pos == input.length() - 1)) { pos--; }</technical_language>

Target:
private void parseUpwardsStepCount() throws ParseException { if (!isDigit(curr())) { fail(); } else if (curr() == '0') { next(); if (curr() == '/' || curr() == '#' || curr() == EOF) { pos--; } else { fail(); } } for (char current = next(); isDigit(current) && pos < input.length(); current = next()) ; }
Source:
<code>private void deleteSite() { <START> final Blog currentBlog = WordPress.getCurrentBlog(); <END> WordPress.getRestClientUtils().deleteSite(currentBlog.getDotComBlogId(), new RestRequest.Listener() { @Override public void onResponse(JSONObject response) { removeBlog(); } }, new RestRequest.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { handleDeleteSiteError(); } }); }</code><technical_language>I this programmer errors, do sense check for currentBlog.isDotcomFlag()</technical_language>

Target:
private void deleteSite() { final Blog currentBlog = WordPress.getCurrentBlog(); if (currentBlog.isDotcomFlag()) { final ProgressDialog progressDialog = ProgressDialog.show(getActivity(), "", getString(R.string.delete_site_progress), true, false); WordPress.getRestClientUtils().deleteSite(currentBlog.getDotComBlogId(), new RestRequest.Listener() { @Override public void onResponse(JSONObject response) { progressDialog.dismiss(); removeBlog(); } }, new RestRequest.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { progressDialog.dismiss(); handleDeleteSiteError(); } }); } }
Source:
<code>private static Pattern buildPattern(final String spec) { <START> if (spec == null) { throw new IllegalArgumentException("null package name"); } if (spec.isEmpty()) { throw new IllegalArgumentException("empty package name"); } <END> final StringBuilder regex = new StringBuilder(); for (int idx = 0; idx < spec.length(); idx++) { char ch = spec.charAt(idx); if (ch == '*') { regex.append(".*"); } else if (ch == '.') { regex.append("\\."); } else if (idx == 0 && !Character.isJavaIdentifierStart(ch)) { throw new IllegalArgumentException("invalid package name: " + spec); } else if (!Character.isJavaIdentifierPart(ch)) { throw new IllegalArgumentException("invalid package name: " + spec); } else { regex.append(ch); } } try { return Pattern.compile(regex.toString()); } catch (PatternSyntaxException e) { throw new IllegalArgumentException("invalid package specification: " + spec, e); } }</code><technical_language>(Optional) IMHO enough if message appeared in this case. If wanted, StringUtils commons-lang3. add dependency in this is done in core Tycho: <LINK_0></technical_language>

Target:
private static Pattern buildPattern(final String spec) { if (StringUtils.isEmpty(spec)) { throw new IllegalArgumentException("empty package name"); } final StringBuilder regex = new StringBuilder(); for (int idx = 0; idx < spec.length(); idx++) { char ch = spec.charAt(idx); if (ch == '*') { regex.append(".*"); } else if (ch == '.') { regex.append("\\."); } else if (idx == 0 && !Character.isJavaIdentifierStart(ch)) { throw new IllegalArgumentException("invalid package name: " + spec); } else if (!Character.isJavaIdentifierPart(ch)) { throw new IllegalArgumentException("invalid package name: " + spec); } else { regex.append(ch); } } try { return Pattern.compile(regex.toString()); } catch (PatternSyntaxException e) { throw new IllegalArgumentException("invalid package specification: " + spec, e); } }
Source:
<code>private void stopStateTransitionExecutor() { int numberOfAttempts = 0; while (!stateTransitionEmitterProcess.isReadyForShutdown() && numberOfAttempts < MAX_NUMBER_OF_SHUTDOWN_READINESS_CHECKS) { LOGGER.info("State transition receiver is not ready for shutdown"); numberOfAttempts++; try { Thread.sleep(DELAY_BETWEEN_SHUTDOWN_CHECKS_IN_MILLISECONDS); } catch (InterruptedException e) { handleInterruptedException(); <START> return; <END> } } stateTransitionMessageExecutorService.shutdown(); try { if (!stateTransitionMessageExecutorService.awaitTermination(2L, TimeUnit.SECONDS)) { stateTransitionMessageExecutorService.shutdownNow(); } LOGGER.info("State transition receiver - number of not processed messages {}", stateTransitionEmitterProcess.getNumberOfNotProcessedMessages()); } catch (InterruptedException e) { handleInterruptedException(); } }</code><technical_language>return is required</technical_language>

Target:
private void stopStateTransitionExecutor() { int numberOfAttempts = 0; while (!stateTransitionEmitterProcess.isReadyForShutdown() && numberOfAttempts < MAX_NUMBER_OF_SHUTDOWN_READINESS_CHECKS) { LOGGER.info("State transition receiver is not ready for shutdown"); numberOfAttempts++; try { Thread.sleep(DELAY_BETWEEN_SHUTDOWN_CHECKS_IN_MILLISECONDS); } catch (InterruptedException e) { handleInterruptedException(); } } stateTransitionMessageExecutorService.shutdown(); try { if (!stateTransitionMessageExecutorService.awaitTermination(2L, TimeUnit.SECONDS)) { stateTransitionMessageExecutorService.shutdownNow(); } LOGGER.info("State transition receiver - number of not processed messages {}", stateTransitionEmitterProcess.getNumberOfNotProcessedMessages()); } catch (InterruptedException e) { handleInterruptedException(); } }
Source:
<code><START> public Hints createHintsFromRequest(Request request) throws UnsupportedEncodingException, URISyntaxException, IOException, <END> RepositoryConnectionException { final Optional<String> nameOptional = Optional.fromNullable(getStringAttribute(request, REPO_ATTR)); if (!nameOptional.isPresent()) { throw new RestletException(String.format( "Cannot create GeoGIG repository. Missing '%s' resource", REPO_ATTR), Status.CLIENT_ERROR_BAD_REQUEST); } final String repoName = nameOptional.get(); final Hints hints = new Hints(); hints.set(Hints.REPOSITORY_NAME, repoName); updateHintsWithParams(hints, getRequestParameters(request)); return hints; }</code><technical_language>static INSTANCE variable of this class is used. this simply a static function called InitRequestUtil.createHintsFromRequest(...)</technical_language>

Target:
public static Hints createHintsFromRequest(Request request) throws UnsupportedEncodingException, URISyntaxException, IOException, RepositoryConnectionException { final Optional<String> nameOptional = Optional.fromNullable(getStringAttribute(request, REPO_ATTR)); if (!nameOptional.isPresent()) { throw new RestletException(String.format( "Cannot create GeoGIG repository. Missing '%s' resource", REPO_ATTR), Status.CLIENT_ERROR_BAD_REQUEST); } final String repoName = nameOptional.get(); final Hints hints = new Hints(); hints.set(Hints.REPOSITORY_NAME, repoName); INSTANCE.updateHintsWithParams(hints, INSTANCE.getRequestParameters(request)); return hints; }
Source:
<code>public boolean startDeleteClaimWorkflow(String userStoreDomain, String userName, String claimURI, String profileName) throws WorkflowException { WorkflowService workflowService = IdentityWorkflowDataHolder.getInstance().getWorkflowService(); String tenant = CarbonContext.getThreadLocalCarbonContext().getTenantDomain(); String nameWithTenant = UserCoreUtil.addTenantDomainToEntry(userName, tenant); String fullyQualifiedName = UserCoreUtil.addDomainToName(nameWithTenant, userStoreDomain); Map<String, Object> wfParams = new HashMap<>(); Map<String, Object> nonWfParams = new HashMap<>(); wfParams.put(USERNAME, userName); wfParams.put(USER_STORE_DOMAIN, userStoreDomain); wfParams.put(CLAIM_URI, claimURI); wfParams.put(PROFILE_NAME, profileName); String uuid = UUID.randomUUID().toString(); boolean state = startWorkFlow(wfParams, nonWfParams, uuid); if (!Boolean.TRUE.equals(getWorkFlowCompleted()) && !state) { try { workflowService.addRequestEntityRelationships(uuid, new Entity[]{new Entity(fullyQualifiedName, <START> "USER"), new Entity(claimURI, "CLAIM")}); <END> } catch (InternalWorkflowException e) { log.info("No workflow associated with the operation."); } } return state; }</code><technical_language>Replace hard-coded strings constants</technical_language>

Target:
public boolean startDeleteClaimWorkflow(String userStoreDomain, String userName, String claimURI, String profileName) throws WorkflowException { WorkflowService workflowService = IdentityWorkflowDataHolder.getInstance().getWorkflowService(); String tenant = CarbonContext.getThreadLocalCarbonContext().getTenantDomain(); String fullyQualifiedName = UserCoreUtil.addDomainToName(userName, userStoreDomain); Map<String, Object> wfParams = new HashMap<>(); Map<String, Object> nonWfParams = new HashMap<>(); wfParams.put(USERNAME, userName); wfParams.put(USER_STORE_DOMAIN, userStoreDomain); wfParams.put(CLAIM_URI, claimURI); wfParams.put(PROFILE_NAME, profileName); String uuid = UUID.randomUUID().toString(); if (workflowService.eventEngagedWithWorkflows(UserStoreWFConstants.DELETE_USER_CLAIM_EVENT) && !Boolean.TRUE .equals(getWorkFlowCompleted()) && !isValidOperation(new Entity[]{new Entity(fullyQualifiedName, UserStoreWFConstants.ENTITY_TYPE_USER, tenant), new Entity(claimURI, UserStoreWFConstants .ENTITY_TYPE_CLAIM, tenant)})) { throw new WorkflowException("Operation is not valid."); } boolean state = startWorkFlow(wfParams, nonWfParams, uuid); if (!Boolean.TRUE.equals(getWorkFlowCompleted()) && !state) { try { workflowService.addRequestEntityRelationships(uuid, new Entity[]{new Entity(fullyQualifiedName, UserStoreWFConstants.ENTITY_TYPE_USER, tenant), new Entity(claimURI, UserStoreWFConstants .ENTITY_TYPE_CLAIM, tenant)}); } catch (InternalWorkflowException e) { if (log.isDebugEnabled()) { log.debug("No workflow associated with the operation.", e); } } } return state; }
Source:
<code><START> public final boolean execute(String sql) <END> throws SQLException { if (connection().shouldStartTransaction()) { internalExecute(connection().getStartTransactionSql()); } return internalExecute(sql); }</code><technical_language>needs overridden in subclass</technical_language>

Target:
public boolean execute(String sql) throws SQLException { if (connection().shouldStartTransaction()) { internalExecute(connection().getStartTransactionSql()); } return internalExecute(sql); }
Source:
<code>public static int calculateThreads(final int executorThreads, final String name) { final int optimalThreads= Math.max(BASE_OPTIMAL_THREADS, (Runtime.getRuntime().availableProcessors() + THREAD_OVERHEAD)); int threadsChosen = optimalThreads; if (executorThreads > optimalThreads) { threadsChosen = executorThreads; <START> LOG.debug("Requested more than optimal threads. This is not necessarily an error, but you may be overallocating."); <END> } else { if (executorThreads > 0) { LOG.warn("You requested less than optimal threads. We've ignored that."); } } LOG.debug("For factory {}, Optimal Threads {}, Configured Threads {}", name, optimalThreads, threadsChosen); return threadsChosen; }</code><technical_language>warning message is in opinion</technical_language>

Target:
public static int calculateThreads(final int executorThreads, final String name) { final int optimalThreads= Math.max(BASE_OPTIMAL_THREADS, (Runtime.getRuntime().availableProcessors() + THREAD_OVERHEAD)); int threadsChosen = optimalThreads; if (executorThreads > optimalThreads) { threadsChosen = executorThreads; LOG.warn("Requested more than optimal threads. This is not necessarily an error, but you may be overallocating."); } else { if (executorThreads > 0) { LOG.warn("You requested less than optimal threads. We've ignored that."); } } LOG.debug("For factory {}, Optimal Threads {}, Configured Threads {}", name, optimalThreads, threadsChosen); return threadsChosen; }
Source:
<code>protected final Map<String, Object> parseIntoCapabilities(String[] capabilities) { Map<String, Object> capabilityMap = new HashMap<String, Object>(); final int TWO = 2; for (String eachCapability : capabilities) { String[] keyValuePair = eachCapability.split(":", 2); <START> if (keyValuePair.length == TWO) { <END> String value = keyValuePair[1]; Object desiredCapability = value; if (value.startsWith("'") && value.endsWith("'")) { String trimmedValue = StringUtils.mid(value, 1, value.length() - 2); if (trimmedValue.equalsIgnoreCase("true")) { desiredCapability = "true"; } else if (trimmedValue.equalsIgnoreCase("false")) { desiredCapability = "false"; } } else if (value.equalsIgnoreCase("true") || value.equalsIgnoreCase("false")) { desiredCapability = Boolean.parseBoolean(value); } capabilityMap.put(keyValuePair[0], desiredCapability); } else { StringBuilder errMsg = new StringBuilder(); errMsg.append("Capabilities are to be provided as name value pair separated by colons. "); errMsg.append("For e.g., capabilityName:capabilityValue"); throw new IllegalArgumentException(errMsg.toString()); } } return capabilityMap; }</code><technical_language>this is silly.. original comparison is fine ... add exception for this one</technical_language>

Target:
protected final Map<String, Object> parseIntoCapabilities(String[] capabilities) { Map<String, Object> capabilityMap = new HashMap<String, Object>(); for (String eachCapability : capabilities) { String[] keyValuePair = eachCapability.split(":", 2); if (keyValuePair.length == 2) { String value = keyValuePair[1]; Object desiredCapability = value; if (value.startsWith("'") && value.endsWith("'")) { String trimmedValue = StringUtils.mid(value, 1, value.length() - 2); if (trimmedValue.equalsIgnoreCase("true")) { desiredCapability = "true"; } else if (trimmedValue.equalsIgnoreCase("false")) { desiredCapability = "false"; } } else if (value.equalsIgnoreCase("true") || value.equalsIgnoreCase("false")) { desiredCapability = Boolean.parseBoolean(value); } capabilityMap.put(keyValuePair[0], desiredCapability); } else { StringBuilder errMsg = new StringBuilder(); errMsg.append("Capabilities are to be provided as name value pair separated by colons. "); errMsg.append("For e.g., capabilityName:capabilityValue"); throw new IllegalArgumentException(errMsg.toString()); } } return capabilityMap; }
Source:
<code>public Weight createWeight(IndexSearcher searcher, boolean needsScores, float boost) throws IOException { return new ConstantScoreWeight(this, 10) { @Override public Scorer scorer(LeafReaderContext context) throws IOException { NumericDocValues fields = context.reader() .getNumericDocValues(IndexFields.NDV_FLAGS); if (fields == null) { return null; } TwoPhaseIterator iterator = new TwoPhaseIterator(fields) { @Override public boolean matches() throws IOException { long flags = fields.longValue(); if (fTrueFlags != 0 && (flags & fTrueFlags) == 0) { return false; } if (fFalseFlags != 0 && (flags & fFalseFlags) != 0) { return false; } return true; } @Override public float matchCost() { return 2; } }; return new ConstantScoreScorer(this, 10, iterator); } @Override public boolean isCacheable(LeafReaderContext ctx) { <START> return false; <END> } }; }</code><technical_language>Please this code return statement: return DocValues.isCacheable(ctx, IndexFields.NDV_FLAGS);</technical_language>

Target:
public Weight createWeight(IndexSearcher searcher, boolean needsScores, float boost) throws IOException { return new ConstantScoreWeight(this, 10) { @Override public Scorer scorer(LeafReaderContext context) throws IOException { NumericDocValues fields = context.reader() .getNumericDocValues(IndexFields.NDV_FLAGS); if (fields == null) { return null; } TwoPhaseIterator iterator = new TwoPhaseIterator(fields) { @Override public boolean matches() throws IOException { long flags = fields.longValue(); if (fTrueFlags != 0 && (flags & fTrueFlags) == 0) { return false; } if (fFalseFlags != 0 && (flags & fFalseFlags) != 0) { return false; } return true; } @Override public float matchCost() { return 2; } }; return new ConstantScoreScorer(this, 10, iterator); } @Override public boolean isCacheable(LeafReaderContext ctx) { return DocValues.isCacheable(ctx, IndexFields.NDV_FLAGS); } }; }
Source:
<code>public void fixupPartReferences(Map<Integer, Part> knownParts) { if (replacementPart instanceof PartRef) { int id = replacementPart.getId(); replacementPart = knownParts.get(id); if ((replacementPart == null) && (id > 0)) { <START> MekHQ.getLogger().error(PartRef.class, String.format("Part %d ('%s') references missing replacement part %d", getId(), getName(), id)); <END> } } if (parentPart instanceof PartRef) { int id = parentPart.getId(); parentPart = knownParts.get(id); if ((parentPart == null) && (id > 0)) { MekHQ.getLogger().error(PartRef.class, String.format("Part %d ('%s') references missing parent part %d", getId(), getName(), id)); } } for (int ii = childParts.size() - 1; ii >= 0; --ii) { Part childPart = childParts.get(ii); if (childPart instanceof PartRef) { Part realPart = knownParts.get(childPart.getId()); if (realPart != null) { childParts.set(ii, realPart); } else if (childPart.getId() > 0) { MekHQ.getLogger().error(PartRef.class, String.format("Part %d ('%s') references missing child part %d", getId(), getName(), childPart.getId())); childParts.remove(ii); } } } }</code><technical_language>suggestion MekHQ.getLogger().error( String.format("Part %d ('%s') references missing replacement part %d", getId(), getName(), id));</technical_language>

Target:
public void fixupPartReferences(Map<Integer, Part> knownParts) { if (replacementPart instanceof PartRef) { int id = replacementPart.getId(); replacementPart = knownParts.get(id); if ((replacementPart == null) && (id > 0)) { MekHQ.getLogger().error( String.format("Part %d ('%s') references missing replacement part %d", getId(), getName(), id)); } } if (parentPart instanceof PartRef) { int id = parentPart.getId(); parentPart = knownParts.get(id); if ((parentPart == null) && (id > 0)) { MekHQ.getLogger().error(PartRef.class, String.format("Part %d ('%s') references missing parent part %d", getId(), getName(), id)); } } for (int ii = childParts.size() - 1; ii >= 0; --ii) { Part childPart = childParts.get(ii); if (childPart instanceof PartRef) { Part realPart = knownParts.get(childPart.getId()); if (realPart != null) { childParts.set(ii, realPart); } else if (childPart.getId() > 0) { MekHQ.getLogger().error(PartRef.class, String.format("Part %d ('%s') references missing child part %d", getId(), getName(), childPart.getId())); childParts.remove(ii); } } } }
Source:
<code>private void spawnOrb() { int xp = ThreadLocalRandom.current().nextInt(9) + 3; ExpBottleEvent event = EventFactory.getInstance() <START> .callEvent(new ExpBottleEvent(this, xp)); <END> ExperienceOrb orb = (ExperienceOrb) world.spawnEntity(location, EntityType.EXPERIENCE_ORB); orb.setExperience(xp); if (orb instanceof GlowExperienceOrb) { ((GlowExperienceOrb) orb).setFromBottle(true); } remove(); }</code><technical_language>Set xp variable result of event.getExperience()</technical_language>

Target:
private void spawnOrb() { int xp = ThreadLocalRandom.current().nextInt(9) + 3; ExpBottleEvent event = EventFactory.getInstance() .callEvent(new ExpBottleEvent(this, xp)); xp = event.getExperience(); ExperienceOrb orb = (ExperienceOrb) world.spawnEntity(location, EntityType.EXPERIENCE_ORB); orb.setExperience(xp); if (orb instanceof GlowExperienceOrb) { ((GlowExperienceOrb) orb).setFromBottle(true); } remove(); }
Source:
<code>protected void validateAndSetFiscalYear(CuBudgetAdjustmentDocument document, AccountingXmlDocumentEntry documentEntry) { Integer fiscalYear = documentEntry.getPostingFiscalYear(); if (ObjectUtils.isNull(fiscalYear)) { throw new RuntimeException("Fiscal year cannot be null"); } @SuppressWarnings("unchecked") List<FiscalYearFunctionControl> allowedYears = fiscalYearFunctionControlService.getBudgetAdjustmentAllowedYears(); boolean fiscalYearAllowed = allowedYears.stream() .anyMatch((fyFunctionControl) -> fiscalYear.equals(fyFunctionControl.getUniversityFiscalYear())); if (!fiscalYearAllowed) { <START> throw new RuntimeException("Budget Adjustments are not allowed for fiscal year: " + fiscalYear); <END> } document.setPostingYear(fiscalYear); }</code><technical_language>this a ValidationException, handled report correctly</technical_language>

Target:
protected void validateAndSetFiscalYear(CuBudgetAdjustmentDocument document, AccountingXmlDocumentEntry documentEntry) { Integer fiscalYear = documentEntry.getPostingFiscalYear(); if (ObjectUtils.isNull(fiscalYear)) { throw new ValidationException("Fiscal year cannot be null"); } @SuppressWarnings("unchecked") List<FiscalYearFunctionControl> allowedYears = fiscalYearFunctionControlService.getBudgetAdjustmentAllowedYears(); boolean fiscalYearAllowed = allowedYears.stream() .anyMatch((fyFunctionControl) -> fiscalYear.equals(fyFunctionControl.getUniversityFiscalYear())); if (!fiscalYearAllowed) { throw new ValidationException("Budget Adjustments are not allowed for fiscal year: " + fiscalYear); } document.setPostingYear(fiscalYear); }
Source:
<code>public long writeTo(WritableByteChannel channel) throws IOException { long written = 0; if (sentBytes < sizeInBytes()) { if (bufferToSend == null) { bufferToSend = ByteBuffer.allocate(sizeExcludingBlobAndCrcSize()); writeHeader(); int crcStart = bufferToSend.position(); bufferToSend.put(blobId.toBytes()); BlobPropertiesSerDe.putBlobPropertiesToBuffer(bufferToSend, properties); bufferToSend.putInt(usermetadata.capacity()); bufferToSend.put(usermetadata); bufferToSend.putShort((short) blobType.ordinal()); bufferToSend.putLong(blobSize); crc.update(bufferToSend.array(), bufferToSend.arrayOffset() + crcStart, bufferToSend.position() - crcStart); crc.update(blob.array(), blob.arrayOffset(), blob.remaining()); crcBuf.putLong(crc.getValue()); crcBuf.flip(); bufferToSend.flip(); } if (bufferToSend.hasRemaining()) { written = channel.write(bufferToSend); } if (!bufferToSend.hasRemaining()) { written += channel.write(blob); <START> if (!blob.hasRemaining()) { <END> blobWriteComplete = true; } } if (currentVersion == Put_Request_Version_V3 && blobWriteComplete && crcBuf.hasRemaining()) { written += channel.write(crcBuf); } sentBytes += written; } return written; }</code><technical_language>minor: blobWriteComplete = !blob.hasRemaining()</technical_language>

Target:
public long writeTo(WritableByteChannel channel) throws IOException { long written = 0; if (sentBytes < sizeInBytes()) { if (bufferToSend == null) { bufferToSend = ByteBuffer.allocate(sizeExcludingBlobAndCrcSize()); writeHeader(); int crcStart = bufferToSend.position(); bufferToSend.put(blobId.toBytes()); BlobPropertiesSerDe.putBlobPropertiesToBuffer(bufferToSend, properties); bufferToSend.putInt(usermetadata.capacity()); bufferToSend.put(usermetadata); bufferToSend.putShort((short) blobType.ordinal()); bufferToSend.putLong(blobSize); crc.update(bufferToSend.array(), bufferToSend.arrayOffset() + crcStart, bufferToSend.position() - crcStart); crc.update(blob.array(), blob.arrayOffset(), blob.remaining()); crcBuf.putLong(crc.getValue()); crcBuf.flip(); bufferToSend.flip(); } if (bufferToSend.hasRemaining()) { written = channel.write(bufferToSend); } if (!bufferToSend.hasRemaining()) { written += channel.write(blob); okayToWriteCrc = !blob.hasRemaining() && currentVersion == Put_Request_Version_V3; } if (okayToWriteCrc && crcBuf.hasRemaining()) { written += channel.write(crcBuf); } sentBytes += written; } return written; }
Source:
<code>public Optional<Metacard> apply(InputStream inputStream, WfsMetadata metadata) { if (!isStateValid(inputStream, metadata)) { LOGGER.debug("Transformer state is invalid: {}, {}", featureType, mappingEntries); return Optional.empty(); } lookupMetacardType(metadata); if (metacardType == null) { return Optional.empty(); } Map<String, String> contextMap = new HashMap<>(); populateContextMap(inputStream, contextMap); if (CollectionUtils.isEmpty(contextMap)) { return Optional.empty(); } MetacardImpl metacard = (MetacardImpl) createMetacard(contextMap); String id = null; if (StringUtils.isBlank(metacard.getId())) { id = contextMap.get(METACARD_ID); if (StringUtils.isNotBlank(id)) { metacard.setId(id); } else { LOGGER.debug("Feature id is blank. Unable to set metacard id."); } } metacard.setSourceId(metadata.getId()); Date date = new Date(); if (metacard.getEffectiveDate() == null) { metacard.setEffectiveDate(date); } if (metacard.getCreatedDate() == null) { metacard.setCreatedDate(date); } if (metacard.getModifiedDate() == null) { metacard.setModifiedDate(date); } if (StringUtils.isBlank(metacard.getTitle())) { metacard.setTitle(id); } metacard.setContentTypeName(metacardType.getName()); try { metacard.setTargetNamespace( new URI(WfsConstants.NAMESPACE_URN_ROOT + metacardType.getName())); } catch (URISyntaxException e) { LOGGER.debug( "Unable to set Target Namespace on metacard: {}.", <START> WfsConstants.NAMESPACE_URN_ROOT + metacardType.getName(), <END> e); } return Optional.of(metacard); }</code><technical_language>concatenate two? parameterized</technical_language>

Target:
public Optional<Metacard> apply(InputStream inputStream, WfsMetadata metadata) { if (!isStateValid(inputStream, metadata)) { LOGGER.debug("Transformer state is invalid: {}, {}", featureType, mappingEntries); return Optional.empty(); } lookupMetacardType(metadata); if (metacardType == null) { return Optional.empty(); } Map<String, String> contextMap = new HashMap<>(); populateContextMap(inputStream, contextMap); if (CollectionUtils.isEmpty(contextMap)) { return Optional.empty(); } return Optional.of(createMetacard(contextMap, metadata.getId())); }
Source:
<code>public void testCreateKey() throws Exception { MockWebServer server = mockEtcdJavaWebServer(); server.enqueue(new MockResponse().setBody(payloadFromResource("/keys-create.json")).setResponseCode(201)); EtcdApi etcdApi = api(server.getUrl("/")); KeysApi api = etcdApi.keysApi(); try { Key createdKey = api.createKey("hello", "world"); assertNotNull(createdKey); assertTrue(createdKey.node().key().equals("/hello")); assertTrue(createdKey.node().value().equals("world")); <START> assertSent(server, "PUT", "/" + EtcdApiMetadata.API_VERSION + "/keys/hello"); <END> } finally { etcdApi.close(); server.shutdown(); } }</code><technical_language>need verify body (the form params in this case) properly sent</technical_language>

Target:
public void testCreateKey() throws Exception { MockWebServer server = mockEtcdJavaWebServer(); server.enqueue(new MockResponse().setBody(payloadFromResource("/keys-create.json")).setResponseCode(201)); EtcdApi etcdApi = api(server.getUrl("/")); KeysApi api = etcdApi.keysApi(); try { Key createdKey = api.createKey("hello", "world"); assertNotNull(createdKey); assertTrue(createdKey.node().key().equals("/hello")); assertTrue(createdKey.node().value().equals("world")); assertSentWithFormData(server, "PUT", "/" + EtcdApiMetadata.API_VERSION + "/keys/hello", "value=world"); } finally { etcdApi.close(); server.shutdown(); } }
Source:
<code>public Network design(NetworkOffering offering, DeploymentPlan plan, Network userSpecified, Account owner) { PhysicalNetworkVO physnet = _physicalNetworkDao.findById(plan.getPhysicalNetworkId()); DataCenter dc = _dcDao.findById(plan.getDataCenterId()); if (!canHandle(offering, dc.getNetworkType(), physnet)) { if (s_logger.isDebugEnabled()) { <START> s_logger.debug("Refusing to design this network"); <END> } return null; } NetworkVO networkObject = (NetworkVO)super.design(offering, plan, userSpecified, owner); if (networkObject == null) { return null; } networkObject.setBroadcastDomainType(Networks.BroadcastDomainType.Vsp); return networkObject; }</code><technical_language>Please provide identifying/context information network for debugging purposes. Also, logged ERROR InvalidStateException thrown</technical_language>

Target:
public Network design(NetworkOffering offering, DeploymentPlan plan, Network userSpecified, Account owner) { PhysicalNetworkVO physnet = _physicalNetworkDao.findById(plan.getPhysicalNetworkId()); DataCenter dc = _dcDao.findById(plan.getDataCenterId()); if (!canHandle(offering, dc.getNetworkType(), physnet)) { if (s_logger.isDebugEnabled()) { s_logger.debug("Refusing to design network using network offering " + offering.getId() + (physnet != null ? " on physical network " + physnet.getId() : "")); } return null; } NetworkVO networkObject = (NetworkVO)super.design(offering, plan, userSpecified, owner); if (networkObject == null) { return null; } networkObject.setBroadcastDomainType(Networks.BroadcastDomainType.Vsp); return networkObject; }
Source:
<code>public static <V,T extends Throwable> hudson.remoting.Future<V> callAsync(final VirtualChannel channel, final Callable<V,T> callable) throws IOException { Future<hudson.remoting.Future<V>> future = Computer.threadPoolForRemoting.submit(new java.util.concurrent.Callable<hudson.remoting.Future<V>>() { @Override public hudson.remoting.Future<V> call() throws IOException { return channel.callAsync(callable); } }); try { return future.get(SupportPlugin.REMOTE_OPERATION_TIMEOUT_MS, TimeUnit.MILLISECONDS); <START> } catch (InterruptedException | ExecutionException | TimeoutException e) { <END> throw new IOException(e); } }</code><technical_language>want want cancel future TimeoutException else is interested in future exception is raised. task executing: } catch (InterruptedException | ExecutionException e) { throw new IOException(e); } catch (TimeoutException te) { future.cancel(true); throw new IOException(e); } @MRamonLeon confirm</technical_language>

Target:
public static <V,T extends Throwable> hudson.remoting.Future<V> callAsync(final VirtualChannel channel, final Callable<V,T> callable) throws IOException { Future<hudson.remoting.Future<V>> future = Computer.threadPoolForRemoting.submit(new java.util.concurrent.Callable<hudson.remoting.Future<V>>() { @Override public hudson.remoting.Future<V> call() throws IOException { return channel.callAsync(callable); } }); try { return future.get(SupportPlugin.REMOTE_OPERATION_TIMEOUT_MS, TimeUnit.MILLISECONDS); } catch (InterruptedException | ExecutionException e) { throw new IOException(e); } catch (TimeoutException te) { future.cancel(true); throw new IOException(te); } }
Source:
<code>protected Text createFilterText(Composite parent) { filterText = new Text(parent, SWT.NONE); Dialog.applyDialogFont(filterText); GridData data = new GridData(GridData.FILL_HORIZONTAL); data.horizontalAlignment = GridData.FILL; data.verticalAlignment = GridData.CENTER; filterText.setLayoutData(data); filterText.addKeyListener(new KeyAdapter() { @Override public void keyPressed(KeyEvent e) { if (e.keyCode == 0x0D) { gotoSelectedElement(); dispose(); } else if (e.keyCode == SWT.ARROW_DOWN) { delegate.getTreeViewer().getTree().setFocus(); } else if (e.character == SWT.ESC) { dispose(); } } }); filterText.setText(""); filterText.addModifyListener(e -> { AtomicBoolean firstMatchFound = new AtomicBoolean(false); TreeViewer viewer = delegate.getTreeViewer(); viewer.getControl().setRedraw(false); viewer.setFilters(new ViewerFilter() { @Override public boolean select(Viewer v, Object parentElement, Object element) { boolean result = isMatch(filterText.getText(), element); if (result && element instanceof FileDiffRegion && !firstMatchFound.getAndSet(true)) { viewer.setSelection( new StructuredSelection(element)); } return result; } }); viewer.expandAll(); <START> viewer.getControl().setRedraw(true); <END> }); return filterText; }</code><technical_language>canonical pattern for this is try { viewer.getControl().setRedraw(false); ... } finally { viewer.getControl().setRedraw(true); }</technical_language>

Target:
protected Text createFilterText(Composite parent) { filterText = new Text(parent, SWT.NONE); Dialog.applyDialogFont(filterText); GridData data = new GridData(GridData.FILL_HORIZONTAL); data.horizontalAlignment = GridData.FILL; data.verticalAlignment = GridData.CENTER; filterText.setLayoutData(data); filterText.addKeyListener(new KeyAdapter() { @Override public void keyPressed(KeyEvent e) { if (e.keyCode == 0x0D) { gotoSelectedElement(); dispose(); } else if (e.keyCode == SWT.ARROW_DOWN) { delegate.getTreeViewer().getTree().setFocus(); } else if (e.character == SWT.ESC) { dispose(); } } }); filterText.setText(""); filterText.addModifyListener(e -> { AtomicBoolean firstMatchFound = new AtomicBoolean(false); TreeViewer viewer = delegate.getTreeViewer(); viewer.getControl().setRedraw(false); String text=filterText.getText(); Pattern pattern = Pattern.compile( ".*" + text.replace('?', '.').replaceAll("\\*", "\\.\\*") + ".*", Pattern.CASE_INSENSITIVE); viewer.setFilters(new ViewerFilter() { @Override public boolean select(Viewer v, Object parentElement, Object element) { boolean result = isMatch(text, pattern, element); if (result && element instanceof FileDiffRegion && !firstMatchFound.getAndSet(true)) { viewer.setSelection( new StructuredSelection(element)); } return result; } }); viewer.expandAll(); viewer.getControl().setRedraw(true); }); return filterText; }
Source:
<code>public void cleanupOldUnusedTasks(Map<String, Set<DatastreamTask>> previousAssignmentByInstance, Map<String, List<DatastreamTask>> newAssignmentsByInstance) { Set<DatastreamTask> newTasks = newAssignmentsByInstance.values().stream().flatMap(Collection::stream).collect(Collectors.toSet()); Set<DatastreamTask> oldTasks = previousAssignmentByInstance.values().stream().flatMap(Collection::stream).collect(Collectors.toSet()); List<DatastreamTask> unusedTasks = oldTasks.stream().filter(x -> !newTasks.contains(x)).collect(Collectors.toList()); <START> LOG.info("Deleting the unused tasks "); <END> unusedTasks.forEach(t -> deleteConnectorTask(t.getConnectorType(), t.getDatastreamTaskName())); }</code><technical_language>nit: want print a value, passing print in log. change warn</technical_language>

Target:
public void cleanupOldUnusedTasks(Map<String, Set<DatastreamTask>> previousAssignmentByInstance, Map<String, List<DatastreamTask>> newAssignmentsByInstance) { Set<DatastreamTask> newTasks = newAssignmentsByInstance.values().stream().flatMap(Collection::stream).collect(Collectors.toSet()); Set<DatastreamTask> oldTasks = previousAssignmentByInstance.values().stream().flatMap(Collection::stream).collect(Collectors.toSet()); List<DatastreamTask> unusedTasks = oldTasks.stream().filter(x -> !newTasks.contains(x)).collect(Collectors.toList()); LOG.info("Deleting the unused tasks ", unusedTasks); unusedTasks.forEach(t -> deleteConnectorTask(t.getConnectorType(), t.getDatastreamTaskName())); }
Source:
<code><START> private List<String> objListToStrList(List<Object> oList) { <END> List<String> sList = new ArrayList<String>(oList.size()); for (Object o : oList) { sList.add(o.toString()); } return sList; }</code><technical_language>static</technical_language>

Target:
private static List<String> objListToStrList(List<Object> oList) { List<String> sList = new ArrayList<String>(oList.size()); for (Object o : oList) { sList.add(o.toString()); } return sList; }
Source:
<code>void reportMultipleCallInTree(List<Type> expectedExceptions, Tree treeToVisit, Tree reportLocation, String placeToRefactor) { List<Type> checkedTypes = expectedExceptions.stream() .filter(e -> !isChecked(e)) .collect(Collectors.toList()); if (checkedTypes.isEmpty()) { return; } MethodInvocationCollector visitor = new MethodInvocationCollector(symbol -> !JUNIT_FAIL_MATCHER.matches(symbol)); treeToVisit.accept(visitor); List<Tree> invocationTree = visitor.invocationTree; if (invocationTree.size() > 1) { reportIssue(reportLocation, <START> String.format("Refactor the %s in order to have only one invocation throwing an expected exception.", placeToRefactor), <END> secondaryLocations(invocationTree), null); } }</code><technical_language>I change "the excepted exception", "the exception". Simplicity is a key</technical_language>

Target:
void reportMultipleCallInTree(List<Type> expectedExceptions, Tree treeToVisit, Tree reportLocation, String placeToRefactor) { List<Type> checkedTypes = expectedExceptions.stream() .filter(e -> !isChecked(e)) .collect(Collectors.toList()); if (checkedTypes.isEmpty()) { return; } MethodInvocationCollector visitor = new MethodInvocationCollector(symbol -> !JUNIT_FAIL_MATCHER.matches(symbol)); treeToVisit.accept(visitor); List<Tree> invocationTree = visitor.invocationTree; if (invocationTree.size() > 1) { reportIssue(reportLocation, String.format("Refactor the %s to have only one invocation throwing an exception.", placeToRefactor), secondaryLocations(invocationTree), null); } }
Source:
<code>int getItemHeightInPixels () { checkWidget(); if (itemCount == 0) { long column = GTK.gtk_tree_view_get_column (handle, 0); int w = new int [1], h = new int [1]; ignoreSize = true; GTK.gtk_tree_view_column_cell_get_size (column, null, null, null, w, h); int height = h [0]; if (GTK.GTK3) { long textRenderer = getTextRenderer (column); GTK.gtk_cell_renderer_get_preferred_height_for_width (textRenderer, handle, 0, h, null); height += h [0]; } ignoreSize = false; return height; } else { int height = 0; long iter = OS.g_malloc (GTK.GtkTreeIter_sizeof ()); GTK.gtk_tree_model_get_iter_first (modelHandle, iter); int columnCount = Math.max (1, this.columnCount); for (int i=0; i<columnCount; i++) { long column = GTK.gtk_tree_view_get_column (handle, i); GTK.gtk_tree_view_column_cell_set_cell_data (column, modelHandle, iter, false, false); int w = new int [1], h = new int [1]; GTK.gtk_tree_view_column_cell_get_size (column, null, null, null, w, h); if (GTK.GTK3) { long textRenderer = getTextRenderer (column); int ypad = new int[1]; <START> GTK.gtk_cell_renderer_get_padding(textRenderer, null, ypad); <END> height = Math.max(height, h [0] + ypad [0]); } else { height = Math.max (height, h [0]); } } OS.g_free (iter); return height; } }</code><technical_language>Please add a check here: if (textRenderer != 0) GTK.gtk_cell_renderer_get_padding(textRenderer, null, ypad); line save space. a check call GTK a null renderer</technical_language>

Target:
int getItemHeightInPixels () { checkWidget(); if (itemCount == 0) { long column = GTK.gtk_tree_view_get_column (handle, 0); int w = new int [1], h = new int [1]; ignoreSize = true; GTK.gtk_tree_view_column_cell_get_size (column, null, null, null, w, h); int height = h [0]; if (GTK.GTK3) { long textRenderer = getTextRenderer (column); if (textRenderer != 0) GTK.gtk_cell_renderer_get_preferred_height_for_width (textRenderer, handle, 0, h, null); height += h [0]; } ignoreSize = false; return height; } else { int height = 0; long iter = OS.g_malloc (GTK.GtkTreeIter_sizeof ()); GTK.gtk_tree_model_get_iter_first (modelHandle, iter); int columnCount = Math.max (1, this.columnCount); for (int i=0; i<columnCount; i++) { long column = GTK.gtk_tree_view_get_column (handle, i); GTK.gtk_tree_view_column_cell_set_cell_data (column, modelHandle, iter, false, false); int w = new int [1], h = new int [1]; GTK.gtk_tree_view_column_cell_get_size (column, null, null, null, w, h); if (GTK.GTK3) { long textRenderer = getTextRenderer (column); int ypad = new int[1]; if (textRenderer != 0) GTK.gtk_cell_renderer_get_padding(textRenderer, null, ypad); height = Math.max(height, h [0] + ypad [0]); } else { height = Math.max (height, h [0]); } } OS.g_free (iter); return height; } }
Source:
<code>protected boolean revalidateCacheEntry() { <START> HttpResponse httpResponse = null; <END> try { httpResponse = cachingExec.revalidateCacheEntry(route, request, context, execAware, cacheEntry); final int statusCode = httpResponse.getStatusLine().getStatusCode(); return isNotServerError(statusCode) && isNotStale(httpResponse); } catch (final IOException ioe) { log.debug("Asynchronous revalidation failed due to I/O error", ioe); return false; } catch (final HttpException pe) { log.error("HTTP protocol exception during asynchronous revalidation", pe); return false; } catch (final RuntimeException re) { log.error("RuntimeException thrown during asynchronous revalidation: " + re); return false; } finally { if(httpResponse!=null) { EntityUtils.consumeQuietly(httpResponse.getEntity()); } } }</code><technical_language>## This kind of convoluted exception handling is absolutely unnecessary. code is perfectly sufficient. HttpResponse httpResponse = cachingExec.revalidateCacheEntry(... try { ... } finally { EntityUtils.consumeQuietly(httpResponse.getEntity()); }</technical_language>

Target:
protected boolean revalidateCacheEntry() { try { final CloseableHttpResponse httpResponse = cachingExec.revalidateCacheEntry(route, request, context, execAware, cacheEntry); try { final int statusCode = httpResponse.getStatusLine().getStatusCode(); return isNotServerError(statusCode) && isNotStale(httpResponse); } finally { httpResponse.close(); } } catch (final IOException ioe) { log.debug("Asynchronous revalidation failed due to I/O error", ioe); return false; } catch (final HttpException pe) { log.error("HTTP protocol exception during asynchronous revalidation", pe); return false; } catch (final RuntimeException re) { log.error("RuntimeException thrown during asynchronous revalidation: " + re); return false; } }