auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { SSOConfig config = (SSOConfig) request.getServletContext().getAttribute(SSOUtils.SSO_CONFIG); Credentials credentials = null; if (config.isAcceptBasicAuthHeaders()) { credentials = SSOUtils.getUserCredentialsFromHeader(request); } if (credentials != null) { request.getSession(true).setAttribute(SSOUtils.USER_CREDENTIALS, credentials); response.sendRedirect(request.getContextPath() + SSOUtils.LOGIN_PHASE3_URI); } if (doAuth(request, response)) { response.sendRedirect(request.getContextPath() + SSOUtils.LOGIN_PHASE4_URI); } else { response.sendRedirect(request.getContextPath() + SSOUtils.LOGIN_PHASE2_URI); } }

Target:
protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { SSOConfig config = (SSOConfig) request.getServletContext().getAttribute(SSOUtils.SSO_CONFIG); Credentials credentials = null; if (config.isAcceptBasicAuthHeaders()) { credentials = SSOUtils.getUserCredentialsFromHeader(request); } if (doAuth(request, response)) { response.sendRedirect(request.getContextPath() + SSOUtils.LOGIN_PHASE4_URI); } else if (credentials != null) { request.getSession(true).setAttribute(SSOUtils.USER_CREDENTIALS, credentials); response.sendRedirect(request.getContextPath() + SSOUtils.LOGIN_PHASE3_URI); } else { response.sendRedirect(request.getContextPath() + SSOUtils.LOGIN_PHASE2_URI); } }
Source:
public void shouldProcessFunctionInForEach() { Validation<String,String> v1 = Validation.valid("Eric Nelson"); Validation<String,String> v2 = Validation.invalid("error"); v1.forEach(System.out::println); v2.forEach(System.out::println); assertThat(true).isTrue(); }

Target:
public void shouldProcessFunctionInForEach() { final java.util.List<String> accumulator = new ArrayList<>(); Validation<String,String> v1 = Validation.valid("valid"); Validation<String,String> v2 = Validation.invalid("error"); accumulator.clear(); v1.forEach(accumulator::add); assertThat(accumulator.size()).isEqualTo(1); assertThat(accumulator.get(0)).isEqualTo("valid"); accumulator.clear(); v2.forEach(accumulator::add); assertThat(accumulator.size()).isEqualTo(0); }
Source:
public static String decryptPassword(String password) { try { return EngineEncryptionUtils.decrypt(password); } catch (Exception e) { log.debug("Failed to decrypt password, error message: {}", e.getMessage()); return password; } }

Target:
public static String decryptPassword(String password) { try { return EngineEncryptionUtils.decrypt(password); } catch (Exception e) { log.debug("Failed to decrypt password", e); return password; } }
Source:
public Guid persistAsyncTaskPlaceHolder(VdcActionType parentCommand) { Guid retValue = Guid.Empty; try { AsyncTasks task = createAsyncTask(new AsyncTaskCreationInfo(), parentCommand); retValue = task.getTaskId(); AsyncTaskUtils.addOrUpdateTaskInDB(task, null, EMPTY_GUID_ARRAY); } catch (RuntimeException ex) { log.errorFormat("Error during persistAsyncTaskPlaceHolders for command: {0}. Exception {1}", this.getClass().getName(), ex); } return retValue; }

Target:
public Guid persistAsyncTaskPlaceHolder(VdcActionType parentCommand) { Guid retValue = Guid.Empty; try { AsyncTasks task = createAsyncTask(new AsyncTaskCreationInfo(), parentCommand); retValue = task.getTaskId(); AsyncTaskUtils.addOrUpdateTaskInDB(task, null, EMPTY_GUID_ARRAY); } catch (RuntimeException ex) { log.errorFormat("Error during persistAsyncTaskPlaceHolders for command: {0}. Exception {1}", getClass().getName(), ex); } return retValue; }
Source:
public VdcQueryReturnValue RunPublicQuery(VdcQueryType queryType, VdcQueryParametersBase params) { log.debug("Server: RunPublicQuery invoked! " + queryType); debugQuery(queryType, params); return getBackend().runPublicQuery(queryType, params); }

Target:
public VdcQueryReturnValue RunPublicQuery(VdcQueryType queryType, VdcQueryParametersBase params) { log.debug("Server: runPublicQuery invoked! " + queryType); debugQuery(queryType, params); return getBackend().runPublicQuery(queryType, params); }
Source:
public static void doSetup() throws Exception { Map<String, String> props = Maps.newHashMapWithExpectedSize(1); props.put(Indexer.INDEX_LAZY_POST_BATCH_WRITE, "true"); setUpTestDriver(new ReadOnlyProps(props.entrySet().iterator())); }

Target:
public static void doSetup() throws Exception { Map<String, String> props = Maps.newHashMapWithExpectedSize(2); props.put(IndexRegionObserver.INDEX_LAZY_POST_BATCH_WRITE, "true"); setUpTestDriver(new ReadOnlyProps(props.entrySet().iterator())); }
Source:
public void setEditable(boolean editableMessage) { isEditable = editableMessage; fireDataChanged(); }

Target:
public void setEditable(boolean editableMessage) { editable = editableMessage; if(editableMessage){ fireDataChanged(); } }
Source:
private void removeEmptyStack(ArrayList<String> stackTypedPackages, Entry<String, Map<String, String>> entry) { if (!CollectionUtils.isEmpty(stackTypedPackages)) { Set<String> keySet = entry.getValue().keySet(); for (String stackTypedPackage : stackTypedPackages) { if (keySet.contains(stackTypedPackage)) { if (StringUtils.isEmpty(entry.getValue().get(stackTypedPackage))) { entry.getValue().remove(stackTypedPackage); } } } } }

Target:
private void removeEmptyStack(ArrayList<String> stackTypedPackages, Entry<String, Map<String, String>> entry) { if (!CollectionUtils.isEmpty(stackTypedPackages)) { Set<String> keySet = entry.getValue().keySet(); for (String stackTypedPackage : stackTypedPackages) { if (keySet.contains(stackTypedPackage)) { if (StringUtils.isEmpty(entry.getValue().get(stackTypedPackage))) { entry.getValue().remove(stackTypedPackage); LOGGER.info("Remove empty stack type: {}", stackTypedPackage); } } } } }
Source:
private void logPluginPathConfigProviderWarning(Map<String, String> rawOriginals) { String rawPluginPath = rawOriginals.get(PLUGIN_PATH_CONFIG); String transformedPluginPath = originalsStrings().get(PLUGIN_PATH_CONFIG); if (!Objects.equals(rawPluginPath, transformedPluginPath)) { log.error( "Config providers do not work with the plugin.path property. The raw value '{}' " + "will be used for plugin scanning, as opposed to the transformed value '{}'. " + "See <LINK_0> for more information.", rawPluginPath, transformedPluginPath ); } }

Target:
private void logPluginPathConfigProviderWarning(Map<String, String> rawOriginals) { String rawPluginPath = rawOriginals.get(PLUGIN_PATH_CONFIG); String transformedPluginPath = Objects.toString(originals().get(PLUGIN_PATH_CONFIG)); if (!Objects.equals(rawPluginPath, transformedPluginPath)) { log.warn( "Variables cannot be used in the 'plugin.path' property, since the property is " + "used by plugin scanning before the config providers that replace the " + "variables are initialized. The raw value '{}' was used for plugin scanning, as " + "opposed to the transformed value '{}', and this may cause unexpected results.", rawPluginPath, transformedPluginPath ); } }
Source:
private void uninstallPlugins(Set<String> pluginsToRemove) { for (String pluginKey : pluginsToRemove) { editionPluginUninstaller.uninstall(pluginKey); } }

Target:
private void uninstallPlugins(Set<String> pluginsToRemove) { pluginsToRemove.stream().forEach(editionPluginUninstaller::uninstall); }
Source:
public void testExceptionOnInsertFunctional() { for (int i = 0; i < SIZE; ++i) { cache(0).putIfAbsent(i * 4096, SIZE * 4096); } try { cache(0).putIfAbsent(-1, SIZE); fail("Should have thrown an exception!"); } catch (Throwable t) { Exceptions.assertException(ContainerFullException.class, getMostNestedSuppressedThrowable(t)); } }

Target:
public void testExceptionOnInsertFunctional() { for (int i = 0; i < SIZE; ++i) { cache(0).computeIfAbsent(i, k -> SIZE); } try { cache(0).computeIfAbsent(-1, k -> SIZE); fail("Should have thrown an exception!"); } catch (Throwable t) { Exceptions.assertException(ContainerFullException.class, getMostNestedSuppressedThrowable(t)); } }
Source:
public String deleteContentletsFromIdList(String List, String userId) throws PortalException, SystemException, DotDataException,DotSecurityException { List<String> conditionletWithErrors = new ArrayList<>(); validateUser(); ContentletAPI conAPI = APILocator.getContentletAPI(); String[] inodes = List.split(","); Integer contdeleted = 0; User user = UserLocalManagerUtil.getUserById(userId); for (int i = 0; i < inodes.length; i++) { inodes[i] = inodes[i].trim(); } List<Contentlet> contentlets = new ArrayList<Contentlet>(); for (String inode : inodes) { if (!inode.trim().equals("")) { contentlets.addAll(conAPI.getSiblings(inode)); } } if (!contentlets.isEmpty()) { for (Contentlet contentlet : contentlets) { contentlet.getMap().put(Contentlet.DONT_VALIDATE_ME, true); boolean delete = conAPI.delete(contentlet, user, true, true); if (!delete){ conditionletWithErrors.add(contentlet.getIdentifier()); }else{ contdeleted++; } } return getDeleteContentletMessage(user, conditionletWithErrors, contdeleted); }else{ return LanguageUtil.get(user, "message.contentlet.delete.error.dontExists"); } }

Target:
public String deleteContentletsFromIdList(String List, String userId) throws PortalException, SystemException, DotDataException,DotSecurityException { List<String> conditionletWithErrors = new ArrayList<>(); validateUser(); ContentletAPI conAPI = APILocator.getContentletAPI(); String[] inodes = List.split(","); Integer contdeleted = 0; User user = UserLocalManagerUtil.getUserById(userId); for (int i = 0; i < inodes.length; i++) { inodes[i] = inodes[i].trim(); } List<Contentlet> contentlets = new ArrayList<Contentlet>(); for (String inode : inodes) { if (!inode.trim().equals("")) { contentlets.addAll(conAPI.getSiblings(inode)); } } if (!contentlets.isEmpty()) { for (Contentlet contentlet : contentlets) { boolean delete = conAPI.destroy(contentlet, user, true); if (!delete){ conditionletWithErrors.add(contentlet.getIdentifier()); }else{ contdeleted++; } } return getDeleteContentletMessage(user, conditionletWithErrors, contdeleted); }else{ return LanguageUtil.get(user, "message.contentlet.delete.error.dontExists"); } }
Source:
public void testZtestPostAggregator() throws Exception { ConstantPostAggregator successCount1, sample1Size, successCount2, sample2Size; successCount1 = new ConstantPostAggregator("successCountPopulation1", 39244); sample1Size = new ConstantPostAggregator("sampleSizePopulation1", 394298); successCount2 = new ConstantPostAggregator("successCountPopulation2", 8991275); sample2Size = new ConstantPostAggregator("sampleSizePopulation2", 9385573); List<PostAggregator> postAggregatorList; postAggregatorList = Lists.newArrayList( successCount1, sample1Size, successCount2, sample2Size ); Map<String, Object> metricValues = new HashMap<>(); for (PostAggregator pa : postAggregatorList) { metricValues.put(pa.getName(), ((ConstantPostAggregator) pa).getConstantValue()); } ztestPostAggregator = new ZtestPostAggregator( "zscore", successCount1, sample1Size, successCount2, sample2Size ); double zscore = ((Number) ztestPostAggregator.compute(metricValues)).doubleValue(); Assert.assertEquals(-1783.8762354220219, zscore, 0.0001 ); System.out.print(ztestPostAggregator.toString()); }

Target:
public void testZtestPostAggregator() throws Exception { ConstantPostAggregator successCount1, sample1Size, successCount2, sample2Size; successCount1 = new ConstantPostAggregator("successCountPopulation1", 39244); sample1Size = new ConstantPostAggregator("sampleSizePopulation1", 394298); successCount2 = new ConstantPostAggregator("successCountPopulation2", 8991275); sample2Size = new ConstantPostAggregator("sampleSizePopulation2", 9385573); List<PostAggregator> postAggregatorList; postAggregatorList = Lists.newArrayList( successCount1, sample1Size, successCount2, sample2Size ); Map<String, Object> metricValues = new HashMap<>(); for (PostAggregator pa : postAggregatorList) { metricValues.put(pa.getName(), ((ConstantPostAggregator) pa).getConstantValue()); } ztestPostAggregator = new ZtestPostAggregator( "zscore", successCount1, sample1Size, successCount2, sample2Size ); double zscore = ((Number) ztestPostAggregator.compute(metricValues)).doubleValue(); Assert.assertEquals(-1783.8762354220219, zscore, 0.0001 ); }
Source:
private void load(File directory) throws ConfigurationException { if (!directory.exists()) { log.warn("The directory \"" + directory.getAbsolutePath() + "\" containing the configuration files doesn't " + "exist."); } else { File[] files = directory.listFiles(); if (files != null) { sort(files); for (File file : files) { if (file.getName().endsWith(".properties")) { try { ExtensionEntry entry = new ExtensionEntry(file); ExtensionEntry alreadyLoded = loadedEntries.get(entry.getName()); if (alreadyLoded != null) { throw new ConfigurationException("Could not load the configuration file \"" + file.getAbsolutePath() + "\". The configuration file + \"" + alreadyLoded.file.getAbsolutePath() + "\" already has the name " + entry.getName()); } loadedEntries.put(entry.name, entry); } catch (IOException exception) { throw new ConfigurationException( "Can't load object configuration file \"" + file.getAbsolutePath() + "\".", exception); } } } } } }

Target:
private void load(File directory) throws ConfigurationException { if (!directory.exists()) { log.warn("The directory \"" + directory.getAbsolutePath() + "\" containing the configuration files doesn't " + "exist."); } else { File[] files = directory.listFiles(); if (files != null) { sort(files); for (File file : files) { if (file.getName().endsWith(".properties")) { try { ExtensionEntry entry = new ExtensionEntry(file); ExtensionEntry alreadyLoded = loadedEntries.get(entry.getName()); if (alreadyLoded != null) { throw new ConfigurationException(String.format("Could not load the configuration file \"%1$s\". The configuration file + \"%2$s\" already has the name %3$s", file.getAbsolutePath(), alreadyLoded.file.getAbsolutePath(), entry.getName())); } loadedEntries.put(entry.name, entry); } catch (IOException exception) { throw new ConfigurationException(String.format("Can't load object configuration file \"%1$s\"", file.getAbsolutePath())); } } } } } }
Source:
public GithubBranchSource owner(final String owner) { this.owner.set(owner); this.owner.sendKeys("" + Keys.TAB); return this; }

Target:
public GithubBranchSource owner(final String owner) { this.owner.set(owner); final String elementTag = this.owner.resolve().getTagName(); final String elementNameAttribute = this.owner.resolve().getAttribute("name"); executeScript("var event = new Event('change');document.getElementsBySelector(\"" + elementTag + "[name='" + elementNameAttribute + "']\")[0].dispatchEvent(event);"); return this; }
Source:
public void testUpdate() throws IOException, VictimsException { try { VictimsDBInterface db = VictimsDB.db(); System.out.println(" DB records: " + db.getRecordCount()); System.out.println(" Syncing..."); db.synchronize(); System.out.println(" DB records: " + db.getRecordCount()); System.out.println("Database last updated on: " + db.lastUpdated().toString()); } catch (VictimsException ex){ if ("Failed to sync database".equals(ex.getMessage())) log.warning(ex.getMessage()); else throw ex; } }

Target:
public void testUpdate() throws IOException, VictimsException { final String victimsDBdir = "target/victimsDB"; System.setProperty(VictimsConfig.Key.HOME, victimsDBdir); FileUtils.deleteQuietly(new File(victimsDBdir)); try { VictimsDBInterface db = VictimsDB.db(); int recordCount = db.getRecordCount(); System.out.println(" DB records: " + recordCount); System.out.println(" Database last updated on: " + db.lastUpdated().toString()); Assert.assertEquals(0, recordCount); System.out.println(" Syncing..."); db.synchronize(); recordCount = db.getRecordCount(); System.out.println(" DB records: " + recordCount); Assert.assertTrue(recordCount > 200); System.out.println(" Database last updated on: " + db.lastUpdated().toString()); } catch (VictimsException ex) { if ("Failed to sync database".equals(ex.getMessage())) log.warning(ex.getMessage()); else throw ex; } }
Source:
public CleanUpDomainCommand(VspDomainCleanUp domainCleanUp) { super(); this._domainCleanUp = domainCleanUp; }

Target:
public CleanUpDomainCommand(VspDomainCleanUp domainCleanUp) { super(); Preconditions.checkNotNull(domainCleanUp); this._domainCleanUp = domainCleanUp; }
Source:
public long countRecordsByLookup(Long entityId, String lookupName, Map<String, Object> lookupMap) { EntityDto entity = getEntity(entityId); validateCredentialsForReading(entity); LookupDto lookup = getLookupByName(entityId, lookupName); Map<String, FieldDto> fieldMap = entityService.getLookupFieldsMapping(entityId, lookupName); MotechDataService service = getServiceForEntity(entity); try { LookupExecutor lookupExecutor = new LookupExecutor(service, lookup, fieldMap); return lookupExecutor.executeCount(lookupMap); } catch (RuntimeException e) { throw new LookupExecutionException(e, "mds.error.lookupExecError"); } }

Target:
public long countRecordsByLookup(Long entityId, String lookupName, Map<String, Object> lookupMap) { EntityDto entity = getEntity(entityId); validateCredentialsForReading(entity); LookupDto lookup = getLookupByName(entityId, lookupName); Map<String, FieldDto> fieldMap = entityService.getLookupFieldsMapping(entityId, lookupName); MotechDataService service = getServiceForEntity(entity); try { LookupExecutor lookupExecutor = new LookupExecutor(service, lookup, fieldMap); return lookupExecutor.executeCount(lookupMap); } catch (RuntimeException e) { throw new LookupExecutionException(e, LOOKUP_EXCEPTION_MESSAGE_KEY); } }
Source:
public void testInitWithConfigDeleted() { ContentDirectoryMonitor monitor = new ContentDirectoryMonitor( camelContext, mock(AttributeRegistry.class), 1, 1, Runnable::run); monitor.systemSubjectBinder = exchange -> {}; monitor.setNumThreads(1); monitor.setReadLockIntervalMilliseconds(1000); monitor.setMonitoredDirectoryPath(monitoredDirectoryPath); monitor.setConfigDeleted(true); monitor.attemptAddRoutes(); assertThat( "The content directory monitor should have no route definitions", monitor.getRouteDefinitions(), hasSize(0)); }

Target:
public void testInitWithConfigDeleted() { monitor.destroy(0); monitor.init(); assertThat( "The content directory monitor should have no route definitions", camelContext.getRouteDefinitions(), hasSize(0)); }
Source:
private Map<String, Object> getMap(AnnotationFieldCollection annotation) { Map<String, Object> metadataMap = new HashMap<>(); for (AnnotationField f : annotation.getFields()) { metadataMap.put(f.getName(), f.getValue()); } if (metadataMap.containsKey(REQUIRES_HTML_CONVERSION) && COMMENT_KEY.equals(metadataMap.get(REQUIRES_HTML_CONVERSION))) { String syntax = (String) metadataMap.getOrDefault(String.format("%s_syntax", COMMENT_KEY), "xwiki/2.1"); metadataMap .put(COMMENT_KEY, this.htmlConverter.fromHTML(String.valueOf(metadataMap.get(COMMENT_KEY)), syntax)); metadataMap.remove(REQUIRES_HTML_CONVERSION); } return metadataMap; }

Target:
private Map<String, Object> getMap(AnnotationFieldCollection annotation) { Map<String, Object> metadataMap = new HashMap<>(); for (AnnotationField f : annotation.getFields()) { metadataMap.put(f.getName(), f.getValue()); } if (metadataMap.containsKey(REQUIRES_HTML_CONVERSION) && COMMENT_KEY.equals(metadataMap.get(REQUIRES_HTML_CONVERSION)) && metadataMap.containsKey(COMMENT_SYNTAX_KEY)) { String syntax = (String) metadataMap.get(COMMENT_SYNTAX_KEY); String convertedComment = this.htmlConverter.fromHTML(String.valueOf(metadataMap.get(COMMENT_KEY)), syntax); metadataMap.put(COMMENT_KEY, convertedComment); metadataMap.remove(REQUIRES_HTML_CONVERSION); } return metadataMap; }
Source:
private static Identity applyRules(final Identity identity) { if (identity.urn().isEmpty()) { throw new DecodingException("urn is empty"); } if (!identity.urn().matches("^(?i)^urn(?-i):[a-z]{1,31}(:([\\-a-zA-Z0-9/]|%[0-9a-fA-F]{2})*)+(\\?\\w+(=([\\-a-zA-Z0-9/]|%[0-9a-fA-F]{2})*)?(&\\w+(=([\\-a-zA-Z0-9/]|%[0-9a-fA-F]{2})*)?)*)?\\*?$")) { throw new DecodingException("urn isn't valid"); } return identity; }

Target:
private static Identity applyRules(final Identity identity) { if (identity.urn().isEmpty()) { throw new DecodingException("urn is empty"); } if (!identity.urn().matches("^(?i)^urn(?-i):[a-zA-Z0-9]([\\-a-zA-Z0-9]{1,31})(:([\\-a-zA-Z0-9/]|%[0-9a-fA-F]{2})*)+(\\?\\w+(=([\\-a-zA-Z0-9/]|%[0-9a-fA-F]{2})*)?(&\\w+(=([\\-a-zA-Z0-9/]|%[0-9a-fA-F]{2})*)?)*)?\\*?$")) { throw new DecodingException("urn isn't valid"); } return identity; }
Source:
public void addFullBody() throws Exception { String mockBody = "{\"message\":{\"data\":\"dGVzdA==\"," + "\"attributes\":{},\"messageId\":\"91010751788941\"" + ",\"publishTime\":\"2017-09-25T23:16:42.302Z\"}}"; mockMvc .perform(post("/").contentType(MediaType.APPLICATION_JSON).content(mockBody)) .andExpect(status().isOk()); }

Target:
public void addFullBody() throws Exception { mockMvc .perform(post("/").contentType(MediaType.APPLICATION_JSON).content(mockBody)) .andExpect(status().isOk()); }
Source:
protected void onFinishInflate() { super.onFinishInflate(); View.inflate(getContext(), R.layout.merge_create_channel_view, this); newChannelName = Views.findById(this, R.id.newChannelName); privateChannelSwitch = Views.findById(this, R.id.privateChannelSwitch); toolbar = Views.findById(this, R.id.toolbar); toolbar.setTitle(R.string.createChannel); toolbar.inflateMenu(R.menu.new_channel_menu); toolbar.setNavigationIcon(R.drawable.ic_clear_white_24dp); }

Target:
protected void onFinishInflate() { super.onFinishInflate(); View.inflate(getContext(), R.layout.merge_create_channel_view, this); newChannelName = Views.findById(this, R.id.newChannelName); privateChannelSwitch = Views.findById(this, R.id.privateChannelSwitch); setupToolbar(); }
Source:
public int getBatchSizeForMutations() { return 8_0000; }

Target:
public int getBatchSizeForMutations() { return 8_000; }
Source:
public static Collection<EClass> getSubClasses(EClass superClass) { return getSubClasses(superClass, false); }

Target:
public static Collection<EClass> getSubClasses(EClass superClass) { final Collection<EClass> classes = new HashSet<EClass>(); for (final EPackage ePackage : getAllRegisteredEPackages()) { for (final EClassifier eClassifier : ePackage.getEClassifiers()) { if (eClassifier instanceof EClass) { final EClass eClass = (EClass) eClassifier; if (superClass.isSuperTypeOf(eClass) && !eClass.isAbstract() && !eClass.isInterface()) { classes.add(eClass); } } } } return classes; }
Source:
private boolean getJUnitTestCaseProposal(IInvocationContext context, ASTNode coveringNode, ArrayList<ICommandAccess> resultingCollections) { if (coveringNode instanceof SimpleName && coveringNode.getParent() instanceof TypeDeclaration) { SimpleName name= (SimpleName) coveringNode; String idName= name.getIdentifier() + JavaModelUtil.DEFAULT_CU_SUFFIX; String unitName= context.getCompilationUnit().getElementName(); if (unitName.equals(idName)) { if (resultingCollections != null) { Image image= JavaPluginImages.get(JavaPluginImages.IMG_OBJS_TEST_CASE); String label= Messages.format(CorrectionMessages.QuickAssistProcessor_create_new_junit_test_case, unitName); Change change= new NullChange(CorrectionMessages.QuickAssistProcessor_create_new_junit_test_case_desc); NewJUnitTestCaseProposal proposal= new NewJUnitTestCaseProposal(label, change, IProposalRelevance.CREATE_JUNIT_TEST_CASE, image, context.getASTRoot()); resultingCollections.add(proposal); } return true; } } return false; }

Target:
private boolean getJUnitTestCaseProposal(IInvocationContext context, ASTNode coveringNode, ArrayList<ICommandAccess> resultingCollections) { if (coveringNode instanceof SimpleName && coveringNode.getParent() instanceof AbstractTypeDeclaration) { SimpleName name= (SimpleName) coveringNode; String idName= name.getIdentifier() + JavaModelUtil.DEFAULT_CU_SUFFIX; String unitName= context.getCompilationUnit().getElementName(); if (unitName.equals(idName)) { if (resultingCollections != null) { Image image= JavaPluginImages.DESC_OBJS_TEST_CASE.createImage(); String label= Messages.format(CorrectionMessages.QuickAssistProcessor_create_new_junit_test_case, unitName); Change change= new NullChange(CorrectionMessages.QuickAssistProcessor_create_new_junit_test_case_desc); NewJUnitTestCaseProposal proposal= new NewJUnitTestCaseProposal(label, change, IProposalRelevance.CREATE_JUNIT_TEST_CASE, image, context.getASTRoot()); resultingCollections.add(proposal); } return true; } } return false; }
Source:
public void test2GhzQualifiedNo5GhzAvailable() { testStayOrSwitch(mThresholdQualifiedRssi2G + 1, false, mThresholdQualifiedRssi2G + 10, false, false); }

Target:
public void test2GhzQualifiedNo5GhzAvailable() { testStayOrSwitch(mThresholdQualifiedRssi2G, false, mThresholdQualifiedRssi2G + 10, false, false); }
Source:
public static String getIDsOfPerunBeans(List<? extends PerunBean> listOfBeans) { if (listOfBeans == null || listOfBeans.isEmpty()) { return ""; } Boolean isFirstIteration = true; StringBuilder str = new StringBuilder(); for(PerunBean perunBean : listOfBeans) { if(isFirstIteration) { str.append(perunBean.getId()); isFirstIteration = false; } else { str.append(",").append(perunBean.getId()); } } return new String(str); }

Target:
public static String getIDsOfPerunBeans(List<? extends PerunBean> listOfBeans) { if (listOfBeans == null || listOfBeans.isEmpty()) { return ""; } Boolean isFirstIteration = true; StringBuilder str = new StringBuilder(); for(PerunBean perunBean : listOfBeans) { if(isFirstIteration) { str.append(perunBean.getId()); isFirstIteration = false; } else { str.append(",").append(perunBean.getId()); } } return str.toString(); }
Source:
public List<Storage> listStorages() { return jdbcTemplate.query("select st_id, st_type, st_configuration from zn_data.storage order by st_id", storageRowMapper); }

Target:
public List<Storage> listStorages() { return jdbcTemplate.query("SELECT st_id, st_type, st_configuration FROM zn_data.storage ORDER BY st_id", storageRowMapper); }
Source:
@Test public void insertCollectionWithCustomId() { final List<User> users = putUsers(1); final User user = users.get(0); assertNotNull(user.getId()); final Tweet tweet = TestFactory.newTweet(user.getId()); final PutResult putResult = storIOSQLiteDb .put() .object(tweet) .withMapFunc(Tweet.MAP_TO_CONTENT_VALUES) .withPutResolver(Tweet.PUT_RESOLVER) .prepare() .executeAsBlocking(); assertNotNull(putResult); assertEquals(true, putResult.wasInserted()); final Cursor cursor = db.query(Tweet.TABLE, null, null, null, null, null, null); assertEquals(1, cursor.getCount()); assertTrue(cursor.moveToNext()); assertEquals(tweet, Tweet.MAP_FROM_CURSOR.map(cursor)); cursor.close(); }

Target:
@Test public void insertCollectionWithCustomId() { final List<User> users = putUsers(1); final User user = users.get(0); assertNotNull(user.getId()); final Tweet tweet = TestFactory.newTweet(user.getId()); final PutResult putResult = storIOSQLiteDb .put() .object(tweet) .withMapFunc(Tweet.MAP_TO_CONTENT_VALUES) .withPutResolver(Tweet.PUT_RESOLVER) .prepare() .executeAsBlocking(); assertNotNull(putResult); assertTrue(putResult.wasInserted()); final Cursor cursor = db.query(Tweet.TABLE, null, null, null, null, null, null); assertEquals(1, cursor.getCount()); assertTrue(cursor.moveToNext()); assertEquals(tweet, Tweet.MAP_FROM_CURSOR.map(cursor)); cursor.close(); }
Source:
public void testGetUserAgent_fromExternalVersionTestJar() throws IOException { assertThat(UserAgents.getUserAgent(VersionTest.class), is(String.format("test-name (test-version)"))); }

Target:
public void testGetUserAgent_fromExternalVersionTestJar() throws IOException { assertThat(UserAgents.fromClass(VersionTest.class), is("test-name (test-version)")); }
Source:
private void alignmentBordersSanityCheck(final byte[] ref) { if (sequenceId == UNMAPPED_OR_NO_REFERENCE) return ; if (alignmentStart > 0 && sequenceId >= 0 && ref == null) throw new NullPointerException("Mapped slice reference is null."); if (alignmentStart > ref.length) { log.error(String.format("Slice mapped outside of reference: seqID=%d, start=%d, counter=%d.", sequenceId, alignmentStart, globalRecordCounter)); throw new RuntimeException("Slice mapped outside of the reference."); } if (alignmentStart - 1 + alignmentSpan > ref.length) { log.warn(String.format("Slice partially mapped outside of reference: seqID=%d, start=%d, span=%d, counter=%d.", sequenceId, alignmentStart, alignmentSpan, globalRecordCounter)); } }

Target:
private void alignmentBordersSanityCheck(final byte[] ref) { if (sequenceId == SAMRecord.NO_ALIGNMENT_REFERENCE_INDEX) return ; if (alignmentStart > 0 && sequenceId >= 0 && ref == null) throw new IllegalArgumentException ("Mapped slice reference is null."); if (alignmentStart > ref.length) { log.error(String.format("Slice mapped outside of reference: seqID=%d, start=%d, counter=%d.", sequenceId, alignmentStart, globalRecordCounter)); throw new RuntimeException("Slice mapped outside of the reference."); } if (alignmentStart - 1 + alignmentSpan > ref.length) { log.warn(String.format("Slice partially mapped outside of reference: seqID=%d, start=%d, span=%d, counter=%d.", sequenceId, alignmentStart, alignmentSpan, globalRecordCounter)); } }
Source:
public void reset(MessageBufferOutput out) throws IOException { MessageBufferOutput newOut = checkNotNull(out, "MessageBufferOutput is null"); this.out = newOut; this.position = 0; }

Target:
public MessageBufferOutput reset(MessageBufferOutput out) throws IOException { MessageBufferOutput newOut = checkNotNull(out, "MessageBufferOutput is null"); MessageBufferOutput old = this.out; this.out = newOut; this.position = 0; return old; }
Source:
private void runFafReplayFile(Path path) throws IOException { byte[] rawReplayBytes = replayFileReader.readRawReplayData(path); Path tempSupComReplayFile = preferencesService.getCacheDirectory().resolve(TEMP_SCFA_REPLAY_FILE_NAME); createDirectories(tempSupComReplayFile.getParent()); Files.copy(new ByteArrayInputStream(rawReplayBytes), tempSupComReplayFile, StandardCopyOption.REPLACE_EXISTING); LocalReplayInfo replayInfo = replayFileReader.parseMetaData(path); String gameType = replayInfo.getFeaturedMod(); Integer replayId = replayInfo.getUid(); Map<String, Integer> modVersions = replayInfo.getFeaturedModVersions(); String mapName = replayInfo.getMapname(); if (StringUtils.isEmptyOrNull(mapName)) { mapName = parseMapFolderName(rawReplayBytes); } if (StringUtils.equalsIgnoreCase(mapName, "None")) { String maybeMapGen = parseMapFolderName(rawReplayBytes); if (mapGeneratorService.isGeneratedMap(maybeMapGen)) { mapName = maybeMapGen; } } Set<String> simMods = replayInfo.getSimMods() != null ? replayInfo.getSimMods().keySet() : emptySet(); Integer version = parseSupComVersion(rawReplayBytes); gameService.runWithReplay(tempSupComReplayFile, replayId, gameType, version, modVersions, simMods, mapName); }

Target:
private void runFafReplayFile(Path path) throws IOException { byte[] rawReplayBytes = replayFileReader.readRawReplayData(path); Path tempSupComReplayFile = preferencesService.getCacheDirectory().resolve(TEMP_SCFA_REPLAY_FILE_NAME); createDirectories(tempSupComReplayFile.getParent()); Files.copy(new ByteArrayInputStream(rawReplayBytes), tempSupComReplayFile, StandardCopyOption.REPLACE_EXISTING); LocalReplayInfo replayInfo = replayFileReader.parseMetaData(path); String gameType = replayInfo.getFeaturedMod(); Integer replayId = replayInfo.getUid(); Map<String, Integer> modVersions = replayInfo.getFeaturedModVersions(); String mapName = replayInfo.getMapname(); if (StringUtils.isEmptyOrNull(mapName)) { mapName = parseMapFolderName(rawReplayBytes); } if (StringUtils.equalsIgnoreCase(mapName, "None")) { String maybeMapGen = parseMapName(rawReplayBytes).replaceAll(".scmap",""); if (mapGeneratorService.isGeneratedMap(maybeMapGen)) { mapName = maybeMapGen; } } Set<String> simMods = replayInfo.getSimMods() != null ? replayInfo.getSimMods().keySet() : emptySet(); Integer version = parseSupComVersion(rawReplayBytes); gameService.runWithReplay(tempSupComReplayFile, replayId, gameType, version, modVersions, simMods, mapName); }
Source:
protected void onMethodInvocationFound(MethodInvocationTree mit) { ExpressionTree firstArgument = mit.arguments().get(0); if (!firstArgument.is(Tree.Kind.METHOD_REFERENCE)) { return; } MethodReferenceTree mrt = (MethodReferenceTree) firstArgument; Tree expression = mrt.expression(); if (isAddMethod(mrt.method()) && expression.is(Tree.Kind.IDENTIFIER)) { context.reportIssue(this, mrt, String.format("Use \"collect(Collectors.toList())\" instead of \"forEach(%s::add)\".", ((IdentifierTree) expression).name())); } }

Target:
protected void onMethodInvocationFound(MethodInvocationTree mit) { ExpressionTree firstArgument = mit.arguments().get(0); if (firstArgument.is(Tree.Kind.METHOD_REFERENCE)) { handleMethodReference((MethodReferenceTree) firstArgument); } else if (firstArgument.is(Tree.Kind.LAMBDA_EXPRESSION)) { handleLambdaExpression((LambdaExpressionTree) firstArgument); } }
Source:
public IRubyObject add(final ThreadContext threadContext, final IRubyObject[] args, Block block) { final IRubyObject rubyMessage; final String progname; if (args.length >= 2 && !args[1].isNil()) { rubyMessage = args[1]; progname = args[2].asJavaString(); } else if (block.isGiven()) { rubyMessage = block.yield(threadContext, getRuntime().getNil()); } else { rubyMessage = args[2]; } final Cursor cursor = getSourceLocation(rubyMessage); final String message = formatMessage(rubyMessage); final Severity severity = mapRubyLogLevel(args[0]); final LogRecord record = createLogRecord(threadContext, severity, cursor, message); rootLogHandler.log(record); return getRuntime().getNil(); }

Target:
public IRubyObject add(final ThreadContext threadContext, final IRubyObject[] args, Block block) { final IRubyObject rubyMessage; if (args.length >= 2 && !args[1].isNil()) { rubyMessage = args[1]; } else if (block.isGiven()) { rubyMessage = block.yield(threadContext, getRuntime().getNil()); } else { rubyMessage = args[2]; } final Cursor cursor = getSourceLocation(rubyMessage); final String message = formatMessage(rubyMessage); final Severity severity = mapRubyLogLevel(args[0]); final LogRecord record = createLogRecord(threadContext, severity, cursor, message); rootLogHandler.log(record); return getRuntime().getNil(); }
Source:
public UnionType setElements(NodeList<ReferenceType<?>> elements) { notifyPropertyChange("elements", this.elements, elements); this.elements = assertNotNull(elements); setAsParentNodeOf(this.elements); return this; }

Target:
public UnionType setElements(NodeList<ReferenceType<?>> elements) { notifyPropertyChange(ObservableProperty.ELEMENTS, this.elements, elements); this.elements = assertNotNull(elements); setAsParentNodeOf(this.elements); return this; }
Source:
public String toString() { StringBuffer result = new StringBuffer(); result.append("Concur Account info: "); result.append(KFSConstants.NEWLINE); result.append("Chart: " + this.chart); result.append(KFSConstants.NEWLINE); result.append("Account number: " + this.accountNumber); result.append(KFSConstants.NEWLINE); result.append("Sub Account number: " + this.subAccountNumber); result.append(KFSConstants.NEWLINE); result.append("Object code: " + this.objectCode); result.append(KFSConstants.NEWLINE); result.append("Sub object code: " + this.subObjectCode); result.append(KFSConstants.NEWLINE); result.append("Project code: " + this.projectCode); result.append(KFSConstants.NEWLINE); result.append("Org Ref Id: " + this.orgRefId); result.append(KFSConstants.NEWLINE); return result.toString(); }

Target:
public String toString() { StringBuilder result = new StringBuilder(); result.append("Concur Account info: "); result.append(KFSConstants.NEWLINE); result.append("Chart: " + this.chart); result.append(KFSConstants.NEWLINE); result.append("Account number: " + this.accountNumber); result.append(KFSConstants.NEWLINE); result.append("Sub Account number: " + this.subAccountNumber); result.append(KFSConstants.NEWLINE); result.append("Object code: " + this.objectCode); result.append(KFSConstants.NEWLINE); result.append("Sub object code: " + this.subObjectCode); result.append(KFSConstants.NEWLINE); result.append("Project code: " + this.projectCode); result.append(KFSConstants.NEWLINE); result.append("Org Ref Id: " + this.orgRefId); result.append(KFSConstants.NEWLINE); return result.toString(); }
Source:
public void edit(final InstallModel model) { driver.edit(model); if (model.getVds().getStatus() == VDSStatus.InstallFailed) { rbPassword.setValue(true); model.setAuthenticationMethod(AuthenticationMethod.Password); displayPasswordField(true); } else { rbPublicKey.setValue(true); model.setAuthenticationMethod(AuthenticationMethod.PublicKey); displayPasswordField(false); } rbPassword.addValueChangeHandler(new ValueChangeHandler<Boolean>() { @Override public void onValueChange(ValueChangeEvent<Boolean> event) { model.setAuthenticationMethod(AuthenticationMethod.Password); displayPasswordField(true); } }); rbPublicKey.addValueChangeHandler(new ValueChangeHandler<Boolean>() { @Override public void onValueChange(ValueChangeEvent<Boolean> event) { model.setAuthenticationMethod(AuthenticationMethod.PublicKey); displayPasswordField(false); } }); userNameEditor.setEnabled(false); networkProviderWidget.edit(model.getNetworkProviderModel()); }

Target:
public void edit(final InstallModel model) { driver.edit(model); boolean installedFailed = model.getVds().getStatus() == VDSStatus.InstallFailed; model.setAuthenticationMethod(installedFailed ? AuthenticationMethod.Password: AuthenticationMethod.PublicKey); displayPasswordField(installedFailed); rbPassword.setValue(installedFailed); rbPublicKey.setValue(!installedFailed); rbPassword.addValueChangeHandler(new ValueChangeHandler<Boolean>() { @Override public void onValueChange(ValueChangeEvent<Boolean> event) { model.setAuthenticationMethod(AuthenticationMethod.Password); displayPasswordField(true); } }); rbPublicKey.addValueChangeHandler(new ValueChangeHandler<Boolean>() { @Override public void onValueChange(ValueChangeEvent<Boolean> event) { model.setAuthenticationMethod(AuthenticationMethod.PublicKey); displayPasswordField(false); } }); userNameEditor.setEnabled(false); networkProviderWidget.edit(model.getNetworkProviderModel()); }
Source:
protected SortedSet<String> getRequestedProjects(String paramName, String cookieName) { TreeSet<String> set = new TreeSet<>(); HashSet<Project> projects = getEnv().getProjects(); if (projects == null) { return set; } if (projects.size() == 1) { for (Project p : projects) { if (authFramework.isAllowed(req, p)) { set.add(p.getName()); } } return set; } List<String> vals = getParamVals(paramName); for (String s : vals) { Project x = Project.getByName(s); if (x != null && authFramework.isAllowed(req, x)) { set.add(s); } } if (set.isEmpty()) { List<String> cookies = getCookieVals(cookieName); for (String s : cookies) { Project x = Project.getByName(s); if (x != null && authFramework.isAllowed(req, x)) { set.add(s); } } } if (set.isEmpty()) { Set<Project> defaultProjects = env.getDefaultProjects(); if (defaultProjects != null) { for (Project project : defaultProjects) { if (authFramework.isAllowed(req, project)) { set.add(project.getName()); } } } } return set; }

Target:
protected SortedSet<String> getRequestedProjects(String paramName, String cookieName) { TreeSet<String> set = new TreeSet<>(); List<Project> projects = getEnv().getProjectList(); if (projects == null) { return set; } if (getProject() != null) { set.add(getProject().getName()); return set; } if (projects.size() == 1) { Project p = projects.get(0); if (authFramework.isAllowed(req, p)) { set.add(p.getName()); } return set; } List<String> vals = getParamVals(paramName); for (String s : vals) { Project x = Project.getByName(s); if (x != null && authFramework.isAllowed(req, x)) { set.add(s); } } if (set.isEmpty()) { List<String> cookies = getCookieVals(cookieName); for (String s : cookies) { Project x = Project.getByName(s); if (x != null && authFramework.isAllowed(req, x)) { set.add(s); } } } if (set.isEmpty()) { Set<Project> defaultProjects = env.getDefaultProjects(); if (defaultProjects != null) { for (Project project : defaultProjects) { if (authFramework.isAllowed(req, project)) { set.add(project.getName()); } } } } return set; }
Source:
public void initialize( ConfigurableApplicationContext configurableApplicationContext) { TestPropertyValues .of("spring.redis.host=" + redisContainer.getContainerIpAddress(), "spring.redis.port=" + redisContainer.getMappedPort(6379)) .applyTo(configurableApplicationContext.getEnvironment()); }

Target:
public void initialize( ConfigurableApplicationContext configurableApplicationContext) { TestPropertyValues .of("spring.redis.host=" + redisContainer.getContainerIpAddress(), "spring.redis.port=" + redisContainer.getFirstMappedPort()) .applyTo(configurableApplicationContext.getEnvironment()); }
Source:
private static void sortInstructorResultList(List<InstructorAttributes> instructorList) { instructorList.sort(Comparator.comparing((InstructorAttributes instructor) -> instructor.courseId) .thenComparing(instructor -> SanitizationHelper.desanitizeIfHtmlSanitized(instructor.role)) .thenComparing(instructor -> SanitizationHelper.desanitizeIfHtmlSanitized(instructor.name)) .thenComparing(instructor -> SanitizationHelper.desanitizeIfHtmlSanitized(instructor.email))); }

Target:
private static void sortInstructorResultList(List<InstructorAttributes> instructorList) { instructorList.sort(Comparator.comparing((InstructorAttributes instructor) -> instructor.courseId) .thenComparing(instructor -> SanitizationHelper.desanitizeIfHtmlSanitized(instructor.role)) .thenComparing(instructor -> SanitizationHelper.desanitizeIfHtmlSanitized(instructor.name)) .thenComparing(instructor -> instructor.email)); }
Source:
public void executeCommand() { if (!pauseGeoReplicationSessions(georepSessions)) { return; } if (!stopSlaveVolumes(georepSessions)) { return; } if (!restoreSlaveVolumesToSnapshot(georepSessions, getParameters().getSnapshotName())) { return; } if (!stopVolume(getGlusterVolumeId())) { return; } if (!restoreVolumeToSnapshot(upServer.getId(), getGlusterVolumeId(), getParameters().getSnapshotName())) { return; } if (!startSlaveVolumes(georepSessions)) { return; } if (!startVolume(getGlusterVolumeId())) { return; } if (!resumeGeoRepSessions(georepSessions)) { return; } setSucceeded(true); }

Target:
public void executeCommand() { Boolean tranRetVal = TransactionSupport.executeInNewTransaction(new TransactionMethod<Boolean>() { @Override public Boolean runInTransaction() { if (!stopGeoReplicationSessions(georepSessions)) { return false; } if (!stopSlaveVolumes(georepSessions)) { return false; } if (!restoreSlaveVolumesToSnapshot(georepSessions, getParameters().getSnapshotName())) { return false; } return true; } }); if (!tranRetVal) { return; } if (!stopVolume(getGlusterVolumeId())) { if (!georepSessions.isEmpty()) { handleVdsError(AuditLogType.GLUSTER_MASTER_VOLUME_STOP_FAILED_DURING_SNAPSHOT_RESTORE, "Failed to stop the master volume while restoring the snapshot, " + "whereas slave volume(s) are restored to older state. " + "Admin should manually inetrevene and set the stime in master to proper value and resume the geo-replication session"); } return; } if (!restoreVolumeToSnapshot(upServer.getId(), getGlusterVolumeId(), getParameters().getSnapshotName())) { if (!georepSessions.isEmpty()) { handleVdsError(AuditLogType.GLUSTER_MASTER_VOLUME_SNAPSHOT_RESTORE_FAILED, "Failed to restore the master volume, whereas slave volume(s) are restored to older state. " + "Admin should manually inetrevene and set the stime in master to proper value and resume the geo-replication session"); } return; } List<GlusterGeoRepSession> updatedGeoRepSessions = getDbFacade().getGlusterGeoRepDao().getGeoRepSessions(getGlusterVolumeId()); if (!startSlaveVolumes(updatedGeoRepSessions)) { return; } if (!startVolume(getGlusterVolumeId())) { return; } if (!startGeoRepSessions(updatedGeoRepSessions)) { return; } if (!resumeGeoRepSessions(updatedGeoRepSessions)) { return; } setSucceeded(true); }
Source:
public ViewExtensionDescription convert() { TransformationCache cache = new TransformationCache(); IDescriptionPreprocessor vedPreprocessor = SiriusPropertiesCorePlugin.getPlugin().getDescriptionPreprocessor(originalDescription); EObject viewExtensionDescription = vedPreprocessor.convert(originalDescription, cache); List<IDescriptionLinkResolver> linkResolvers = SiriusPropertiesCorePlugin.getPlugin().getDescriptionPreprocessorLinkResolvers(); for (IDescriptionLinkResolver linkResolver : linkResolvers) { linkResolver.resolve(viewExtensionDescription, cache); } return (ViewExtensionDescription) viewExtensionDescription; }

Target:
public Optional<ViewExtensionDescription> convert() { TransformationCache cache = new TransformationCache(); Optional<IDescriptionPreprocessor> vedPreprocessor = SiriusPropertiesCorePlugin.getPlugin().getDescriptionPreprocessor(originalDescription); if (vedPreprocessor.isPresent()) { EObject viewExtensionDescription = vedPreprocessor.get().convert(originalDescription, cache); List<IDescriptionLinkResolver> linkResolvers = SiriusPropertiesCorePlugin.getPlugin().getDescriptionPreprocessorLinkResolvers(); linkResolvers.forEach(linkResolver -> linkResolver.resolve(viewExtensionDescription, cache)); return Optional.ofNullable((ViewExtensionDescription) viewExtensionDescription); } return Optional.empty(); }
Source:
protected final void doGet(final HttpServletRequest request, final HttpServletResponse response) throws IOException, ServletException { String path = request.getPathInfo(); String fullPath = getFullPath(path); if (fullPath != null) { File file = new File(fullPath); if (file == null || !file.exists() || !file.canRead() || file.isDirectory()) { log.error("Unable to locate file, will send a " + "404 error response."); response.sendError(HttpServletResponse.SC_NOT_FOUND); } else { String etag = generateEtag(file); if (etag.equals(request.getHeader(GwtDynamicHostPageServlet. IF_NONE_MATCH_HEADER))) { response.setStatus(HttpServletResponse.SC_NOT_MODIFIED); } else { String mime = ServletUtils.getMimeMap(). getContentType(file); response.addHeader(GwtDynamicHostPageServlet.ETAG_HEADER, etag); ServletUtils.sendFile(request, response, file, mime); } } } else { response.sendError(HttpServletResponse.SC_NOT_FOUND); } }

Target:
protected final void doGet(final HttpServletRequest request, final HttpServletResponse response) throws IOException, ServletException { String path = request.getPathInfo(); String fullPath = getFullPath(path); if (fullPath != null) { File file = new File(fullPath); if (!file.exists() || !file.canRead() || file.isDirectory()) { log.error("Unable to locate file, will send a 404 error response."); response.sendError(HttpServletResponse.SC_NOT_FOUND); } else { String etag = generateEtag(file); if (etag.equals(request.getHeader(GwtDynamicHostPageServlet. IF_NONE_MATCH_HEADER))) { response.setStatus(HttpServletResponse.SC_NOT_MODIFIED); } else { String mime = ServletUtils.getMimeMap(). getContentType(file); response.addHeader(GwtDynamicHostPageServlet.ETAG_HEADER, etag); ServletUtils.sendFile(request, response, file, mime); } } } else { response.sendError(HttpServletResponse.SC_NOT_FOUND); } }
Source:
public void before() { assertThat(simpleMeterRegistry).isNotNull(); meter = simpleMeterRegistry.find("jvm.memory.committed").meter(); assertThat(meter).isNotNull().withFailMessage( "The jvm.memory.committed meter mast be present in SpringBoot apps!"); }

Target:
public void before() { Metrics.globalRegistry.getMeters().forEach(Metrics.globalRegistry::remove); assertThat(simpleMeterRegistry).isNotNull(); meter = simpleMeterRegistry.find("spring.integration.handlers").meter(); assertThat(meter).isNotNull().withFailMessage( "The spring.integration.handlers meter must be present in SpringBoot apps!"); }
Source:
public void auditFinished(AuditEvent event) { fileMessages.forEach((fileName, messages) -> { writeFileOpeningTag(fileName); for (AuditEvent fileEvent : messages.getErrors()) { writeFileError(fileEvent); } for (Throwable throwable : messages.getExceptions()) { writeException(throwable); } }); fileMessages.clear(); writer.println("</checkstyle>"); if (closeStream) { writer.close(); } else { writer.flush(); } }

Target:
public void auditFinished(AuditEvent event) { fileMessages.forEach(this::writeFileMessages); fileMessages.clear(); writer.println("</checkstyle>"); if (closeStream) { writer.close(); } else { writer.flush(); } }