How to generate testng report without overwritng the previous test result - maven

I am automating Web Application using Selenium with Java.
I am executing multiple testng xml files in parallel, so the result gets overridden every time.
Eg: I have two xml files (testng1.xml and testng 2.xml). When I run these two files in parallel, result from testng2.xml is override with testng1.xml in the emailable report.
How to generate a separate report for each xml file?

I have achieved this scenario by using the below code.
public String xmlString;
public int xmlIndex;
public String folderName;
public String locationName;
public static String reportName = "emailable-report.html";
xmlString = <list of xml files>;
xmlIndex = xmlString.lastIndexOf("/");
locationName = xmlString.substring(xmlIndex+1);
folderName = locationName.replace(".xml", "").toUpperCase();
File dir = new File("Result"); // Here I am creating a common folder and the sub folders will be created as per the xml file executions.
if(dir.exists())
{
try {
FileUtils.deleteDirectory(dir);
} catch (IOException e) {
e.printStackTrace();
}
dir.mkdir();
}
else
{
dir.mkdir();
}
String xmlFolderPath = System.getProperty("user.dir") +"/"+ dir + "/"+ folderName;
testng.setOutputDirectory(xmlFolderPath);
File resultFile = new File(System.getProperty("user.dir") +"/"+ dir + "/" +"ResultFiles"); // In this folder only testng result (.html)files are moved here.
resultFile.mkdir();
File folder = new File(xmlFolderPath); // In this folder, separate sub folders were created according to the xml files and the sub folder will be the xml file names.
File[] listOfFiles = folder.listFiles();
for (int i = 0; i < listOfFiles.length; i++)
{
if (listOfFiles[i].isFile())
{
if(reportName.equalsIgnoreCase("emailable-report.html"))
{
Path src = Paths.get(xmlFolderPath + "/" + reportName);
Path desc = Paths.get(resultFile + "/" + folderName + ".html"); // Here emailable-report.html is renamed according to the XML file name and moved to this folder
try
{
Files.move(src, desc, StandardCopyOption.REPLACE_EXISTING);
System.out.println(src.resolveSibling(folderName + ".html"));
break;
}
catch (IOException e)
{
System.out.println(e);
}
}
else
{
System.out.println("Expected file not present in the specified folder..!!!");
}
}
}

Related

I want to download files using SpringBoot

An attempt was made to implement file downloads through the SpringBoot MVC structure. There is no error, it says it has run normally, but the download does not proceed.
All information about the file is entered correctly, and also the path and name of the file are entered correctly.
I'd like to know why the download doesn't proceed even though there's no error.
#RestController
public class Controller {
#PostMapping("/fileDownload")
public void fileDownload(#RequestBody BoardFileDTO dto,HttpServletRequest request,HttpServletResponse response) throws UnsupportedEncodingException {
//File contains all stored paths, names, and extensions
Path fileNamePath = Paths.get(Directory + dto.getFile_save_name()).toAbsolutePath();
String filename = dto.getFile_save_name(); //The name of the saved file
String downname = dto.getFile_name(); //The name of the file to be saved
if (filename == null || "".equals(filename)) {
filename = downname;
}
try {
String browser = request.getHeader("User-Agent");
//File Encoding
if (browser.contains("MSIE") || browser.contains("Trident")
|| browser.contains("Chrome")) {
filename = URLEncoder.encode(filename, "UTF-8").replaceAll("\\+",
"%20");
} else {
filename = new String(filename.getBytes("UTF-8"), "ISO-8859-1");
}
} catch (UnsupportedEncodingException ex) {
System.out.println("UnsupportedEncodingException");
}
System.out.println(fileNamePath);
File file1 = new File(fileNamePath.toString());
if (!file1.exists()) {
return ;
}
// Specifying a File
response.setContentType("application/octer-stream");
response.setHeader("Content-Transfer-Encoding", "binary;");
response.setHeader("Content-Disposition", "attachment; filename=\"" + filename + "\"");
try {
OutputStream os = response.getOutputStream();
FileInputStream fis = new FileInputStream(fileNamePath.toString());
int ncount = 0;
byte[] bytes = new byte[512];
while ((ncount = fis.read(bytes)) != -1 ) {
os.write(bytes, 0, ncount);
}
fis.close();
os.close();
} catch (FileNotFoundException ex) {
System.out.println("FileNotFoundException");
} catch (IOException ex) {
System.out.println("IOException");
}
}
}
Your code is a bit convoluted imho. A couple of issues I see with your code
Using Path.toString to convert to a File, use the proper factory methods instead or use java.nio.Files to check the existence.
Your content-type is wrong application/octer-stream isn't a known content-type (you probably want application/octet-stream.
Copying from a Path or File is better done with either the StreamUtils from Spring or the java.nio.Files class (if you already have a Path use that).
#PostMapping("/fileDownload")
public void fileDownload(#RequestBody BoardFileDTO dto, HttpServletRequest request, HttpServletResponse response) throws UnsupportedEncodingException {
//File contains all stored paths, names, and extensions
Path fileNamePath = Paths.get(Directory, dto.getFile_save_name()).toAbsolutePath();
if (!Files.exists(fileNamePath)) {
return;
}
String filename = determineFilename(dto, request);
// Specifying a File
response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
response.setHeader("Content-Transfer-Encoding", "binary;");
response.setHeader("Content-Disposition", "attachment; filename=\"" + filename + "\"");
try {
Files.copy(fileNamePath, response.getOutputStream());
} catch (IOException ex) {
System.out.println("IOException");
}
}
private static String determineFilename(BoardFileDTO dto, HttpServletRequest request) {
String filename = dto.getFile_save_name(); //The name of the saved file
if (filename == null || "".equals(filename)) {
filename = dto.getFile_name();
}
String browser = request.getHeader("User-Agent");
//File Encoding
if (browser.contains("MSIE") || browser.contains("Trident") || browser.contains("Chrome")) {
filename = URLEncoder.encode(filename, StandardCharsets.UTF_8).replaceAll("\\+", "%20");
} else {
filename = new String(filename.getBytes(StandardCharsets.UTF_8), StandardCharsets.ISO_8859_1);
}
return filename;
}
It would write it something like that. As you have a path use the java.nio.Files to check for existence and copying. Use constants for mediatypes and charsets.
Your error handling is quite basic (I would say non-existing and at least not proper) as the processing just stops and returns an empty 200 to the client. No information what so ever.
I took the liberty to factor out the logic to determine the filename, which should make your code more readable.

Send multiple files from angular typescript to spring and return as zip folder for downloading?

I want to send multiple files in an array to spring and create a zip folder for downloading
UploadController:
#Autowired
StorageService storageService;
#PostMapping("/upload")
public ResponseEntity<ResponseMessage> uploadFiles(#RequestParam("files") MultipartFile[] files) {
String message = "";
try {
storageService.zip(files);
message = "Uploaded the files successfully";
return ResponseEntity.status(HttpStatus.OK).body(new ResponseMessage(message));
} catch (Exception e) {
message = "Fail to upload files!";
return ResponseEntity.status(HttpStatus.EXPECTATION_FAILED).body(new ResponseMessage(message));
}
}
StorageService
public void zip(MultipartFile[] files) {
List<Path> filepaths = new ArrayList();
for (MultipartFile file : files) {
Path filepath = Paths.get("my/tmp/dir", file.getOriginalFilename());
filepaths.add(filepath);
try (OutputStream os = Files.newOutputStream(filepath)) {
os.write(file.getBytes());
}
}
File zip = new File("path/to/my/zip");
try { zip.createNewFile(); }
FileOutputStream output = null;
try { output = new FileOutputStream(zip); }
ZipOutputStream out = new ZipOutputStream(output);
try {
for (Path filepath : filepaths) {
File f = new File(filepath);
FileInputStream input = new FileInputStream(f);
ZipEntry e = new ZipEntry(f.getName());
out.putNextEntry(e);
byte[] bytes = new byte[1024];
int length;
while((length = input.read(bytes)) >= 0) {
out.write(bytes, 0, length);
}
input.close();
}
out.close();
output.close();
}
}

Spring Boot | Upload an image to relative path in resources

I get "System can't find the path specified." when I try to upload an image to project folder inside resources.
Here is my project structure:
|Project
|src
|main
|resources
|META-INF.resources
|images
Project Structural Hierarchy can be seen here in the image format.
I have defined the path as
String path = "\\resources\\images\\" + imageName; File file = new File(path );
try {
InputStream is = event.getFile().getInputstream();
OutputStream out = new FileOutputStream(path );
byte buf[] = new byte[1024];
int len;
while ((len = is.read(buf)) > 0)
out.write(buf, 0, len);
is.close();
out.close();
} catch (Exception e) {
System.out.println(e);
}
What can be the exact path to images folder under META-INF.resources directory?
The following should work fine:
//App.java
String path = "\\META-INF.resources\\images\\" + imageName;
InputStream is = App.class.getClassLoader().getResourceAsStream(
path);
In a nut shell, use "getClassLoader().getResourceAsStream()" instead of FileInputStream or FileOutputStream.
Following worked for me.
In application.properties I defined my path string as:
image.path = src/main/resources/META-INF/resources/images/uploads/
Here is my uploadImage function in a class file.
#Autowired
private Environment environment;
public String uploadImg(FileUploadEvent event, String imagePrefix) {
String path = environment.getProperty("image.path");
SimpleDateFormat fmt = new SimpleDateFormat("yyyyMMddHHmmss");
String name = fmt.format(new Date())
+ event.getFile().getFileName().substring(
event.getFile().getFileName().lastIndexOf('.'));
name = String.format("%s%s" ,imagePrefix ,name );
String finalPath = String.format("%s%s" ,path ,name);
System.out.println("image is going to save # " +finalPath);
File file = new File(finalPath).getAbsoluteFile();
try {
InputStream is = event.getFile().getInputstream();
OutputStream out = new FileOutputStream(file);
byte buf[] = new byte[1024];
int len;
while ((len = is.read(buf)) > 0)
out.write(buf, 0, len);
is.close();
out.close();
} catch (Exception e) {
System.out.println(e);
}
return name;
}
I am not sure whether it will work at production or not. Basically I get absolute path of the project and then append my relatively extracted path. Correct me if I am wrong.

Export FileContentResult files to ZIP

I use C#-MVC3. I have an "export" page. I have some functions for exporting different tables from the DB, every function creates a CSV file from the table and returns a FileContentResult file to the user.
Now I want to create a button for "export all", to download all the files at once.
I tried to use ZipFile but it gets only file names and path - files that were saved on the server, not "FileContentResult" files.
So I wanted to save the "FileContentResult" files temporarily on the server, zip them and delete them - but I can't find how to save a "FileContentResult" file.
If you can help me or give me another idea, I'll glad to hear.
my solution:
public ZipFile DownloadAllToZip()
{
string path = "c:\\TempCSV";
try
{
if (Directory.Exists(path))
{
EmptyFolder(path);
}
else
{
DirectoryInfo di = Directory.CreateDirectory(path);
}
List<FileContentResult> filesToExport = GetAllCSVs();
foreach (var file in filesToExport)
{
try
{
using (FileStream stream = new FileStream(path + "\\" + file.FileDownloadName, FileMode.CreateNew))
{
using (StreamWriter writer = new StreamWriter(stream, Encoding.UTF8))
{
byte[] buffer = file.FileContents;
stream.Write(buffer, 0, buffer.Length);
writer.Close();
}
}
}
catch { }
}
}
catch{ }
Response.Clear();
Response.BufferOutput = false;
Response.ContentType = "application/zip";
Response.AddHeader("content-disposition", "attachment; filename=MaterialAssetTracker.zip");
ZipFile zip= new ZipFile();
using (zip)
{
zip.CompressionLevel = CompressionLevel.None;
zip.AddSelectedFiles("*.csv", path + "\\", "", false);
zip.Save(Response.OutputStream);
}
Response.Close();
EmptyFolder(path);
return zip;
}

MVC3 controlling FilePath in fileupload

I need help to make fileupload.cs reusable for uploading gallery images in content/gallery folder and downloadable files in content/files folder. I believe the solution will be in making the filepaths string somehow dynamic. The gallery and File have different controllers,models and views. Below is the fileupload.cs code
public static class FileUpload
{
public static char DirSeparator = System.IO.Path.DirectorySeparatorChar;
public static string FilesPath = "Content" + DirSeparator + "Files" + DirSeparator;
public static string UploadFile(HttpPostedFileBase file)
{
// Check if we have a file
if (null == file) return "";
// Make sure the file has content
if (!(file.ContentLength > 0)) return "";
string fileName = file.FileName;
string fileExt = Path.GetExtension(file.FileName);
// Make sure we were able to determine a proper
// extension
if (null == fileExt) return "";
// Check if the directory we are saving to exists
if (!Directory.Exists(AppDomain.CurrentDomain.BaseDirectory+FilesPath))
{
// If it doesn't exist, create the directory
Directory.CreateDirectory(AppDomain.CurrentDomain.BaseDirectory+FilesPath);
}
// Set our full path for saving
string path = FilesPath + DirSeparator + fileName;
// Save our file
//file.SaveAs(Path.GetFullPath(path));
file.SaveAs(Path.GetFullPath(AppDomain.CurrentDomain.BaseDirectory +path));
// Return the filename
return fileName;
}
public static void DeleteFile(string fileName)
{
// Don't do anything if there is no name
if (fileName.Length == 0) return;
// Set our full path for deleting
string path = FilesPath + DirSeparator + fileName;
// Check if our file exists
if (File.Exists(Path.GetFullPath(AppDomain.CurrentDomain.BaseDirectory+path)))
{
// Delete our file
File.Delete(Path.GetFullPath(AppDomain.CurrentDomain.BaseDirectory+path));
}
}
}
You can check if uploaded file has konwn image format extension (jpg, gif, png, etc) and if so then save to your content/gallery folder otherwise save to your content/files folder.
You are checking the file etension anyway
string fileExt = Path.GetExtension(file.FileName);
but you never use it.

Resources