auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public static OkHttpClient getInstance() { if (sOkHttpClient == null) { sOkHttpClient = new OkHttpClient(); sOkHttpClient.setConnectTimeout(CONNECTION_TIMEOUT_SECONDS, TimeUnit.SECONDS); sOkHttpClient.setReadTimeout(CONNECTION_TIMEOUT_SECONDS, TimeUnit.SECONDS); sOkHttpClient.setWriteTimeout(CONNECTION_TIMEOUT_SECONDS, TimeUnit.SECONDS); sOkHttpClient.networkInterceptors().add(new UserAgentInterceptor(getUserAgentString())); } return sOkHttpClient; }

Target:
このメソッドをsynchronizedにするかsynchronizedブロックでThread safeにした方がよさそうです
Source:
protected boolean hasVideoAvailable() { if ( isTokenEvent ) { return tokenAd != null; } else { return incentivizedInterstitial.isAdReadyToDisplay(); } }

Target:
what happens when this is called before incentivizedInterstitial is assigned?
Source:
public void handleClick(@NonNull final View view) { super.handleClick( view ); parentNativeAd.launchClickTarget( view.getContext() ); notifyAdClicked(); }

Target:
Can we keep the order we have previously? That is 1. notify ad click, 2. launch click target.
Source:
private static void mkdirsOrThrow(File dir) throws IOException { if (!dir.exists()) { if (!dir.mkdirs()) { throw new IOException("Failed to create directory " + dir); } } }

Target:
It's not an issue but I think that it's better to put the both checks on a single line (`if (!dir.exists() && !dir.mkdirs())`)
Source:
private boolean pluginNotStarted(String pluginId) { if (pluginId != null) { PluginWrapper pluginWrapper = pluginManager.getPlugin(pluginId); if (PluginState.STARTED != pluginWrapper.getPluginState()) { return true; } log.trace("Checking extensions from plugin '{}'", pluginId); } else { log.trace("Checking extensions from classpath"); } return false; }

Target:
I think that the log messages related to extensions cannot be part of "pluginNotStarted"
Source:
public void startPlugins() { for (PluginWrapper pluginWrapper : resolvedPlugins) { PluginState pluginState = pluginWrapper.getPluginState(); if ((PluginState.DISABLED != pluginState) && (PluginState.STARTED != pluginState)) { tryStartPlugin(pluginWrapper, pluginWrapper.getDescriptor(), pluginState); } } }

Target:
this is a mechanic extraction. it's enough to pass only the pluginWrapper
Source:
public void testCreateFailNotFound() { PluginDescriptor pluginDescriptor = mock(DefaultPluginDescriptor.class); when(pluginDescriptor.getPluginClass()).thenReturn("org.pf4j.plugin.NotFoundTestPlugin"); PluginWrapper pluginWrapper = mock(PluginWrapper.class); when(pluginWrapper.getDescriptor()).thenReturn(pluginDescriptor); when(pluginWrapper.getPluginClassLoader()).thenReturn(getClass().getClassLoader()); DefaultPluginFactory instance = new DefaultPluginFactory(); Plugin result = instance.create(pluginWrapper); assertNull(result); }

Target:
No need to change. I feel that it's from the refactoring action
Source:
public void accumulate(long cx) { N += cx; M += (cx == 0 ? 0 : cx * Math.log(cx)); }

Target:
simpler to wrap both lines in an if: ``` if (cx > 0) { .. } ```
Source:
public void cleanup() { if(this.streamEstimator != null) { this.streamEstimator.reset(); } }

Target:
streamEstimator should never be null right?
Source:
public Object exec(Tuple input) throws IOException { if (input.size() == 0) { throw new RuntimeException("Expected at least one parameter"); } for (Object o : input) { if (o != null) { return o; } } return null; }

Target:
I think it should be: ``` java if (input == null || input.size() == 0) return null; ```
Source:
public void shouldReturnNullForEmptyFilename() { S3FileMapper s3FileMapper = new S3FileMapper(mockFileBrowser, mockFileHelper); S3File file = s3FileMapper.transform(null); assertNull(file); }

Target:
Since the test is for an empty filename I was expecting this to be `transform("")`?
Source:
public void helpBuildingEvent(EventBuilder eventBuilder) { eventBuilder.withSdkName(RavenEnvironment.SDK_NAME + ":android"); String release = tags.get(VERSION_NAME_TAG_KEY); if (!TextUtils.isEmpty(release)) { eventBuilder.withRelease(release); } for (String key : tags.keySet()) { eventBuilder.withTag(key, tags.get(key)); } }

Target:
I was just wondering if perhaps it makes sense to include this in the `for` loop below instead i.e. `if (VERSION_NAME_TAG_KEY.equals()) {...}` One other issue is whether you want the version name to be included both in the release property and as a tag.
Source:
private boolean isRequestFiltered(@Nullable Integer orderBy) { return orderBy != null && (orderBy == Constants.ORDER_BY_DISTANCE || orderBy == Constants.ORDER_BY_DATE || orderBy == Constants.ORDER_BY_STATUS || orderBy == Constants.ORDER_BY_NAME); return false; }

Target:
I guess this is never reached, right?
Source:
public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } ApiDataPoint that = (ApiDataPoint) o; return id.equals(that.id); }

Target:
ha! this is a new construct for me. I thought `that.id` is a private field ...?
Source:
public InternetDataConnection.InputStreamProvider forInput() throws IOException { if (input != null) throw new RuntimeException("Input has already been enabled"); if (connected) throw new RuntimeException("Cannot enable input after having already connected"); connection.setDoInput(true); input = new InternetDataConnection.InputStreamProvider(); return input; }

Target:
It is not a good practice to leave the brackets even if there is only one line you should always have them. If someone else comes and adds another line it may produce a bug.
Source:
public InternetDataConnection.OutputStreamProvider forOutput() throws IOException { if (output != null) throw new RuntimeException("Output has already been enabled"); if (connected) throw new RuntimeException("Cannot enable output after having already connected"); connection.setDoOutput(true); output = new InternetDataConnection.OutputStreamProvider(); return output; }

Target:
Missing brackets
Source:
public InternetDataConnection.BothStreams andInput() throws IOException { if (connected) throw new RuntimeException("Cannot enable output after having already connected"); return new InternetDataConnection.BothStreams(new InternetDataConnection.InputStreamProvider(), this); }

Target:
Missing brackets
Source:
public void stop(Throwable cause) throws Exception { if (body != null) body.cancel(cause); Run<?, ?> r = getContext().get(Run.class); TaskListener listener = getContext().get(TaskListener.class); ThrottleJobProperty.DescriptorImpl descriptor = Jenkins.getActiveInstance().getDescriptorByType(ThrottleJobProperty.DescriptorImpl.class); descriptor.removeThrottledPipelineForCategory(r.getExternalizableId(), getCategory(), listener); }

Target:
This method can be left blank—will not be called for a block-scoped step anyway, unless it is doing something between returning from `start` and the `BodyInvoker.start`.
Source:
private Boolean isInMutualCategory(ThrottleJobProperty jobBeingChecked, ThrottleJobProperty executingJob) { for (String category: jobBeingChecked.getCategories()) { if (executingJob.getCategories().contains(category)) { return true; } } return false; }

Target:
should be `boolean`
Source:
private ThrottleJobProperty getThrottleJobProperty(Task task) { if (task instanceof Job) { Job<?,?> p = (Job<?,?>) task; if (task instanceof MatrixConfiguration) { p = (Job<?,?>)((MatrixConfiguration)task).getParent(); } ThrottleJobProperty tjp = p.getProperty(ThrottleJobProperty.class); return tjp; } return null; }

Target:
BTW class cast to Job should not be required here
Source:
public ThrottleCategory(String categoryName, Integer maxConcurrentPerNode, Integer maxConcurrentTotal, String blockingCategories, List<NodeLabeledPair> nodeLabeledPairs) { this.maxConcurrentPerNode = maxConcurrentPerNode == null ? 0 : maxConcurrentPerNode; this.maxConcurrentTotal = maxConcurrentTotal == null ? 0 : maxConcurrentTotal; this.categoryName = categoryName; this.blockingCategories = blockingCategories; this.nodeLabeledPairs = nodeLabeledPairs == null ? new ArrayList<NodeLabeledPair>() : nodeLabeledPairs; convertCategoriesToList(blockingCategories); }

Target:
Please save the previous constructor as well. Otherwise the change affects the binary compatibility with previous versions
Source:
public void teleport(Location location, String successMessage, String failMessage) { PaperLib.teleportAsync(getPlayer(), BukkitAdapter.adapt(location)) .thenApply(success -> { if (success) { if (successMessage != null && !successMessage.isEmpty()) { MessagingUtil.sendStringToChat(this, successMessage); } } else { if (failMessage != null && !failMessage.isEmpty()) { printError(failMessage); } } return success; }); }

Target:
I don't think this needs changed? Definitely shouldn't need to add the null/isEmpty checks here, not sure about `MessagingUtil.sendStringToChat`
Source:
public boolean canFlipToNextPage() { if (selectedDataObservable.getValue() == null || selectedDataObservable.getValue() instanceof Document) { return false; } return super.canFlipToNextPage(); }

Target:
extract variable
Source:
public boolean isPageComplete() { if (availableBusinessData.isEmpty() && dataTypeSelectionOptions.isBusinessDataTypeSelected()) { return false; } if (availableDocuments.isEmpty() && !dataTypeSelectionOptions.isBusinessDataTypeSelected()) { return false; } if (selectedDataObservable.getValue() instanceof BusinessObjectData) { return isNoBusinessDataSelected() ? false : super.isPageComplete(); } if (selectedDataObservable.getValue() instanceof Document) { return super.isPageComplete(); } return super.isPageComplete(); }

Target:
<> if (availableBusinessData.isEmpty()) return false;
Source:
public void updateButtons() { super.updateButtons(); final Button nextButton = getButton(IDialogConstants.NEXT_ID); if (getCurrentPage() instanceof CreateContractInputFromBusinessObjectWizardPage) { final CreateContractInputFromBusinessObjectWizardPage page = (CreateContractInputFromBusinessObjectWizardPage) getCurrentPage(); nextButton.setText(Messages.preview); } else { nextButton.setText(IDialogConstants.NEXT_LABEL); } }

Target:
page variable is not used.
Source:
private JarPackageData configureJar(final ICompilationUnit[] compilationUnits) { final JarPackageData jarPackakeData = newJarPackageData(); jarPackakeData.setJarLocation(Path.fromOSString(toFile.getAbsolutePath())); jarPackakeData.setElements(compilationUnits); jarPackakeData.setDeprecationAware(true); jarPackakeData.setExportJavaFiles(includeSources); jarPackakeData.setOverwrite(true); jarPackakeData.setExportErrors(false); return jarPackakeData; }

Target:
It will have some side effects on connectors. (When sources does not compile.)
Source:
public String getText(final Object element) { if (element instanceof FieldToContractInputMapping) { final FieldToContractInputMapping mapping = (FieldToContractInputMapping) element; return new Boolean(!mapping.getField().isNullable()).toString(); } return super.getText(element); }

Target:
Boolean.valueOf to avoid object instanciation
Source:
protected boolean isBonitaGroovyBasedValidator(final Instance validator) { final String className = validator.get("validatorClass"); final boolean isBonitaGroovyBasedValidator = className != null && (className.contains("GroovyPageValidator") || className.contains("GroovyFieldValidator")); return isBonitaGroovyBasedValidator; }

Target:
return className != null && (className.contains("GroovyPageValidator") || className.contains("GroovyFieldValidator"));
Source:
private static IEclipseContext headlessContext() { if (HEADLESS_CONTEXT == null) { HEADLESS_CONTEXT = EclipseContextFactory.create("headlessContext"); } return HEADLESS_CONTEXT; }

Target:
shouldn't it be synchronized? (SIngleton)
Source:
public OutputMappingBuilder setProcessTarget(final Data data) { outputMapping.setProcessTarget(data);; return this; }

Target:
2 columns
Source:
public void update() { if (toolItem != null) { toolItem.setEnabled(canCreateNewForm() || canEditForm()); final PageFlow pageFlow = unwrap(selectionProvider.getSelection()); if (pageFlow != null) { if (pageFlow instanceof Pool) { toolItem.setToolTipText(NLS.bind(Messages.newFormTooltip, Messages.pool)); } else { toolItem.setToolTipText(NLS.bind(Messages.newFormTooltip, Messages.task)); } } } }

Target:
I think the button is always enabled. Either no form is defined -> new form A form is defined -> open form
Source:
public void should_fail_if_neither_name_nor_version_is_changed() throws Exception { final MustUpdateValidator mustUpdateValidator = new MustUpdateValidator(aPool().withName("Pool").withVersion("1.0").build(), new WritableValue("Pool", String.class), new WritableValue("1.0", String.class)); final IStatus status = mustUpdateValidator.validate(); StatusAssert.assertThat(status).isNotOK(); }

Target:
the linebreak place is not the best choice
Source:
protected void validationStatusChanged(final IStatus status) { updateTextEditorFeedback(status); messageManager.removeAllMessages(); if (!status.isOK() && getViewer().isCellEditorActive()) { messageManager.addMessage("", status.getMessage(), null, new StatusToMessageSeverity(status).toMessageSeverity()); } }

Target:
Why using empty string as first argument?
Source:
protected boolean isConnectorIsOnPool(final Connector connector) { if (connector.eContainer() instanceof Pool) { return true; } return false; }

Target:
why not directly return connector.eContainer() instanceof Pool; ?
Source:
public void should_failed_when_event_isNot_ON_ENTER_Or_ON_FINISH(){ ConnectorEventFilter failFilter = new ConnectorEventFilter("a"); }

Target:
left operand is useless
Source:
public void init() { // Check things are going to work. try { log.info("Search using solr on: "+ getSolrUrl()); } catch (IllegalStateException e) { log.error(e.getMessage()); } }

Target:
It would probably be better to have a clear separation between the call to `getSolrUrl()` and the creation of a log.
Source:
public void init() { solrUrl = serverConfigurationService.getString("ses.solr.server", null); solrServer = new ConcurrentUpdateSolrServer(solrUrl, 1000, 1); Integer.parseInt(serverConfigurationService.getString("recent.days", "14")); }

Target:
This doesn't do anything.
Source:
public void deleteAll() { try { String query = new String("*:*"); solrServer.deleteByQuery(query); } catch (SolrServerException e) { log.error(e.getLocalizedMessage(), e); } catch (IOException e) { log.error(e.getLocalizedMessage(), e); } }

Target:
new String() is redundant.
Source:
public void write(OutputStream out) { try { IOUtils.copy(results.getInputStream(), out); results.disconnect(); } catch (IOException e) { throw new WebApplicationException(Response.status(Status.SERVICE_UNAVAILABLE).entity("Service Unavailable, IO Exception with Search Engine").build()); } }

Target:
I think the results.disconnect() should be in a finally block as you always want to release the connection back.
Source:
public CourseCategoryDAO findCourseCategory(final String id) { List<Object> results = getHibernateTemplate().executeFind(new HibernateCallback() { public Object doInHibernate(Session session) { Query query = session.createSQLQuery( "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; }

Target:
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.
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)); PermissionAlertDialogFragment permissionDialogFragment = PermissionAlertDialogFragment.newInstance(); permissionDialogFragment.setArguments(args); navigationHandler.showDialog(permissionDialogFragment); } else { Toast.makeText(this, R.string.toast_attachment_error, Toast.LENGTH_SHORT).show(); finish(); } }

Target:
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
Source:
protected void saveTableOrdering() { Logger.debug(this, "saveTableOrdering"); ((DraggableEditableCardsAdapter)adapter).saveNewOrder(getTableController()); }

Target:
Rather than casting, can we ensure that the `adapter` is a `DraggableEditableCardsAdapter` when defined?
Source:
public Multimap<String, String> getQueryParams() { return queryParams; }

Target:
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.
Source:
public HttpMessage cookie(Cookie cookie) { this.cookies.add(cookie); setHeader( HttpMessageHeaders.HTTP_COOKIE_PREFIX + cookie.getName(), cookieConverter.getCookieString(cookie)); return this; }

Target:
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)?
Source:
public HomeView( Binder uiBinder) { initWidget(uiBinder.createAndBindUi(this)); }

Target:
Remove public
Source:
public HomePagePresenter(EventBus eventBus, MyView view, MyProxy proxy) { super(eventBus, view, proxy, ApplicationPresenter.SLOT_SetMainContent); }

Target:
Clean the "public" as well
Source:
protected void configure() { bindPresenterWidget(HeaderPresenter.class, HeaderPresenter.MyView.class, HeaderView.class); bind(new TypeLiteral<UiHandlersStrategy<HeaderUiHandlers>>() { }).to(new TypeLiteral<SetterUiHandlersStrategy<HeaderUiHandlers>>() { }); bind(HeaderUiHandlers.class).to(HeaderPresenter.class); }

Target:
spaces on empty line
Source:
public void userIsTakenToDiscussionsPostViewAfterClickOnPostSzl() { new MixedContentFooter().openWikiMainPage() .scrollToMCFooter() .getDiscussionsCard() .scrollToDiscussions() .clickDiscussionsPost(); String url = driver.getCurrentUrl(); Assertion.assertTrue(url.contains(".wikia.com/szl/d/")); }

Target:
`url` is used only once, so I guess we could use it inline i.e. `driver.getCurrentUrl().contains()`
Source:
public String getUrlForWikiPageWithWWW(String pageName) { if ("".equals(pageName)) throw new WebDriverException("Page name is missing"); return getUrl(true) + URLsContent.WIKI_DIR + pageName; }

Target:
please add curly braces here
Source:
public SpecialAnonymizationUserPage fillFutureAnon(String anonymizedUser) { jsActions.scrollBy(0, 400); wait.forElementClickable(submitButton); AnonymizationTextBox.sendKeys(anonymizedUser); return this; }

Target:
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).
Source:
public SpecialAnonymizationUserPage submitAnonymization() { try { Thread.sleep(10000); } catch (Exception e) { } jsActions.scrollToElement(submitButton); submitButton.click(); return this; }

Target:
just FYI, I think there's a method `scrollAndClick()`
Source:
private String getEditUrl(String page, String query) { return urlBuilder.appendQueryStringToURL( urlBuilder.getUrlForWikiPage(String.format("/wiki/%s", urlBuilder.normalizePageName(page))), query); }

Target:
![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)
Source:
public void snippetIsNotAffectedByXSS() { new ArticlePage().open("/File:Mala-mi.jpg"); FilePageObject filePage = new FilePageObject(); Assertion.assertTrue(filePage.doesSnippetContainXSS()); AlertHandler xssAlert = new AlertHandler(); Assertion.assertFalse(xssAlert.isAlertPresent(driver)); }

Target:
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)`
Source:
public void verifyNoAdsOnPage() { scrollToSelector(AdsContent.getSlotSelector(AdsContent.BOTTOM_LB)); verifyNoAds(); PageObjectLogging.log( "verifyNoAdsOnPage", "No ads detected", true, driver ); }

Target:
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 :(
Source:
public Optional<PostEntity> getPostById(String postId) { return Optional.ofNullable( 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)))); }

Target:
This outer optional shouldnt be needed here
Source:
public boolean isPostFollowed() { this.waitForPageLoad(); return this.getPost().findNewestPost().isFollowed(); }

Target:
is `this.` necessary?
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); if (getParams() != null) { httpPost.setEntity(new UrlEncodedFormEntity(getParams(), StandardCharsets.UTF_8)); } return httpClient.execute(httpPost); }

Target:
It doesn't look like this method can ever return a `null`.
Source:
@Override public SignInPage typeUsername(String username) { fillInput(usernameField, username); return this; }

Target:
I think the code style suggests the annotations should be above the methods.
Source:
public void scrollToSlot(String slotName) { if (slotName.equals(AdsContent.BOTTOM_LB)) { triggerComments(); } if (slotName.equals(AdsContent.MOBILE_BOTTOM_LB)) { scrollToFooter(); } scrollToPosition("#" + slotName); }

Target:
nitpick: `if ... else` would be more appropriate here
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)) .filter(activity -> activity.getWallThreadAuthor().contains(threadAuthor)) .anyMatch(activity -> activity.getWallThreadContent().contains(threadContent)); }

Target:
`.equals` here?
Source:
private void verifyUapBtf(long btfId, String slotName, String bottomSlotName, AdsFandomObject fandomPage) { 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)); }

Target:
![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)
Source:
private String parseDuration() { NumberFormat formatter = new DecimalFormat("00"); int hours = (int) Math.floor(duration / 3600); int minutes = (int) Math.floor(duration / 60 % 60); int seconds = (int) Math.floor(duration % 60); return String.format("%s:%s:%s", formatter.format(hours), formatter.format(minutes), formatter.format(seconds)); }

Target:
it looks like an universal operation, did we checked if sth similar is not performed in repo already?
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) { return true; } 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; }

Target:
you can use result of comparison as returned value
Source:
public void waitSafely(Runnable o) { try { o.run(); } catch (TimeoutException e) { PageObjectLogging.log("Timed out waiting", e.getMessage(), true); } }

Target:
Create a ticket to improve Sonar rules?
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); Assertion.assertTrue(base.isStringInURL(URLsContent.SPECIAL_UPLOAD)); }

Target:
Static import `assertTrue`?
Source:
public void vuapDefaultStateShouldStartPlayingAdvertisementAutomatically(Page page, String slot, String videoIframeSelector) { openPageWithVideoInLocalStorage(page, VuapVideos.PORVATA_VAST, VuapVideos.VAST_VIDEO); final AutoplayVuap vuap = new AutoplayVuap(driver, slot, videoIframeSelector); VuapAssertions.verifyVideoPlay(vuap); }

Target:
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?
Source:
public void deleteAllCategories(final String siteId, User user) { ArrayList<CategoryPill.Data> categories = getCategoriesFromSite(siteId, user); for (CategoryPill.Data category : categories) { PageObjectLogging.logInfo("Deleting category: " + category.getName()); deleteCategory(siteId, category); } }

Target:
Interface can be used here.
Source:
public ArrayList<CategoryPill.Data> getCategoriesFromSite(final String siteId, User user) { return new Categories(user).execute(CreateCategoryContext.defaultContextUsing(siteId, "")); }

Target:
Interface can be used for the return signature.
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); } catch (UnsupportedEncodingException|RemoteException x) { PageObjectLogging.log("Error while creating http post entity.", ExceptionUtils.getStackTrace(x), false); } return result; }

Target:
Nitpick: you're missing spaces before and after the pipe. I'd suggest naming the exception variables `ex`.
Source:
public CategoryPill findCategoryOn(int position) { CategoryPill result = null; final List<WebElement> categoryPills = findCategoryPills(); if (position < categoryPills.size()) { result = new CategoryPill(categoryPills.get(position)); } return result; }

Target:
``` 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) { driver.findElement(By.cssSelector(selector)); js.executeScript( "document.querySelector(arguments[0]).style.opacity = arguments[1];", selector, value); }

Target:
what is the purpose of this line?
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); } return dialog; }

Target:
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); } ```
Source:
private void assertThatPostCanBeUnfollowed(PostDetailsPage page) { final PostActionsRow postActions = page.getPost().findNewestPost().findPostActions(); postActions.clickFollow(); sleepForOneSecond(); Assertion.assertFalse(postActions.isFollowed(), SHOULD_UNFOLLOW_MESSAGE); }

Target:
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
Source:
private ArrayList<String> getTabUrls() { 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; }

Target:
Maybe you could use here `List` interface instead specific implementation?
Source:
public void selectCategory(int categoryId) { wait.forElementVisible(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); }

Target:
clickable
Source:
public static String createUniqueText() { return String.format(UNIQUE_TEXT_FORMAT, System.nanoTime()); }

Target:
just millis shoud be enought
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)); Assertion.assertEquals(latestDate, currentDate, "Current date and the latest possible date are not the same"); }

Target:
I think latestDate should be passed as second param, according to doc: `assertEquals(Object actual, Object expected, String message)`
Source:
public VisualEditorPageObject typeInParameterField(int i, String parameter) { WebElement element = parametersFieldList.get(i); wait.forElementClickable(element); element.click(); element.sendKeys(parameter); return this; }

Target:
can we add here more descriptive name instead of `element`? Maybe `parameterInput` or `input` or `field`?
Source:
public Navigate toPage(String pageName) { String host = UrlBuilder.getHostForWiki(); String cacheBuster = pageName.equals("") || pageName.equals("/") ? "" : "?cb=" + DateTime.now().getMillis(); String abGroup = pageName.equals("") || pageName.equals("/") ? "" : defaultTestingGroup; driver.get("http://" + host + pageName + cacheBuster + abGroup); return this; }

Target:
if you will navigate to page with `/` you will get `http://www.example.com/&ABTEST.` add your parameter to the end of line above
Source:
public Navigation clickExploreWikiHeader() { Loading loading = new Loading(driver); PageObjectLogging.logInfo("Click 'Explore Wiki' header"); wait.forElementClickable(exploreWikiHeader); exploreWikiHeader.click(); loading.handleAsyncPageReload(); return this; }

Target:
Just use `loading` declared class field
Source:
public void mercury_search_searchNoResultsPageDisplayed() { init(); SearchResultsPage searchResults = new SearchResultsPage().openForQuery(SEARCH_PHRASE_NO_RESULTS); Assertion.assertTrue(searchResults.isNoResultsPagePresent()); }

Target:
new line is not needed here
Source:
public PortableInfoboxObject clickGalleryImage(int index) { Assertion.assertFalse(galleryImageList.isEmpty()); wait.forElementClickable(galleryImageList.get(index)); galleryImageList.get(index).click(); return this; }

Target:
Why asserting this?
Source:
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 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; }

Target:
so it's fixed or not? :D (per line 56)
Source:
public boolean isUserOnChat() { try { wait.forElementVisible(chatInlineAlert); return chatInlineAlert.isDisplayed(); } catch (Exception e) { return false; } }

Target:
isn't `wait.forElementVisible` checks if element is displayed? if yes, we can return `true` instead of running `chatInlineAlert.isDisplayed()`
Source:
private void init() { this.head = new Head(driver); this.navigate = new Navigate(driver); }

Target:
Please use `@BeforeMethod(alwaysRun = true)` insted of `init()` inside of test body
Source:
public InfoboxBuilderPage changeHeaderCollapsibilityState(int index) { JavascriptExecutor js = (JavascriptExecutor) driver; 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; }

Target:
this line: `JavascriptExecutor js = (JavascriptExecutor) driver;` is not needed, `driver` object is already inheriting `JavascriptExecutor` class. Just use: `driver.executeScript(script).toString();` :)
Source:
public RecentWikiActivityPage open(){ editArticle("RWA" + DateTime.now().getMillis()); getUrl(String.format("%s%s", urlBuilder.getUrlForWiki(), URLsContent.RECENT_WIKI_ACTIVITY)); return this; }

Target:
Why push content always before opening recent wiki activity?
Source:
public RecentWikiActivity goBackToRWA() { wait.forElementClickable(backArrow); backArrow.click(); loading.handleAsyncPageReload(); PageObjectLogging.logInfo("The arrow that redirect user back to RWA was clicked"); Assertion.assertTrue(driver.getCurrentUrl().contains(URLsContent.RECENT_WIKI_ACTIVITY), "You were not redirected to the recent wiki activity"); PageObjectLogging.logInfo("You were redirected to the recent wiki activity"); return this; }

Target:
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 ;)
Source:
public RecentWikiActivityPage open(){ editArticle("RWA Tests"); getUrl(String.format("%s%s", urlBuilder.getUrlForWiki(), URLsContent.RECENT_WIKI_ACTIVITY)); return this; }

Target:
Please edit article in test, not when openning a page
Source:
public void closeDropdown() { JavascriptExecutor js = (JavascriptExecutor) driver; js.executeScript("arguments[0].classList.remove('active')", exploreWikiaDropdown); }

Target:
please use method directly, you don't need to store it in variable
Source:
public int getPostsListLength() { wait.forElementNotVisible(By.className(".spinner")); return postList.size(); }

Target:
don't wait for spinner here, instead before method invocation call `new BasePageObject(driver).waitForLoadingOverlayToDisappear();` in test case class
Source:
private void redirectFromFullSiteToOasis() { MercuryFooterComponentObject footer = new MercuryFooterComponentObject(driver); ArticleNavigationComponentObject navigation = new ArticleNavigationComponentObject(driver); SkinHelper helper = new SkinHelper(driver); new ArticlePageObject(driver).openWikiPage(url); footer.clickFullSiteLink(); navigation.clickRandomArticle(); Assertion.assertTrue(helper.isSkin(Skin.OASIS)); }

Target:
footer is used once, cast it directly
Source:
protected void setWindowSize() { if (!Configuration.getBrowser().contains("ANDROID")) { if (Configuration.getBrowserSize() != null) { driver.manage().window().setSize(Configuration.getBrowserSize()); } else { driver.manage().window().maximize(); } } }

Target:
what do you think about: ``` if ( ! "ANDROID".equals(Configuration.getBrowser()) && 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", "Invalid width of the flite unit was passed. Make sure you provide width parameter with numeric value.", "#mw-content-text .error"}, {"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"}}; }

Target:
``` 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.
Source:
public static Object[][] fliteTagOasis() { return new Object[][]{ {"adtest", "SyntheticTests/FliteTag", ".flite-tag-extension"}, {"adtest", "SyntheticTests/FliteTagModifiedTag", ".flite-tag-extension"}}; }

Target:
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
Source:
public void Login_006_authModalInGlobalNav_staff() { WikiBasePageObject base = new WikiBasePageObject(driver); base.openWikiPage(wikiURL); NavigationBar signInLink = new NavigationBar(driver); signInLink.clickOnSignIn(); AuthModal authModal = signInLink.getAuthModal(); Assert.assertTrue(authModal.isOpened()); authModal.login(credentials.userNameStaff, credentials.passwordStaff); base.verifyUserLoggedIn(credentials.userNameStaff); }

Target:
Move this after `WikiBasePageObject base = new WikiBasePageObject(driver);`
Source:
public boolean isTestElementVisible() { boolean isVisible = false; try { wait.forElementVisible(testElement, 3, 1); isVisible = true; } catch (TimeoutException exception) { isVisible = false; } return isVisible; }

Target:
Add JavaDOC
Source:
public boolean isEnableTestModeButtonVisible() { boolean isButtonVisible = false; try { wait.forElementVisible(enableTestModeButton, 5, 1); isButtonVisible = true; } catch (TimeoutException exception) { isButtonVisible = false; } return isModuleVisible() && isButtonVisible; }

Target:
this method states it check the button visibility. It doesn't mention checking the module visibility. Please make this diversion more precise
Source:
public String getUrlForPathWithoutWiki(String wikiName, String wikiPath) { String url = getUrlForWiki(wikiName); url = url + wikiPath; return url; }

Target:
please replace this with `return getUrlForWiki(wikiName) + wikiPath`
Source:
public WidgetPageObject createMultiple() { String[] tags = getTags(); String articleContentString = ""; ArticleContent articleContent = new ArticleContent(); articleContent.clear(getArticleName()); for (String tag: tags) { articleContentString += tag + "\n"; } articleContent.push(articleContentString, getArticleName()); return this; }

Target:
you are using `tags` ones, please access value directly in `for`
Source:
public boolean isLoadedOnMercury() { boolean result = isTagLoadedOnMercury(); Assertion.assertTrue(result, MercuryMessages.INVISIBLE_MSG); PageObjectLogging.log(getTagName(), MercuryMessages.VISIBLE_MSG, result); return result; }

Target:
assertion should made in test. Page objects are from keeping page state not asserting if something is correct or not
Source:
public ImageGenerator() { imageWidth = 200; imageHeight = 200; imageBuffer = new BufferedImage(imageWidth, imageHeight, BufferedImage.TYPE_INT_ARGB); }

Target:
why not declare those values there https://github.com/Wikia/selenium-tests/pull/846/files#diff-bf8374f56664979c48c1a542fe88bf39R25?
Source:
private String getRandomText(int textLength) { SecureRandom random = new SecureRandom(); return new BigInteger(5 * textLength, random).toString(32); }

Target:
those 2 lines could be merged
Source:
public Boolean isPasswordTogglerDisabled() { String togglerDisabled = passwordField.getAttribute("type"); return togglerDisabled.equals("password"); }

Target:
`getAttribute()` can return `null`, you should handle that
Source:
public Page(String wikiName) { this.wikiName = wikiName; this.wikiPath = null; }

Target:
Redundant
Source:
private String getActivationLinkFromMail(String email, String password, String language) { String mailSubject; if (language == "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; }

Target:
String is an object, so for String comparison please use: language.equals("ja")
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 Thread.sleep(1000); Assertion.assertTrue(loginPage.isSubmitButtonDisabled()); }

Target:
Why do you use sleep ? It is highly discouraged, wait for an element instead
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 Thread.sleep(1000); Assertion.assertTrue(loginPage.isSubmitButtonDisabled()); }

Target:
Why do you use sleep ? It is highly discouraged, wait for an element instead
Source:
public static String getDisableFlash() { return String.valueOf(getProp("disableFlash")); }

Target:
Why do we need `String.valueOf`?
Source:
public SpecialCuratedContentPageObject(WebDriver driver) { super(driver); PageFactory.initElements(driver, this); }

Target:
Your parent constructor is doing that for you `WikiBasePageObject::WikiBasePageObject()`
Source:
public static Object[][] testAdsHopPostMessage() { return new Object[][]{ {"adtest", "DFP/hop", 1, "mobile"}, {"adtest", "DFP/hophop", 2, "mobile_remnant"} }; }

Target:
Consider removing magic numbers and using just source to get the the right div you want.
Source:
private Point getStartPoint(BufferedImage patternImage, boolean isLeft) { return isLeft ? new Point(articleLeftSideX - patternImage.getWidth(), startSkinY) : new Point(articleRightSideX, startSkinY); }

Target:
A ternary operator here should be replaced for more visibility, can you please do it?
Source:
private boolean shouldCutPattern(int patternWidth, boolean isLeft) { return isLeft ? patternWidth > articleLeftSideX : patternWidth > viewPortWidth - articleRightSideX; }

Target:
please replace with regular if/else
Source:
public String getDisableFlash() { return config.get("disable-flash"); }

Target:
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"))`
Source:
public IntraWikiSearchPageObject searchFor(String query) { typeQuery(query); PageObjectLogging.log("searchFor", "searching for query: " + query, true, driver); return clickSearchButton(); }

Target:
You already logged query in typeQuery()
Source:
public void loginExistingAccount(String userName, String password) { waitForElementByElement(existingUsernameField); existingUsernameField.sendKeys(userName); PageObjectLogging.log("loginExistingAccount", "username " + userName + " typed into the field", true); waitForElementByElement(existingPasswordField); existingPasswordField.sendKeys(password); PageObjectLogging.log("loginExistingAccount", "password " + password + " typed into the field", true); loginExistingButton.click(); PageObjectLogging.log("loginExistingAccount", "login button clicked", true); }

Target:
We have global event listener which log each click, so you don't need to do it by yourself.
Source:
public void waitForDialogVisible() { waitForElementByElement(dialog); waitForElementVisibleByElement(dialog); }

Target:
Those two methods are similar. Consider using one.
Source:
public VisualEditorSaveChangesDialog clickReturnToSaveFormButton() { waitForElementClickableByElement(returnToSaveFormButton); returnToSaveFormButton.click(); PageObjectLogging .log("clickReturnToSaveFormButton", "Return To Save Form button clicked", true); return new VisualEditorSaveChangesDialog(driver); }

Target:
Global listener catch each click. You don't need to log it.
Source:
public VisualEditorSaveChangesDialog clickSaveWithRecaptcha() { waitForElementClickableByElement(publishButton); if (checkIfElementOnPage(recaptchaArea)) { recaptchaContainer = saveDialogBody.findElement(recaptchaImageBy); waitForElementVisibleByElement(recaptchaContainer); } publishButton.click(); PageObjectLogging.log("clickSaveWithRecaptcha", "The 2nd Publish Button is clicked", true); return new VisualEditorSaveChangesDialog(driver); }

Target:
You are logging already logged click.
Source:
public VisualEditorReviewChangesDialog clickReviewYourChanges() { waitForElementVisibleByElement(reviewChangesButton); waitForElementClickableByElement(reviewChangesButton); reviewChangesButton.click(); PageObjectLogging.log("clickReviewYourChanges", "Review Your Changes Button is clicked", true); return new VisualEditorReviewChangesDialog(driver); }

Target:
double wait
Source:
public void typeInEditArea(String text) { waitForDialogVisible(); waitForElementNotVisibleByElement(loadingIndicator); WebElement editArea = dialog.findElement(editAreaBy); waitForElementVisibleByElement(editArea); waitForElementClickableByElement(editArea); editArea.sendKeys(text); waitForValueToBePresentInElementsAttributeByElement(editArea, "value", text); PageObjectLogging.log("typeInEditArea", "Typed " + text, true, driver); }

Target:
double wait
Source:
public void verifyOpeningArticleInNav(int anchorIndex) { waitForElementVisibleByElement(noChevrons.get(anchorIndex)); if (noChevrons.size() != 0) { noChevrons.get(anchorIndex).click(); PageObjectLogging.log("verifyOpeningArticleInNav", "New article opened", true, driver); } }

Target:
is this check necessary since noChevrons.get(index) is already being called prior to this?
Source:
public void verifyBackLinkFunctionality(int anchorIndex) { waitForElementVisibleByElement(chevrons.get(anchorIndex)); if (chevrons.size() != 0) { chevrons.get(anchorIndex).click(); waitForElementVisibleByElement(backChevron); backChevron.click(); PageObjectLogging.log("verifyBackLinkFunctionality", "Back button is working", true, driver); } }

Target:
is this check necessary since chevrons.get(index) is already being called prior to this?
Source:
private void showSlot(String selector, WebDriver driver) { changeVisibility(selector, "visible", driver); }

Target:
why is this private? and show slot is public?
Source:
public VenusGlobalNavPageObject openHubsMenuViaHover() { Actions actions = new Actions(driver); actions.moveToElement(menuButton); actions.build().perform(); WebDriverWait wait = new WebDriverWait(driver, 5); wait.until(CommonExpectedConditions.elementVisible(hubsMenu)); return this; }

Target:
no need to declare a avriable "wait" just ``` new WebdriverWait(driver, 5).until(...) .... ``` will do the job