Vaadin - deleting temporary Files from Upload-Component - java

hope you can help me. I have a Spring-Boot vaadin-Project with a few Upload-Fields.
Everythings fine. if you click on the send button in the end everything is processed and tempfiles are deleted. Though when you upload a file and leave the site then the temp-directory stays untouched. Is there any way to programatically delete all temporary files when a new instance is called?
When I upload a file on a built-with-vaadin-website and leave the site then, my temp directory gets fuller and fuller. i just want to delete all files which were created in the actual Vaadin Session when starting a new one. Or is there a way to find all files created in a spring session periodically?

I would create a custom VaadinServiceInitListener class (annotated with #Component), I would make a deleting method and in the serviceInit method I would call the deleting method with the uploading path. Something like this:
#Component
public class ApplicationServiceInitListener
implements VaadinServiceInitListener {
#Override
public void serviceInit(ServiceInitEvent event) {
// Delete the upload directory's content
try {
deleteDirectory(new File("[your_upload_directory_path]"));
} catch (IOException e) {
throw new RuntimeException(e);
}
// ...
}
private boolean deleteDirectory(File directoryToBeDeleted) {
File[] allContents = directoryToBeDeleted.listFiles();
if (allContents != null) {
for (File file : allContents) {
deleteDirectory(file);
}
}
return directoryToBeDeleted.delete();
}
}
Service Init Listener Vaadin doc: https://vaadin.com/docs/latest/advanced/service-init-listener
Ps: Of course, you can also use a File Util class, e.g. from common-io.

Related

jnotify - anything else to use instead of Thread.Sleep when file is detected

I am really needing some help on this.
I have adopted the JNOTIFY approach to detecting any new files in a directory. When the file arrives the Listener informs that a new file is in the location.
#BeforeTest(alwaysRun=true)
public void Polling() throws Exception {
ListenToNotifications.checkFolderPickup();
}
I have attempted this where I addded a call to my Setup function in order to call my setup function after the file is detected.
//snippet from Listener Class from checkFolderPickup();
public void fileCreated(int wd, String rootPath, String name) {
print("New File just created " + rootPath + " : " + name);
Thread.currentThread().setContextClassLoader( getClass().getClassLoader() );
try {
BaseTest.setup();
} catch (Exception e) {
e.printStackTrace();
}
}
My question is //Thread.sleep(1000000) i feel this is not a safe approach and I wanted to know if there is any other approach that I could possibly use instead of a Thread.Sleep, because this function will have to be executed once each time a new file is available and the old file will be deleted eventually and so on, I cannot make the Sleep to short , it will just ignore and continue with Base.Setup()
public static void checkFolderPickup() throws Exception {
...removed other code
boolean watchSubtree = true;
int watchID = JNotify.addWatch(path, mask, watchSubtree, new Listener());
//Thread.sleep(1000000);
Thread.sleep(20000);
boolean res = JNotify.removeWatch(watchID);
if (!res) {
// invalid watch ID specified.
}
}
I basically need my framework to keep polling that directory and each time it will execute the base setup process and follow a workflow, delete the file then poll again and so on.
Can anyone please advise?
You don't need any other modules , you can use custom expected condition:##
using:
import java.io.File;
define the method inside any pageobject class:
private ExpectedCondition<Boolean> newfilepresent() {
return new ExpectedCondition<Boolean>() {
#Override
public Boolean apply(WebDriver driver) {
File f = new File("D:\\workplace");
return f.listFiles().length>1;
}
#Override
public String toString() {
return String.format("wait for new file to be present within the time specified");
}
};
}
we created a custom expected condition method now use it as:
and in code wait like:
wait.until(pageobject.filepresent());
Output:
Failed:
Passed
Once you register a watch on a directory with JNotify, it will continue to deliver events for files in that directory. You should not remove the watch if you wish to continue to receive events for that directory.

Deleting photo saved in folder using room database in android

I am taking photo using default camera in mobile. After that saving the photo in specific path in folder which path have been created using File class. In Room database I have storing only the path of image. Now, I added delete method to delete specific photo. I am using following query to delete,
#Query("DELETE FROM record_table WHERE photo_path = photoPath")
int deletePhotoPath(String photoPath);
below methods are used for deleting photo(DataRepository.class)
public void deletePhotoPath(String photoPath){
new deletePhotoPathAsyncTask(RecordDao).execute(photoPath);
}
private class deletePhotoPathAsyncTask extends AsyncTask<String,Void,Void>{
public deletePhotoPathAsyncTask(RecordDao dao) {
RecordDao=dao;
}
#Override
protected Void doInBackground(final String... strings) {
int photoPathDeleted=RecordDao.deletePhotoPath(strings[0]);
Log.d("deletePhotoPath"," Photo Path"+photoPathDeleted+strings[0]);
return null;
}
}
I am calling delete method as below(MyActivity.class),
HolderData.deletePhotoPath(photopathArrayList.get(positionOfCurrentViewPhoto));
In HolderData class I have following method to call delete method from database(HolderData.class),
public static void deletePhotoPath(String photoPath){
Log.d(LOG_TAG, "deletPhotoPath:"+photoPath);
dataRepository.deletePhotoPath(photoPath);
}
But my photo is not getting deleted. Logcats inside delete method works fine.
Doesn't know to delete photo. And How do I reflect the change in my design.
Anybody help me to solve this..Already Surfed a lot but not able to find a solution.
Don`t forget to add the colon when you refer to the argument parameter in your query:
DELETE FROM record_table WHERE photo_path = :photoPath
Before deleting the link from Room extract it, create a File instance programmatically and call "delete" method on that instance:
File file = new File("path to your file");
file.delete();

Creating File & Directories not working properly

I am currently working on a method that will create files and directories. Bellow is the use case & problem explained.
1) When a user specifies a path e.g "/parent/sub folder/file.txt", the system should be able to create the directory along with the file.txt. (This one works)
2) When a user specifies a path e.g "/parent/sub-folder/" or "/parent/sub-folder", the system should be able to create all directories. (Does not work), Instead of it creating the "/sub-folder/" or /sub-folder" as a folder, it will create a file named "sub-folder".
Here is the code I have
Path path = Paths.get(rootDir+"test/hello/");
try {
Files.createDirectories(path.getParent());
if (!Files.isDirectory(path)) {
Files.createFile(path);
} else {
Files.createDirectory(path);
}
} catch (IOException e) {
System.out.println(e.getMessage());
}
You need to use createDirectories(Path) instead of createDirectory(path). As explained in the tutorial:
To create a directory several levels deep when one or more of the
parent directories might not yet exist, you can use the convenience
method, createDirectories(Path, FileAttribute). As with the
createDirectory(Path, FileAttribute) method, you can specify an
optional set of initial file attributes. The following code snippet
uses default attributes:
Files.createDirectories(Paths.get("foo/bar/test"));
The directories
are created, as needed, from the top down. In the foo/bar/test
example, if the foo directory does not exist, it is created. Next, the
bar directory is created, if needed, and, finally, the test directory
is created.
It is possible for this method to fail after creating some, but not
all, of the parent directories.
Not sure of which File API you are using. But find below the simplest code to create file along with folders using java.io package.
import java.io.File;
import java.io.IOException;
public class FileTest {
public static void main(String[] args) {
FileTest fileTest = new FileTest();
fileTest.createFile("C:"+File.separator+"folder"+File.separator+"file.txt");
}
public void createFile(String rootDir) {
String filePath = rootDir;
try {
if(rootDir.contains(File.separator)){
filePath = rootDir.substring(0, rootDir.lastIndexOf(File.separator));
}
File file = new File(filePath);
if(!file.exists()) {
System.out.println(file.mkdirs());
file = new File(rootDir);
System.out.println(file.createNewFile());
}
} catch (IOException e) {
System.out.println(e.getMessage());
}
}
}

recursively delete a folder in java

I already have a code that works, but I don't want it to actually delete the temp folder if possible. I am using the apache fileutils. Also does anyone know how to exclude folders from being deleted?
public class Cleartemp {
static String userprofile = System.getenv("USERPROFILE");
public static void main(String[] args) {
try {
File directory = new File(userprofile+"\\AppData\\Local\\Temp");
//
// Deletes a directory recursively. When deletion process is fail an
// IOException is thrown and that's why we catch the exception.
//
FileUtils.deleteDirectory(directory);
} catch (IOException e) {
e.printStackTrace();
}
}
}
Here's an actually recursive method:
public void deleteDirectory(File startFile, FileFilter ignoreFilter) {
if(startFile.isDirectory())
for(File f : startFile.listFiles()) {
deleteDirectory(f, ignoreFilter);
}
if(!ignoreFilter.accept(startFile)) {
startFile.delete();
}
}
Hand it a file filter set to return true for directories (see below) to make it not delete directories. You can also add exceptions for other files too
FileFilter folderFilter = new FileFilter() {
#Override
public boolean accept(File paramFile) {
return paramFile.isDirectory();
}
};
How about FileUtils.cleanDirectory ? It cleans a directory without deleting it.
You could also use Apache Commons DirectoryWalker if you need some filtering logic. One of the examples on the page includes FileCleaner implementation.
Simple,
Use isDirectory() to exclude it from being deleted.
Refer here: http://docs.oracle.com/javase/1.4.2/docs/api/java/io/File.html#isDirectory()
First ever post, don't consider myself an expert but am stuck with 1.4...
Here's a recursive delete method that works well, deletes all files and subfolders within a parent folder then the parent folder itself, assumes the File being passed is a directory as it is in my case.
private void deleteTemp(File tempDir) {
File[] a = (tempDir.listFiles());
for (int i = 0; i < a.length; i++) {
File b = a[i];
if (b.isDirectory())
deleteTemp(b);
b.delete();
}
tempDir.delete();
}

How can I notify my application that one file was deleted from the SDCard (Android)?

I am saving a few songs in a playlist (in my application database). When a particular song is deleted from the SDCard which already exists in the playlist, how can I reflect the changes in my database?
Look into using a FileObserver
You can monitor either a single file or directory. So what you'll have to do is determine which directories you have songs in and monitor each. Otherwise you can monitor your external storage directory and then each time anything changes, check if its one of the files in your db.
It works real simple, something like this should work:
import android.os.FileObserver;
public class SongDeletedFileObserver extends FileObserver {
public String absolutePath;
public MyFileObserver(String path) {
//not sure if you need ALL_EVENTS but it was the only one in the doc listed as a MASK
super(path, FileObserver.ALL_EVENTS);
absolutePath = path;
}
#Override
public void onEvent(int event, String path) {
if (path == null) {
return;
}
//a new file or subdirectory was created under the monitored directory
if ((FileObserver.DELETE & event)!=0) {
//handle deleted file
}
//data was written to a file
if ((FileObserver.MODIFY & event)!=0) {
//handle modified file (maybe id3 info changed?)
}
//the monitored file or directory was deleted, monitoring effectively stops
if ((FileObserver.DELETE_SELF & event)!=0) {
//handle when the whole directory being monitored is deleted
}
//a file or directory was opened
if ((FileObserver.MOVED_TO & event)!=0) {
//handle moved file
}
//a file or subdirectory was moved from the monitored directory
if ((FileObserver.MOVED_FROM & event)!=0) {
//?
}
//the monitored file or directory was moved; monitoring continues
if ((FileObserver.MOVE_SELF & event)!=0) {
//?
}
}
}
Then of course you need to have this FileObserver running at all times for it to be effective so you need to put it in a service. From the service you would do
SongDeletedFileObserver fileOb = new SongDeletedFileObserver(Environment.getExternalStorageDirectory());
There are some tricky things to this that you have to keep in mind:
This will drain battery worse if you have it running all the time..
You'll have to synchronize when the sdcard is mounted (and on reboot). This could be slow

Categories