How to clear webview cache when server side content updated? - java

I have a HTML cache enabled WebView app that sends Javascript fetch request to server and gets images list from server, images on server updating every random hour like: today 11:00, 16:00, tomorrow 14:00, 19:00. Images count is always 20 and their names are always like: 0.png, 1.png, 2.png,... 20.png.
Problem is once when app caches images with names like that, after replacing/updating them with other same name images Web app is not showing them, shows just old first time cached images. I know that i can pass get parameter in javascript code while sending get request like: "site.com?time="+Date.getHours();
But i need cache update only on image update on server
Tried code below to clear cache every day but that is not enought:
//helper method for clearCache() , recursive
//returns number of deleted files
static int clearCacheFolder(final File dir, final int numDays) {
int deletedFiles = 0;
if (dir!= null && dir.isDirectory()) {
try {
for (File child:dir.listFiles()) {
//first delete subdirectories recursively
if (child.isDirectory()) {
deletedFiles += clearCacheFolder(child, numDays);
}
//then delete the files and subdirectories in this dir
//only empty directories can be deleted, so subdirs have been done first
if (child.lastModified() < new Date().getTime() - numDays * DateUtils.DAY_IN_MILLIS) {
if (child.delete()) {
deletedFiles++;
}
}
}
}
catch(Exception e) {
Log.e(TAG, String.format("Failed to clean the cache, error %s", e.getMessage()));
}
}
return deletedFiles;
}
/*
* Delete the files older than numDays days from the application cache
* 0 means all files.
*/
public static void clearCache(final Context context, final int numDays) {
Log.i(TAG, String.format("Starting cache prune, deleting files older than %d days", numDays));
int numDeletedFiles = clearCacheFolder(context.getCacheDir(), numDays);
Log.i(TAG, String.format("Cache pruning completed, %d files deleted", numDeletedFiles));
}

Related

Java executable .jar file not working properly after compiling in NETBeans IDE

I am exporting a .jar file from a GUI built in Netbeans IDE. It works fine within Netbeans but once it is exported, some logic in the code does not execute properly.
I have tried debugging by running test cases displaying which items are passing through the if clauses. It seems to work well in IDE but not when it is run through .jar file.
for(Chamber chamber: chs)
{
if(!scheduledTools.containsKey(chamber))//unscheduled chambers
{
JOptionPane.showMessageDialog(this, chamber.getName()+": is unscheduled");
model.addElement(chamber.getName());
}
else//scheduled
{
if((scheduledTools.get(chamber).size()/range) > .25)
{
System.out.println("Range: " +range+" Scheduled: " +scheduledTools.get(chamber).size());
System.out.println("Cannot use this chambers:" +chamber.getName());
JOptionPane.showMessageDialog(this, chamber.getName()+": Cannot use this chamber");
}
else{
System.out.println("Scheduled but can use"+chamber.getName());
altModel.addElement(chamber.getName());
}
}
}
alternateChambers.setModel(altModel);alternateChambers.setSelectedIndex(0);
suggestedChambers.setModel(model);suggestedChambers.setSelectedIndex(0);
if(altModel.size()>1){JOptionPane.showMessageDialog(this, "Scheduled but can use these chambers:"+altModel);}
After making the necessary queries in seekDates method below:
private void seekDates(ResultSet rs) throws SQLException
{
ArrayList<String> entries;
//get how many dates we have so we can update progressbar
int results = 0;
setProgress(results);
if(rs.last()){results=rs.getRow();rs.beforeFirst();}
// processing returned data and printing into console
while(rs.next()) {
String scheduledChamber = rs.getString(2);
for(Chamber chamber : chambers){
//if the scheduled tool is a thermal chamber
//chambers get listed so far
if(!scheduledChamber.trim().toLowerCase().contains(chamber.getName().toLowerCase()))
{}//print chambers im not saving
else{
if(scheduledTools.containsKey(chamber))
{
//if key already used, just grab the list and add date
entries = scheduledTools.get(chamber);
entries.add(rs.getString(1).split(" ")[0]);
}
else
{
//if chamber hasnt been saved, add chamber and date
entries = new ArrayList<String>();
entries.add(rs.getString(1).split(" ")[0]);
scheduledTools.put(chamber, entries);
}
//System.out.println("Just saved this chamber:" +scheduledChamber+" with this date:" +scheduledTools.get(chamber));
}
;
}
publish(rs.getRow());
Thread.yield();
setProgress(100*(rs.getRow()/results));
}
}
The GUI should display the chambers found in the queries in one text field while displaying the rest of the chambers in another text field.
When I run this in the IDE. I get the correct outcome but once I compile using the package-for-store option in the build.xml file, the outcome then just lists all of the chambers in one text field.
In the .jar file, it seems that all of the chambers only satisfy the first if clause and none of the others.

How do I clear app cache every X minutes?

I have an app that uses webview and utilizes cache. But I need to clear that cache every X minutes even if the app isn't runnung. How would I do that?
I've enabled cache like this:
myWebView.getSettings().setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);
myWebView.getSettings().setAppCacheEnabled(true);
I use this statement to delete cache with a help of a button:
myWebView.clearCache(true);
The edited code snippet above posted by Gaunt Face contains an error in that if a directory fails to delete because one of its files cannot be deleted, the code will keep retrying in an infinite loop. I rewrote it to be truly recursive, and added a numDays parameter so you can control how old the files must be that are pruned:
//helper method for clearCache() , recursive
//returns number of deleted files
static int clearCacheFolder(final File dir, final int numDays) {
int deletedFiles = 0;
if (dir!= null && dir.isDirectory()) {
try {
for (File child:dir.listFiles()) {
//first delete subdirectories recursively
if (child.isDirectory()) {
deletedFiles += clearCacheFolder(child, numDays);
}
//then delete the files and subdirectories in this dir
//only empty directories can be deleted, so subdirs have been done first
if (child.lastModified() < new Date().getTime() - numDays * DateUtils.DAY_IN_MILLIS) {
if (child.delete()) {
deletedFiles++;
}
}
}
}
catch(Exception e) {
Log.e(TAG, String.format("Failed to clean the cache, error %s", e.getMessage()));
}
}
return deletedFiles;
}
/*
* Delete the files older than numDays days from the application cache
* 0 means all files.
*/
public static void clearCache(final Context context, final int numDays) {
Log.i(TAG, String.format("Starting cache prune, deleting files older than %d days", numDays));
int numDeletedFiles = clearCacheFolder(context.getCacheDir(), numDays);
Log.i(TAG, String.format("Cache pruning completed, %d files deleted", numDeletedFiles));
}
public static void deleteDirectoryTree(File fileOrDirectory) {
if (fileOrDirectory.isDirectory()) {
for (File child : fileOrDirectory.listFiles()) {
deleteDirectoryTree(child);
}
}
fileOrDirectory.delete();
}
deleteDirectoryTree(this.getCacheDir());
You can setup a timer in the Activity and after a specified timeout, call the deleteDirectoryTree

Spring inbound channel adapter - how to auto delete folders and files older than 10 days

Integration.xml - this will take all files in the directory
<int-file:inbound-channel-adapter id="delFiles" channel="delFiles"
directory="C:/abc/abc" use-watch-service="true" prevent-duplicates="false" auto-startup="true"
watch-events="CREATE,MODIFY">
<int:poller fixed-delay="1000"/>
<int-file:nio-locker/>
</int-file:inbound-channel-adapter>
I need to delete all files older than 10 days in that folder and sub folder. Can some one pls help?
Listener
#Transformer(inputChannel="delFiles")
public JobLaunchRequest deleteJob(Message<File> message) throws IOException {
Long timeStamp = message.getHeaders().getTimestamp();
return JobHandler.deleteJob(message.getPayload(), jobRepository, fileProcessor, timeStamp);
}
Handler
public static JobLaunchRequest deleteJob(File file, JobRepository jobRepository, Job fileProcessor, Long timeStamp) throws IOException {
//Is there a way in spring integration whether I can check this easily?
//How to check for folder and subfolders?
// This will check for files once it's dropped.
// How to run this job daily to check the file's age and delete?
}
This is not a <int-file:inbound-channel-adapter> responsibility. This one is really about polling files from the directory according filtering setting you provide.
If you are not interested in old files, you can implement a custom FileListFilter to skip files which are really so old.
If you still would like to delete those old files as some application functionality, you need to take a look into some other solution, something like #Scheduled method it iterate through files in that dir and remove them, e.g. once a day let's say at midnight.
You also can just remove processed files in the and of your logic. Since you use prevent-duplicates="false", you are going to poll the same file again and again.
To perform directory clean up you don't need Spring Integration:
public void recursiveDelete(File file) {
if (file != null && file.exists()) {
File[] files = file.listFiles();
if (files != null) {
for (File fyle : files) {
if (fyle.isDirectory()) {
recursiveDelete(fyle);
}
else {
if (fyle.lastModified() > 10 * 24 * 60 * 60 * 1000) {
fyle.delete();
}
}
}
}
}
}
(You might to improve this function a bit: haven't tested...)

Google drive rest API, Download files from root folder only

I am trying to download files in the root directory only. Currently I am not specifying any folders as I do not know how to so it downloads the most recent files that are in other folders that aren't the root. All I would like are the files in the root. The code that is getting the files and the download URLs is below:
public static void startDownload() throws IOException, ParseException {
Drive serv = getDriveService();
FileList result = serv.files().list().setMaxResults(10).execute(); //there are 10 files in the root folder
List<File> listA = result.getItems();
if (listA == null || listA.isEmpty()) {
System.out.println("No files found.");
} else {
System.out.println("Files:"+lista.size());
for (File file : listA) {
System.out.printf("%s (%s)\n", file.getTitle(), file.getDownloadUrl());
downloadFile(serv, file);
}
}
}
I would like to download all files in the root file only and not in any other folders. Any help would be appreciated.
You need to use the Q parameter to search
q string A query for filtering the file results. See the "Search for
Files" guide for supported syntax.
Sending something like the following will return everything that is not a folder with the parent of root.
mimeType != 'application/vnd.google-apps.folder' and 'root' in parents
There are a number of considerations.
Your line 3 needs to be
String q = "trashed = false and 'root' in parents and mimeType != 'application/vnd.google-apps.folder' "
FileList result = serv.files().list().setFields("*").setQ(q).setMaxResults(10).execute();
You need to be aware that this will return a maximum of 10 results, but even more so, you need to be aware that there is no minimum number of results. This means that if you have 11 files, you might get 10 in the first iteration and 1 in the 2nd. However, you could also get 1 and 10, or 3 and 6 and 2, or 0 and 0 and 1 and 10. You need to keep fetching results until the value of getNextPageToken() == null. So your line
if (listA == null || listA.isEmpty()) {
should be something like
if (result.getNextPageToken() == null) {
I realise that you've copy/pasted from the official documentation, but sadly that documentation is wrong.

EWS Java how to find emails older than xx days and Delete all in one shot

I want to find items in a folder which are older than xx days and Delete all the items found in one shot.
I was able to find the items matching my criteria. here is my code.
import org.joda.time.DateTime;
int purgeDays = 14;
try {
ItemView view = new ItemView(Integer.MAX_VALUE);
Folder purgeFolder = Folder.bind(service, folderId);
// need to convert to get Mon Sep 12 16:31:27 CDT 2016
SearchFilter searchFilter = new SearchFilter.IsLessThanOrEqualTo(ItemSchema.DateTimeReceived, (DateTime.now().minusDays(purgeDays).toDate()));
FindItemsResults<Item> emailsToPurge = service.findItems(purgeFolder.getId(), searchFilter, view);
if (emailsToPurge != null && emailsToPurge.getItems() != null && emailsToPurge.getTotalCount() > 0 ) {
// want something to delete all items at once
emailsToPurge.deleteAll();
} else {
log.info("Found no emails to purge for Mailbox-"+ userName);
}
} catch (Exception e) {
log.error("Exception "+ e.getMessage());
}
Have a look at the deleteItems method on the ExchangeService class https://msdn.microsoft.com/en-us/library/microsoft.exchange.webservices.data.exchangeservice.deleteitems(v=exchg.80).aspx this allows you to send a batch DeleteItem request. I would suggest you page your deletes though at no more than 1000 items at a time else you may have issue with throttling and/or the requests timing out.

Categories