Deleting reports generated by JR Server at scheduled duration - java

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

Related

Java - wait for a file to download with partial filename

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.

Android Studio :: Want to list files saved in default location

I'm new to Android Studio 3.0, emulating on a Nexus 4, Marshmallow. I'm trying to build simple "Save File" and "Load File" parts of my app. Here's the "Save File" part:
String filename = "myFile01"; // Then "myFile02", "myFile03", etc...
String userData = "Some useful data here...";
try {
// Adapted from: https://www.youtube.com/watch?v=_15mKw--RG0
FileOutputStream fileOutputStream = openFileOutput(filename, MODE_PRIVATE); // creates a file with given filename
fileOutputStream.write(userData.getBytes()); // puts userData into the file
fileOutputStream.close();
Toast.makeText(getApplicationContext(), "File saved!", Toast.LENGTH_LONG).show();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
The above code will be called again and again as the user creates and saves additional files. Later, the user may want to view all the saved files and load one. I'll have a ListView displaying all the files... but I need help reading the current directory to get that list.
I thought I read somewhere that in Android, there's one flat directory for your app to save and retrieve files. So I was hoping if I saved a bunch of files and then called a read() method, all my saved files would simply be in the default directory, no need to search. That seems to be a bad assumption; here's why:
Here's my code looking in the default directory and listing all the files found within there. First, I need the path of said default directory:
// Get current directory adapted from: https://stackoverflow.com/questions/5527764/get-application-directory
String packName, currDir;
PackageManager m = getPackageManager();
packName = getPackageName();
PackageInfo p = null;
try {
p = m.getPackageInfo(packName, 0);
} catch (PackageManager.NameNotFoundException e) {
e.printStackTrace();
}
currDir = p.applicationInfo.dataDir;
And then I open "currDir," and store the names of all the local files in an array:
// get list of files adapted from: https://stackoverflow.com/questions/9317483/showing-a-list-of-files-in-a-listview#9317583
File dir = new File(currDir);
File[] filelist = dir.listFiles();
String[] fileArr = new String[filelist.length];
for (int i = 0; i < fileArr.length; i++) {
fileArr[i] = filelist[i].getName();
}
The plan from here is to load the "fileArr" into a ListView and go from there. But when I step through the debugger, I see this as the contents of "fileArr":
"cache"
"code_cache"
"files"
This is true no matter how many files I've saved previously.
BTW, in the debugger, the assignments for packName and currDir look 100% correct:
packName = com.mydomain.myapp
currDir = /data/user/0/com.mydomain.myapp
So... I'm kinda assuming that my saved files are actually here:
/data/user/0/com.mydomain.myapp/files
And therefore, I should append this to my "get current directory" code:
// Get current directory adapted from: https://stackoverflow.com/questions/5527764/get-application-directory
String packName, currDir;
...everything from before...
currDir = p.applicationInfo.dataDir+"/files"; // <---- appending "+"/files"
Or am I way off? Any advice will be appreciated, thanks!
First of all, if you want to save your files in the app's directory, then you should call create a directory,
File directoryDefault = new File(Environment.DIRECTORY_DOCUMENTS, "YOUR_FOLDER_NAME");
if (!directoryDefault.exists()) {
directoryDefault.mkdir();
}
Then you have to save whatever files you have to save in the above mentioned default directory. Afterwards, when you want to list all the files available in that directory, you should call,
private ArrayList<String> fileNames() {
ArrayList<String> namesArray = new ArrayList<>();
File[] arrayFiles = directoryDefault.listFiles();
for (File file : arrayFiles) {
namesArray.add(file.getName());
}
return namesArray;
}

Set last modified timestamp of a file using jimfs in Java

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

keeping last 7 days zip files and deleting rest all files from a directory

I have developed an application which moves source file from source directory to target directory
by using apache Fileutils class methods as shown below..
private void filemove(String FilePath2, String s2) {
String filetomove = FilePath2 + s2; //file to move its complete path
File f = new File(filetomove);
File d = new File(targetFilePath); // path of target directory
try {
FileUtils.copyFileToDirectory(f, d);
f.delete(); //from source dirrectory we are deleting the file if it succesfully move
//*********** code need to add to delete the zip files of target directory and only keeping the latest two zip files ************//
} catch (IOException e) {
String errorMessage = e.getMessage();
logger.error(errorMessage);
}
}
Now when I'm moving the file to the target directory, so in that case the target directory will be having certain zip files, what I am trying is that
when ever I move my source file to target directory... it should do a pre-check such that in target directory it should delete all zip files but keeping only last 7 days zip files (so it should not delete last 7 day zip files)
What I have tried is working for last two days zip files that is it keeps recent two days zip files.
Please advise how can i change this in seven days such that it should keep last seven days zip files?
Take all the files in an array, and sort them, then just ignore the first two:
Comparator<File> fileDateComparator = new Comparator<File>() {
#Override
public int compare(File o1, File o2) {
if(null == o1 || null == o2){
return 0;
}
return (int) (o2.lastModified() - o1.lastModified());//yes, casting to an int. I'm assuming the difference will be small enough to fit.
}
};
File f = new File("/tmp");
if (f.isDirectory()) {
final File[] files = f.listFiles();
List<File> fileList = Arrays.asList(files);
Collections.sort(fileList, fileDateComparator);
System.out.println(fileList);
}
Do you really need to sort and all? If you need to delete files which are more than 7 days old, get the lastModifieddate and substract it from current time. if the difference is more than 7*24*60*60 seconds then you can delete it.
All you need is a for loop after the f.listFiles() line. Not actual code - use to get to the working code.
long timeInEpoch = System.currentTimeMillis(); // slightly faster than new Date().getTimeInMillis();
File f = new File("/tmp");
if (f.isDirectory()) {
final File[] files = f.listFiles();
for(int i =0; i < files.length ; i++ ) {
if( timeInEpoch - f.lastModifiedDate() > 1000*60*60*24*7 )
files[i].delete();
}
System.out.println(fileList);
}

How to Delete files in /data/data/providers/downloads/cache on Android

I want to create and delete some files located in /data/data/providers/downloads/cache. So far, I can download target files and save in /data/data/providers/downloads/cache successfully, but when I trying to delete a file located in /data/data/providers/downloads/cache it fails in the end. My methods are as follows
File directory = new File("/data/data/providers/downloads/cache");
File[] files = directory.listFiles();
I want to list all files, so that I can find the target files need to be deleted.
I found that listFiles() method always return NULL, so my question is, can I use listFile() to the dir /data/data/providers/downloads/cache ?
Any ideals are welcomed.
BR
Alan
I use this method: when i want to delete all the files including the directory.
static public boolean deleteDirectory(File path) {
if( path.exists() ) {
File[] files = path.listFiles();
if (files == null) {
return true;
}
for(int i = 0; i < files.length; i++) {
if(files[i].isDirectory()) {
deleteDirectory(files[i]);
}
else {
files[i].delete();
}
Log.d("Deleting Files", files[i].getPath());
}
}
return( path.delete() );
}
But android has it's own clear cache method you can use, but it requires you to actually save stuff to the cache. The problem might be that you never add anything to it, and you only have permission to clear your own cache?
How do I take advantage of Android's "Clear Cache" button Discusses the problem anyway :)
Good luck
EDIT:
Also, are you sure your file path is correct? You can use
Environment.getDownloadCacheDirectory()
in order to find the root directory to the cache i think?

Categories