auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public CourseCategoryDAO findCourseCategory(final String id) { List<Object> results = getHibernateTemplate().executeFind(new HibernateCallback() { public Object doInHibernate(Session session) { START Query query = session.createSQLQuery( END "select * from course_category " + "where categoryId = :id").addEntity(CourseCategoryDAO.class); query.setString("id", id); return query.list(); } }); if (!results.isEmpty()) { return (CourseCategoryDAO)results.get(0); } return null; } I think you're loading a CourseCategoryDAO by primary key so you Can just use session.get(Class, Serializable) which will only ever return one item.

Target:
public CourseCategoryDAO findCourseCategory(final String id) { return (CourseCategoryDAO)getHibernateTemplate().execute(new HibernateCallback() { public CourseCategoryDAO doInHibernate(Session session) { return (CourseCategoryDAO)session.get(CourseCategoryDAO.class, id); } }); }
Source:
public void presentIntentImportFatalError() { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { Bundle args = new Bundle(); args.putBoolean("shouldShowRationale", shouldShowRequestPermissionRationale(Manifest.permission.READ_EXTERNAL_STORAGE)); START PermissionAlertDialogFragment permissionDialogFragment = PermissionAlertDialogFragment.newInstance(); END permissionDialogFragment.setArguments(args); navigationHandler.showDialog(permissionDialogFragment); } else { Toast.makeText(this, R.string.toast_attachment_error, Toast.LENGTH_SHORT).show(); finish(); } } Let's move the `bundle` stuff into the `newInstance()` method like: ``` ... newInstance(String permission) { Bundle args = new Bundle(); args.putBoolean(...) } ``` So the logic is contained entirely in that fragment

Target:
public void presentIntentImportFatalError() { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { navigationHandler.showDialog(PermissionAlertDialogFragment.newInstance(this)); } else { Toast.makeText(this, R.string.toast_attachment_error, Toast.LENGTH_SHORT).show(); finish(); } }
Source:
protected void saveTableOrdering() { Logger.debug(this, "saveTableOrdering"); START ((DraggableEditableCardsAdapter)adapter).saveNewOrder(getTableController()); END } Rather than casting, can we ensure that the `adapter` is a `DraggableEditableCardsAdapter` when defined?

Target:
protected void saveTableOrdering() { Logger.debug(this, "saveTableOrdering"); adapter.saveNewOrder(getTableController()); }
Source:
START public Multimap<String, String> getQueryParams() { END return queryParams; } This breaks the public API of `HttpMessage`. But in this case, we have to break the API so that the returned value is able to represent the query parameter content regarding its specification. Nevertheless, I'd recommend to go wit a `Map<String, Collection<String>>` to keep the guava stuff internal and have an java standard conform interface to the outer world.

Target:
public Map<String, Collection<String>> getQueryParams() { return queryParams; }
Source:
public HttpMessage cookie(Cookie cookie) { START this.cookies.add(cookie); END setHeader( HttpMessageHeaders.HTTP_COOKIE_PREFIX + cookie.getName(), cookieConverter.getCookieString(cookie)); return this; } Does it make sense here to overwrite cookies with same name (i.e. check using name if already in list and overwrite rather than allowing multiple cookies with the same name)?

Target:
public HttpMessage cookie(Cookie cookie) { this.cookies.put(cookie.getName(), cookie); setHeader( HttpMessageHeaders.HTTP_COOKIE_PREFIX + cookie.getName(), cookieConverter.getCookieString(cookie)); return this; }
Source:
START public HomeView( END Binder uiBinder) { initWidget(uiBinder.createAndBindUi(this)); } Remove public

Target:
HomeView(Binder uiBinder) { initWidget(uiBinder.createAndBindUi(this)); }
Source:
START public HomePagePresenter(EventBus eventBus, MyView view, MyProxy proxy) { END super(eventBus, view, proxy, ApplicationPresenter.SLOT_SetMainContent); } Clean the "public" as well

Target:
HomePagePresenter(EventBus eventBus, MyView view, MyProxy proxy) { super(eventBus, view, proxy, ApplicationPresenter.SLOT_SetMainContent); }
Source:
protected void configure() { bindPresenterWidget(HeaderPresenter.class, HeaderPresenter.MyView.class, HeaderView.class); START END bind(new TypeLiteral<UiHandlersStrategy<HeaderUiHandlers>>() { }).to(new TypeLiteral<SetterUiHandlersStrategy<HeaderUiHandlers>>() { }); bind(HeaderUiHandlers.class).to(HeaderPresenter.class); } spaces on empty line

Target:
protected void configure() { bindPresenterWidget(HeaderPresenter.class, HeaderPresenter.MyView.class, HeaderView.class); }
Source:
public void userIsTakenToDiscussionsPostViewAfterClickOnPostSzl() { new MixedContentFooter().openWikiMainPage() .scrollToMCFooter() .getDiscussionsCard() .scrollToDiscussions() .clickDiscussionsPost(); String url = driver.getCurrentUrl(); START Assertion.assertTrue(url.contains(".wikia.com/szl/d/")); END } `url` is used only once, so I guess we could use it inline i.e. `driver.getCurrentUrl().contains()`

Target:
public void userIsTakenToDiscussionsPostViewAfterClickOnPostSzl() { new MixedContentFooter().openWikiMainPage() .scrollToMCFooter() .getDiscussionsCard() .scrollToDiscussions() .clickDiscussionsPost(); Assertion.assertTrue(driver.getCurrentUrl().contains(".wikia.com/szl/d/")); }
Source:
public String getUrlForWikiPageWithWWW(String pageName) { START if ("".equals(pageName)) END throw new WebDriverException("Page name is missing"); return getUrl(true) + URLsContent.WIKI_DIR + pageName; } please add curly braces here

Target:
public String getUrlForWikiPageWithWWW(String pageName) { if ("".equals(pageName)) { throw new WebDriverException("Page name is missing"); } return getUrl(true) + URLsContent.WIKI_DIR + pageName; }
Source:
public SpecialAnonymizationUserPage fillFutureAnon(String anonymizedUser) { START jsActions.scrollBy(0, 400); END wait.forElementClickable(submitButton); AnonymizationTextBox.sendKeys(anonymizedUser); return this; } Would be nice to create an integer constant and assign 400 to it, and than use it here. E.g. `public static int WINDOW_HEIGHT = 400`. It'd be more explicit for another person (no magic numbers).

Target:
public SpecialAnonymizationUserPage fillFutureAnon(String anonymizedUser) { wait.forElementClickable(submitButton); AnonymizationTextBox.sendKeys(anonymizedUser); return this; }
Source:
public SpecialAnonymizationUserPage submitAnonymization() { try { Thread.sleep(10000); } catch (Exception e) { } jsActions.scrollToElement(submitButton); START submitButton.click(); END return this; } just FYI, I think there's a method `scrollAndClick()`

Target:
public SpecialAnonymizationUserPage submitAnonymization() { jsActions.scrollToElement(submitButton); submitButton.click(); return this; }
Source:
START private String getEditUrl(String page, String query) { END return urlBuilder.appendQueryStringToURL( urlBuilder.getUrlForWikiPage(String.format("/wiki/%s", urlBuilder.normalizePageName(page))), query); } ![MAJOR](https://sonarsource.github.io/sonar-github/severity-major.png 'Severity: MAJOR') Remove this unused private "getEditUrl" method. [![rule](https://sonarsource.github.io/sonar-github/rule.png)](http://sonar-s4/coding_rules#rule_key=squid%3AUnusedPrivateMethod)

Target:
private String getEditUrl(String page, String query) { return urlBuilder.appendQueryStringToURL( urlBuilder.getUrlForWikiPage(urlBuilder.normalizePageName(page)), query); }
Source:
public void snippetIsNotAffectedByXSS() { new ArticlePage().open("/File:Mala-mi.jpg"); FilePageObject filePage = new FilePageObject(); Assertion.assertTrue(filePage.doesSnippetContainXSS()); START AlertHandler xssAlert = new AlertHandler(); END Assertion.assertFalse(xssAlert.isAlertPresent(driver)); } as I wrote above, you don't need to create any instance of AlertHandler since isAlertPresent() is a static method. You can invoke it like this: `AlertHandler.isAlertPresent(driver)`

Target:
public void snippetIsNotAffectedByXSS() { new ArticlePage().open("/File:Mala-mi.jpg"); FilePageObject filePage = new FilePageObject(); Assertion.assertTrue(filePage.doesSnippetContainXSS()); Assertion.assertFalse(AlertHandler.isAlertPresent(driver)); }
Source:
public void verifyNoAdsOnPage() { START scrollToSelector(AdsContent.getSlotSelector(AdsContent.BOTTOM_LB)); END verifyNoAds(); PageObjectLogging.log( "verifyNoAdsOnPage", "No ads detected", true, driver ); } Shouldn't be a part of logic in verifyNoAd? Can we reuse SLOT_TRIGGERS in verifyNoAd and scroll to given slot when it's necessary? https://github.com/Wikia/selenium-tests/blob/7e8de247fd9bc0d96769993f1ca7794218cd6086/src/test/java/com/wikia/webdriver/common/contentpatterns/AdsContent.java#L96 I'm pretty sure it was implemented somewhere here :(

Target:
public void verifyNoAdsOnPage() { verifyNoAds(); PageObjectLogging.log( "verifyNoAdsOnPage", "No ads detected", true, driver ); }
Source:
public Optional<PostEntity> getPostById(String postId) { START return Optional.ofNullable( END getPost() .getPosts() .stream() .peek(postEntity -> scrollTo(postEntity.getWebElement())) .filter(postEntity -> postEntity.findId().equals(postId)) .findFirst() .orElseThrow(() -> new RuntimeException(String.format("Post with id [%s] not found on page", postId)))); } This outer optional shouldnt be needed here

Target:
public PostEntity getPostById(String postId) { return getPost() .getPosts() .stream() .peek(postEntity -> scrollTo(postEntity.getWebElement())) .filter(postEntity -> postEntity.findId().equals(postId)) .findFirst() .orElseThrow( () -> new RuntimeException(String.format("Post with id [%s] not found on page", postId))); }
Source:
public boolean isPostFollowed() { START this.waitForPageLoad(); END return this.getPost().findNewestPost().isFollowed(); } is `this.` necessary?

Target:
public boolean isPostFollowed() { waitForPageLoad(); return getPost().findNewestPost().isFollowed(); }
Source:
private HttpResponse createTestUser(String appId) throws IOException, URISyntaxException { URL url = new URL(getURLCreateUser(appId)); CloseableHttpClient httpClient = HttpClientBuilder.create().disableAutomaticRetries().build(); HttpPost httpPost = getHttpPost(url); START if (getParams() != null) { END httpPost.setEntity(new UrlEncodedFormEntity(getParams(), StandardCharsets.UTF_8)); } return httpClient.execute(httpPost); } It doesn't look like this method can ever return a `null`.

Target:
private HttpResponse createTestUser(String appId) throws IOException, URISyntaxException { URL url = new URL(getURLCreateUser(appId)); CloseableHttpClient httpClient = HttpClientBuilder.create().disableAutomaticRetries().build(); HttpPost httpPost = getHttpPost(url); httpPost.setEntity(new UrlEncodedFormEntity(getParams(), StandardCharsets.UTF_8)); return httpClient.execute(httpPost); }
Source:
START @Override public SignInPage typeUsername(String username) { END fillInput(usernameField, username); return this; } I think the code style suggests the annotations should be above the methods.

Target:
public SignInPage typeUsername(String username) { fillInput(usernameField, username); return this; }
Source:
public void scrollToSlot(String slotName) { if (slotName.equals(AdsContent.BOTTOM_LB)) { triggerComments(); } if (slotName.equals(AdsContent.MOBILE_BOTTOM_LB)) { scrollToFooter(); START } END scrollToPosition("#" + slotName); } nitpick: `if ... else` would be more appropriate here

Target:
public void scrollToSlot(String slotName) { if (slotName.equals(AdsContent.BOTTOM_LB)) { triggerComments(); } else if (slotName.equals(AdsContent.MOBILE_BOTTOM_LB)) { scrollToFooter(); } scrollToPosition("#" + slotName); }
Source:
public boolean isNewWallThreadActivityDisplayed(String title, String threadAuthor, String threadContent) { return activities.stream() .filter(activity -> activity.getType() == ActivityType.WALL_POST) .filter(activity -> activity.getTitleLink().getText().contains(title)) START .filter(activity -> activity.getWallThreadAuthor().contains(threadAuthor)) END .anyMatch(activity -> activity.getWallThreadContent().contains(threadContent)); } `.equals` here?

Target:
public boolean isNewWallThreadActivityDisplayed(String title, String threadAuthor, String threadContent) { return activities.stream() .filter(activity -> activity.getType() == ActivityType.WALL_POST) .filter(activity -> activity.getTitleLink().getText().contains(title)) .filter(activity -> activity.getWallThreadAuthor().equals(threadAuthor)) .anyMatch(activity -> activity.getWallThreadContent().contains(threadContent)); }
Source:
START private void verifyUapBtf(long btfId, String slotName, String bottomSlotName, AdsFandomObject fandomPage) { END fandomPage.verifySlot(slotName); Assertion.assertEquals(btfId, fandomPage.getLineItemId(AdsFandomContent.INCONTENT_BOXAD)); fandomPage.verifySlot(bottomSlotName); Assertion.assertEquals(btfId, fandomPage.getLineItemId(AdsFandomContent.BOTTOM_LEADERBOARD)); Assertion.assertNull(fandomPage.getSlot(AdsFandomContent.BOTTOM_BOXAD)); } ![MAJOR](https://sonarsource.github.io/sonar-github/severity-major.png 'Severity: MAJOR') Remove this unused private "verifyUapBtf" method. [![rule](https://sonarsource.github.io/sonar-github/rule.png)](http://sonar-s4/coding_rules#rule_key=squid%3AUnusedPrivateMethod)

Target:
private void verifyUapBtf(long btfId, String slotName, String bottomSlotName, AdsFandomObject fandomPage) { fandomPage.verifySlot(slotName); Assertion.assertEquals(btfId, fandomPage.getLineItemId(slotName)); fandomPage.verifySlot(bottomSlotName); Assertion.assertEquals(btfId, fandomPage.getLineItemId(bottomSlotName)); }
Source:
private String parseDuration() { NumberFormat formatter = new DecimalFormat("00"); int hours = (int) Math.floor(duration / 3600); int minutes = (int) Math.floor(duration / 60 % 60); START int seconds = (int) Math.floor(duration % 60); END return String.format("%s:%s:%s", formatter.format(hours), formatter.format(minutes), formatter.format(seconds)); } it looks like an universal operation, did we checked if sth similar is not performed in repo already?

Target:
private String parseDuration() { NumberFormat formatter = new DecimalFormat("00"); int hours = (int) Math.floor(duration / 3600), minutes = (int) Math.floor(duration / 60 % 60), seconds = (int) Math.floor(duration % 60); return String.format("%s:%s:%s", formatter.format(hours), formatter.format(minutes), formatter.format(seconds)); }
Source:
public boolean isVideoAdBiggerThanImageAd(double videoHeight, double imageHeight) { int percentResult = (int)Math.round(100-(100/(videoHeight/imageHeight))); if (percentResult == PERCENTAGE_DIFFERENCE_BETWEEN_VIDEO_AND_IMAGE_AD) { START return true; END } PageObjectLogging.log("isVideoAdBiggerThanImageAdOasis", "Expected percentage difference between video height and image height is not equal with " + PERCENTAGE_DIFFERENCE_BETWEEN_VIDEO_AND_IMAGE_AD + " percent", false, driver); return false; } you can use result of comparison as returned value

Target:
public boolean isVideoAdBiggerThanImageAd(double videoHeight, double imageHeight) { int percentResult = (int)Math.round(100-(100/(videoHeight/imageHeight))); return percentResult == PERCENTAGE_DIFFERENCE_BETWEEN_VIDEO_AND_IMAGE_AD; }
Source:
public void waitSafely(Runnable o) { try { o.run(); START } catch (TimeoutException e) { END PageObjectLogging.log("Timed out waiting", e.getMessage(), true); } } Create a ticket to improve Sonar rules?

Target:
public void waitSafely(Runnable o) { try { o.run(); } catch (TimeoutException e) { PageObjectLogging.log("Timed out waiting", e, true); } }
Source:
public void anonCanLogInViaUserLoginPage() { WikiBasePageObject base = new WikiBasePageObject(); base.openSpecialUpload(wikiURL); base.verifyLoginRequiredMessage(); base.clickLoginOnSpecialPage(); new AttachedSignInPage().login(credentials.userName10, credentials.password10); base.verifyUserLoggedIn(credentials.userName10); START Assertion.assertTrue(base.isStringInURL(URLsContent.SPECIAL_UPLOAD)); END } Static import `assertTrue`?

Target:
public void anonCanLogInViaUserLoginPage() { WikiBasePageObject base = new WikiBasePageObject(); base.openSpecialUpload(wikiURL); base.verifyLoginRequiredMessage(); base.clickLoginOnSpecialPage(); new AttachedSignInPage().login(credentials.userName10, credentials.password10); base.verifyUserLoggedIn(credentials.userName10); assertTrue(base.isStringInURL(URLsContent.SPECIAL_UPLOAD)); }
Source:
public void vuapDefaultStateShouldStartPlayingAdvertisementAutomatically(Page page, String slot, String videoIframeSelector) { START openPageWithVideoInLocalStorage(page, VuapVideos.PORVATA_VAST, VuapVideos.VAST_VIDEO); END final AutoplayVuap vuap = new AutoplayVuap(driver, slot, videoIframeSelector); VuapAssertions.verifyVideoPlay(vuap); } I see that you pass those parameters a lot `VuapVideos.PORVATA_VAST, VuapVideos.VAST_VIDEO`. Maybe you could extract method from it or hardcode those two parameters?

Target:
public void vuapDefaultStateShouldStartPlayingAdvertisementAutomatically(Page page, String slot, String videoIframeSelector) { openPageWithVideoInLocalStorage(page); final AutoplayVuap vuap = new AutoplayVuap(driver, slot, videoIframeSelector); VuapAssertions.verifyVideoPlay(vuap); }
Source:
public void deleteAllCategories(final String siteId, User user) { START ArrayList<CategoryPill.Data> categories = getCategoriesFromSite(siteId, user); END for (CategoryPill.Data category : categories) { PageObjectLogging.logInfo("Deleting category: " + category.getName()); deleteCategory(siteId, category); } } Interface can be used here.

Target:
public void deleteAllCategories(final String siteId, User user) { List<CategoryPill.Data> categories = getCategoriesFromSite(siteId, user); for (CategoryPill.Data category : categories) { PageObjectLogging.logInfo("Deleting category: " + category.getName()); deleteCategory(siteId, category); } }
Source:
START public ArrayList<CategoryPill.Data> getCategoriesFromSite(final String siteId, User user) { END return new Categories(user).execute(CreateCategoryContext.defaultContextUsing(siteId, "")); } Interface can be used for the return signature.

Target:
public List<CategoryPill.Data> getCategoriesFromSite(final String siteId, User user) { return new Categories(user).execute(CreateCategoryContext.defaultContextUsing(siteId, "")); }
Source:
String execute(final HttpEntityEnclosingRequestBase request, final JSONObject jsonObject) { String result = StringUtils.EMPTY; try { request.setHeader(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_JSON.toString()); request.setEntity(new StringEntity(jsonObject.toString())); result = execute(request); START } catch (UnsupportedEncodingException|RemoteException x) { END PageObjectLogging.log("Error while creating http post entity.", ExceptionUtils.getStackTrace(x), false); } return result; } Nitpick: you're missing spaces before and after the pipe. I'd suggest naming the exception variables `ex`.

Target:
String execute(final HttpEntityEnclosingRequestBase request, final JSONObject jsonObject) { String result = StringUtils.EMPTY; try { request.setHeader(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_JSON.toString()); request.setEntity(new StringEntity(jsonObject.toString())); result = execute(request); } catch (UnsupportedEncodingException | RemoteException ex) { PageObjectLogging.log("Error while creating http post entity.", ExceptionUtils.getStackTrace(ex), false); } return result; }
Source:
public CategoryPill findCategoryOn(int position) { CategoryPill result = null; final List<WebElement> categoryPills = findCategoryPills(); if (position < categoryPills.size()) { result = new CategoryPill(categoryPills.get(position)); } START return result; END } ``` final List<WebElement> categoryPills = findCategoryPills(); if (position < categoryPills.size()) { return new CategoryPill(categoryPills.get(position)); } else { return null; } ```

Target:
public CategoryPill findCategoryOn(int position) { final List<WebElement> categoryPills = findCategoryPills(); if (position < categoryPills.size()) { return new CategoryPill(categoryPills.get(position)); } else { return null; } }
Source:
public void changeElementOpacity(String selector, int value) { START driver.findElement(By.cssSelector(selector)); END js.executeScript( "document.querySelector(arguments[0]).style.opacity = arguments[1];", selector, value); } what is the purpose of this line?

Target:
public void changeElementOpacity(String selector, int value) { js.executeScript( "document.querySelector(arguments[0]).style.opacity = arguments[1];", selector, value); }
Source:
private WebElement getActiveDialog() { WebElement dialog = null; List<WebElement> elements = driver.findElements(By.cssSelector(".discussion-dialog.is-visible")); if (elements.isEmpty()) { // allow selenium to throw exception dialog = driver.findElement(By.cssSelector(".discussion-dialog.is-visible.modal-dialog-approve")); } else if (1 < elements.size()) { // only one modal dialog should be visible throw new IllegalStateException("Only one modal dialog should be visible!"); } else { dialog = elements.get(0); } START return dialog; END } Remove the pre-defined variable? ``` private WebElement getActiveDialog() { List<WebElement> elements = driver.findElements(By.cssSelector(".discussion-dialog.is-visible")); if (elements.isEmpty()) { // allow selenium to throw exception return driver.findElement(By.cssSelector(".discussion-dialog.is-visible.modal-dialog-approve")); } else if (1 < elements.size()) { // only one modal dialog should be visible throw new IllegalStateException("Only one modal dialog should be visible!"); } else { return elements.get(0); } ```

Target:
private WebElement getActiveDialog() { List<WebElement> elements = driver.findElements(By.cssSelector(".discussion-dialog.is-visible")); if (elements.isEmpty()) { // allow selenium to throw exception return driver.findElement(By.cssSelector(".discussion-dialog.is-visible.modal-dialog-approve")); } else if (1 < elements.size()) { // only one modal dialog should be visible throw new IllegalStateException("Only one modal dialog should be visible!"); } else { return elements.get(0); } }
Source:
private void assertThatPostCanBeUnfollowed(PostDetailsPage page) { final PostActionsRow postActions = page.getPost().findNewestPost().findPostActions(); postActions.clickFollow(); START sleepForOneSecond(); END Assertion.assertFalse(postActions.isFollowed(), SHOULD_UNFOLLOW_MESSAGE); } Can we move `sleepForOneSecond` method inside `clickFollow`? As I understood from our previous discussion, explicit wait is always necessary in case of following a post. My request also includes following tests

Target:
private void assertThatPostCanBeUnfollowed(PostDetailsPage page) { final PostActionsRow postActions = page.getPost().findNewestPost().findPostActions(); postActions.clickFollow(); Assertion.assertFalse(postActions.isFollowed(), SHOULD_UNFOLLOW_MESSAGE); }
Source:
START private ArrayList<String> getTabUrls() { END String currentTab = driver.getWindowHandle(); ArrayList<String> result = new ArrayList<>(); for(String windowHandler : driver.getWindowHandles()) { driver.switchTo().window(windowHandler); result.add(driver.getCurrentUrl()); } driver.switchTo().window(currentTab); return result; } Maybe you could use here `List` interface instead specific implementation?

Target:
private List<String> getTabUrls() { String currentTab = driver.getWindowHandle(); List<String> result = new ArrayList<>(); for(String windowHandler : driver.getWindowHandles()) { driver.switchTo().window(windowHandler); result.add(driver.getCurrentUrl()); } driver.switchTo().window(currentTab); return result; }
Source:
public void selectCategory(int categoryId) { START wait.forElementVisible(wikiCategoryDropdown); END wikiCategoryDropdown.click(); WebElement selectedCategory = wikiCategoryList.findElement(By.id(String.valueOf(categoryId))); wait.forElementClickable(selectedCategory); String selectedCategoryText = selectedCategory.getText(); selectedCategory.click(); PageObjectLogging.log("selectCategory", "selected " + selectedCategoryText + " category", true, driver); } clickable

Target:
public void selectCategory(int categoryId) { wait.forElementClickable(wikiCategoryDropdown); wikiCategoryDropdown.click(); WebElement selectedCategory = wikiCategoryList.findElement(By.id(String.valueOf(categoryId))); wait.forElementClickable(selectedCategory); String selectedCategoryText = selectedCategory.getText(); selectedCategory.click(); PageObjectLogging.log("selectCategory", "selected " + selectedCategoryText + " category", true, driver); }
Source:
public static String createUniqueText() { START return String.format(UNIQUE_TEXT_FORMAT, System.nanoTime()); END } just millis shoud be enought

Target:
public static String createUniqueText() { return String.format(UNIQUE_TEXT_FORMAT, System.currentTimeMillis()); }
Source:
public void verifyLatestDateInDatePicker() { String currentDate = datePickerInput.getAttribute("value"); String latestDate = DateTimeFormat.forPattern("MMMM d, yyyy").withLocale(Locale.ENGLISH) .print(DateTime.now().minus(Period.days(2)).withZone(DateTimeZone.UTC)); START Assertion.assertEquals(latestDate, currentDate, "Current date and the latest possible date are not the same"); END } I think latestDate should be passed as second param, according to doc: `assertEquals(Object actual, Object expected, String message)`

Target:
public void verifyLatestDateInDatePicker() { String currentDate = datePickerInput.getAttribute("value"); String latestDate = DateTimeFormat.forPattern("MMMM d, yyyy").withLocale(Locale.ENGLISH) .print(DateTime.now().minus(Period.days(2)).withZone(DateTimeZone.UTC)); Assertion.assertEquals(currentDate, latestDate, "Current date and the latest possible date are not the same"); }
Source:
public VisualEditorPageObject typeInParameterField(int i, String parameter) { WebElement element = parametersFieldList.get(i); wait.forElementClickable(element); element.click(); START element.sendKeys(parameter); END return this; } can we add here more descriptive name instead of `element`? Maybe `parameterInput` or `input` or `field`?

Target:
public VisualEditorPageObject typeInParameterField(int i, String parameter) { WebElement field = parametersFieldList.get(i); wait.forElementClickable(field); field.click(); field.sendKeys(parameter); return this; }
Source:
public Navigate toPage(String pageName) { String host = UrlBuilder.getHostForWiki(); String cacheBuster = pageName.equals("") || pageName.equals("/") ? "" : "?cb=" + DateTime.now().getMillis(); START String abGroup = pageName.equals("") || pageName.equals("/") ? "" : defaultTestingGroup; END driver.get("http://" + host + pageName + cacheBuster + abGroup); return this; } if you will navigate to page with `/` you will get `http://www.example.com/&ABTEST.` add your parameter to the end of line above

Target:
public Navigate toPage(String pageName) { String host = UrlBuilder.getHostForWiki(); String cacheBuster = pageName.equals("") || pageName.equals("/") ? "" : "?cb=" + DateTime.now().getMillis() + defaultTestingGroup; driver.get("http://" + host + pageName + cacheBuster); return this; }
Source:
public Navigation clickExploreWikiHeader() { START Loading loading = new Loading(driver); END PageObjectLogging.logInfo("Click 'Explore Wiki' header"); wait.forElementClickable(exploreWikiHeader); exploreWikiHeader.click(); loading.handleAsyncPageReload(); return this; } Just use `loading` declared class field

Target:
public Navigation clickExploreWikiHeader() { PageObjectLogging.logInfo("Click 'Explore Wiki' header"); wait.forElementClickable(exploreWikiHeader); exploreWikiHeader.click(); loading.handleAsyncPageReload(); return this; }
Source:
public void mercury_search_searchNoResultsPageDisplayed() { init(); START SearchResultsPage END searchResults = new SearchResultsPage().openForQuery(SEARCH_PHRASE_NO_RESULTS); Assertion.assertTrue(searchResults.isNoResultsPagePresent()); } new line is not needed here

Target:
public void mercury_search_searchNoResultsPageDisplayed() { SearchResultsPage searchResults = new SearchResultsPage() .openForQuery(SEARCH_PHRASE_NO_RESULTS); Assertion.assertTrue(searchResults.isNoResultsPagePresent()); }
Source:
public PortableInfoboxObject clickGalleryImage(int index) { START Assertion.assertFalse(galleryImageList.isEmpty()); END wait.forElementClickable(galleryImageList.get(index)); galleryImageList.get(index).click(); return this; } Why asserting this?

Target:
public PortableInfoboxObject clickGalleryImage(int index) { wait.forElementClickable(galleryImageList.get(index)).click(); return this; }
Source:
public SmartBanner scrollDown() { PageObjectLogging.logInfo("Smart banner is visible"); wait.forElementVisible(smartBannerComponent); PageObjectLogging.logInfo("Scroll down"); jsActions.scrollBy(0, 100); START PageObjectLogging.logInfo("Smart banner position is fixed at the top"); END wait.forElementPresent(smartBannerComponent); Assertion.assertFalse( driver.findElement(smartBannerComponent).getLocation().getY() == SMART_BANNER_POS_Y, "Smart banner position is not fixed at the top" ); return this; } so it's fixed or not? :D (per line 56)

Target:
public SmartBanner scrollDown() { PageObjectLogging.logInfo("Smart banner is visible"); wait.forElementVisible(smartBannerComponent); PageObjectLogging.logInfo("Scroll down"); jsActions.scrollBy(0, 100); PageObjectLogging.logInfo("Smart banner position is not fixed at the top"); wait.forElementPresent(smartBannerComponent); Assertion.assertFalse( driver.findElement(smartBannerComponent).getLocation().getY() == SMART_BANNER_POS_Y, "Smart banner position is not fixed at the top" ); return this; }
Source:
public boolean isUserOnChat() { try { START wait.forElementVisible(chatInlineAlert); END return chatInlineAlert.isDisplayed(); } catch (Exception e) { return false; } } isn't `wait.forElementVisible` checks if element is displayed? if yes, we can return `true` instead of running `chatInlineAlert.isDisplayed()`

Target:
public boolean isUserOnChat() { try { wait.forElementVisible(chatInlineAlert); return true; } catch (Exception e) { return false; } }
Source:
START private void init() { END this.head = new Head(driver); this.navigate = new Navigate(driver); } Please use `@BeforeMethod(alwaysRun = true)` insted of `init()` inside of test body

Target:
private void init() { this.head = new Head(); this.navigate = new Navigate(driver); }
Source:
public InfoboxBuilderPage changeHeaderCollapsibilityState(int index) { START JavascriptExecutor js = (JavascriptExecutor) driver; END headers.get(index).click(); wait.forElementClickable(sidebarCheckbox); sidebarCheckbox.click(); String script = "return window.getComputedStyle(document" + ".querySelector('.pi-header'),':after').content"; String chevronContent = js.executeScript(script).toString(); if (sidebarCheckbox.isSelected()) { Assertion.assertFalse(chevronContent.isEmpty()); } else { Assertion.assertTrue(chevronContent.isEmpty()); } return this; } this line: `JavascriptExecutor js = (JavascriptExecutor) driver;` is not needed, `driver` object is already inheriting `JavascriptExecutor` class. Just use: `driver.executeScript(script).toString();` :)

Target:
public InfoboxBuilderPage changeHeaderCollapsibilityState(int index) { headers.get(index).click(); wait.forElementClickable(sidebarCheckbox); sidebarCheckbox.click(); String script = "return window.getComputedStyle(document" + ".querySelector('.pi-header'),':after').content"; String chevronContent = driver.executeScript(script).toString(); if (sidebarCheckbox.isSelected()) { Assertion.assertFalse(chevronContent.isEmpty()); } else { Assertion.assertTrue(chevronContent.isEmpty()); } return this; }
Source:
public RecentWikiActivityPage open(){ START editArticle("RWA" + DateTime.now().getMillis()); END getUrl(String.format("%s%s", urlBuilder.getUrlForWiki(), URLsContent.RECENT_WIKI_ACTIVITY)); return this; } Why push content always before opening recent wiki activity?

Target:
public RecentWikiActivityPage open() { getUrl(String.format("%s%s", urlBuilder.getUrlForWiki(), URLsContent.RECENT_WIKI_ACTIVITY)); return this; }
Source:
public RecentWikiActivity goBackToRWA() { wait.forElementClickable(backArrow); backArrow.click(); loading.handleAsyncPageReload(); PageObjectLogging.logInfo("The arrow that redirect user back to RWA was clicked"); START Assertion.assertTrue(driver.getCurrentUrl().contains(URLsContent.RECENT_WIKI_ACTIVITY), END "You were not redirected to the recent wiki activity"); PageObjectLogging.logInfo("You were redirected to the recent wiki activity"); return this; } Moving assertion to test will actually make test more readable - reading the assertion gives you an idea about _what is the expected behaviour?_ Hiding an assertion is a bad pattern, I know it's used a lot in legacy code, but I wouldn't like it to be used in new tests ;)

Target:
public RecentWikiActivity goBackToRWA() { wait.forElementClickable(backArrow); backArrow.click(); loading.handleAsyncPageReload(); PageObjectLogging.logInfo("The arrow that redirect user back to RWA was clicked"); return this; }
Source:
public RecentWikiActivityPage open(){ START editArticle("RWA Tests"); END getUrl(String.format("%s%s", urlBuilder.getUrlForWiki(), URLsContent.RECENT_WIKI_ACTIVITY)); return this; } Please edit article in test, not when openning a page

Target:
public RecentWikiActivityPage open() { getUrl(String.format("%s%s", urlBuilder.getUrlForWiki(), URLsContent.RECENT_WIKI_ACTIVITY)); return this; }
Source:
public void closeDropdown() { JavascriptExecutor js = (JavascriptExecutor) driver; START js.executeScript("arguments[0].classList.remove('active')", exploreWikiaDropdown); END } please use method directly, you don't need to store it in variable

Target:
public void closeDropdown() { ((JavascriptExecutor) driver) .executeScript("arguments[0].classList.remove('active')", exploreWikiaDropdown); }
Source:
public int getPostsListLength() { START wait.forElementNotVisible(By.className(".spinner")); END return postList.size(); } don't wait for spinner here, instead before method invocation call `new BasePageObject(driver).waitForLoadingOverlayToDisappear();` in test case class

Target:
public int getPostsListLength() { return postList.size(); }
Source:
private void redirectFromFullSiteToOasis() { MercuryFooterComponentObject footer = new MercuryFooterComponentObject(driver); ArticleNavigationComponentObject navigation = new ArticleNavigationComponentObject(driver); SkinHelper helper = new SkinHelper(driver); new ArticlePageObject(driver).openWikiPage(url); START footer.clickFullSiteLink(); END navigation.clickRandomArticle(); Assertion.assertTrue(helper.isSkin(Skin.OASIS)); } footer is used once, cast it directly

Target:
private void redirectFromFullSiteToOasis() { ArticleNavigationComponentObject navigation = new ArticleNavigationComponentObject(driver); SkinHelper helper = new SkinHelper(driver); new ArticlePageObject(driver).openWikiPage(url); new MercuryFooterComponentObject(driver).clickFullSiteLink(); navigation.clickRandomArticle(); Assertion.assertTrue(helper.isSkin(Skin.OASIS)); }
Source:
protected void setWindowSize() { START if (!Configuration.getBrowser().contains("ANDROID")) { END if (Configuration.getBrowserSize() != null) { driver.manage().window().setSize(Configuration.getBrowserSize()); } else { driver.manage().window().maximize(); } } } what do you think about: ``` if ( ! "ANDROID".equals(Configuration.getBrowser()) && Configuration.getBrowserSize() != null ) { driver.manage().window().setSize(Configuration.getBrowserSize()); } else { driver.manage().window().maximize(); } ```

Target:
protected void setWindowSize() { if (!Configuration.getBrowser().contains("ANDROID") && Configuration.getBrowserSize() != null) { driver.manage().window().setSize(Configuration.getBrowserSize()); } else { driver.manage().window().maximize(); } }
Source:
public static Object[][] fliteTagBrokenOasis() { return new Object[][]{ {"adtest", "SyntheticTests/FliteTagBrokenWidth", START "Invalid width of the flite unit was passed. Make sure you provide width parameter with numeric value.", "#mw-content-text .error"}, END {"adtest", "SyntheticTests/FliteTagBrokenHeight", "Invalid height of the flite unit was passed. Make sure you provide height parameter with numeric value.", "#mw-content-text .error"}, {"adtest", "SyntheticTests/FliteTagBrokenTag", "Invalid guid parameter was passed. Provide valid guid or remove this tag from article's content.", "#mw-content-text .error"}}; } ``` java { "adtest", "SyntheticTests/FliteTagBrokenWidth", "Invalid width of the flite unit was passed. Make sure you provide width parameter with numeric value.", "#mw-content-text .error" }, ``` And the same for the below.

Target:
public static Object[][] fliteTagBrokenOasis() { return new Object[][]{ { "SyntheticTests/FliteTagBrokenWidth", "Invalid width of the flite unit was passed. Make sure you provide width parameter with numeric value." }, { "SyntheticTests/FliteTagBrokenHeight", "Invalid height of the flite unit was passed. Make sure you provide height parameter with numeric value." }, { "SyntheticTests/FliteTagBrokenTag", "Invalid guid parameter was passed. Provide valid guid or remove this tag from article's content." } }; }
Source:
public static Object[][] fliteTagOasis() { return new Object[][]{ {"adtest", "SyntheticTests/FliteTag", ".flite-tag-extension"}, START {"adtest", "SyntheticTests/FliteTagModifiedTag", ".flite-tag-extension"}}; END } Why we need to keep css selector in dataProvider? I would move it to a test level as a static var like here: https://github.com/Wikia/selenium-tests/blob/master/src/test/java/com/wikia/webdriver/testcases/adstests/TestPad.java#L14

Target:
public static Object[][] fliteTagOasis() { return new Object[][]{ {"SyntheticTests/FliteTag"}, {"SyntheticTests/FliteTagModifiedTag"}}; }
Source:
public void Login_006_authModalInGlobalNav_staff() { WikiBasePageObject base = new WikiBasePageObject(driver); base.openWikiPage(wikiURL); START NavigationBar signInLink = new NavigationBar(driver); END signInLink.clickOnSignIn(); AuthModal authModal = signInLink.getAuthModal(); Assert.assertTrue(authModal.isOpened()); authModal.login(credentials.userNameStaff, credentials.passwordStaff); base.verifyUserLoggedIn(credentials.userNameStaff); } Move this after `WikiBasePageObject base = new WikiBasePageObject(driver);`

Target:
public void Login_006_authModalInGlobalNav_staff() { WikiBasePageObject base = new WikiBasePageObject(driver); NavigationBar signInLink = new NavigationBar(driver); base.openWikiPage(wikiURL); signInLink.clickOnSignIn(); AuthModal authModal = signInLink.getAuthModal(); Assert.assertTrue(authModal.isOpened()); authModal.login(credentials.userNameStaff, credentials.passwordStaff); base.verifyUserLoggedIn(credentials.userNameStaff); }
Source:
START public boolean isTestElementVisible() { END boolean isVisible = false; try { wait.forElementVisible(testElement, 3, 1); isVisible = true; } catch (TimeoutException exception) { isVisible = false; } return isVisible; } Add JavaDOC

Target:
public boolean isTestElementVisible() { boolean isVisible = false; try { wait.forElementVisible(testElement, 3, 1); isVisible = true; } catch (TimeoutException e) { isVisible = false; } return isVisible; }
Source:
public boolean isEnableTestModeButtonVisible() { boolean isButtonVisible = false; try { wait.forElementVisible(enableTestModeButton, 5, 1); isButtonVisible = true; } catch (TimeoutException exception) { isButtonVisible = false; } START return isModuleVisible() && isButtonVisible; END } this method states it check the button visibility. It doesn't mention checking the module visibility. Please make this diversion more precise

Target:
public boolean isEnableTestModeButtonVisible() { boolean isButtonVisible = false; try { wait.forElementVisible(enableTestModeButton, 5, 1); isButtonVisible = true; } catch (TimeoutException e) { isButtonVisible = false; } return isModuleVisible() && isButtonVisible; }
Source:
public String getUrlForPathWithoutWiki(String wikiName, String wikiPath) { String url = getUrlForWiki(wikiName); url = url + wikiPath; START return url; END } please replace this with `return getUrlForWiki(wikiName) + wikiPath`

Target:
public String getUrlForPathWithoutWiki(String wikiName, String wikiPath) { return getUrlForWiki(wikiName) + wikiPath; }
Source:
public WidgetPageObject createMultiple() { START String[] tags = getTags(); END String articleContentString = ""; ArticleContent articleContent = new ArticleContent(); articleContent.clear(getArticleName()); for (String tag: tags) { articleContentString += tag + "\n"; } articleContent.push(articleContentString, getArticleName()); return this; } you are using `tags` ones, please access value directly in `for`

Target:
public WidgetPageObject createMultiple() { String text = ""; ArticleContent articleContent = new ArticleContent(); articleContent.clear(getArticleName()); for (String tag : getTags()) { text += tag + "\n"; } articleContent.push(text, getArticleName()); return this; }
Source:
public boolean isLoadedOnMercury() { boolean result = isTagLoadedOnMercury(); START Assertion.assertTrue(result, MercuryMessages.INVISIBLE_MSG); END PageObjectLogging.log(getTagName(), MercuryMessages.VISIBLE_MSG, result); return result; } assertion should made in test. Page objects are from keeping page state not asserting if something is correct or not

Target:
public boolean isLoadedOnMercury() { boolean result = isTagLoadedOnMercury(); PageObjectLogging.log(getTagName(), MercuryMessages.VISIBLE_MSG, result); return result; }
Source:
public ImageGenerator() { START imageWidth = 200; END imageHeight = 200; imageBuffer = new BufferedImage(imageWidth, imageHeight, BufferedImage.TYPE_INT_ARGB); } why not declare those values there https://github.com/Wikia/selenium-tests/pull/846/files#diff-bf8374f56664979c48c1a542fe88bf39R25?

Target:
public ImageGenerator() { imageBuffer = new BufferedImage(imageWidth, imageHeight, BufferedImage.TYPE_INT_ARGB); }
Source:
private String getRandomText(int textLength) { SecureRandom random = new SecureRandom(); START return new BigInteger(5 * textLength, random).toString(32); END } those 2 lines could be merged

Target:
private String getRandomText(int textLength) { return new BigInteger(5 * textLength, new SecureRandom()).toString(32); }
Source:
public Boolean isPasswordTogglerDisabled() { START String togglerDisabled = passwordField.getAttribute("type"); END return togglerDisabled.equals("password"); } `getAttribute()` can return `null`, you should handle that

Target:
public Boolean isPasswordTogglerDisabled() { String togglerDisabled = passwordField.getAttribute("type"); return "password".equals(togglerDisabled); }
Source:
public Page(String wikiName) { this.wikiName = wikiName; START this.wikiPath = null; END } Redundant

Target:
public Page(String wikiName) { this.wikiName = wikiName; }
Source:
private String getActivationLinkFromMail(String email, String password, String language) { String mailSubject; START if (language == "ja") { END mailSubject = "メールアドレスの認証を行ってウィキアを始めよう！"; } else { mailSubject = "Confirm your email and get started on Wikia!"; } String www = MailFunctions.getActivationLinkFromEmailContent( MailFunctions.getFirstEmailContent(email, password, mailSubject)); PageObjectLogging.log("getActivationLinkFromMail", "activation link is visible in email content: " + www, true); return www; } String is an object, so for String comparison please use: language.equals("ja")

Target:
private String getActivationLinkFromMail(String email, String password, String language) { String mailSubject; if (language.equals("ja")) { mailSubject = "メールアドレスの認証を行ってウィキアを始めよう！"; } else { mailSubject = "Confirm your email and get started on Wikia!"; } String www = MailFunctions.getActivationLinkFromEmailContent( MailFunctions.getFirstEmailContent(email, password, mailSubject)); PageObjectLogging.log("getActivationLinkFromMail", "activation link is visible in email content: " + www, true); return www; }
Source:
public void notPossibleToLogInWhenPasswordFieldBlank() throws InterruptedException { LoginPage loginPage = new LoginPage(driver).get(); loginPage.logUserIn(Configuration.getCredentials().userName10, ""); //we must wait some seconds to make sure button is activated START Thread.sleep(1000); END Assertion.assertTrue(loginPage.isSubmitButtonDisabled()); } Why do you use sleep ? It is highly discouraged, wait for an element instead

Target:
public void notPossibleToLogInWhenPasswordFieldBlank() throws InterruptedException { LoginPage loginPage = new LoginPage(driver).get(); loginPage.logUserIn(Configuration.getCredentials().userName10, ""); Assertion.assertTrue(loginPage.isSubmitButtonDisabled(2)); }
Source:
public void notPossibleToLogInWhenUsernameFieldBlank() throws InterruptedException { LoginPage loginPage = new LoginPage(driver).get(); loginPage.logUserIn("", Configuration.getCredentials().password10); //we must wait some seconds to make sure button is activated START Thread.sleep(1000); END Assertion.assertTrue(loginPage.isSubmitButtonDisabled()); } Why do you use sleep ? It is highly discouraged, wait for an element instead

Target:
public void notPossibleToLogInWhenUsernameFieldBlank() throws InterruptedException { LoginPage loginPage = new LoginPage(driver).get(); loginPage.logUserIn("", Configuration.getCredentials().password10); Assertion.assertTrue(loginPage.isSubmitButtonDisabled(2)); }
Source:
public static String getDisableFlash() { START return String.valueOf(getProp("disableFlash")); END } Why do we need `String.valueOf`?

Target:
public static String getDisableFlash() { return getProp("disableFlash"); }
Source:
public SpecialCuratedContentPageObject(WebDriver driver) { super(driver); START PageFactory.initElements(driver, this); END } Your parent constructor is doing that for you `WikiBasePageObject::WikiBasePageObject()`

Target:
public SpecialCuratedContentPageObject(WebDriver driver) { super(driver); }
Source:
public static Object[][] testAdsHopPostMessage() { return new Object[][]{ {"adtest", "DFP/hop", 1, "mobile"}, START {"adtest", "DFP/hophop", 2, "mobile_remnant"} END }; } Consider removing magic numbers and using just source to get the the right div you want.

Target:
public static Object[][] testAdsHopPostMessage() { return new Object[][]{ {"adtest", "DFP/hop", "mobile"}, {"adtest", "DFP/hophop", "mobile_remnant"} }; }
Source:
private Point getStartPoint(BufferedImage patternImage, boolean isLeft) { START return isLeft ? END new Point(articleLeftSideX - patternImage.getWidth(), startSkinY) : new Point(articleRightSideX, startSkinY); } A ternary operator here should be replaced for more visibility, can you please do it?

Target:
private Point getStartPoint(BufferedImage patternImage, boolean isLeft) { if (isLeft) { return new Point(articleLeftSideX - patternImage.getWidth(), startSkinY); } else { return new Point(articleRightSideX, startSkinY); } }
Source:
private boolean shouldCutPattern(int patternWidth, boolean isLeft) { START return isLeft ? patternWidth > articleLeftSideX : END patternWidth > viewPortWidth - articleRightSideX; } please replace with regular if/else

Target:
private boolean shouldCutPattern(int patternWidth, boolean isLeft) { if (isLeft) { return patternWidth > articleLeftSideX; } else { return patternWidth > viewPortWidth - articleRightSideX; } }
Source:
public String getDisableFlash() { START return config.get("disable-flash"); END } if you put in config file: `disable-flash: true` this wont work - can't cast boolean to String. A solution: `String.valueOf(config.get("disable-flash"))`

Target:
public String getDisableFlash() { return String.valueOf(config.get("disable-flash")); }
Source:
public IntraWikiSearchPageObject searchFor(String query) { typeQuery(query); START PageObjectLogging.log("searchFor", "searching for query: " + query, true, driver); END return clickSearchButton(); } You already logged query in typeQuery()

Target:
public IntraWikiSearchPageObject searchFor(String query) { PageObjectLogging.log("searchFor", "searching for query: " + query, true, driver); typeQuery(query); return clickSearchButton(); }