Why is close() method highlighted as redundant in Intellij, when using CSVPrinter from apcache.commons? - apache

I am using CSVPrinter class from apache.commons.csv, and I am trying to print some lines in a csv file. As I know, we need to call close() method on a FileWriter, after the writing is done. And based on that assumption, I tried to call CSVPrinter.close().However, IntelliJ IDEA warns me that this method is redundant. Besides, examples in https://www.callicoder.com/java-read-write-csv-file-apache-commons-csv/ does not include this method, either. I want to know why is that method redundant and if I just use .flush() everything will be alright?
Here is an example copied from website mentioned above.
import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVPrinter;
import java.io.*;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Arrays;
public class CSVWriter {
private static final String SAMPLE_CSV_FILE = "./sample.csv";
public static void main(String[] args) throws IOException {
try (
BufferedWriter writer = Files.newBufferedWriter(Paths.get(SAMPLE_CSV_FILE));
CSVPrinter csvPrinter = new CSVPrinter(writer, CSVFormat.DEFAULT
.withHeader("ID", "Name", "Designation", "Company"));
) {
csvPrinter.printRecord("1", "Sundar Pichai ♥", "CEO", "Google");
csvPrinter.printRecord("2", "Satya Nadella", "CEO", "Microsoft");
csvPrinter.printRecord("3", "Tim cook", "CEO", "Apple");
csvPrinter.printRecord(Arrays.asList("4", "Mark Zuckerberg", "CEO", "Facebook"));
csvPrinter.flush();
// I added the following line
csvPrinter.close();
}
}
}

As #user207421 explained in the comments.
First: The try-with-resources statement provides an automatic close at the end of its scope.
Second: Flush is redundant before close.

Related

Selenium (Java): the method dndScript() is undefined

I'm trying to verify that a former colleague's old demo Selenium script still works, but have run into a curious error. The colleague is no longer around to consult, unfortunately. First, here's the script in question, which is supposed to drag and drop one element over another on a page:
import java.util.List;
import java.util.concurrent.ThreadLocalRandom;
import java.util.function.Supplier;
import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.junit.Assert;
import org.junit.jupiter.api.Test;
public class DragNDrop {
#Test
public void testDragAndDropWithCheck() throws InterruptedException {
System.setProperty("webdriver.gecko.driver","D:\\WebDriver\\geckodriver.exe");
WebDriver driver=new FirefoxDriver();
driver.get("https://the-internet.herokuapp.com/drag_and_drop");
By css = By.cssSelector("div[id^=\"column-\"]");
WebDriverWait wait = new WebDriverWait(driver, 10);
Supplier<List<WebElement>> fetchComponents = () -> wait
.until(ExpectedConditions.presenceOfAllElementsLocatedBy(css));
/**
* Starting check for element position
*/
List<WebElement> startingCheck = fetchComponents.get();
Assert.assertEquals("Starting - Draggable number does not match!", 2, startingCheck.size());
Assert.assertEquals("Starting - A position does not match!", "A", startingCheck.get(0).getText());
Assert.assertEquals("Starting - B position does not match!", "B", startingCheck.get(1).getText());
int index = ThreadLocalRandom.current().nextInt(startingCheck.size());
WebElement from = startingCheck.get(index);
WebElement to = startingCheck.get(1 - index);
JavascriptExecutor jse = (JavascriptExecutor) driver;
jse.executeScript(
dndScript() + "simulateDragAndDrop(arguments[0], arguments[1])",
from,
to);
/**
* Ending check for element position
*/
List<WebElement> endingCheck = fetchComponents.get();
Assert.assertEquals("Ending - Draggable number does not match!", 2, endingCheck.size());
Assert.assertEquals("Ending - A position does not match!", "A", endingCheck.get(1).getText());
Assert.assertEquals("Ending - B position does not match!", "B", endingCheck.get(0).getText());
}
}
The problem is with this part:
jse.executeScript(
dndScript() + "simulateDragAndDrop(arguments[0], arguments[1])",
from,
to);
Eclipse highlighted dndScript() and threw the message:
The method dndScript() is undefined for the type DragNDrop
I first figured this was due to a missing import, so I got to googling, but I can't find any information on it. The most I could find was some references to something called "RichFaces", but I couldn't find any further clarification (may be my own fault -- I'm by no means a Selenium/Java expert).
Any idea on what the story is with this function and how to properly implement it in this script?
It is unlikely related to the missing import (probably the static one). Since this is just a method name there could be three cases:
This is a static method in scope of some different classand used to be imported with static import
This is the method that has to be implemented in the scope of your current class
This is the method that has to be implemented in scope of parent classes
The reason of you currently have is that the code of your current class changed since that time. You need to check revision history if you take this code from version control.
There are few possible stories which seem possible:
There was a method in scope of current class and then it was moved so some parent class. In some reason someone forgot to add extends keyword to current class.
There was a method in scope of parent class. After that someone decided to break relationship between the classes and forgot to move that method to your current class.
There was static method in some different class. It was imported to the current class as static import. Then someone loaded that class to IDE and didn't add that "different class" to project's class path. Then they applied "organize imports" feature which removed that broken import from your current class.

Fitnesse wiki unable to call selenium method correctly

I am trying to write a simple fixture that opens the browser and navigates to www.google.com. When I run the wiki page, it passes with all green, but the browser never opens up (I don't think the method even gets called by the wiki). Can someone take a look at my fixture and wiki to see what I am doing wrong? Many thanks in advance,
Here is the Wiki -
!|SeleniumFitness|
|URL |navigateToSite?|
|http://www.google.com| |
After Running -
!|SeleniumFitnesse| java.lang.NoSuchMethodError: org.openqa.selenium.remote.service.DriverCommandExecutor.<init>(Lorg/openqa/selenium/remote/service/DriverService;Ljava/util/Map;)V
|URL |The instance decisionTable_4.setURL. does not exist|navigateToSite?
|http://www.google.com|!The instance decisionTable_4.navigateToSite. does not exist |
Here is the Fixture -
package FitNesseConcept.fitNesse;
import java.util.Properties;
import org.junit.BeforeClass;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.annotations.BeforeMethod;
//import com.google.common.base.Preconditions.*;
//import com.google.common.collect.Lists;
import fit.ColumnFixture;
public class SeleniumFitnesse extends ColumnFixture {
public static ChromeDriver driver = null;
private String navigateToSite = "";
public String URL = "";
public SeleniumFitnesse() {
Properties props = System.getProperties();
props.setProperty("webdriver.chrome.driver", "/home/ninad/eclipse-workspace/chromedriver");
driver = new ChromeDriver();
}
// SET-GET Methods
public String getURL() {
return URL;
}
public void setURL(String uRL) {
URL = uRL;
}
public String getNavigateToSite() {
return navigateToSite;
}
public void setNavigateToSite(String navigateToSite) {
this.navigateToSite = navigateToSite;
}
// Navigate to URL
public void navigateToSite() throws Throwable {
System.out.println("Navigating to Website");
try {
driver.navigate().to(URL);
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
You are getting some good recommendations as comments - but to answer your question directly, for an old-style ColumnFixture, which is what you have written, the method "navigateToSite" is indeed not going to be called.
These styles of fixtures are not often used anymore, Slim is preferred, and your fitnesse instance in its documentation will show you how to use Slim style. However, for a column fixture as you have written, if you want a method to be called it needs to be a "?" following name of the method in the header row.
See basic docs for column fixture:
http://fitnesse.org/FitNesse.UserGuide.FixtureGallery.BasicFitFixtures.ColumnFixture
You are mis-using column fixture, even granted the old style though. Column fixture's pattern is "here is a series of columns that represent inputs, now here is a method call I want to make to get the output and check result". Navigating a website does not often fit that pattern. In old style fitnesse it would probably be approached by an ActionFixture:
http://fitnesse.org/FitNesse.UserGuide.FixtureGallery.BasicFitFixtures.ActionFixture
In the newer Slim style, a good fit for navigation and checking where you are would be a Scenario Table.
http://www.fitnesse.org/FitNesse.UserGuide.WritingAcceptanceTests.SliM.ScenarioTable
In general doing WebDriver / Selenium tests through a wiki is worth extra thought as to whether it's your best medium. Fitnesse is really designed to be a collaborative tool for documenting and verifying business requirements, directly against source code.
Here's an example of how to do with a ColumnFixture, although again ColumnFixture not exactly appropriate:
|url|navigateToUrl?|
|www.google.com| |
java class:
public String url;
public void navigateToUrl() {
}
You could return an "OK" if it navigates alright, or return the title of the page as opposed to void if you wanted.

JavaFX: Display PDF in WebView

I need to display a PDF inside the default WebView of JavaFX. I assumed, that i would easily be able to do that like this.
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.web.WebEngine;
import javafx.scene.web.WebView;
import javafx.stage.Stage;
public class ShowPdfTest extends Application {
public static void main(String[] args) {
launch();
}
#Override
public void start(Stage primaryStage) throws Exception {
WebView webView = new WebView();
WebEngine engine = webView.getEngine();
Scene scene = new Scene(webView);
primaryStage.setScene(scene);
primaryStage.show();
// engine.load("https://www.google.com");
engine.load("http://www.orimi.com/pdf-test.pdf");
}
}
I was wrong. Nothing happens. It seems like the WebEngine has no built-in PDF-Renderer. I tried JxBrowser which worked fine, but is a rather costly alternative.
So is there any way to display a PDF directly inside the default WebView component?
JxBrowser which worked fine, but is a rather costly alternative.
If you your application is an open-source project, you can obtain the JxBrowser Open-Source license here.

Program doesn't wait for modal dialog

With this program I am attempting to have the user select a text file that is a representation of a 4x4 sudoku problem. My agent will then take this file and attempt to solve the sudoku puzzle.
The problem I'm running into is that I can't seem to figure out how to get the proper file selected, and then passed into the method call for processing.
This is the file selector class I've created. So far it successfully brings up a button, and when clicked brings up the computer's file structure so the user can select a file.
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
/**
* Created by neil on 7/12/17.
*/
public class file_selector {
public JPanel panel1;
public File file;
JButton button1;
public file_selector() {
final JFileChooser fc = new JFileChooser();
button1.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
int returnVal = fc.showOpenDialog(null);
if (returnVal == JFileChooser.APPROVE_OPTION) {
file = fc.getSelectedFile();
System.out.println("You chose to open " + file.getName());
}
}
});
}
public File getFile() {
return file;
}
}
This is my main method in which I attempt to use the file that the user selected. When I put the function calls in a while loop (like it is currently) it never proceeds because the file is never set. If I don't put the function calls in a while loop, I get a nullPointerException error when I try to process the file because the file has a null value.
public class sudoku {
//create 2d array that represents the 16x16 world
public cell[][] world_array = new cell[15][15];
static File myFile;
ArrayList<String> world_constraints;
public static void main(String[] args) throws IOException {
JFrame frame = new JFrame("file_selector");
file_selector fs = new file_selector();
frame.setContentPane(fs.panel1);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setVisible(true);
myFile = fs.getFile();
while(myFile != null) {
sudoku my_puzzle = new sudoku();
my_puzzle.solve_puzzle();
}
}
I've done a ton of searching and can't seem to find what's wrong with my file_selector class such that it isn't setting the user selected value for the file.
You call getFile immediately after showing the frame and before the user has opportunity to click anything. Since the condition for while is false, the loop ends immediately and the method doesn't do anything afterwards, in particular it never calls getFile again.
Two options:
Make the button solve the puzzle, not just set file (easier, just change actionPerformed method).
Make file_selector emit an event when a file is selected and add a listener to it (this can be a challenge for you).

Cucumber not running selenium Code

When I try to run my code, it only shows cucumber skeleton. I use a JUnit runner class as JUnit test suite.
Code is below for all three classes.
Feature is :
Feature: Check addition in Google calculator
In order to verify that google calculator work correctly
As a user of google
I should be able to get correct addition result
#Runme
Scenario: Addition
Given I open google
When I enter "2+2" in search textbox
Then I should get result as "4"
Selenium Class :
package cucumberTest;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
public class SeleniumTest {
private SeleniumTest()
{
}
private static WebDriver driver = null;
public static void seleniumTest() {
// Create a new instance of the Firefox driver
driver = new FirefoxDriver();
//Put a Implicit wait, this means that any search for elements on the page could take the time the implicit wait is set for before throwing exception
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
//Launch the Online Store Website
driver.get("http://www.store.demoqa.com");
// Find the element that's ID attribute is 'account'(My Account)
driver.findElement(By.xpath(".//*[#id='account']/a")).click();
// Find the element that's ID attribute is 'log' (Username)
// Enter Username on the element found by above desc.
driver.findElement(By.id("log")).sendKeys("testuser_1");
// Find the element that's ID attribute is 'pwd' (Password)
// Enter Password on the element found by the above desc.
driver.findElement(By.id("pwd")).sendKeys("Test#123");
// Now submit the form. WebDriver will find the form for us from the element
driver.findElement(By.id("login")).click();
// Print a Log In message to the screen
System.out.println("Login Successfully");
// Find the element that's ID attribute is 'account_logout' (Log Out)
driver.findElement (By.xpath(".//*[#id='account_logout']/a")).click();
// Print a Log In message to the screen
System.out.println("LogOut Successfully");
// Close the driver
driver.quit();
}
}
JUnit Class:
package cucumberTest;
import org.junit.runner.RunWith;
import cucumber.api.CucumberOptions;
import cucumber.api.junit.Cucumber;
#RunWith(Cucumber.class)
//#CucumberOptions(
// features = "Feature/googleCalc.feature"
////,glue={"stepDefinition"}
// )
#CucumberOptions(
features = {"Feature/googleCalc.feature"},glue={"stepDefinition"},
plugin = {"pretty"},
tags = {"#Runme"}
)
public class TestRunner {
}
Step Definitions :
package stepDefination;
import java.util.concurrent.TimeUnit;
import org.junit.Assert;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.By;
import cucumber.api.java.After;
import cucumber.api.java.Before;
import cucumber.api.java.en.Given;
import cucumber.api.java.en.Then;
import cucumber.api.java.en.When;
import cucumberTest.SeleniumTest;
public class googleCalcStepDefinition {
#Given("^I open google$")
public void i_open_google() throws Throwable {
// Write code here that turns the phrase above into concrete actions
SeleniumTest.seleniumTest();
}
#When("^I enter \"(.*?)\" in search textbox$")
public void i_enter_in_search_textbox(String arg1) throws Throwable {
// Write code here that turns the phrase above into concrete actions
SeleniumTest.seleniumTest();
}
#Then("^I should get result as \"(.*?)\"$")
public void i_should_get_result_as(String arg1) throws Throwable {
// Write code here that turns the phrase above into concrete actions
SeleniumTest.seleniumTest();
}
}
Output shown is :
Feature: Check addition in Google calculator
In order to verify that google calculator work correctly
As a user of google
I should be able to get correct addition result
#Runme
Scenario: Addition [90m# Feature/googleCalc.feature:7[0m
[33mGiven [0m[33mI open google[0m
[33mWhen [0m[33mI enter "2+2" in search textbox[0m
[33mThen [0m[33mI should get result as "4"[0m
1 Scenarios ([33m1 undefined[0m)
3 Steps ([33m3 undefined[0m)
0m0.000s
You can implement missing steps with the snippets below:
#Given("^I open google$")
public void i_open_google() throws Throwable {
// Write code here that turns the phrase above into concrete actions
throw new PendingException();
}
#When("^I enter \"(.*?)\" in search textbox$")
public void i_enter_in_search_textbox(String arg1) throws Throwable {
// Write code here that turns the phrase above into concrete actions
throw new PendingException();
}
#Then("^I should get result as \"(.*?)\"$")
public void i_should_get_result_as(String arg1) throws Throwable {
// Write code here that turns the phrase above into concrete actions
throw new PendingException();
}
I found the reason it was not executing because i added Selenium test class and Junit runner class in Package cucumberTest; and skeleton was in package stepDefination; so what i did was i moved skeleton to pacakge cucumberTest; where junit runner and selenium classes are it resolved the issue for . Issue was occuring because when you place Junit class in package it will search for skeleton in that package but if you add JUnit runner class in source folder then it will be able to find the page under src folder