auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public void testNavWithoutAutoSelect() { SessionWrapper session = mApp.getSession(); sessionNavigator.startNextSessionStep(); Assert.assertEquals(SessionNavigator.GET_COMMAND, <START> mSessionNavigationResponder.getLastResultCode()); <END> session.setCommand("m0"); sessionNavigator.startNextSessionStep(); Assert.assertEquals(SessionNavigator.GET_COMMAND, mSessionNavigationResponder.getLastResultCode()); session.setCommand("m0-f1"); sessionNavigator.startNextSessionStep(); Assert.assertEquals(SessionNavigator.START_ENTITY_SELECTION, mSessionNavigationResponder.getLastResultCode()); session.stepBack(); sessionNavigator.startNextSessionStep(); Assert.assertEquals(SessionNavigator.GET_COMMAND, mSessionNavigationResponder.getLastResultCode()); session.setCommand("m0-f0"); sessionNavigator.startNextSessionStep(); Assert.assertEquals(SessionNavigator.START_FORM_ENTRY, mSessionNavigationResponder.getLastResultCode()); }</code><technical_language>This code block is repeated times, good lift a helper put in setUp method</technical_language>

Target:
public void testNavWithoutAutoSelect() { SessionWrapper session = mApp.getSession(); triggerSessionStepAndCheckResultCode(SessionNavigator.GET_COMMAND); session.setCommand("m0"); triggerSessionStepAndCheckResultCode(SessionNavigator.GET_COMMAND); session.setCommand("m0-f1"); triggerSessionStepAndCheckResultCode(SessionNavigator.START_ENTITY_SELECTION); session.stepBack(); triggerSessionStepAndCheckResultCode(SessionNavigator.GET_COMMAND); session.setCommand("m0-f0"); triggerSessionStepAndCheckResultCode(SessionNavigator.START_FORM_ENTRY); }
Source:
<code>public boolean isActivated() { boolean isResourceRootUrlSet = ResourceDomainConfiguration.isResourceDomainConfigured(); <START> boolean isOverriddenCSP = SystemProperties.getString(DirectoryBrowserSupport.class.getName() + ".CSP") != null; <END> return isOverriddenCSP && !isResourceRootUrlSet; }</code><technical_language>introduce a constant</technical_language>

Target:
public boolean isActivated() { boolean isResourceRootUrlSet = ResourceDomainConfiguration.isResourceDomainConfigured(); boolean isOverriddenCSP = SystemProperties.getString(DirectoryBrowserSupport.CSP_PROPERTY_NAME) != null; return isOverriddenCSP && !isResourceRootUrlSet; }
Source:
<code>private void loadImage(@NonNull String mediaUri) { int width = DisplayUtils.getDisplayPixelWidth(this); int height = DisplayUtils.getDisplayPixelHeight(this); if (mediaUri.startsWith("http")) { showProgress(true); String imageUrl = PhotonUtils.getPhotonImageUrl(mediaUri, width, height); mImageLoader.get(imageUrl, new ImageLoader.ImageListener() { @Override public void onResponse(ImageLoader.ImageContainer response, boolean isImmediate) { <START> if (response.getBitmap() != null) { <END> showProgress(false); mImageView.setImageBitmap(response.getBitmap()); } } @Override public void onErrorResponse(VolleyError error) { AppLog.e(AppLog.T.MEDIA, error); showProgress(false); delayedFinish(true); } }, width, height); } else { byte[] bytes = ImageUtils.createThumbnailFromUri(this, Uri.parse(mediaUri), width, null, 0); if (bytes == null) { delayedFinish(true); return; } Bitmap bmp = BitmapFactory.decodeByteArray(bytes, 0, bytes.length); if (bmp != null) { mImageView.setImageBitmap(bmp); } else { delayedFinish(true); } } PhotoViewAttacher attacher = new PhotoViewAttacher(mImageView); attacher.setOnPhotoTapListener(new PhotoViewAttacher.OnPhotoTapListener() { @Override public void onPhotoTap(View view, float v, float v2) { finish(); } }); attacher.setOnViewTapListener(new PhotoViewAttacher.OnViewTapListener() { @Override public void onViewTap(View view, float v, float v2) { finish(); } }); }</code><technical_language>add a call if (isFinishing()) return; here</technical_language>

Target:
private void loadImage(@NonNull String mediaUri) { int width = DisplayUtils.getDisplayPixelWidth(this); int height = DisplayUtils.getDisplayPixelHeight(this); if (mediaUri.startsWith("http")) { showProgress(true); String imageUrl = PhotonUtils.getPhotonImageUrl(mediaUri, width, height); mImageLoader.get(imageUrl, new ImageLoader.ImageListener() { @Override public void onResponse(ImageLoader.ImageContainer response, boolean isImmediate) { if (!isFinishing() && response.getBitmap() != null) { showProgress(false); mImageView.setImageBitmap(response.getBitmap()); } } @Override public void onErrorResponse(VolleyError error) { AppLog.e(AppLog.T.MEDIA, error); if (!isFinishing()) { showProgress(false); delayedFinish(true); } } }, width, height); } else { byte[] bytes = ImageUtils.createThumbnailFromUri(this, Uri.parse(mediaUri), width, null, 0); if (bytes == null) { delayedFinish(true); return; } Bitmap bmp = BitmapFactory.decodeByteArray(bytes, 0, bytes.length); if (bmp != null) { mImageView.setImageBitmap(bmp); } else { delayedFinish(true); } } PhotoViewAttacher attacher = new PhotoViewAttacher(mImageView); attacher.setOnPhotoTapListener(new PhotoViewAttacher.OnPhotoTapListener() { @Override public void onPhotoTap(View view, float v, float v2) { finish(); } }); attacher.setOnViewTapListener(new PhotoViewAttacher.OnViewTapListener() { @Override public void onViewTap(View view, float v, float v2) { finish(); } }); }
Source:
<code>public Attribute createAttribute(HttpRequest request, String name, long definedSize) { <START> Attribute attribute; <END> if (useDisk) { attribute = new DiskAttribute(name, definedSize, charset); } else if (checkSize) { attribute = new MixedAttribute(name, definedSize, minSize, charset); } else { attribute = new MemoryAttribute(name, definedSize); } attribute.setMaxSize(maxSize); List<HttpData> list = getList(request); list.add(attribute); return attribute; }</code><technical_language>nit: this final</technical_language>

Target:
public Attribute createAttribute(HttpRequest request, String name, long definedSize) { final Attribute attribute; if (useDisk) { attribute = new DiskAttribute(name, definedSize, charset); } else if (checkSize) { attribute = new MixedAttribute(name, definedSize, minSize, charset); } else { attribute = new MemoryAttribute(name, definedSize); } attribute.setMaxSize(maxSize); List<HttpData> list = getList(request); list.add(attribute); return attribute; }
Source:
<code><START> public ArrayList<RemoteXBeeDevice> getDevices() { <END> ArrayList<RemoteXBeeDevice> nodes = new ArrayList<RemoteXBeeDevice>(); nodes.addAll(remotesBy64BitAddr.values()); nodes.addAll(remotesBy16BitAddr.values()); return nodes; }</code><technical_language>List instead of ArrayList java public List<RemoteXBeeDevice> getDevices() {</technical_language>

Target:
public List<RemoteXBeeDevice> getDevices() { List<RemoteXBeeDevice> nodes = new ArrayList<RemoteXBeeDevice>(); nodes.addAll(remotesBy64BitAddr.values()); nodes.addAll(remotesBy16BitAddr.values()); return nodes; }
Source:
<code>private void addAttributeArgument(Argument argument, EntityProjectionBuilder projectionBuilder) { String argumentName = argument.getName(); Class<?> entityType = projectionBuilder.getType(); Attribute argumentAttribute = projectionBuilder.getAttributeByAlias(argumentName); com.yahoo.elide.request.Argument elideArgument = com.yahoo.elide.request.Argument.builder() .name(argumentName) .value(variableResolver.resolveValue(argument.getValue())) .build(); if (argumentAttribute == null) { <START> Class<?> attributeType = entityDictionary.getParameterizedType(entityType, argumentName); <END> if (attributeType == null) { throw new InvalidEntityBodyException( String.format("Invalid attribute field/alias for argument: {%s}.{%s}", entityType, argumentName) ); } argumentAttribute = Attribute.builder() .type(attributeType) .name(argumentName) .alias(argumentName) .argument(elideArgument) .build(); projectionBuilder.attribute(argumentAttribute); } else { argumentAttribute.getArguments().add(elideArgument); } }</code><technical_language>getType instead of getParameterizedType</technical_language>

Target:
private void addAttributeArgument(Argument argument, EntityProjectionBuilder projectionBuilder) { String argumentName = argument.getName(); Class<?> entityType = projectionBuilder.getType(); Attribute existingAttribute = projectionBuilder.getAttributeByAlias(argumentName); com.yahoo.elide.request.Argument elideArgument = com.yahoo.elide.request.Argument.builder() .name(argumentName) .value(variableResolver.resolveValue(argument.getValue())) .build(); if (existingAttribute != null) { Attribute toAdd = Attribute.builder() .type(existingAttribute.getType()) .name(existingAttribute.getName()) .alias(existingAttribute.getAlias()) .argument(elideArgument) .build(); projectionBuilder.attribute(toAdd); } else { Class<?> attributeType = entityDictionary.getType(entityType, argumentName); if (attributeType == null) { throw new InvalidEntityBodyException( String.format("Invalid attribute field/alias for argument: {%s}.{%s}", entityType, argumentName) ); } Attribute toAdd = Attribute.builder() .type(attributeType) .name(argumentName) .alias(argumentName) .argument(elideArgument) .build(); projectionBuilder.attribute(toAdd); } }
Source:
<code>public void scheduleJob(CronTaskConfigurationDto cronTaskConfiguration) { String jobClassName = cronTaskConfiguration.getProperty("jobClass"); Class<? extends Job> jobClass; try { jobClass = (Class<? extends Job>) Class.forName(jobClassName); } catch (ClassNotFoundException e1) { logger.error(String.format("Failed to shcedule cron job [%s]", jobClassName)); return; } String cronExpression = cronTaskConfiguration.getProperty("cronExpression"); JobDataMap jobDataMap = new JobDataMap(); jobDataMap.put("config", cronTaskConfiguration); JobKey jobKey = JobKey.jobKey(cronTaskConfiguration.getName()); JobDetail jobDetail = JobBuilder.newJob(jobClass) .withIdentity(jobKey) .setJobData(jobDataMap) .build(); TriggerKey triggerKey = TriggerKey.triggerKey(cronTaskConfiguration.getName()); TriggerBuilder<Trigger> triggerBuilder = TriggerBuilder.newTrigger() .withIdentity(triggerKey) .forJob(jobDetail); if (cronTaskConfiguration.isOneTimeExecution()) { triggerBuilder.startNow(); } else <START> { <END> triggerBuilder.withSchedule(CronScheduleBuilder.cronSchedule(cronExpression)); } Trigger trigger = triggerBuilder.build(); try { scheduler.scheduleJob(jobDetail, Collections.singleton(trigger), true); } catch (SchedulerException e) { logger.error(String.format("Failed to add Cron Job:\n [%s]", cronTaskConfiguration), e); return; } logger.debug("Job '" + cronTaskConfiguration.getName() + "' scheduled."); }</code><technical_language>hmmm isOneTimeExecution started right ... I schedule a OneTimeExecution day for example</technical_language>

Target:
public void scheduleJob(CronTaskConfigurationDto cronTaskConfiguration) { String jobClassName = cronTaskConfiguration.getProperty("jobClass"); Class<? extends Job> jobClass; try { jobClass = (Class<? extends Job>) Class.forName(jobClassName); } catch (ClassNotFoundException e1) { logger.error(String.format("Failed to shcedule cron job [%s]", jobClassName)); return; } JobDataMap jobDataMap = new JobDataMap(); jobDataMap.put("config", cronTaskConfiguration); JobKey jobKey = JobKey.jobKey(cronTaskConfiguration.getName()); JobDetail jobDetail = JobBuilder.newJob(jobClass) .withIdentity(jobKey) .setJobData(jobDataMap) .storeDurably() .build(); TriggerKey triggerKey = TriggerKey.triggerKey(cronTaskConfiguration.getName()); TriggerBuilder<Trigger> triggerBuilder = TriggerBuilder.newTrigger() .withIdentity(triggerKey) .forJob(jobDetail); if (cronTaskConfiguration.isOneTimeExecution()) { triggerBuilder.startNow(); } else { String cronExpression = cronTaskConfiguration.getProperty("cronExpression"); triggerBuilder.withSchedule(CronScheduleBuilder.cronSchedule(cronExpression)); } Trigger trigger = triggerBuilder.build(); try { doScheduleJob(cronTaskConfiguration, jobKey, jobDetail, trigger); } catch (SchedulerException e) { logger.error(String.format("Failed to add Cron Job:%n [%s]", cronTaskConfiguration), e); return; } logger.debug("Job '" + cronTaskConfiguration.getName() + "' scheduled."); }
Source:
<code>private void updateEid() { List<UiccCardInfo> infos = mTelephonyManager.getUiccCardsInfo(); <START> if (!infos.isEmpty()) { <END> for (UiccCardInfo info : infos) { if (info != null && info.getSlotIndex() == mSlotId) { if (info.isEuicc()) { String eid = info.getEid(); if (!TextUtils.isEmpty(eid)) { mDialog.setText(EID_INFO_VALUE_ID, eid); } } else { mDialog.removeSettingFromScreen(EID_INFO_LABEL_ID); mDialog.removeSettingFromScreen(EID_INFO_VALUE_ID); } break; } } } }</code><technical_language>need check this</technical_language>

Target:
private void updateEid() { List<UiccCardInfo> infos = mTelephonyManager.getUiccCardsInfo(); for (UiccCardInfo info : infos) { if (info != null && info.getSlotIndex() == mSlotId) { if (info.isEuicc()) { String eid = info.getEid(); if (!TextUtils.isEmpty(eid)) { mDialog.setText(EID_INFO_VALUE_ID, eid); } } else { mDialog.removeSettingFromScreen(EID_INFO_LABEL_ID); mDialog.removeSettingFromScreen(EID_INFO_VALUE_ID); } break; } } }
Source:
<code>public Collection<DataSource> listDataSources() throws IOException, IllegalAccessException, InstantiationException { Collection<DataSource> dataSources = this.dao.<DataSource>list(DATA_SOURCE_NAMESPACE); if (dataSources != null) { for (DataSource ds : dataSources) { DataSourceSubType dataSourcesubType = getSubtypeFromDataSource(ds); ds.setTypeConfig(CoreUtils.storableToJson(dataSourcesubType)); <START> ds.setTags(tagService.getTags(new EntityId(ds.getId(), ds.getNameSpace()))); <END> } } return dataSources; }</code><technical_language>Instead of EntityId, TaggedEntity, a namespace id. i.e. tag registry stores TaggedEntity -> Tag mappings</technical_language>

Target:
public Collection<DataSource> listDataSources() throws IOException, IllegalAccessException, InstantiationException { Collection<DataSource> dataSources = this.dao.<DataSource>list(DATA_SOURCE_NAMESPACE); if (dataSources != null) { for (DataSource ds : dataSources) { DataSourceSubType dataSourcesubType = getSubtypeFromDataSource(ds); ds.setTypeConfig(CoreUtils.storableToJson(dataSourcesubType)); ds.setTags(tagClient.getTags(new TaggedEntity(ds))); } } return dataSources; }
Source:
<code>private Pair<Date, Date> parseDateRange(String dateRange) throws ParseException { if (StringUtils.isEmpty(dateRange) || dateRange.length() != 24) { <START> dateRange = dateRange == null ? KFSConstants.EMPTY_STRING : dateRange; <END> throw new ParseException("The Date Range is Invalid [" + dateRange + "]. The expected length is 24 (YYYY-MM-DD to YYYY-MM-DD).", 0); } DateTimeService dateTimeService = SpringContext.getBean(DateTimeService.class); Date endDate = dateTimeService.convertToSqlDate(dateRange.substring(14)); Date startDate = dateTimeService.convertToSqlDate(dateRange.substring(0, 10)); return new Pair<>(startDate, endDate); }</code><technical_language>lines some of cleanup mentioned earlier (use a constant for expected length, a StringUtils helper method for null/blank defaults, etc.)</technical_language>

Target:
private Pair<Date, Date> parseDateRange(String dateRange) throws ParseException { if (StringUtils.length(dateRange) != CuArConstants.CINV_DATE_RANGE_EXPECTED_FORMAT_LENGTH) { dateRange = StringUtils.defaultString(dateRange); String errorMessage = SpringContext.getBean(ConfigurationService.class).getPropertyValueAsString(CUKFSKeyConstants.WARNING_CINV_DATE_RANGE_INVALID_FORMAT_LENGTH); throw new ParseException(MessageFormat.format(errorMessage, new String[] {dateRange}), 0); } DateTimeService dateTimeService = SpringContext.getBean(DateTimeService.class); Date startDate = dateTimeService.convertToSqlDate(dateRange.substring(CuArConstants.CINV_DATE_RANGE_START_DATE_START_INDEX, CuArConstants.CINV_DATE_RANGE_START_DATE_END_INDEX)); Date endDate = dateTimeService.convertToSqlDate(dateRange.substring(CuArConstants.CINV_DATE_RANGE_END_DATE_START_INDEX)); return Pair.of(startDate, endDate); }
Source:
<code><START> public LocalPageStore(LocalPageStoreOptions options) throws IOException { <END> mRoot = options.getRootDir(); mPageSize = options.getPageSize(); Path rootDir = Paths.get(mRoot); try { boolean invalidPage = Files.exists(rootDir) && Files.walk(rootDir) .filter(Files::isRegularFile) .anyMatch(path -> { if (getPageId(path) == null) { return true; } mSize.incrementAndGet(); return false; }); if (invalidPage || (long) mSize.get() * mPageSize > options.getCacheSize()) { FileUtils.cleanDirectory(new File(mRoot)); mSize.set(0); } } catch (IOException e) { throw new IOException(String.format("can't initialize page store at %s", mRoot), e); } }</code><technical_language>in general, avoid throw checked exceptions in a constructor --- this leave unfinished instance creation state hard clean</technical_language>

Target:
public LocalPageStore(LocalPageStoreOptions options) throws IOException { mRoot = options.getRootDir(); mPageSize = options.getPageSize(); Path rootDir = Paths.get(mRoot); mPagePattern = Pattern.compile( String.format("%s/%d/(\\d+)/(\\d+)", Pattern.quote(rootDir.toString()), mPageSize)); try { boolean invalidPage = Files.exists(rootDir) && Files.walk(rootDir) .filter(Files::isRegularFile) .anyMatch(path -> { if (getPageId(path) == null) { LOG.warn("Invalid page path {}", path); return true; } mSize.incrementAndGet(); return false; }); if (invalidPage || (long) mSize.get() * mPageSize > options.getCacheSize()) { LOG.warn("Cannot recover from cached data: {}", invalidPage ? "Invalid page file found" : "Cached data size exceeded configured value"); FileUtils.cleanDirectory(new File(mRoot)); mSize.set(0); } } catch (IOException e) { throw new IOException(String.format("can't initialize page store at %s", mRoot), e); } }
Source:
<code>private boolean isSource(Block block) { <START> if (isLiquid(block.getType())) { <END> BlockData data = block.getBlockData(); if (data instanceof Levelled) { Levelled levelled = (Levelled) data; return levelled.getLevel() == 0; } } return false; }</code><technical_language>Block#isLiquid()</technical_language>

Target:
private boolean isSource(Block block) { if (block.isLiquid()) { BlockData data = block.getBlockData(); if (data instanceof Levelled) { Levelled levelled = (Levelled) data; return levelled.getLevel() == 0; } } return false; }
Source:
<code>public void setup() { createDirectoryForLeaderForEachClientUseCase(NAMESPACE_1); createDirectoryTimestampUseCase(NAMESPACE_2); <START> createDirectoryTimestampUseCase(PaxosTimeLockConstants.LEADER_PAXOS_NAMESPACE); <END> diskNamespaceLoader = new DiskNamespaceLoader(tempFolder.getRoot().toPath()); }</code><technical_language>nit: createDirectoryInRootDataDirectory avoid confusion</technical_language>

Target:
public void setup() { diskNamespaceLoader = new DiskNamespaceLoader(tempFolder.getRoot().toPath()); createDirectoryForLeaderForEachClientUseCase(NAMESPACE_1); createDirectoryInRootDataDirectory(NAMESPACE_2); }
Source:
<code>public SetFacesToCull(int mode) { <START> if (!modeNameMap.containsKey(mode)) { <END> throw new IllegalArgumentException("Mode must be GL_BACK, GL_FRONT or GL_FRONT_AND_BACK."); } this.mode = mode; }</code><technical_language>case of this if statement is I think</technical_language>

Target:
public SetFacesToCull(int mode) { if (mode == GL_BACK || mode == GL_FRONT || mode == GL_FRONT_AND_BACK) { this.mode = mode; } else { throw new IllegalArgumentException("Mode must be GL_BACK, GL_FRONT or GL_FRONT_AND_BACK."); } }
Source:
<code>public static final int headerEnd(final byte[] b, int ptr) { final int sz = b.length; while (ptr < sz) { final byte c = b[ptr++]; <START> if (c == '\n' && (ptr == sz || b[ptr] != ' ')) <END> return ptr - 1; } return ptr - 1; }</code><technical_language>Missing curly braces</technical_language>

Target:
public static final int headerEnd(final byte[] b, int ptr) { final int sz = b.length; while (ptr < sz) { final byte c = b[ptr++]; if (c == '\n' && (ptr == sz || b[ptr] != ' ')) { return ptr - 1; } } return ptr - 1; }
Source:
<code>public Object downloadFile(@PathVariable("candidateId") Long candidateId, RedirectAttributes redirectAttrs) throws Exception { String cvFilename = candidateService.getCvFilenameById(candidateId); <START> if (cvFilename != null && !cvFilename.isEmpty()) { <END> try { File file = new File(uploadLocation + File.separator + cvFilename); InputStream inputStream = new BufferedInputStream(new FileInputStream(file)); InputStreamResource inputStreamResource = new InputStreamResource(inputStream); HttpHeaders responseHeaders = new HttpHeaders(); responseHeaders.set(CONTENT_DISPOSITION, String.format(INLINE_FORMAT + cvFilename + "\"")); responseHeaders.setContentType(MediaType.APPLICATION_OCTET_STREAM); responseHeaders.setContentLength(file.length()); return new ResponseEntity<>(inputStreamResource, responseHeaders, HttpStatus.OK); } catch (IOException e) { redirectAttrs.addFlashAttribute(FILE_ERROR_MESSAGE, FILE_ERROR_MESSAGE_KEY); } } else { redirectAttrs.addFlashAttribute(FILE_ERROR_MESSAGE, FILE_ERROR_MESSAGE_KEY); } return new ModelAndView(REDIRECT_CANDIDATE_PAGE + "/" + candidateId); }</code><technical_language>I suggest this method: org.apache.commons.lang3.StringUtils.isNotEmpty</technical_language>

Target:
public Object downloadFile(@PathVariable("candidateId") Long candidateId, RedirectAttributes redirectAttrs) throws Exception { CandidateDTO candidateDTO = candidateService.getCandidate(candidateId); String candidateCVFilename = candidateDTO.getCvFilename(); if (StringUtils.isNotBlank(candidateCVFilename)) { try { File file = candidateCVFileHandler .createCVFileFromFolderLocationAndCandidateDtoAndCVFilename(uploadLocation, candidateId, candidateCVFilename); if (!file.exists()) { throw new IOException(); } InputStream inputStream = new BufferedInputStream(new FileInputStream(file)); InputStreamResource inputStreamResource = new InputStreamResource(inputStream); HttpHeaders responseHeaders = new HttpHeaders(); responseHeaders.set(CONTENT_DISPOSITION, String.format(INLINE_FORMAT + candidateCVFilename)); responseHeaders.setContentType(MediaType.APPLICATION_OCTET_STREAM); responseHeaders.setContentLength(file.length()); return new ResponseEntity<>(inputStreamResource, responseHeaders, HttpStatus.OK); } catch (IOException e) { redirectAttrs.addFlashAttribute(FILE_ERROR_MESSAGE, FILE_ERROR_MESSAGE_KEY); } } else { redirectAttrs.addFlashAttribute(FILE_ERROR_MESSAGE, FILE_ERROR_MESSAGE_KEY); } return new ModelAndView(REDIRECT_CANDIDATE_PAGE + "/" + candidateId); }
Source:
<code>public void testCorrectHeaderFormatWithoutInstanceId() { UserAgent baseUserAgent = UserAgent.of("service", "1.0.0"); assertThat(UserAgents.format(baseUserAgent)).isEqualTo("service (1.0.0)"); <START> UserAgent derivedAgent = UserAgents.merge(baseUserAgent, UserAgent.of("remoting", "2.0.0")); <END> assertThat(UserAgents.format(derivedAgent)).isEqualTo("service (1.0.0), remoting (2.0.0)"); }</code><technical_language>This syntax more clunky</technical_language>

Target:
public void testCorrectHeaderFormatWithoutInstanceId() { UserAgent baseUserAgent = UserAgent.of(UserAgent.Agent.of("service", "1.0.0")); assertThat(UserAgents.format(baseUserAgent)).isEqualTo("service (1.0.0)"); UserAgent derivedAgent = baseUserAgent.addAgent(UserAgent.Agent.of("remoting", "2.0.0")); assertThat(UserAgents.format(derivedAgent)).isEqualTo("service (1.0.0), remoting (2.0.0)"); }
Source:
<code>public void return_default_values_map() { final NullToleranceTest.Builder builder = NullToleranceTest.newBuilder(); int expectedSize = 0; int actualSize = builder.getDefaultValues() .size(); assertEquals(expectedSize, actualSize); builder.addDefaultValue(0); builder.addDefaultValue('\u000f'); expectedSize = 2; actualSize = builder.getDefaultValues() .size(); assertEquals(expectedSize, actualSize); final Map<? super Class, ? super Object> expectedMap = newHashMap(); <START> expectedMap.put(Integer.class, 0); <END> expectedMap.put(Character.class, '\u000f'); assertEquals(expectedMap, builder.getDefaultValues()); }</code><technical_language>duplicating values</technical_language>

Target:
public void return_default_values_map() { final NullToleranceTest.Builder builder = NullToleranceTest.newBuilder(); final int integerDefaultValue = 0; builder.addDefaultValue(integerDefaultValue); final int actualSize = builder.getDefaultValues() .size(); assertEquals(1, actualSize); final Map<? super Class, ? super Object> expectedMap = newHashMap(); expectedMap.put(Integer.class, integerDefaultValue); assertEquals(expectedMap, builder.getDefaultValues()); }
Source:
<code>public void testCtfTmfTimestamp() { long timestamp = 1L; CtfTmfTimestamp result = new CtfTmfTimestamp(timestamp); assertNotNull(result); <START> assertEquals("19:00:00.000 000 001", result.toString()); END> assertEquals(0, result.getPrecision()); assertEquals(-9, result.getScale()); assertEquals(1L, result.getValue()); }</code><technical_language>test timezone-independent calculating correct long for "00:00:00" based local time, changing timezone of TmfTimestampFormat.getDefaulTimeFormat() GMT in test case</technical_language>

Target:
public void testCtfTmfTimestamp() { long timestamp = 1L; DateFormat df = new SimpleDateFormat("HH:mm:ss.SSS"); Date d = new Date(timestamp / 1000000); CtfTmfTimestamp result = new CtfTmfTimestamp(timestamp); assertNotNull(result); assertEquals(df.format(d) + " 000 001", result.toString()); assertEquals(0, result.getPrecision()); assertEquals(-9, result.getScale()); assertEquals(1L, result.getValue()); }
Source:
<code>public void testOkWithResource() throws Exception { assertEquals("No warnings.", <START> lintProject(xml("AndroidManifest.xml", "" <END> + "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n" + "<manifest xmlns:android=\"<LINK_0>\"\n" + " package=\"com.example.helloworld\" >\n" + "\n" + " <application\n" + " android:allowBackup=\"true\"\n" + " android:icon=\"@mipmap/ic_launcher\"\n" + " android:label=\"@string/app_name\"\n" + " android:theme=\"@style/AppTheme\" >\n" + " <activity\n" + " android:name=\".FullscreenActivity\"\n" + " android:configChanges=\"orientation|keyboardHidden|screenSize\"\n" + " android:label=\"@string/title_activity_fullscreen\"\n" + " android:theme=\"@style/FullscreenTheme\" >\n" + " <intent-filter android:label=\"@string/title_activity_fullscreen\">\n" + " <action android:name=\"android.intent.action.VIEW\" />\n" + " <data android:scheme=\"http\"\n" + " android:host=\"example.com\"\n" + " android:pathPrefix=\"@string/path_prefix\"\n" + " android:port=\"@string/port\"/>\n" + " <category android:name=\"android.intent.category.DEFAULT\" />\n" + " <category android:name=\"android.intent.category.BROWSABLE\" />\n" + " </intent-filter>\n" + " </activity>\n" + " </application>\n" + "\n" + "</manifest>\n"), xml("res/values/strings.xml", "" + "<resources>\n" + " <string name=\"path_prefix\">/gizmos</string>\n" + " <string name=\"port\">8080</string>\n" + "</resources>\n"))); }</code><technical_language>lintProjectIncrementally too</technical_language>

Target:
public void testOkWithResource() throws Exception { assertEquals("No warnings.", lintProjectIncrementally( "AndroidManifest.xml", "appindexing_manifest.xml=>AndroidManifest.xml", "res/values/appindexing_strings.xml")); }
Source:
<code><START> public WrappingFileHandle( File file, File baseDirectory, FileSystemAbstraction fs ) <END> { this.file = file; this.baseDirectory = baseDirectory; this.fs = fs; }</code><technical_language>Checkstyle this public modifier is redundant</technical_language>

Target:
WrappingFileHandle( File file, File baseDirectory, FileSystemAbstraction fs ) { this.file = file; this.baseDirectory = baseDirectory; this.fs = fs; }
Source:
<code>private void rollbackTest(boolean killTransactor) throws Exception { Transactor t1 = new Transactor(config); TestTransaction tx = new TestTransaction(config); tx.mutate().row("bob").col(balanceCol).set("10"); tx.mutate().row("joe").col(balanceCol).set("20"); tx.mutate().row("jill").col(balanceCol).set("60"); tx.commit(); TestTransaction tx2 = new TestTransaction(config, t1); <START> int bal1 = Integer.parseInt(tx2.get().row("bob").col(balanceCol).toString()); <END> int bal2 = Integer.parseInt(tx2.get().row("joe").col(balanceCol).toString()); tx2.mutate().row("bob").col(balanceCol).set("" + (bal1 - 7)); tx2.mutate().row("joe").col(balanceCol).set("" + (bal2 + 7)); CommitData cd = tx2.createCommitData(); Assert.assertTrue(tx2.preCommit(cd)); if (killTransactor) { t1.close(); } TransactionImpl tx3 = new TransactionImpl(config); Assert.assertEquals(0, tx3.getStats().getDeadRollbacks()); Assert.assertEquals(0, tx3.getStats().getTimeoutRollbacks()); int bobFinal = Integer.parseInt(tx3.get(new ArrayByteSequence("bob"), balanceCol).toString()); Assert.assertEquals(10, bobFinal); if (killTransactor) { Assert.assertEquals(1, tx3.getStats().getDeadRollbacks()); Assert.assertEquals(0, tx3.getStats().getTimeoutRollbacks()); } else { Assert.assertEquals(0, tx3.getStats().getDeadRollbacks()); Assert.assertEquals(1, tx3.getStats().getTimeoutRollbacks()); } if (!killTransactor) { t1.close(); } }</code><technical_language>call toInteger() drop Integer.parseInt</technical_language>

Target:
private void rollbackTest(boolean killTransactor) throws Exception { TransactorID t1 = new TransactorID(config); TestTransaction tx = new TestTransaction(config); tx.mutate().row("bob").col(balanceCol).set("10"); tx.mutate().row("joe").col(balanceCol).set("20"); tx.mutate().row("jill").col(balanceCol).set("60"); tx.commit(); TestTransaction tx2 = new TestTransaction(config, t1); int bal1 = tx2.get().row("bob").col(balanceCol).toInteger(); int bal2 = tx2.get().row("joe").col(balanceCol).toInteger(); tx2.mutate().row("bob").col(balanceCol).set(bal1 - 7); tx2.mutate().row("joe").col(balanceCol).set(bal2 + 7); CommitData cd = tx2.createCommitData(); Assert.assertTrue(tx2.preCommit(cd)); if (killTransactor) { t1.close(); } TransactionImpl tx3 = new TransactionImpl(config); Assert.assertEquals(0, tx3.getStats().getDeadLocks()); Assert.assertEquals(0, tx3.getStats().getTimedOutLocks()); int bobFinal = Integer.parseInt(tx3.get(new ArrayByteSequence("bob"), balanceCol).toString()); Assert.assertEquals(10, bobFinal); if (killTransactor) { Assert.assertEquals(1, tx3.getStats().getDeadLocks()); Assert.assertEquals(0, tx3.getStats().getTimedOutLocks()); } else { Assert.assertEquals(0, tx3.getStats().getDeadLocks()); Assert.assertEquals(1, tx3.getStats().getTimedOutLocks()); } long commitTs = OracleClient.getInstance(config).getTimestamp(); if (killTransactor) { exception.expect(IllegalStateException.class); tx2.commitPrimaryColumn(cd, commitTs); } else { Assert.assertFalse(tx2.commitPrimaryColumn(cd, commitTs)); t1.close(); } }
Source:
<code>public void upgrade() { final VDS host = getSelectedItem(); Model model; <START> if (host.getVdsType() == VDSType.oVirtNode) { <END> model = new UpgradeModel(host); } else { model = new UpgradeConfirmationModel(host); } setWindow(model); model.initialize(); model.getCommands().add(UICommand.createCancelUiCommand("Cancel", this)); }</code><technical_language>consideration</technical_language>

Target:
public void upgrade() { final VDS host = getSelectedItem(); Model model = createUpgradeModel(host); setWindow(model); model.initialize(); model.getCommands().add(UICommand.createCancelUiCommand("Cancel", this)); }
Source:
<code>OneMeasurement constructOneMeasurement(String name) { switch (_measurementType) { case HISTOGRAM: return new OneMeasurementHistogram(name, _props); case HDRHISTOGRAM: return new OneMeasurementHdrHistogram(name, _props); case HDRHISTOGRAM_AND_HISTOGRAM: return new TwoInOneMeasurement(name, new OneMeasurementHdrHistogram("Hdr"+name, _props), new OneMeasurementHistogram("Bucket"+name, _props)); case HDRHISTOGRAM_AND_RAW: return new TwoInOneMeasurement(name, new OneMeasurementHdrHistogram("Hdr"+name, _props), new OneMeasurementHistogram("Raw"+name, _props)); case HDRHISTOGRAM_AND_PERIODICHISTOGRAM: return new TwoInOneMeasurement(name, new OneMeasurementHdrHistogram("Hdr"+name, _props), <START> new PeriodicHistogram(name, _props)); <END> case PERIODICHISTOGRAM: return new PeriodicHistogram(name, _props); case TIMESERIES: return new OneMeasurementTimeSeries(name, _props); case RAW: return new OneMeasurementRaw(name, _props); default: throw new AssertionError("Impossible to be here. Dead code reached. Bugs?"); } }</code><technical_language>this bit "Periodic"+name</technical_language>

Target:
OneMeasurement constructOneMeasurement(String name) { switch (_measurementType) { case HISTOGRAM: return new OneMeasurementHistogram(name, _props); case HDRHISTOGRAM: return new OneMeasurementHdrHistogram(name, _props); case HDRHISTOGRAM_AND_HISTOGRAM: return new TwoInOneMeasurement(name, new OneMeasurementHdrHistogram("Hdr"+name, _props), new OneMeasurementHistogram("Bucket"+name, _props)); case HDRHISTOGRAM_AND_RAW: return new TwoInOneMeasurement(name, new OneMeasurementHdrHistogram("Hdr"+name, _props), new OneMeasurementRaw("Raw"+name, _props)); case HDRHISTOGRAM_AND_PERIODICHISTOGRAM: return new TwoInOneMeasurement(name, new OneMeasurementHdrHistogram("Hdr"+name, _props), new PeriodicHistogram(name, _props)); case PERIODICHISTOGRAM: return new PeriodicHistogram(name, _props); case TIMESERIES: return new OneMeasurementTimeSeries(name, _props); case RAW: return new OneMeasurementRaw(name, _props); default: throw new AssertionError("Impossible to be here. Dead code reached. Bugs?"); } }
Source:
<code>protected void failWithCustomSubject(String verb, Object expected, Object actual) { StringBuilder message = new StringBuilder("Not true that "); <START> message.append((actual == null) ? "null reference" : actual).append(" ").append(verb); <END> failureStrategy.fail(message.toString()); }</code><technical_language>drop StringBuilder...I'm convinced buys (and if does, in a failure case test code)</technical_language>

Target:
protected void failWithCustomSubject(String verb, Object expected, Object actual) { String message = String.format("Not true that <%s> %s <%s>", ((actual == null) ? "null reference" : actual), verb, expected); failureStrategy.fail(message); }
Source:
<code>private void redirectToAuthorization(DeviceAuthorizationCacheControl cacheData) { try { log.info("Redirecting to authorization code flow to process device authorization, data: {}", cacheData); String authorizationEndpoint = appConfiguration.getAuthorizationEndpoint(); String clientId = cacheData.getClient().getClientId(); <START> String responseType = "code"; <END> String scope = Util.listAsString(cacheData.getScopes()); String state = UUID.randomUUID().toString(); String nonce = UUID.randomUUID().toString(); RedirectUri authRequest = new RedirectUri(authorizationEndpoint); authRequest.addResponseParameter(CLIENT_ID, clientId); authRequest.addResponseParameter(RESPONSE_TYPE, responseType); authRequest.addResponseParameter(SCOPE, scope); authRequest.addResponseParameter(STATE, state); authRequest.addResponseParameter(NONCE, nonce); authRequest.addResponseParameter(USER_CODE, cacheData.getUserCode()); FacesContext.getCurrentInstance().getExternalContext().redirect(authRequest.toString()); } catch (IOException e) { log.error("Problems trying to redirect to authorization page from device authorization action", e); String message = languageBean.getMessage("error.errorEncountered"); facesMessages.add(FacesMessage.SEVERITY_WARN, message); } catch (Exception e) { log.error("Exception processing redirection", e); String message = languageBean.getMessage("error.errorEncountered"); facesMessages.add(FacesMessage.SEVERITY_WARN, message); } }</code><technical_language>sense configurable</technical_language>

Target:
private void redirectToAuthorization(DeviceAuthorizationCacheControl cacheData) { try { log.info("Redirecting to authorization code flow to process device authorization, data: {}", cacheData); String authorizationEndpoint = appConfiguration.getAuthorizationEndpoint(); String clientId = cacheData.getClient().getClientId(); String responseType = appConfiguration.getDeviceAuthzResponseTypeToProcessAuthz(); String scope = Util.listAsString(cacheData.getScopes()); String state = UUID.randomUUID().toString(); String nonce = UUID.randomUUID().toString(); RedirectUri authRequest = new RedirectUri(authorizationEndpoint); authRequest.addResponseParameter(CLIENT_ID, clientId); authRequest.addResponseParameter(RESPONSE_TYPE, responseType); authRequest.addResponseParameter(SCOPE, scope); authRequest.addResponseParameter(STATE, state); authRequest.addResponseParameter(NONCE, nonce); FacesContext.getCurrentInstance().getExternalContext().redirect(authRequest.toString()); } catch (IOException e) { log.error("Problems trying to redirect to authorization page from device authorization action", e); String message = languageBean.getMessage("error.errorEncountered"); facesMessages.add(FacesMessage.SEVERITY_WARN, message); } catch (Exception e) { log.error("Exception processing redirection", e); String message = languageBean.getMessage("error.errorEncountered"); facesMessages.add(FacesMessage.SEVERITY_WARN, message); } }
Source:
<code>public void doCreateAccount(@NonNull String token) { progressDialog.show(); String email = null; if (emailEdit.getText().length() != 0) { email = emailEdit.getText().toString(); } String password = passwordEdit.getText().toString(); String repeat = passwordInput.isPasswordVisible() ? password : passwordRepeatEdit.getText().toString(); createAccountClient.request(wiki, usernameEdit.getText().toString(), password, repeat, token, email, captchaHandler.isActive() ? captchaHandler.captchaId() : "null", captchaHandler.isActive() ? captchaHandler.captchaWord() : "null", new CreateAccountClient.Callback() { @Override public void success(@NonNull Call<CreateAccountResponse> call, @NonNull final CreateAccountSuccessResult result) { if (!progressDialog.isShowing()) { return; } <START> getUserId(new <END> UserIdCallback() { @Override public void success(@NonNull Call<MwQueryResponse<UserIdClient.QueryUserInfo>> call, int userId) { finishWithUserResult(result, userId); } @Override public void failure(@NonNull Call<MwQueryResponse<UserIdClient.QueryUserInfo>> call, @NonNull Throwable caught) { finishWithUserResult(result, 0); L.e("Failed to obtain new user ID", caught); } }); } @Override public void failure(@NonNull Call<CreateAccountResponse> call, @NonNull Throwable caught) { L.e(caught.toString()); if (!progressDialog.isShowing()) { return; } progressDialog.dismiss(); FeedbackUtil.showError(CreateAccountActivity.this, caught); } }); }</code><technical_language>Purely optional, consider LoginClient flow instead of duplicating user ID path</technical_language>

Target:
public void doCreateAccount(@NonNull String token) { progressDialog.show(); String email = null; if (emailEdit.getText().length() != 0) { email = emailEdit.getText().toString(); } String password = passwordEdit.getText().toString(); String repeat = passwordInput.isPasswordVisible() ? password : passwordRepeatEdit.getText().toString(); createAccountClient.request(wiki, usernameEdit.getText().toString(), password, repeat, token, email, captchaHandler.isActive() ? captchaHandler.captchaId() : "null", captchaHandler.isActive() ? captchaHandler.captchaWord() : "null", new CreateAccountClient.Callback() { @Override public void success(@NonNull Call<CreateAccountResponse> call, @NonNull final CreateAccountSuccessResult result) { if (!progressDialog.isShowing()) { return; } finishWithUserResult(result); } @Override public void failure(@NonNull Call<CreateAccountResponse> call, @NonNull Throwable caught) { L.e(caught.toString()); if (!progressDialog.isShowing()) { return; } progressDialog.dismiss(); FeedbackUtil.showError(CreateAccountActivity.this, caught); } }); }
Source:
<code>private String getRefererHeaderUrl() { if (backStack.size() > 0) { <START> PageBackStackItem item = backStack.get(backStack.size() - 1); if (item.getHistoryEntry().getSource() == HistoryEntry.SOURCE_INTERNAL_LINK && fragment.isRefererHeaderUrlEnabled()) { <END> fragment.setRefererHeaderUrlEnabled(false); return item.getHistoryEntry().getTitle().getCanonicalUri(); } } return null; }</code><technical_language>This is right idea, clarify need extra isRefererHeaderUrlEnabled parameter? (Wouldn't sufficient rely HistoryEntry.SOURCE_INTERNAL_LINK?)</technical_language>

Target:
private String getRefererHeaderUrl() { if (backStack.size() > 0) { if (fragment.isRefererHeaderUrlAvailable(model.getTitle()) && backStack.get(backStack.size() - 1).getHistoryEntry().getSource() == HistoryEntry.SOURCE_INTERNAL_LINK) { return fragment.getRefererHeaderPage(model.getTitle()).getCanonicalUri(); } } return null; }
Source:
<code>public void testBoolFromFunction() throws ParseException { JSONObject object = MapboxTestUtils.object("{'expr': { 'base': 1, 'stops': [ [ 0, true ], [ 10, true ], [ 22, true ] ] }}"); <START> Expression expression = parser.string(object, "expr", "name"); <END> assertTrue("Parse result must be a function", Function.class.isAssignableFrom(expression.getClass())); }</code><technical_language>This parser.bool</technical_language>

Target:
public void testBoolFromFunction() throws ParseException { JSONObject object = MapboxTestUtils.object("{'expr': { 'base': 1, 'stops': [ [ 0, true ], [ 10, true ], [ 22, true ] ] }}"); Expression expression = parser.bool(object, "expr", true); assertTrue("Parse result must be a function", Function.class.isAssignableFrom(expression.getClass())); }
Source:
<code>protected void startInner() throws VoldemortException { JNAUtils.tryMlockall(); logger.info("Starting " + basicServices.size() + " services."); long start = System.currentTimeMillis(); boolean goOnline; if (getMetadataStore().getServerStateUnlocked() == MetadataStore.VoldemortState.NORMAL_SERVER) goOnline = true; else if (getMetadataStore().getServerStateUnlocked() == MetadataStore.VoldemortState.OFFLINE_SERVER) goOnline = false; else <START> throw new VoldemortException("Invalid Server state. Neither online nor offline found"); <END> for(VoldemortService service: basicServices) { try { service.start(); } catch (DisabledStoreException e) { logger.error("Got a DisabledStoreException from " + service.getType().getDisplayName(), e); goOnline = false; } } if (goOnline) { startOnlineServices(); } else { goOffline(); } long end = System.currentTimeMillis(); logger.info("Startup completed in " + (end - start) + " ms."); }</code><technical_language>server 3 states, online, offline rebalancing. This server start is in Rebalancing mode. I 2 cases here, offline else</technical_language>

Target:
protected void startInner() throws VoldemortException { JNAUtils.tryMlockall(); logger.info("Starting " + basicServices.size() + " services."); long start = System.currentTimeMillis(); boolean goOnline; if (getMetadataStore().getServerStateUnlocked() == MetadataStore.VoldemortState.OFFLINE_SERVER) goOnline = false; else goOnline = true; for(VoldemortService service: basicServices) { try { service.start(); } catch (DisabledStoreException e) { logger.error("Got a DisabledStoreException from " + service.getType().getDisplayName(), e); goOnline = false; } } if (goOnline) { startOnlineServices(); } else { goOffline(); } long end = System.currentTimeMillis(); logger.info("Startup completed in " + (end - start) + " ms."); }
Source:
<code>protected void doStart() { try { <START> server.start().await(); <END> } catch(InterruptedException e) { Thread.currentThread().interrupt(); } }</code><technical_language>assert result of this is null? AFAIKT, means promise a result (or exception) in default/environment timeout. (Which implies start failed?)</technical_language>

Target:
protected void doStart() { try { Assert.notNull(server.start().await(), "Server did not start properly"); } catch(InterruptedException e) { Thread.currentThread().interrupt(); } }
Source:
<code>private MultiServerRetryInterceptor(List<String> uris) { <START> this.uris = uris; <END> }</code><technical_language>immutable copy</technical_language>

Target:
private MultiServerRetryInterceptor(List<String> uris) { this.uris = ImmutableList.copyOf(uris); }
Source:
<code>public static OSGIUtil getInstance() { if (instance == null) { <START> instance = new OSGIUtil(Config.CONTEXT); <END> } return instance; }</code><technical_language>this is thread safe, is suppose thread safe</technical_language>

Target:
public static OSGIUtil getInstance() { return OSGIUtilHolder.instance; }
Source:
<code>public void createTable(HTableDescriptor desc) throws IOException { CreateTableRequest.Builder builder = CreateTableRequest.newBuilder(); clusterMetadataSetter.setMetadata(builder); builder.setTableId(desc.getTableName().getQualifierAsString()); builder.setTable(tableAdapter.adapt(desc)); try { bigtableAdminClient.createTable(builder.build()); } catch (Throwable throwable) { <START> throwable.printStackTrace(); <END> throw new IOException( String.format( "Failed to create table '%s'", desc.getTableName().getNameAsString()), throwable); } }</code><technical_language>log it</technical_language>

Target:
public void createTable(HTableDescriptor desc) throws IOException { CreateTableRequest.Builder builder = CreateTableRequest.newBuilder(); clusterMetadataSetter.setMetadata(builder); builder.setTableId(desc.getTableName().getQualifierAsString()); builder.setTable(tableAdapter.adapt(desc)); try { bigtableAdminClient.createTable(builder.build()); } catch (Throwable throwable) { throw new IOException( String.format( "Failed to create table '%s'", desc.getTableName().getNameAsString()), throwable); } }
Source:
<code>public JAXBModule() { <START> this.jaxbContextFactory = defaultJAXBContextFactory(); <END> }</code><technical_language>kill default (provider) method inline</technical_language>

Target:
public JAXBModule() { this.jaxbContextFactory = new JAXBContextFactory.Builder().build(); }
Source:
<code>private static Optional<Path> findWebInfParentDirectory(FileSystem fs) { FilePredicates predicates = fs.predicates(); <START> ArrayList<InputFile> inputFiles = new ArrayList<>(); <END> fs.inputFiles(predicates.matchesPathPattern("**/WEB-INF/**")).forEach(inputFiles::add); if (!inputFiles.isEmpty()) { Path path = Paths.get(inputFiles.get(0).absolutePath()); Path parent = path.getParent(); while (parent != null) { if (parent.endsWith("WEB-INF")) { return Optional.ofNullable(parent.getParent()); } parent = parent.getParent(); } } LOG.debug("WEB-INF directory not found, will use basedir as context root"); return Optional.empty(); }</code><technical_language>interface</technical_language>

Target:
private static Optional<Path> findWebInfParentDirectory(FileSystem fs) { FilePredicates predicates = fs.predicates(); List<InputFile> inputFiles = new ArrayList<>(); fs.inputFiles(predicates.matchesPathPattern("**/WEB-INF/**")).forEach(inputFiles::add); if (!inputFiles.isEmpty()) { Path path = Paths.get(inputFiles.get(0).absolutePath()); Path parent = path.getParent(); while (parent != null) { if (parent.endsWith("WEB-INF")) { return Optional.ofNullable(parent.getParent()); } parent = parent.getParent(); } } LOG.debug("WEB-INF directory not found, will use basedir as context root"); return Optional.empty(); }
Source:
<code>private final boolean isValidFile(LocatedFileStatus fileStatus) { if (fileStatus.isFile()) { <START> if (whitelistRegexp!=null) { <END> return Pattern.matches(whitelistRegexp, fileStatus.getPath().getName()); } else { return true; } } return false; }</code><technical_language>if (WHITELIST_REGEXP != null) checking a constant for null defensive</technical_language>

Target:
private final boolean isValidFile(LocatedFileStatus fileStatus) { if (fileStatus.isFile()) { return WHITELIST_REGEXP.matcher(fileStatus.getPath().getName()).matches(); } else { return false; } }
Source:
<code>private String externalChildSensorName(final String threadId, final String operationName, final String entityName) { <START> return "external" + SENSOR_PREFIX_DELIMITER + threadId <END> + SENSOR_PREFIX_DELIMITER + "entity" + SENSOR_PREFIX_DELIMITER + entityName + SENSOR_NAME_DELIMITER + operationName; }</code><technical_language>nit: for external, entity</technical_language>

Target:
private String externalChildSensorName(final String threadId, final String operationName, final String entityName) { return SENSOR_EXTERNAL_LABEL + SENSOR_PREFIX_DELIMITER + threadId + SENSOR_PREFIX_DELIMITER + SENSOR_ENTITY_LABEL + SENSOR_PREFIX_DELIMITER + entityName + SENSOR_NAME_DELIMITER + operationName; }