Test temporary file existence in JUNIT , mockito - java

I have a function, which generates a CSV file using CSV printer, emails and then deletes the file by calling another private function. The private function which sends the email is :
private void sendEmail(File fileToSend) {
List<String> emailTo = xyz#gmail.com
String emailFrom = abc#gmail.com
String host = host //cannot write the proper host name
try
{
mailUtil.sendMailWithAttachment(emailFrom, emailTo, host)
logger.debug("Email successfully sent");
} catch (Exception e) {
logger.error("Exception when sending mail ", e);
}
finally {
deleteFile(fileToSend);
}
}
private File saveInCsv(List<List <String> > valuesToStore) {
String fileName = "hello.csv";
File deletedIncidentCsv = new File(fileName);
try (BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(deletedIncidentCsv));
CSVPrinter csvPrinter = new CSVPrinter(bufferedWriter, CSVFormat.EXCEL.withHeader(headers).withQuoteMode(QuoteMode.ALL));
)
{
for (List<String> strings : valuesToStore) {
csvPrinter.printRecord(strings);
}
csvPrinter.flush();
}
catch (Exception e)
{
logger.error("Error in writing to CSV file ", e);
}
return deletedIncidentCsv;
}
both these private functions are being called by public function , which I am testing:
public generateEmailFile(){
//does some work to retrieve dataToWriteInCSV
File csvFileGenerated = saveInCsv(dataToWriteInCsv);
sendEmail(csvFileGenerated);
}
In my unit test I want to check the contents of the file before its deleted. Is there anyway of doing it.

Related

Output file location of BufferedWriter() in java project with 2 modules

I have a JavaFX project with 2 modules..
[Project structure][1]
public class SkiResortModel {
private static final String FILE_NAME_RESORTS = "/SKI_RESORTS.csv";
//Code for reading file is:
private BufferedReader getReader() {
InputStream inputStreamResorts = getClass().getResourceAsStream(SkiResortModel.FILE_NAME_RESORTS);
assert inputStreamResorts != null;
InputStreamReader readerResorts = new InputStreamReader(inputStreamResorts, StandardCharsets.UTF_8);
return new BufferedReader(readerResorts);
}
private List<SkiResortModel> readFromFile() {
try (BufferedReader reader = getReader()) {
return reader.lines()
.skip(1)
.map(line -> new SkiResortModel(line.split(DELIMITER, 0)))
.collect(Collectors.toList());
} catch (IOException e) {
throw new IllegalStateException("failed");
}
}
//Code for writing file is:
private BufferedWriter getWriter(String filename) {
try {
String file = Objects.requireNonNull(getClass().getResource(filename)).getFile();
return new BufferedWriter(new FileWriter(file, StandardCharsets.UTF_8));
} catch (IOException e) {
throw new IllegalStateException("wrong file " + filename);
}
}
public void save() {
try (BufferedWriter writer = getWriter(FILE_NAME_RESORTS)) {
writer.write(
"ENTITY_ID;NAME;REGION;COMMUNES_IN_RESORT;MASL_MIN;MASL_MAX;SKI_RUNS_KM;DRAG_LIFTS;CHAIR_LIFTS;CABLE_CARS;OPEN_LIFTS;SNOW_DEPTH_CM;VISITORS_TODAY;CAR_FREE;FUNPARK_AVAILABLE;IMAGE_URL");
writer.newLine();
int id = 100;
for (SkiResortModel s : allSkiResorts) {
writer.write(s.infoAsLine(";", id));
writer.newLine();
id++;
}
} catch (IOException e) {
throw new IllegalStateException(e);
}
}
We have created a small application which displays the data in a table and allows for some modification. The data should then be written back into the original csv file.
The data is stored in the resources folder (screenshot). When the save function is called the data should then be written back into the original csv-file. However Intellij creates a new csv file under skiresorts-model/target.
I tried to indicate the path by copying the path from the context menue (Right click on file => Copy path / reference. I tried all the options to copy the path but then the program is unable to find the file. Strange is also that after I used copy path/reference
the program is unable to run even with the original path. The only thing that helps then is to check out another branch and return to the branch. Is this a bug in Intellij?
The save function is called from another class after the modifications have been done.
Any help is greatly appreciated.
[1]: https://i.stack.imgur.com/NwtB2.png

How to let user download -in backend generated- CSV file from frontend?

I am currently working on a web application. I created a button called "export", in the front end. A user click should trigger the download of a CSV file, which I generated in the back end. The CSV file is filled with values from a database table.
Do I need to generate a link to pass it to the front end button (maybe with JSON?)?
How should I proceed?
Additional information: The application is programmed with Java. The framework I use is Spring-Boot.
Code for generating CSV file
public class readDb {
public static List<Success> getDataFromDb (List<Success> success){
System.out.println("getDataFromDb");
erfolg.forEach(System.out::println);
return erfolg;
}
public static void successExport (List<Success> success) throws IOException {
String csvFile = "\\\\fs-vcs-02\\userhome\\username\\Desktop\\test.csv";
FileWriter writer = new FileWriter(csvFile);
CSVUtils.writeLine(writer, Arrays.asList("id", "endDate", "dataFromB", "dataToB", "dataToE", "report", "amountOfM", "rate", "amountOfA", "statistics", "resultP", "resultN", "resultO", "chancel", "assignmentVolume));
for (Erfolg d : erfolg) {
List<String> list = new ArrayList<>();
list.add(d.getId().toString());
list.add(d.getEndDate().toString());
list.add(d.getDataFromB().toString());
list.add(d.getDataToB().toString());
list.add(d.getDataToE().toString());
list.add(d.getReport().toString());
list.add(d.getAmountOfM().toString());
list.add(d.getRate().toString());
list.add(d.getAmountOfA().toString());
list.add(d.getStatistics().toString());
list.add(d.getResultP().toString());
list.add(d.getResultN().toString());
list.add(d.getResultO().toString());
list.add(d.getChancel().toString());
list.add(d.getAssignmentVolume().toString());
CSVUtils.writeLine(writer, list);
}
writer.flush();
writer.close();
}
}
Code for file export
public static void export() {
File f = null;
boolean bool = false;
try {
f = new File("\\\\fs-vcs-02\\userhome\\agoenkur\\Desktop\\test.csv");
bool = f.createNewFile();
System.out.println("File created: "+bool);
f.delete();
System.out.println("delete() method is invoked");
bool = f.createNewFile();
System.out.println("File created: "+bool);
} catch(Exception e) {
e.printStackTrace();
}
}
}

Java File.renamTo not working

I have made the code which renames all the jpg files in a directory from 1 to n (number of files)..
if there were let say 50 jpg files that after running the program all the files are renamed to 1.jpg ,2.jpg and so on till 50.jpg
But i am facing the problem if I manually rename the file let say 50.jpg to aaa.jpg then again running the program doesn't rename that file
I have wasted one day to resove that issue
Kindly help me
Code:
public class Renaming {
private static String path; // string for storing the path
public static void main(String[] args) {
FileReader fileReader = null; // filereader for opening the file
BufferedReader bufferedReader = null; // buffered reader for buffering the data of file
try{
fileReader = new FileReader("input.txt"); // making the filereader object and paasing the file name
bufferedReader = new BufferedReader(fileReader); //making the buffered Reader object
path=bufferedReader.readLine();
fileReader.close();
bufferedReader.close();
}
catch (FileNotFoundException e) { // Exception when file is not found
e.printStackTrace();
}
catch (IOException e) { // IOException
e.printStackTrace();
}
finally {
File directory=new File(path);
File[] files= directory.listFiles(); // Storing the all the files in Array
int file_counter=1;
for(int file_no=0;file_no<files.length;file_no++){
String Extension=getFileExtension(files[file_no]); //getting the filw extension
if (files[file_no].isFile() && (Extension .equals("jpg")|| Extension.equals("JPG"))){ // checking that if file is of jpg type then apply renaming // checking thaat if it is file
File new_file = new File(path+"\\"+files[file_no].getName()); //making the new file
new_file.renameTo(new File(path+"\\"+String.valueOf(file_no+1)+".jpg")); //Renaming the file
System.out.println(new_file.toString());
file_counter++; // incrementing the file counter
}
}
}
}
private static String getFileExtension(File file) { //utility function for getting the file extension
String name = file.getName();
try {
return name.substring(name.lastIndexOf(".") + 1); // gettingf the extension name after .
} catch (Exception e) {
return "";
}
}`
first of all, you should use the path separator / . It's work on Windows, Linux and Mac OS.
This is my version of your problem to rename all files into a folder provide. Hope this will help you. I use last JDK version to speed up and reduce the code.
public class App {
private String path = null;
public static int index = 1;
public App(String path){
if (Files.isDirectory(Paths.get( path ))) {
this.path = path;
}
}
public void rename() throws IOException{
if ( this.path != null){
Files.list(Paths.get( this.path ))
.forEach( f ->
{
String fileName = f.getFileName().toString();
String extension = fileName.replaceAll("^.*\\.([^.]+)$", "$1");
try {
Files.move( f ,Paths.get( this.path + "/" + App.index + "." + extension));
App.index++;
} catch (IOException e) {
e.printStackTrace();
}
}
);
}
}
public static void main(String[] args) throws IOException {
App app = new App("c:/Temp/");
app.rename();
}
}

How to add data to the end of a CSV file (Java)

I am developing an Android application that produces results and I am saving this results in a CSV file. After that I want to close the app, open it again, get other results and write them at the end of the same existing CSV file. Right now every time it ovverrides the previous results.
This is my class to save the results in a CSV file:
public class SaveCSV {
private File file;
private RandomAccessFile randomAccessFile;
public SaveCSV(){
this.file = getPath("RisultatiTest.csv");
try {
this.randomAccessFile = new RandomAccessFile(file, "rwd");
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
public void salvaRisultati (int[] array) {
try {
file.createNewFile();
String s = "";
for (int i = 0; i < array.length; i++) {
s = s + array[i] + ",";
}
randomAccessFile.writeBytes(s);
randomAccessFile.writeBytes("\n");
} catch (IOException e) {
throw new RuntimeException("Unable to create File " + e);
}
}
public static File getPath(String fileName){
return new File(Environment.getExternalStorageDirectory(), fileName);
}
}

Can't copy internal file to user's computer

I have a program that requires that an internal file (DICTIONARY) be copied to the user's computer into the folder defined like so:
private static final String DIC_NAME = "WordHelp.dic";
private static final String DIC_FOLDER = System.getProperty("user.home");
private static final String PATH_SEP = System.getProperty("file.separator");
public static final String DICTIONARY = DIC_FOLDER + PATH_SEP + DIC_NAME;
Here's what works on MY computer, where all the Java stuff is:
public static void createDictionaryIfNecessary() throws IOException{
Path out_path = FileSystems.getDefault().getPath(DICTIONARY);
boolean dic_exists = Files.exists(out_path,
new LinkOption[]{LinkOption.NOFOLLOW_LINKS});
if(dic_exists)
return;
File file = new File("src/dictionary"); // here's problem for user ************
Path in_path = file.toPath();
try {
Files.copy(in_path, out_path,
REPLACE_EXISTING, COPY_ATTRIBUTES, NOFOLLOW_LINKS);
} catch (IOException e) { JOptionPane.showMessageDialog(null, e); }
}
But user gets this error:
java.nio.file.NoSuchFileException: src\dictionary
SOURCE file (internal to .jar file) can't be found.
If I look at in_path while debugging, the value is:
(sun.nio.fs.Windowspath) src/dictionary
And below is a bunch of info about in_path:
This all works on MY computer and I could have sworn that it ONCE worked on a user's computer...
How should I define file (see line with ********** to enable copying internal file (src/dictionary) onto a user's computer?
Here's Netbeans project view:
I worked around it by using a Scanner to read individual strings from the internal file instead of using Files.copy. Here's the code. (It's not quite as fast using Scanner, but it works.)
public static void write(FileOutputStream outfile, String s) {
try {
for(int i = 0; i < s.length(); i++)
outfile.write(s.charAt(i));
outfile.write(13); outfile.write(10);
} catch (IOException ex) {JOptionPane.showMessageDialog(null, ex);}
}
public static Scanner openDic(){
InputStream myStream = null;
try { myStream = Class.forName("masterwords.Masterwords").getClassLoader()
.getResourceAsStream("dictionary");
}catch (ClassNotFoundException ex) {/* ... */}
return new Scanner(myStream).useDelimiter("\r");
}
public static void createDictionaryIfNecessary(){
Path out_path = FileSystems.getDefault().getPath(DICTIONARY);
if(Files.exists(out_path, new LinkOption[]{LinkOption.NOFOLLOW_LINKS})) return;
FileOutputStream outStream = null;
try {outStream = new FileOutputStream(out_path.toFile());}
catch (FileNotFoundException ex) {JOptionPane.showMessageDialog(null,ex);}
Scanner scInternalDic = IO.openDic();
while(scInternalDic.hasNext()){
Utilities.write(outStream,scInternalDic.next());
}
try {outStream.close();}
catch (IOException ex) {JOptionPane.showMessageDialog(null,ex);}
scInternalDic.close();
}

Categories

Resources