I'm trying to wait for a file to get downloaded using fluent wait. But since the file downloads with different date format. I want to validate with "Partial filename" of the file using fluentWait. For Eg: cancelled_07092019, cancelled_09_07_2019. So here the filename 'canceled_' remains constant
Below code works fine for the actual filename.
Downloaded_report= new File("DownloadPath");
FluentWait<WebDriver> wait = new FluentWait<WebDriver>(driver);
wait.pollingEvery(1, TimeUnit.SECONDS);
wait.withTimeout(15, TimeUnit.SECONDS);
wait.until(x -> downloaded_report.exists());
Here, I want to check the startof the file name. How do I do this?
Thanks in Advance
I am not sure if I understood the question correctly but you can check if the file with the partial name exists in the given directory.
File dir = new File("DownloadPath");
String partialName = downloaded_report.split("_")[0].concat("_"); //get cancelled and add underscore
FluentWait<WebDriver> wait = new FluentWait<WebDriver>(driver);
wait.pollingEvery(1, TimeUnit.SECONDS);
wait.withTimeout(15, TimeUnit.SECONDS);
wait.until(x -> {
File[] filesInDir = dir.listFiles();
for (File fileInDir : filesInDir) {
if (fileInDir.getName().startsWith(partialName)) {
return true;
}
}
return false;
});
In the above code, we list all files in the download path directory. Then, iterate over each file, get its name and check if it contains the partial name that we want.
It might be a problem if you have multiple reports in the directory. Then I would advise clearing DownloadPath from files that start with cancelled_ in some kind of #Before hook.
Related
I'm using multiple JVMs, but I need that each JVM to use a specific folder. What I'm trying to do is iterate through folders till it finds a file that is not locked and then lock it to use that specific folder.
Here I'm filtering the folders I want to use:
// Filter 'fran' folders
String dir = System.getProperty("user.dir");
FilenameFilter filter = new FilenameFilter() {
public boolean accept(File dir, String name) {
String lowercaseName = name.toLowerCase();
if (lowercaseName.startsWith("fran")) {
return true;
} else {
return false;
}
}
};
File[] dirs = new File(dir).listFiles(filter);
Then I'm trying to go through the folders and check if it is locked or not with f.canWrite(). However it always appears to use only one folder and ignore the others.
// Find available folder
boolean lock = true;
String lock_folder = "";
FileChannel fileChannel = null;
FileLock lockfile = null;
File f = null;
while (lock) {
for (File folder : dirs) {
f = new File(folder + "\\lock.txt");
Boolean isnotlocked = f.canWrite();
if (isnotlocked) {
fileChannel = new RandomAccessFile(f, "rw").getChannel();
lockfile = fileChannel.lock();
lock = false;
lock_folder = folder.getAbsolutePath();
break;
}
}
}
I+ve previously tried to accomplish what I needed without FileLock, creating a file in the specific folder and then deleting after completed. If the folder did not have that file it would create and lock that JVM. However I think the JVMs were getting mixed cause the results were bad.
Hope u can understand what my problem is, would really appreciate some help.
Here are some ideas:
Assuming a process class - CustomProcess.java. This runs in a separate thread. The class has a constructor which takes a file folder as an argument. Lets assume the filePath1 is the folder's path and is accepted from a FileChooser.
(a) How the application works:
Put the selected folder filePath1 in a collection like List<File> or List<Path> - lets call it processFilesList; this is shared (perhaps a static member) by all the processes (this needs to be a concurrent collection from java.util.concurrent package). This list tracks the folders which are already being processed. Before the process starts check if the filePath1 is already in the processFilesList.
(b) Create and start the process:
CustomProcess p1 = new CustomProcess(filePath1);
p1.startProcess(); // here the application does whatever with the files in the folder.
Option 2:
Put all the folder file paths that need to be processed in a Queue collection. Process each folder (and its files as needed) one at a time or by multiple processes. The queue can be a first-in-first-out (FIFO) or a last-in-first-out (LIFO). One can consider these concurrent queue implementations based on the requirement: ConcurrentLinkedQueue, LinkedBlockingQueue, ConcurrentLinkedDeque or LinkedBlockingDeque.
How can I set a last modified date of a file using jimfs?
I have smth. like this:
final FileSystem fileSystem = Jimfs.newFileSystem(Configuration.unix());
Path rootPath = Files.createDirectories(fileSystem.getPath("root/path/to/directory"));
Path filePath = rootPath.resolve("test1.pdf");
Path anotherFilePath = rootPath.resolve("test2.pdf");
After creating the stuff I then create a directory iterator like:
try (final DirectoryStream<Path> dirStream = Files.newDirectoryStream(rootPath, "*.pdf")) {
final Iterator<Path> pathIterator = dirStream.iterator();
}
After that I iterate over the files and read the last modified file, which I then return:
Path resolveLastModified(Iterator<Path> dirStreamIterator){
long lastModified = Long.MIN_VALUE;
File lastModifiedFile = null;
while (dirStreamIterator.hasNext()) {
File file = new File(dirStreamIterator.next().toString());
final long actualLastModified = file.lastModified();
if (actualLastModified > lastModified) {
lastModifiedFile = file;
lastModified = actualLastModified;
}
}
return lastModifiedFile.toPath();
}
The problem is that both files "test1.pdf" and "test2.pdf" have lastModified being "0" so I actually can't really test the behavior as the method would always return the first file in the directory. I tried doing:
File file = new File(filePath.toString());
file.setLastModified(1);
but the method returns false.
UDPATE
I just saw that File#getLastModified() uses the default file system. This means that the default local file system will be used to read the time stamp. And this means I am not able to create a temp file using Jimfs, read the last modified and then assert the paths of those files. The one will have jimfs:// as uri scheme and the another will have OS dependent scheme.
Jimfs uses the Java 7 file API. It doesn't really mix with the old File API, as File objects are always tied to the default file system. So don't use File.
If you have a Path, you should use the java.nio.file.Files class for most operations on it. In this case, you just need to use
Files.setLastModifiedTime(path, FileTime.fromMillis(millis));
i am newbie in this but here is my point of view if you choose 1 specific FOLDER and you want to extract the last file from it.
public static void main(String args[]) {
//choose a FOLDER
File folderX = new File("/home/andy/Downloads");
//extract all de files from that FOLDER
File[] all_files_from_folderX = folderX.listFiles();
System.out.println("all_files_from_folderXDirectories = " +
Arrays.toString(all_files_from_folderX));
//we gonna need a new file
File a_simple_new_file = new File("");
// set to 0L (1JAN1970)
a_simple_new_file.setLastModified(0L);
//check 1 by 1 if is bigger or no
for (File temp : all_files_from_folderX) {
if (temp.lastModified() > a_simple_new_file.lastModified()) {
a_simple_new_file = temp;
}
//at the end the newest will be printed
System.out.println("a_simple_new_file = "+a_simple_new_file.getPath());
}
}}
I would like to locate a file named SAVE.properties. I have looked at different questions that seem like they would answer me, but I can't see that they do.
For example, I would like to check to see whether or not SAVE.properties exists within a directory (and its subfolders).
I would also like to know how I could save a .properties file (and then read it afterwards from this location) to the directory where my program is being run from. If it is run from the desktop, it should save the .properties file there.
Saving properties can easily be achieved through the use of Properties#store(OutputStream, String), this allows you to define where the contents is saved to through the use of an OutputStream.
So you could use...
Properties properties = ...;
//...
try (FileOutputStream os = new FileOutputStream(new File("SAVE.properties"))) {
properties.store(os, "Save");
} catch (IOException exp) {
exp.printStackTrace();
}
You can also use Properties#load(InputStream) to read the contents of a "properties" file.
Take a closer look at Basic I/O for more details.
Locating a File is as simple as using
File file = new File("SAVE.properties");
if (file.exists) {...
This checks the current working directory for the existence of the specified file.
Searching the sub directories is little more involved and will require you to use some recursion, for example...
public File find(File path) {
File save = new File(path, "SAVE.properties");
if (!save.exists()) {
save = null;
File[] dirs = path.listFiles(new FileFilter() {
#Override
public boolean accept(File pathname) {
return pathname.isDirectory();
}
});
for (File dir : dirs) {
save = find(dir);
if (save != null) {
break;
}
}
}
return save;
}
Using find(new File(".")) will start searching from the current working directory. Just beware, under the right circumstances, this could search your entire hard disk.
I want to perform deletion on generated reports (PDF files) at scheduled duration.
I am done with Scheduler part. The only thing is to make a method which got logic to delete the bunch of reports generated in between those hours.
Is there any JasperReports API available which I can use to delete those generated reports from the specified location?
How about to use ResourceLookup, find resources and delete resources. I don't have much idea about to use it.
A small example/link to resources would help
You know the directory where to delete the reports.
So, in simple Java, using the lastModified date:
File dir = new File("directoryName");
Date deleteStartDate;
Date deleteEndDate;
File[] children = dir.listFiles();
if (children == null) {
// Either dir does not exist or is not a directory
} else {
for (int i=0; i<children.length; i++) {
// Get filename of file or directory
File file = children[i];
Date lastModified = new Date(file.lastModified());
if (lastModified.after(deleteStartDate) && lastModified.before(deleteEndDate))
{
file.delete();
}
}
}
I am having a tough time deleting a file. I will show you what is working, and you can be the judge if this is acceptable.
class StupidService{
def doThings(){
def tmpDirString = "dumpit"
def currentDir = new File("../${tempDirString}")
currentDir.eachFile(FileType.FILES){
def f=it
def answer = SuperComplicatedService.doStuff(f)
//this works, now I need to move the file to the "done" folder
File dir = new File("../${tempDirString}/done");
def endupFile = new File("../${tempDirString}/done/${f.name}")
FileUtils.copyFile(f, endupFile)
//this works; the file is copied to where I want it successfully; now I just need to delete the initial file.
def thisIsAJoke=0
while(f.delete()==false){
println "This is not a joke: ${thisIsAJoke}"
thisIsAJoke++
}
}
}
}
And so this prints out between 40k and 150k lines of "This is not a joke: 64457" etc. and then finally deletes the file.
What is going on?
What does SuperComplicatedService.doStuff(f) do? If it opens the file, make sure it closes it before returning. Otherwise, you won't be able to delete the file until the garbage collector collects the object that references it.
See I can't delete a file in java
Code for delete a file and folder of the file in Groovy/Grails
String filePath = "c:/dir"+"/"+"carpeta"+"/"+documentoInstance.nombreArchivo
String folderPath = "c:/dir"+"/"+"carpeta"+"/"
boolean fileSuccessfullyDeleted = new File(filePath).delete()
boolean folderSuccessDeleted = new File(folderPath).deleteDir()
if(fileSuccessfullyDeleted && folderSuccessDeleted){
documentoInstance.delete flush:true
}
else{
flash.error = "Archivo no borrado."
return
}