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

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();
}
}
}

Related

Test temporary file existence in JUNIT , mockito

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.

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 load the correct language (set in config) instead of the language last in an array

I'm creating a little java app and I'm trying to load the yml files based on config.yml lang set (en/it) but I can't find a way to load them, only the last one in an array is loaded which is "it" for me.
I know that my method is probably the worst solution for a language file, I'm open to every method that will help me with the problem. But I prefer an external lang_en/it file instead of internal ones (Or is it better internal?)
After I set the language, the app will self-update every text in every class.
static final Properties props = new Properties();
static WelcomeMessage main = new WelcomeMessage();
static File file = null;
static File folder = null;
static boolean os = main.os.startsWith("Windows");
public static void create() {
String[] lang = {"en", "it"};
for (String s : lang) {
file = new File(WelcomeMessage.user + "/AppData/Roaming/MyApp/lang_" + s + ".yml");
folder = new File(file.getParent());
SetLanguages(s);
}
if (!file.exists()) {
try {
if (os) {
folder.mkdir();
file.createNewFile();
} else {
file = new File(main.user + "/Library/Application Support/MyApp/config.yml");
folder.mkdir();
file.createNewFile();
}
} catch (Exception e) {
System.out.println(e + " " + file);
}
}
}
public static void SetLanguages(String lang) {
if (lang.equals("en")) {
store("Settings.Save", "Save");
store("Settings.ConfigPath", "Config Path");
store("Settings.Language", "Language");
store("Settings.Title", "Settings");
} else if (lang.equals("it")) {
store("Settings.Save", "Salva");
store("Settings.ConfigPath", "Percorso config");
store("Settings.Language", "Lingua");
store("Settings.Title", "Impostazioni");
}
}
public static String get(String value) {
String key = null;
try {
FileInputStream in = new FileInputStream(file);
props.load(in);
key = props.getProperty(value);
in.close();
} catch (Exception fnf) {
System.out.println(fnf);
}
return key;
}
public static void store(String value, String key) {
try {
FileOutputStream out = new FileOutputStream(file);
props.setProperty(value, key);
props.store(out, null);
out.close();
} catch (Exception fnf) {
System.out.println(fnf);
}
}
This is how I get a text from yml:
path.setText(Language.get("Settings.ConfigPath"));
language.setText(Language.get("Settings.Language"));
f.setTitle(Language.get("Settings.Title"));
save.setText(Language.get("Settings.Save"));
And this my Language.get(key)
public static String get(String value) {
String key = null;
try {
FileInputStream in = new FileInputStream(file);
props.load(in);
key = props.getProperty(value);
in.close();
} catch (Exception fnf) {
System.out.println(fnf);
}
return key;
}
I suggest the following changes:
Create a Settings class to hold the properties save, configPath, language and title. Even better if this class uses an immutable builder pattern, because once set, the properties will never change.
Create a SettingsFactory class with method getSettings(language). This class shall also have a field Map<String, Settings>. In the constructor (or a static block), first check if a file exists on the disk, and if yes, load it into the map. If not, populate the map, one entry for each language, and persist to the disk.
getSettings would simply return the value from the map corresponding to the given language.
The format of the file written to the disk is a different matter. You say YAML, but I'm not seeing any YAML specific code in your snippet. If you don't know how to write a map to YAML, open a different question.

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();
}
}

JDK 7: Existing file gets empty on new File("path/to/file.html");

I'm using JDK 7. I've got a class with a method that creates a html-file using PrintStream. Another method in the same class is supposed to use the created file and do stuff with it. The problem is that once i use new File("path/to/file.html), the file lenght is reduced to 0. My code:
public class CreatePDFServiceImpl {
private final PrintStream printStream;
public CreatePDFServiceImpl() throws IOException {
printStream = new PrintStream("/mnt/test.html", "UTF-8");
}
public void createHtmlFile() throws IncorporationException {
try {
StringBuilder html = new StringBuilder();
HtmlFragments htmlFragments = new HtmlFragments();
html.append(htmlFragments.getHtmlTop())
.append(htmlFragments.getHeading())
.append(htmlFragments.buildBody())
.append(htmlFragments.buildFooter());
printStream.print(html.toString());
} finally {
if(printStream != null) {
printStream.close();
}
}
}
This next method is supposed to use the html file created in "createHtmlFile()":
public void convertHtmlToPdf() {
PrintStream out = null;
try {
File file = new File("/mnt/test.html");
/** this code added just for debug **/
if (file.createNewFile()){
System.out.println("File is created!");
} else {
System.out.println("File already exists. size: " + file.length());
}
/* PDF generation commented out. */
//out = new PrintStream("/mnt/testfs.pdf", "UTF-8");
//defaultFileWriter.writeFile(file, out, iTextRenderer);
} catch (IOException e) {
throw new IncorporationException("Could not save pdf file", e);
} finally {
if(out != null) {
out.close();
}
}
My junit integration test class:
#Category(IntegrationTest.class)
public class CreatePDFServiceIntegrationTest {
private static CreatePDFServiceImpl createPDFService;
#BeforeClass
public static void init() throws IOException {
createPDFService = new CreatePDFServiceImpl();
}
#Test
public void testCreateHtmlFile() throws IncorporationException {
createPDFService.createHtmlFile();
File createdFile = new File("/mnt/test.html");
System.out.println("createdFile.length() = " + createdFile.length());
Assert.assertTrue(createdFile.length() > 1);
}
#Test
public void testCreatePDF() throws Exception {
File fileThatShouldExist = new File("/mnt/testfs.pdf");
createPDFService.convertHtml2Pdf();
Assert.assertTrue(fileThatShouldExist.exists());
}
}
The first test passes, output:
"createdFile.length() = 3440".
I checked the file system, there is the file. size 3,44kb.
Second test fails, output from CreatePDFServiceImpl:
"File already exists. size: 0"
Looking in the file system, the file now is actually 0 bytes.
I'm stumped. The new File("path") should only create a reference to that file and not empty it?
I doubt there's an error in File.createNewFile(). I don't yet fully grasp in which order you run your code, but are you aware that this sets the file size to zero?
out = new PrintStream("/mnt/testfs.pdf", "UTF-8");
From the PrintStream(File file) Javadoc:
file - The file to use as the destination of this print stream. If the
file exists, then it will be truncated to zero size; otherwise, a new
file will be created. The output will be written to the file and is
buffered.
I think that's the culprit - but in your code that line is commented out. Am I right you have run your tests with that line commented in?

Categories

Resources