Bug 999577 - disable addon access to cache v1 IDLs, r=michal+jduell

This commit is contained in:
Honza Bambas
2014-06-05 18:27:38 +02:00
parent 4c13f77dcb
commit eb1d05b716
27 changed files with 156 additions and 1547 deletions

View File

@@ -18,6 +18,7 @@
*/
Components.utils.import("resource://gre/modules/XPCOMUtils.jsm");
let {LoadContextInfo} = Cu.import("resource://gre/modules/LoadContextInfo.jsm", {});
XPCOMUtils.defineLazyModuleGetter(this, "FormHistory",
"resource://gre/modules/FormHistory.jsm");
@@ -567,10 +568,14 @@ var gAllTests = [
pm.addFromPrincipal(principal, "offline-app", Ci.nsIOfflineCacheUpdateService.ALLOW_NO_WARN);
// Store something to the offline cache
const nsICache = Components.interfaces.nsICache;
var cs = Components.classes["@mozilla.org/network/cache-service;1"]
.getService(Components.interfaces.nsICacheService);
var session = cs.createSession(URL + "/manifest", nsICache.STORE_OFFLINE, nsICache.STREAM_BASED);
var appcacheserv = Cc["@mozilla.org/network/application-cache-service;1"]
.getService(Ci.nsIApplicationCacheService);
var appcachegroupid = appcacheserv.buildGroupID(makeURI(URL + "/manifest"), LoadContextInfo.default);
var appcache = appcacheserv.createApplicationCache(appcachegroupid);
var cacheserv = Cc["@mozilla.org/netwerk/cache-storage-service;1"]
.getService(Ci.nsICacheStorageService);
var storage = cacheserv.appCacheStorage(LoadContextInfo.default, appcache);
// Open the dialog
let wh = new WindowHelper();
@@ -587,27 +592,19 @@ var gAllTests = [
// Check if the cache has been deleted
var size = -1;
var visitor = {
visitDevice: function (deviceID, deviceInfo)
onCacheStorageInfo: function (aEntryCount, aConsumption, aCapacity, aDiskDirectory)
{
if (deviceID == "offline")
size = deviceInfo.totalSize;
// Do not enumerate entries
return false;
},
visitEntry: function (deviceID, entryInfo)
{
// Do not enumerate entries.
return false;
size = aConsumption;
}
};
cs.visitEntries(visitor);
storage.asyncVisitStorage(visitor, false);
// Offline cache visit happens synchronously, since it's forwarded to the old code
is(size, 0, "offline application cache entries evicted");
};
var cacheListener = {
onCacheEntryAvailable: function (entry, access, status) {
onCacheEntryCheck: function() { return Ci.nsICacheEntryOpenCallback.ENTRY_WANTED; },
onCacheEntryAvailable: function (entry, isnew, appcache, status) {
is(status, Cr.NS_OK);
var stream = entry.openOutputStream(0);
var content = "content";
@@ -618,7 +615,7 @@ var gAllTests = [
}
};
session.asyncOpenCacheEntry(URL, nsICache.ACCESS_READ_WRITE, cacheListener);
storage.asyncOpenURI(makeURI(URL), "", Ci.nsICacheStorage.OPEN_TRUNCATE, cacheListener);
},
function () {
// Test for offline apps permission deletion

View File

@@ -329,30 +329,21 @@ var gAdvancedPane = {
updateActualAppCacheSize: function ()
{
var visitor = {
visitDevice: function (deviceID, deviceInfo)
onCacheStorageInfo: function (aEntryCount, aConsumption, aCapacity, aDiskDirectory)
{
if (deviceID == "offline") {
var actualSizeLabel = document.getElementById("actualAppCacheSize");
var sizeStrings = DownloadUtils.convertByteUnits(deviceInfo.totalSize);
var sizeStrings = DownloadUtils.convertByteUnits(aConsumption);
var prefStrBundle = document.getElementById("bundlePreferences");
var sizeStr = prefStrBundle.getFormattedString("actualAppCacheSize", sizeStrings);
actualSizeLabel.value = sizeStr;
}
// Do not enumerate entries
return false;
},
visitEntry: function (deviceID, entryInfo)
{
// Do not enumerate entries.
return false;
}
};
var cacheService =
Components.classes["@mozilla.org/network/cache-service;1"]
.getService(Components.interfaces.nsICacheService);
cacheService.visitEntries(visitor);
Components.classes["@mozilla.org/netwerk/cache-storage-service;1"]
.getService(Components.interfaces.nsICacheStorageService);
var storage = cacheService.appCacheStorage(LoadContextInfo.default, null);
storage.asyncVisitStorage(visitor, false);
},
updateCacheSizeUI: function (smartSizeEnabled)

View File

@@ -314,30 +314,21 @@ var gAdvancedPane = {
updateActualAppCacheSize: function ()
{
var visitor = {
visitDevice: function (deviceID, deviceInfo)
onCacheStorageInfo: function (aEntryCount, aConsumption, aCapacity, aDiskDirectory)
{
if (deviceID == "offline") {
var actualSizeLabel = document.getElementById("actualAppCacheSize");
var sizeStrings = DownloadUtils.convertByteUnits(deviceInfo.totalSize);
var sizeStrings = DownloadUtils.convertByteUnits(aConsumption);
var prefStrBundle = document.getElementById("bundlePreferences");
var sizeStr = prefStrBundle.getFormattedString("actualAppCacheSize", sizeStrings);
actualSizeLabel.textContent = sizeStr;
}
// Do not enumerate entries
return false;
},
visitEntry: function (deviceID, entryInfo)
{
// Do not enumerate entries.
return false;
actualSizeLabel.value = sizeStr;
}
};
var cacheService =
Components.classes["@mozilla.org/network/cache-service;1"]
.getService(Components.interfaces.nsICacheService);
cacheService.visitEntries(visitor);
Components.classes["@mozilla.org/netwerk/cache-storage-service;1"]
.getService(Components.interfaces.nsICacheStorageService);
var storage = cacheService.appCacheStorage(LoadContextInfo.default, null);
storage.asyncVisitStorage(visitor, false);
},
updateCacheSizeUI: function (smartSizeEnabled)

View File

@@ -29,6 +29,7 @@ const { classes: Cc, interfaces: Ci, utils: Cu } = Components;
let { XPCOMUtils } = Cu.import("resource://gre/modules/XPCOMUtils.jsm", {});
let { Services } = Cu.import("resource://gre/modules/Services.jsm", {});
let { LoadContextInfo } = Cu.import("resource://gre/modules/LoadContextInfo.jsm", {});
let { Promise: promise } = Cu.import("resource://gre/modules/Promise.jsm", {});
this.EXPORTED_SYMBOLS = ["AppCacheUtils"];
@@ -247,37 +248,35 @@ AppCacheUtils.prototype = {
let entries = [];
Services.cache.visitEntries({
visitDevice: function(deviceID, deviceInfo) {
return true;
},
let appCacheStorage = Services.cache2.appCacheStorage(LoadContextInfo.default, null);
appCacheStorage.asyncVisitStorage({
onCacheStorageInfo: function() {},
visitEntry: function(deviceID, entryInfo) {
if (entryInfo.deviceID == "offline") {
let entry = {};
let lowerKey = entryInfo.key.toLowerCase();
onCacheEntryInfo: function(aURI, aIdEnhance, aDataSize, aFetchCount, aLastModifiedTime, aExpirationTime) {
let lowerKey = aURI.asciiSpec.toLowerCase();
if (searchTerm && lowerKey.indexOf(searchTerm.toLowerCase()) == -1) {
return true;
return;
}
for (let [key, value] of Iterator(entryInfo)) {
if (key == "QueryInterface") {
continue;
}
if (key == "clientID") {
entry.key = entryInfo.key;
}
if (key == "expirationTime" || key == "lastFetched" || key == "lastModified") {
value = new Date(value * 1000);
}
entry[key] = value;
if (aIdEnhance) {
aIdEnhance += ":";
}
let entry = {
"deviceID": "offline",
"key": aIdEnhance + aURI.asciiSpec,
"fetchCount": aFetchCount,
"lastFetched": null,
"lastModified": new Date(aLastModifiedTime * 1000),
"expirationTime": new Date(aExpirationTime * 1000),
"dataSize": aDataSize
};
entries.push(entry);
}
return true;
}
});
}, true);
if (entries.length === 0) {
throw new Error(l10n.GetStringFromName("noResults"));
@@ -286,31 +285,11 @@ AppCacheUtils.prototype = {
},
viewEntry: function ACU_viewEntry(key) {
let uri;
Services.cache.visitEntries({
visitDevice: function(deviceID, deviceInfo) {
return true;
},
visitEntry: function(deviceID, entryInfo) {
if (entryInfo.deviceID == "offline" && entryInfo.key == key) {
uri = "about:cache-entry?client=" + entryInfo.clientID +
"&sb=1&key=" + entryInfo.key;
return false;
}
return true;
}
});
if (uri) {
let wm = Cc["@mozilla.org/appshell/window-mediator;1"]
.getService(Ci.nsIWindowMediator);
let win = wm.getMostRecentWindow("navigator:browser");
win.gBrowser.selectedTab = win.gBrowser.addTab(uri);
} else {
return l10n.GetStringFromName("entryNotFound");
}
win.gBrowser.selectedTab = win.gBrowser.addTab(
"about:cache-entry?storage=appcache&context=&eid=&uri=" + key);
},
clearAll: function ACU_clearAll() {

View File

@@ -19,7 +19,6 @@
#include "nsIDocShellTreeItem.h"
#include "nsIURI.h"
#include "nsIContentViewer.h"
#include "nsICacheService.h"
#include "nsIObserverService.h"
#include "prclist.h"
#include "mozilla/Services.h"
@@ -190,7 +189,7 @@ nsSHistoryObserver::Observe(nsISupports *aSubject, const char *aTopic,
if (!strcmp(aTopic, NS_PREFBRANCH_PREFCHANGE_TOPIC_ID)) {
nsSHistory::UpdatePrefs();
nsSHistory::GloballyEvictContentViewers();
} else if (!strcmp(aTopic, NS_CACHESERVICE_EMPTYCACHE_TOPIC_ID) ||
} else if (!strcmp(aTopic, "cacheservice:empty-cache") ||
!strcmp(aTopic, "memory-pressure")) {
nsSHistory::GloballyEvictAllContentViewers();
}
@@ -370,7 +369,7 @@ nsSHistory::Startup()
// Observe empty-cache notifications so tahat clearing the disk/memory
// cache will also evict all content viewers.
obsSvc->AddObserver(gObserver,
NS_CACHESERVICE_EMPTYCACHE_TOPIC_ID, false);
"cacheservice:empty-cache", false);
// Same for memory-pressure notifications
obsSvc->AddObserver(gObserver, "memory-pressure", false);
@@ -391,7 +390,7 @@ nsSHistory::Shutdown()
nsCOMPtr<nsIObserverService> obsSvc =
mozilla::services::GetObserverService();
if (obsSvc) {
obsSvc->RemoveObserver(gObserver, NS_CACHESERVICE_EMPTYCACHE_TOPIC_ID);
obsSvc->RemoveObserver(gObserver, "cacheservice:empty-cache");
obsSvc->RemoveObserver(gObserver, "memory-pressure");
}
NS_RELEASE(gObserver);

View File

@@ -13,7 +13,6 @@
#include "nsNetUtil.h"
#include "nsNetCID.h"
#include "nsICacheSession.h"
#include "nsICacheService.h"
#include "nsIOfflineCacheUpdate.h"
#include "nsAutoPtr.h"
#include "nsContentUtils.h"

View File

@@ -3,6 +3,7 @@ var Cc = SpecialPowers.Cc;
var Ci = SpecialPowers.Ci;
var Cu = SpecialPowers.Cu;
var LoadContextInfo = Cu.import("resource://gre/modules/LoadContextInfo.jsm", {}).LoadContextInfo;
var CommonUtils = Cu.import("resource://services-common/utils.js", {}).CommonUtils;
const kNetBase = 2152398848; // 0x804B0000
var NS_ERROR_CACHE_KEY_NOT_FOUND = kNetBase + 61;
@@ -22,13 +23,14 @@ QueryInterface: function(iid) {
}
return this;
},
onCacheEntryAvailable: function(desc, accessGranted, status) {
onCacheEntryCheck: function() { return Ci.nsICacheEntryOpenCallback.ENTRY_WANTED; },
onCacheEntryAvailable: function(desc, isnew, applicationCache, status) {
if (!desc) {
this.fetch(this.callback);
return;
}
var stream = desc.QueryInterface(Ci.nsICacheEntryDescriptor).openInputStream(0);
var stream = desc.openInputStream(0);
var sstream = Cc["@mozilla.org/scriptableinputstream;1"]
.createInstance(SpecialPowers.Ci.nsIScriptableInputStream);
sstream.init(stream);
@@ -49,8 +51,8 @@ fetch: function(callback)
var url = this.urls.shift();
var self = this;
var cacheSession = OfflineTest.getActiveSession();
cacheSession.asyncOpenCacheEntry(url, Ci.nsICache.ACCESS_READ, this);
var cacheStorage = OfflineTest.getActiveStorage();
cacheStorage.asyncOpenURI(CommonUtils.makeURI(url), "", Ci.nsICacheStorage.OPEN_READONLY | Ci.nsICacheStorage.FORCE_ASYNC_CALLBACK, this);
}
};
@@ -255,7 +257,8 @@ waitForAdd: function(url, onFinished) {
var numChecks = 20;
var waitForAddListener = {
onCacheEntryAvailable: function(entry, access, status) {
onCacheEntryCheck: function() { return Ci.nsICacheEntryOpenCallback.ENTRY_WANTED; },
onCacheEntryAvailable: function(entry, isnew, applicationCache, status) {
if (entry) {
entry.close();
onFinished();
@@ -272,10 +275,8 @@ waitForAdd: function(url, onFinished) {
};
var waitFunc = function() {
var cacheSession = OfflineTest.getActiveSession();
cacheSession.asyncOpenCacheEntry(url,
Ci.nsICache.ACCESS_READ,
waitForAddListener);
var cacheStorage = OfflineTest.getActiveStorage();
cacheStorage.asyncOpenURI(CommonUtils.makeURI(url), "", Ci.nsICacheStorage.OPEN_READONLY | Ci.nsICacheStorage.FORCE_ASYNC_CALLBACK, waitForAddListener);
}
setTimeout(this.priv(waitFunc), 500);
@@ -327,18 +328,16 @@ getActiveCache: function(overload)
return serv.getActiveCache(groupID);
},
getActiveSession: function()
getActiveStorage: function()
{
var cache = this.getActiveCache();
if (!cache) {
return null;
}
var cacheService = Cc["@mozilla.org/network/cache-service;1"]
.getService(Ci.nsICacheService);
return cacheService.createSession(cache.clientID,
Ci.nsICache.STORE_OFFLINE,
true);
var cacheService = Cc["@mozilla.org/netwerk/cache-storage-service;1"]
.getService(Ci.nsICacheStorageService);
return cacheService.appCacheStorage(LoadContextInfo.default, cache);
},
priv: function(func)
@@ -365,13 +364,13 @@ checkCacheEntries: function(entries, callback)
checkCache: function(url, expectEntry, callback)
{
var cacheSession = this.getActiveSession();
this._checkCache(cacheSession, url, expectEntry, callback);
var cacheStorage = this.getActiveStorage();
this._checkCache(cacheStorage, url, expectEntry, callback);
},
_checkCache: function(cacheSession, url, expectEntry, callback)
_checkCache: function(cacheStorage, url, expectEntry, callback)
{
if (!cacheSession) {
if (!cacheStorage) {
if (expectEntry) {
this.ok(false, url + " should exist in the offline cache (no session)");
} else {
@@ -382,7 +381,8 @@ _checkCache: function(cacheSession, url, expectEntry, callback)
}
var _checkCacheListener = {
onCacheEntryAvailable: function(entry, access, status) {
onCacheEntryCheck: function() { return Ci.nsICacheEntryOpenCallback.ENTRY_WANTED; },
onCacheEntryAvailable: function(entry, isnew, applicationCache, status) {
if (entry) {
if (expectEntry) {
OfflineTest.ok(true, url + " should exist in the offline cache");
@@ -412,10 +412,7 @@ _checkCache: function(cacheSession, url, expectEntry, callback)
}
};
cacheSession.asyncOpenCacheEntry(url,
Ci.nsICache.ACCESS_READ,
_checkCacheListener,
false);
cacheStorage.asyncOpenURI(CommonUtils.makeURI(url), "", Ci.nsICacheStorage.OPEN_READONLY | Ci.nsICacheStorage.FORCE_ASYNC_CALLBACK, _checkCacheListener);
},
setSJSState: function(sjsPath, stateQuery)

View File

@@ -12,7 +12,6 @@
#include "gfxPlatform.h"
#include "nsUnicharUtils.h"
#include "nsNetUtil.h"
#include "nsICacheService.h"
#include "nsIProtocolHandler.h"
#include "nsIPrincipal.h"
#include "gfxFontConstants.h"
@@ -863,7 +862,7 @@ gfxUserFontSet::UserFontCache::Flusher::Observe(nsISupports* aSubject,
return NS_OK;
}
if (!strcmp(aTopic, NS_CACHESERVICE_EMPTYCACHE_TOPIC_ID)) {
if (!strcmp(aTopic, "cacheservice:empty-cache")) {
sUserFonts->Clear();
} else if (!strcmp(aTopic, "last-pb-context-exited")) {
sUserFonts->EnumerateEntries(Entry::RemoveIfPrivate, nullptr);
@@ -917,7 +916,7 @@ gfxUserFontSet::UserFontCache::CacheFont(gfxFontEntry *aFontEntry)
mozilla::services::GetObserverService();
if (obs) {
Flusher *flusher = new Flusher;
obs->AddObserver(flusher, NS_CACHESERVICE_EMPTYCACHE_TOPIC_ID,
obs->AddObserver(flusher, "cacheservice:empty-cache",
false);
obs->AddObserver(flusher, "last-pb-context-exited", false);
obs->AddObserver(flusher, "xpcom-shutdown", false);

View File

@@ -1309,6 +1309,18 @@ nsCacheService::CreateSession(const char * clientID,
{
*result = nullptr;
if (net::CacheObserver::UseNewCache())
return NS_ERROR_NOT_IMPLEMENTED;
return CreateSessionInternal(clientID, storagePolicy, streamBased, result);
}
nsresult
nsCacheService::CreateSessionInternal(const char * clientID,
nsCacheStoragePolicy storagePolicy,
bool streamBased,
nsICacheSession **result)
{
if (this == nullptr) return NS_ERROR_NOT_AVAILABLE;
nsCacheSession * session = new nsCacheSession(clientID, storagePolicy, streamBased);
@@ -1460,6 +1472,14 @@ nsCacheService::IsStorageEnabledForPolicy_Locked(nsCacheStoragePolicy storagePo
}
NS_IMETHODIMP nsCacheService::VisitEntries(nsICacheVisitor *visitor)
{
if (net::CacheObserver::UseNewCache())
return NS_ERROR_NOT_IMPLEMENTED;
return VisitEntriesInternal(visitor);
}
nsresult nsCacheService::VisitEntriesInternal(nsICacheVisitor *visitor)
{
NS_ENSURE_ARG_POINTER(visitor);
@@ -1514,6 +1534,14 @@ void nsCacheService::FireClearNetworkCacheStoredAnywhereNotification()
}
NS_IMETHODIMP nsCacheService::EvictEntries(nsCacheStoragePolicy storagePolicy)
{
if (net::CacheObserver::UseNewCache())
return NS_ERROR_NOT_IMPLEMENTED;
return EvictEntriesInternal(storagePolicy);
}
nsresult nsCacheService::EvictEntriesInternal(nsCacheStoragePolicy storagePolicy)
{
if (storagePolicy == nsICache::STORE_ANYWHERE) {
// if not called on main thread, dispatch the notification to the main thread to notify observers

View File

@@ -228,6 +228,14 @@ public:
typedef bool (*DoomCheckFn)(nsCacheEntry* entry);
// Accessors to the disabled functionality
nsresult CreateSessionInternal(const char * clientID,
nsCacheStoragePolicy storagePolicy,
bool streamBased,
nsICacheSession **result);
nsresult VisitEntriesInternal(nsICacheVisitor *visitor);
nsresult EvictEntriesInternal(nsCacheStoragePolicy storagePolicy);
private:
friend class nsCacheServiceAutoLock;
friend class nsOfflineCacheDevice;

View File

@@ -13,10 +13,19 @@ interface nsICacheSession;
interface nsICacheVisitor;
interface nsIEventTarget;
/**
* @deprecated
*
* IMPORTANT NOTE: THIS INTERFACE IS NO LONGER SUPPORTED AND PLANNED TO BE
* REMOVED SOON. WE STRONGLY ENCORAGE TO MIGRATE THE EXISTING CODE AND FOR
* THE NEW CODE USE ONLY THE NEW HTTP CACHE API IN netwerk/cache2/.
*/
[scriptable, uuid(14dbe1e9-f3bc-45af-92f4-2c574fcd4e39)]
interface nsICacheService : nsISupports
{
/**
* @throws NS_ERROR_NOT_IMPLEMENTED when the cache v2 is prefered to use.
*
* Create a cache session
*
* A cache session represents a client's access into the cache. The cache
@@ -41,11 +50,15 @@ interface nsICacheService : nsISupports
in boolean streamBased);
/**
* @throws NS_ERROR_NOT_IMPLEMENTED when the cache v2 is prefered to use.
*
* Visit entries stored in the cache. Used to implement about:cache.
*/
void visitEntries(in nsICacheVisitor visitor);
/**
* @throws NS_ERROR_NOT_IMPLEMENTED when the cache v2 is prefered to use.
*
* Evicts all entries in all devices implied by the storage policy.
*
* @note This function may evict some items but will throw if it fails to evict

View File

@@ -10,7 +10,7 @@
#include "nsICacheEntryDoomCallback.h"
#include "nsICacheService.h"
#include "nsCacheService.h"
#include "nsIApplicationCache.h"
#include "nsIApplicationCacheService.h"
#include "nsIURI.h"
@@ -119,7 +119,7 @@ NS_IMETHODIMP AppCacheStorage::AsyncEvictStorage(nsICacheEntryDoomCallback* aCal
do_GetService(NS_CACHESERVICE_CONTRACTID, &rv);
NS_ENSURE_SUCCESS(rv, rv);
rv = serv->EvictEntries(nsICache::STORE_OFFLINE);
rv = nsCacheService::GlobalInstance()->EvictEntriesInternal(nsICache::STORE_OFFLINE);
NS_ENSURE_SUCCESS(rv, rv);
}
else {
@@ -161,7 +161,7 @@ NS_IMETHODIMP AppCacheStorage::AsyncVisitStorage(nsICacheStorageVisitor* aVisito
nsRefPtr<_OldVisitCallbackWrapper> cb = new _OldVisitCallbackWrapper(
"offline", aVisitor, aVisitEntries, LoadInfo());
rv = serv->VisitEntries(cb);
rv = nsCacheService::GlobalInstance()->VisitEntriesInternal(cb);
NS_ENSURE_SUCCESS(rv, rv);
return NS_OK;

View File

@@ -618,7 +618,7 @@ GetCacheSession(nsCSubstring const &aScheme,
NS_ENSURE_SUCCESS(rv, rv);
nsCOMPtr<nsICacheSession> session;
rv = serv->CreateSession(clientId.get(),
rv = nsCacheService::GlobalInstance()->CreateSessionInternal(clientId.get(),
storagePolicy,
nsICache::STREAM_BASED,
getter_AddRefs(session));
@@ -984,7 +984,7 @@ NS_IMETHODIMP _OldStorage::AsyncEvictStorage(nsICacheEntryDoomCallback* aCallbac
do_GetService(NS_CACHESERVICE_CONTRACTID, &rv);
NS_ENSURE_SUCCESS(rv, rv);
rv = serv->EvictEntries(nsICache::STORE_OFFLINE);
rv = nsCacheService::GlobalInstance()->EvictEntriesInternal(nsICache::STORE_OFFLINE);
NS_ENSURE_SUCCESS(rv, rv);
}
else {
@@ -1073,7 +1073,7 @@ NS_IMETHODIMP _OldStorage::AsyncVisitStorage(nsICacheStorageVisitor* aVisitor,
nsRefPtr<_OldVisitCallbackWrapper> cb = new _OldVisitCallbackWrapper(
deviceID, aVisitor, aVisitEntries, mLoadInfo);
rv = serv->VisitEntries(cb);
rv = nsCacheService::GlobalInstance()->VisitEntriesInternal(cb);
NS_ENSURE_SUCCESS(rv, rv);
return NS_OK;

View File

@@ -1,285 +0,0 @@
var DEBUG = true;
var clientID = "javascript";
var nsICache = Components.interfaces.nsICache;
function getEventQueue()
{
var nsIEventQueueService = Components.interfaces.nsIEventQueueService;
var CID = Components.classes["@mozilla.org/event-queue-service;1"];
var service = CID.getService(nsIEventQueueService);
return service.getSpecialEventQueue(nsIEventQueueService.CURRENT_THREAD_EVENT_QUEUE);
}
var eventQueue = getEventQueue();
function getCacheService()
{
var nsCacheService = Components.classes["@mozilla.org/network/cache-service;1"];
var service = nsCacheService.getService(Components.interfaces.nsICacheService);
return service;
}
function createCacheSession(clientID, storagePolicy, streamable)
{
var service = getCacheService();
var session = service.createSession(clientID, storagePolicy, streamable);
return session;
}
function openCacheEntry(url, mode)
{
var session = createCacheSession(clientID, nsICache.STORE_ON_DISK, true);
var entry = session.openCacheEntry(url, mode);
return entry;
}
function wrapInputStream(input)
{
var nsIScriptableInputStream = Components.interfaces.nsIScriptableInputStream;
var factory = Components.classes["@mozilla.org/scriptableinputstream;1"];
var wrapper = factory.createInstance(nsIScriptableInputStream);
wrapper.init(input);
return wrapper;
}
function download(url)
{
var data = "";
var buffer = java.lang.reflect.Array.newInstance(java.lang.Byte.TYPE, 65536);
var stream = url.getContent();
while (true) {
var count = stream.read(buffer);
if (count <= 0)
break;
var str = new java.lang.String(buffer, 0, count);
data += str;
}
stream.close();
return data;
}
function write(url, data)
{
var key = url.toString();
var outputEntry = openCacheEntry(key, nsICache.ACCESS_WRITE);
var output = outputEntry.transport.openOutputStream(0, -1, 0);
var count = output.write(data, data.length);
// store some metadata.
outputEntry.setMetaDataElement("size", data.length);
output.close();
outputEntry.markValid();
outputEntry.close();
return count;
}
function CacheListener()
{
this.done = false;
}
CacheListener.prototype = {
QueryInterface : function(iid)
{
if (iid.equals(Components.interfaces.nsICacheListener))
return this;
throw Components.results.NS_NOINTERFACE;
},
onCacheEntryAvailable : function(/* in nsICacheEntryDescriptor */ descriptor,
/* in nsCacheAccessMode */ accessGranted,
/* in nsresult */ status)
{
this.descriptor = descriptor;
this.status = status;
this.done = true;
}
};
function asyncOpenCacheEntry(url, mode)
{
var session = createCacheSession(clientID, nsICache.STORE_ON_DISK, true);
var listener = new CacheListener();
session.asyncOpenCacheEntry(url, mode, listener);
while (!listener.done)
eventQueue.processPendingEvents();
return listener.descriptor;
}
function asyncWrite(key, data)
{
var outputEntry = asyncOpenCacheEntry(key, nsICache.ACCESS_WRITE);
var output = outputEntry.transport.openOutputStream(0, -1, 0);
var count = output.write(data, data.length);
// store some metadata.
outputEntry.setMetaDataElement("size", data.length);
output.close();
outputEntry.markValid();
outputEntry.close();
return count;
}
function StreamListener()
{
this.done = false;
this.data = "";
this.wrapper = null;
}
StreamListener.prototype = {
QueryInterface : function(iid)
{
if (iid.equals(Components.interfaces.nsIStreamListener) ||
iid.equals(Components.interfaces.nsIStreamObserver))
return this;
throw Components.results.NS_NOINTERFACE;
},
onStartRequest : function(request, context)
{
},
onStopRequest : function(request, context, statusCode, statusText)
{
this.statusCode = statusCode;
this.done = true;
},
onDataAvailable : function(request, context, input, offset, count)
{
if (this.wrapper == null)
this.wrapper = wrapInputStream(input);
input = this.wrapper;
this.data += input.read(count);
}
};
function asyncRead(key)
{
var inputEntry = asyncOpenCacheEntry(key, nsICache.ACCESS_READ);
var listener = new StreamListener();
inputEntry.transport.asyncRead(listener, null, 0, inputEntry.dataSize, 0);
while (!listener.done)
eventQueue.processPendingEvents();
inputEntry.close();
return listener.data;
}
function read(key)
{
var inputEntry = openCacheEntry(key, nsICache.ACCESS_READ);
var input = wrapInputStream(inputEntry.transport.openInputStream(0, -1, 0));
var data = input.read(input.available());
input.close();
inputEntry.close();
return data;
}
function readMetaData(key, element)
{
var inputEntry = openCacheEntry(key, nsICache.ACCESS_READ);
var metadata = inputEntry.getMetaDataElement(element);
inputEntry.close();
return metadata;
}
function doom(url)
{
var key = url.toString();
var doomedEntry = openCacheEntry(key, nsICache.ACCESS_READ_WRITE);
doomedEntry.doom();
doomedEntry.close();
}
function test()
{
// download some real content from the network.
var url = new java.net.URL("http://www.mozilla.org");
var key = url.toString();
var data = download(url);
if (asyncWrite(key, data) == data.length)
print("disk cache write works!");
else
print("disk cache write broken!");
if (asyncRead(key) == data)
print("disk cache read works!");
else
print("disk cache read broken!");
if (readMetaData(key, "size") == data.length)
print("disk cache metadata works!");
else
print("disk cache metadata broken!");
}
function median(array)
{
var cmp = function(x, y) { return x - y; }
array.sort(cmp);
var middle = Math.floor(array.length / 2);
return array[middle];
}
function sum(array)
{
var s = 0;
var len = array.length;
for (var i = 0; i < len; ++i)
s += array[i];
return s;
}
function time()
{
var N = 50;
var System = java.lang.System;
var url = new java.net.URL("http://www.mozilla.org");
var key = url.toString();
var downloadTimes = new Array();
for (var i = 0; i < N; ++i) {
var begin = System.currentTimeMillis();
download(url);
var end = System.currentTimeMillis();
downloadTimes.push(end - begin);
}
var downloadTotal = sum(downloadTimes);
var downloadMean = downloadTotal / N;
var downloadMedian = median(downloadTimes);
print("" + N + " downloads took " + downloadTotal + " milliseconds.");
print("mean = " + downloadMean + " milliseconds.");
print("median = " + downloadMedian + " milliseconds.");
var readTimes = new Array();
for (var i = 0; i < N; ++i) {
var begin = System.currentTimeMillis();
asyncRead(key);
var end = System.currentTimeMillis();
readTimes.push(end - begin);
}
var readTotal = sum(readTimes);
var readMean = readTotal / N;
var readMedian = median(readTimes);
print("" + N + " reads took " + readTotal + " milliseconds.");
print("mean = " + readMean + " milliseconds.");
print("median = " + readMedian + " milliseconds.");
}
// load the cache service before doing anything with Java...
getCacheService();
if (DEBUG) {
print("cache service loaded.");
} else {
print("running disk cache test.");
test();
print("disk cache test complete.");
}

View File

@@ -1,291 +0,0 @@
var DEBUG = true;
var clientID = "HTTP";
var nsICache = Components.interfaces.nsICache;
function getEventQueue()
{
var nsIEventQueueService = Components.interfaces.nsIEventQueueService;
var CID = Components.classes["@mozilla.org/event-queue-service;1"];
var service = CID.getService(nsIEventQueueService);
return service.getSpecialEventQueue(nsIEventQueueService.CURRENT_THREAD_EVENT_QUEUE);
}
var eventQueue = getEventQueue();
function getCacheService()
{
var nsCacheService = Components.classes["@mozilla.org/network/cache-service;1"];
var service = nsCacheService.getService(Components.interfaces.nsICacheService);
return service;
}
function createCacheSession(clientID, storagePolicy, streamable)
{
var service = getCacheService();
var session = service.createSession(clientID, storagePolicy, streamable);
return session;
}
function openCacheEntry(url, mode)
{
var session = createCacheSession(clientID, nsICache.STORE_ON_DISK, true);
var entry = session.openCacheEntry(url, mode);
return entry;
}
function wrapInputStream(input)
{
var nsIScriptableInputStream = Components.interfaces.nsIScriptableInputStream;
var factory = Components.classes["@mozilla.org/scriptableinputstream;1"];
var wrapper = factory.createInstance(nsIScriptableInputStream);
wrapper.init(input);
return wrapper;
}
function download(key)
{
var url = new java.net.URL(key);
var data = "";
var buffer = java.lang.reflect.Array.newInstance(java.lang.Byte.TYPE, 65536);
var stream = url.openStream();
while (true) {
var count = stream.read(buffer);
if (count <= 0)
break;
var str = new java.lang.String(buffer, 0, count);
data += str;
}
stream.close();
return data;
}
function write(url, data)
{
var key = url.toString();
var outputEntry = openCacheEntry(key, nsICache.ACCESS_WRITE);
var output = outputEntry.transport.openOutputStream(0, -1, 0);
var count = output.write(data, data.length);
// store some metadata.
outputEntry.setMetaDataElement("size", data.length);
output.close();
outputEntry.markValid();
outputEntry.close();
return count;
}
function CacheListener()
{
this.done = false;
}
CacheListener.prototype = {
QueryInterface : function(iid)
{
if (iid.equals(Components.interfaces.nsICacheListener))
return this;
throw Components.results.NS_NOINTERFACE;
},
onCacheEntryAvailable : function(/* in nsICacheEntryDescriptor */ descriptor,
/* in nsCacheAccessMode */ accessGranted,
/* in nsresult */ status)
{
this.descriptor = descriptor;
this.status = status;
this.done = true;
}
};
function asyncOpenCacheEntry(url, mode)
{
var session = createCacheSession(clientID, nsICache.STORE_ON_DISK, true);
var listener = new CacheListener();
session.asyncOpenCacheEntry(url, mode, listener);
while (!listener.done)
eventQueue.processPendingEvents();
return listener.descriptor;
}
function asyncWrite(key, data)
{
var outputEntry = asyncOpenCacheEntry(key, nsICache.ACCESS_WRITE);
var output = outputEntry.transport.openOutputStream(0, -1, 0);
var count = output.write(data, data.length);
// store some metadata.
outputEntry.setMetaDataElement("size", data.length);
output.close();
outputEntry.markValid();
outputEntry.close();
return count;
}
function StreamListener()
{
this.done = false;
this.data = "";
this.wrapper = null;
}
StreamListener.prototype = {
QueryInterface : function(iid)
{
if (iid.equals(Components.interfaces.nsIStreamListener) ||
iid.equals(Components.interfaces.nsIStreamObserver))
return this;
throw Components.results.NS_NOINTERFACE;
},
onStartRequest : function(request, context)
{
},
onStopRequest : function(request, context, statusCode, statusText)
{
this.statusCode = statusCode;
this.done = true;
},
onDataAvailable : function(request, context, input, offset, count)
{
if (this.wrapper == null)
this.wrapper = wrapInputStream(input);
input = this.wrapper;
this.data += input.read(count);
}
};
function asyncRead(key)
{
var inputEntry = asyncOpenCacheEntry(key, nsICache.ACCESS_READ);
var listener = new StreamListener();
inputEntry.transport.asyncRead(listener, null, 0, inputEntry.dataSize, 0);
while (!listener.done)
eventQueue.processPendingEvents();
inputEntry.close();
return listener.data;
}
function read(key)
{
var inputEntry = openCacheEntry(key, nsICache.ACCESS_READ);
var input = wrapInputStream(inputEntry.transport.openInputStream(0, -1, 0));
var data = input.read(input.available());
input.close();
inputEntry.close();
return data;
}
function readMetaData(key, element)
{
var inputEntry = openCacheEntry(key, nsICache.ACCESS_READ);
var metadata = inputEntry.getMetaDataElement(element);
inputEntry.close();
return metadata;
}
function doom(url)
{
var key = url.toString();
var doomedEntry = openCacheEntry(key, nsICache.ACCESS_READ_WRITE);
doomedEntry.doom();
doomedEntry.close();
}
// two keys which are known to collide right now.
var key1 = "http://a772.g.akamai.net/7/772/51/7648437e551b56/www.apple.com/t/2001/us/en/i/2.gif";
var key2 = "http://a772.g.akamai.net/7/772/51/70601300d0bde6/www.apple.com/t/2001/us/en/i/1right.gif";
function test()
{
// 1. generate a collision, and close the colliding entry first.
var entry1 = asyncOpenCacheEntry(key1, nsICache.ACCESS_READ_WRITE);
var data1 = key1;
entry1.setMetaDataElement("size", data1.length);
entry1.markValid();
var output1 = entry1.transport.openOutputStream(0, -1, 0);
output1.write(data1, data1.length);
var entry2 = asyncOpenCacheEntry(key2, nsICache.ACCESS_READ_WRITE);
var data2 = key2;
entry2.setMetaDataElement("size", data2.length);
entry2.markValid();
var output2 = entry2.transport.openOutputStream(0, -1, 0);
output2.write(data2, data2.length);
output1.close();
output2.close();
entry1.close();
entry2.close();
}
function median(array)
{
var cmp = function(x, y) { return x - y; }
array.sort(cmp);
var middle = Math.floor(array.length / 2);
return array[middle];
}
function sum(array)
{
var s = 0;
var len = array.length;
for (var i = 0; i < len; ++i)
s += array[i];
return s;
}
function time()
{
var N = 50;
var System = java.lang.System;
var url = new java.net.URL("http://www.mozilla.org");
var key = url.toString();
var downloadTimes = new Array();
for (var i = 0; i < N; ++i) {
var begin = System.currentTimeMillis();
download(url);
var end = System.currentTimeMillis();
downloadTimes.push(end - begin);
}
var downloadTotal = sum(downloadTimes);
var downloadMean = downloadTotal / N;
var downloadMedian = median(downloadTimes);
print("" + N + " downloads took " + downloadTotal + " milliseconds.");
print("mean = " + downloadMean + " milliseconds.");
print("median = " + downloadMedian + " milliseconds.");
var readTimes = new Array();
for (var i = 0; i < N; ++i) {
var begin = System.currentTimeMillis();
asyncRead(key);
var end = System.currentTimeMillis();
readTimes.push(end - begin);
}
var readTotal = sum(readTimes);
var readMean = readTotal / N;
var readMedian = median(readTimes);
print("" + N + " reads took " + readTotal + " milliseconds.");
print("mean = " + readMean + " milliseconds.");
print("median = " + readMedian + " milliseconds.");
}
// load the cache service before doing anything with Java...
getCacheService();
if (DEBUG) {
print("cache service loaded.");
} else {
print("running disk cache test.");
test();
print("disk cache test complete.");
}

View File

@@ -1,198 +0,0 @@
var DEBUG = true;
var clientID = "javascript";
var nsICache = Components.interfaces.nsICache;
function getCacheService()
{
var nsCacheService = Components.classes["@mozilla.org/network/cache-service;1"];
var service = nsCacheService.getService(Components.interfaces.nsICacheService);
return service;
}
function createCacheSession(clientID, storagePolicy, streamable)
{
var service = getCacheService();
var session = service.createSession(clientID, storagePolicy, streamable);
return session;
}
function openCacheEntry(url, mode)
{
var session = createCacheSession(clientID, nsICache.STORE_ON_DISK, true);
var entry = session.openCacheEntry(url, mode);
return entry;
}
function wrapInputStream(input)
{
var nsIScriptableInputStream = Components.interfaces.nsIScriptableInputStream;
var factory = Components.classes["@mozilla.org/scriptableinputstream;1"];
var wrapper = factory.createInstance(nsIScriptableInputStream);
wrapper.init(input);
return wrapper;
}
function getIOService()
{
var CID = Components.classes["@mozilla.org/network/io-service;1"];
var service = CID.getService(Components.interfaces.nsIIOService);
return service;
}
function downloadHTTP(spec)
{
var ioService = getIOService();
var uri = ioService.newURI(spec, null, null);
var channel = ioService.newChannelFromURI(uri);
var input = wrapInputStream(channel.open());
var data = input.read(input.available());
input.close();
return data;
}
function download(url)
{
var data = "";
var buffer = java.lang.reflect.Array.newInstance(java.lang.Byte.TYPE, 65536);
var stream = url.getContent();
while (true) {
var count = stream.read(buffer);
if (count <= 0)
break;
var str = new java.lang.String(buffer, 0, count);
data += str;
}
stream.close();
return data;
}
function write(url, data)
{
var key = url.toString();
var outputEntry = openCacheEntry(key, nsICache.ACCESS_WRITE);
var output = outputEntry.transport.openOutputStream(0, -1, 0);
var count = output.write(data, data.length);
// store some metadata.
outputEntry.setMetaDataElement("size", data.length);
output.close();
outputEntry.markValid();
outputEntry.close();
return count;
}
function read(url)
{
var key = url.toString();
var inputEntry = openCacheEntry(key, nsICache.ACCESS_READ);
var input = wrapInputStream(inputEntry.transport.openInputStream(0, -1, 0));
var data = input.read(input.available());
input.close();
inputEntry.close();
return data;
}
function readMetaData(url, element)
{
var key = url.toString();
var inputEntry = openCacheEntry(key, nsICache.ACCESS_READ);
var metadata = inputEntry.getMetaDataElement(element);
inputEntry.close();
return metadata;
}
function doom(url)
{
var key = url.toString();
var doomedEntry = openCacheEntry(key, nsICache.ACCESS_READ_WRITE);
doomedEntry.doom();
doomedEntry.close();
}
function test()
{
// download some real content from the network.
var url = new java.net.URL("http://www.mozilla.org");
var key = url.toString();
var data = download(url);
if (write(url, data) == data.length)
print("disk cache write works!");
else
print("disk cache write broken!");
if (read(url) == data)
print("disk cache read works!");
else
print("disk cache read broken!");
if (readMetaData(url, "size") == data.length)
print("disk cache metadata works!");
else
print("disk cache metadata broken!");
}
function median(array)
{
var cmp = function(x, y) { return x - y; }
array.sort(cmp);
var middle = Math.floor(array.length / 2);
return array[middle];
}
function sum(array)
{
var s = 0;
var len = array.length;
for (var i = 0; i < len; ++i)
s += array[i];
return s;
}
function time()
{
var N = 50;
var System = java.lang.System;
var url = new java.net.URL("http://www.mozilla.org");
var downloadTimes = new Array();
for (var i = 0; i < N; ++i) {
var begin = System.currentTimeMillis();
download(url);
var end = System.currentTimeMillis();
downloadTimes.push(end - begin);
}
var downloadTotal = sum(downloadTimes);
var downloadMean = downloadTotal / N;
var downloadMedian = median(downloadTimes);
print("" + N + " downloads took " + downloadTotal + " milliseconds.");
print("mean = " + downloadMean + " milliseconds.");
print("median = " + downloadMedian + " milliseconds.");
var readTimes = new Array();
for (var i = 0; i < N; ++i) {
var begin = System.currentTimeMillis();
read(url);
var end = System.currentTimeMillis();
readTimes.push(end - begin);
}
var readTotal = sum(readTimes);
var readMean = readTotal / N;
var readMedian = median(readTimes);
print("" + N + " reads took " + readTotal + " milliseconds.");
print("mean = " + readMean + " milliseconds.");
print("median = " + readMedian + " milliseconds.");
}
// load the cache service before doing anything with Java...
getCacheService();
if (DEBUG) {
print("cache service loaded.");
} else {
print("running disk cache test.");
test();
print("disk cache test complete.");
}

View File

@@ -1,199 +0,0 @@
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*-
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
#include "nspr.h"
#include "nscore.h"
#include "nsError.h"
#include "nsIServiceManager.h"
#include "nsNetCID.h"
#include "nsICache.h"
#include "nsICacheService.h"
#include "nsICacheSession.h"
#include "nsICacheEntryDescriptor.h"
#include "nsICacheListener.h"
#include "nsIDNSService.h"
#include "nsXPCOM.h"
#include "nsISupportsPrimitives.h"
#include "nsSupportsPrimitives.h"
#include "nsIEventQueueService.h"
static NS_DEFINE_CID(kEventQueueServiceCID, NS_EVENTQUEUESERVICE_CID);
static NS_DEFINE_CID(kCacheServiceCID, NS_CACHESERVICE_CID);
nsCOMPtr<nsIEventQueue> gEventQ;
nsCOMPtr<nsICacheService> gCacheService;
class AsyncCacheRequest
{
public:
AsyncCacheRequest(const char * key);
~AsyncCacheRequest();
const char * mKey;
};
nsresult
MakeCacheSession(const char * clientID, nsICacheSession **session)
{
nsresult rv;
if (!gCacheService) {
// nsCOMPtr<nsICacheService> cacheService =
// do_GetService(kCacheServiceCID, &rv);
gCacheService = do_GetService(kCacheServiceCID, &rv);
if (NS_FAILED(rv) || !gCacheService) {
printf("do_GetService(kCacheServiceCID) failed : %x\n", rv);
goto error_exit;
}
}
rv = gCacheService->CreateSession(clientID,
nsICache::STORE_IN_MEMORY,
nsICache::NOT_STREAM_BASED,
session);
if (NS_FAILED(rv))
printf("nsCacheService::CreateSession() failed : %x\n", rv);
error_exit:
return rv;
}
void
TestMemoryObjectCache()
{
printf("\nTesting Memory Object Cache:\n");
nsCOMPtr<nsICacheSession> session;
nsresult rv = MakeCacheSession("testClientID", getter_AddRefs(session));
if (NS_FAILED(rv)) return;
nsCOMPtr<nsICacheEntryDescriptor> descriptor;
// Test ACCESS_READ for nonexistent entry
printf("\nTest ACCESS_READ:\n");
rv = session->OpenCacheEntry(NS_LITERAL_CSTRING("nonexistent entry"),
nsICache::ACCESS_READ,
nsICache::BLOCKING,
getter_AddRefs(descriptor));
if (rv != NS_ERROR_CACHE_KEY_NOT_FOUND)
printf("OpenCacheEntry(ACCESS_READ) returned: %x for nonexistent entry\n", rv);
NS_NAMED_LITERAL_CSTRING(cacheKey, "http://www.mozilla.org/somekey");
// Test creating new entry
printf("\nTest ACCESS_READ_WRITE:\n");
rv = session->OpenCacheEntry(cacheKey,
nsICache::ACCESS_READ_WRITE,
nsICache::BLOCKING,
getter_AddRefs(descriptor));
if (NS_FAILED(rv)) {
printf("OpenCacheEntry(ACCESS_READ_WRITE) failed: %x\n", rv);
goto error_exit;
}
nsCOMPtr<nsISupportsCString> foo =
do_CreateInstance(NS_SUPPORTS_CSTRING_CONTRACTID, &rv);
foo->SetData(NS_LITERAL_CSTRING("hello world"));
rv = descriptor->SetCacheElement(foo);
rv = descriptor->SetDataSize(11);
rv = descriptor->SetMetaDataElement("itemOne", "metaData works");
descriptor = nullptr;
// Test refetching entry
rv = session->OpenCacheEntry(cacheKey,
nsICache::ACCESS_READ_WRITE,
nsICache::BLOCKING,
getter_AddRefs(descriptor));
if (NS_FAILED(rv)) {
printf("OpenCacheEntry(ACCESS_READ_WRITE #2) failed: %x", rv);
goto error_exit;
}
nsCOMPtr<nsISupportsCString> bar;
descriptor->GetCacheElement(getter_AddRefs(bar));
if (foo.get() != bar.get()) {
printf("cache elements not the same\n");
} else {
printf("data matches...\n");
}
char * metaData;
rv = descriptor->GetMetaDataElement("itemOne", &metaData);
if (NS_SUCCEEDED(rv)) printf("metaData = %s\n", metaData);
else printf("GetMetaDataElement failed : rv = %x\n", rv);
descriptor = nullptr;
// Test ACCESS_WRITE entry
printf("\nTest ACCESS_WRITE:\n");
rv = session->OpenCacheEntry(cacheKey,
nsICache::ACCESS_WRITE,
nsICache::BLOCKING,
getter_AddRefs(descriptor));
if (NS_FAILED(rv)) {
printf("OpenCacheEntry(ACCESS_WRITE) failed: %x", rv);
goto error_exit;
}
rv = descriptor->GetCacheElement(getter_AddRefs(bar));
if (bar)
printf("FAILED: we didn't get new entry.\n");
if (NS_FAILED(rv))
printf("GetCacheElement failed : %x\n", rv);
rv = descriptor->GetMetaDataElement("itemOne", &metaData);
if (NS_SUCCEEDED(rv))
if (metaData) printf("metaData = %s\n", metaData);
else printf("metaData = nullptr\n");
else printf("GetMetaDataElement failed : rv = %x\n", rv);
printf("\n");
error_exit:
return;
}
int
main(int argc, char* argv[])
{
nsresult rv = NS_OK;
// Start up XPCOM
rv = NS_InitXPCOM2(nullptr, nullptr, nullptr);
if (NS_FAILED(rv)) return rv;
/**
* Create event queue for this thread
*/
nsCOMPtr<nsIEventQueueService> eventQService =
do_GetService(kEventQueueServiceCID, &rv);
if (NS_FAILED(rv)) goto error_exit;
eventQService->GetThreadEventQueue(NS_CURRENT_THREAD, getter_AddRefs(gEventQ));
/**
* Test Cache
*/
TestMemoryObjectCache();
error_exit:
gEventQ = nullptr;
eventQService = nullptr;
NS_ShutdownXPCOM(nullptr);
printf("XPCOM shut down.\n\n");
return rv;
}

View File

@@ -1,54 +0,0 @@
var DEBUG = true;
var clientID = "javascript";
var nsICache = Components.interfaces.nsICache;
function getCacheService()
{
var nsCacheService = Components.classes["@mozilla.org/network/cache-service;1"];
var service = nsCacheService.getService(Components.interfaces.nsICacheService);
return service;
}
function CacheVisitor()
{
}
CacheVisitor.prototype = {
QueryInterface : function(iid)
{
if (iid.equals(Components.interfaces.nsICacheVisitor))
return this;
throw Components.results.NS_NOINTERFACE;
},
visitDevice : function(deviceID, deviceInfo)
{
print("[visiting device (deviceID = " + deviceID + ", description = " + deviceInfo.description + ")]");
return true;
},
visitEntry : function(deviceID, entryInfo)
{
print("[visiting entry (clientID = " + entryInfo.clientID + ", key = " + entryInfo.key + ")]");
return true;
}
};
function test()
{
var cacheService = getCacheService();
var visitor = new CacheVisitor();
cacheService.visitEntries(visitor);
}
// load the cache service before doing anything with Java...
getCacheService();
if (DEBUG) {
print("cache service loaded.");
} else {
print("running cache visitor test.");
test();
print("cache visitor test complete.");
}

View File

@@ -1,84 +0,0 @@
var DEBUG = false;
var clientID = "javascript";
var key = "theme:button";
var nsICache = Components.interfaces.nsICache;
function getCacheService()
{
var nsCacheService = Components.classes["@mozilla.org/network/cache-service;1"];
var service = nsCacheService.getService(Components.interfaces.nsICacheService);
return service;
}
function createCacheSession(clientID, storagePolicy, streamable)
{
var service = getCacheService();
var session = service.createSession(clientID, storagePolicy, streamable);
return session;
}
function openCacheEntry(mode)
{
var session = createCacheSession(clientID, nsICache.STORE_ON_DISK, true);
var entry = session.openCacheEntry(key, mode);
return entry;
}
function wrapInputStream(input)
{
var nsIScriptableInputStream = Components.interfaces.nsIScriptableInputStream;
var factory = Components.classes["@mozilla.org/scriptableinputstream;1"];
var wrapper = factory.createInstance(nsIScriptableInputStream);
wrapper.init(input);
return wrapper;
}
function test()
{
var outputEntry = openCacheEntry(nsICache.ACCESS_WRITE);
var output = outputEntry.transport.openOutputStream(0, -1, 0);
if (output.write("foo", 3) == 3)
print("disk cache write works!");
else
print("disk cache write broken!");
// store some metadata.
outputEntry.setMetaDataElement("size", "3");
output.close();
outputEntry.markValid();
outputEntry.close();
var inputEntry = openCacheEntry(nsICache.ACCESS_READ);
var input = wrapInputStream(inputEntry.transport.openInputStream(0, -1, 0));
if (input.read(input.available()) == "foo")
print("disk cache read works!");
else
print("disk cache read broken!");
if (inputEntry.getMetaDataElement("size") == "3")
print("disk cache metadata works!");
else
print("disk cache metadata broken!");
input.close();
inputEntry.close();
}
function doom()
{
var doomedEntry = openCacheEntry(nsICache.ACCESS_READ_WRITE);
doomedEntry.doom();
doomedEntry.close();
}
if (DEBUG) {
getCacheService();
print("cache service loaded.");
} else {
print("running disk cache test.");
test();
print("disk cache test complete.");
}

View File

@@ -1,226 +0,0 @@
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
#include <stdio.h>
#include "nsIServiceManager.h"
#include "nsIEventQueueService.h"
#include "nsIOutputStream.h"
#include "nsIStreamListener.h"
#include "nsITransport.h"
#include "nsIInputStream.h"
#include "nsIOutputStream.h"
#include "nsCOMPtr.h"
#include "plstr.h"
#include "prprf.h"
#include <algorithm>
#ifndef USE_CREATE_INSTANCE
#include "nsICacheService.h"
#include "nsICacheSession.h"
#include "nsICacheEntryDescriptor.h"
#include "nsNetCID.h"
static NS_DEFINE_CID(kCacheServiceCID, NS_CACHESERVICE_CID);
static nsICacheSession *session = nullptr;
static nsICacheEntryDescriptor *desc = nullptr;
#endif
/**
* This test program exercises the memory cache's nsITransport implementation.
*
* This test program loads a file into the memory cache (using OpenOutputStream),
* and then reads the file back out (using AsyncRead). The data read from the
* memory cache is written to a new file (with .out added as a suffix to the file
* name).
*/
static NS_DEFINE_CID(kEventQueueServiceCID, NS_EVENTQUEUESERVICE_CID);
static nsIEventQueue *gEventQ = nullptr;
class TestListener : public nsIStreamListener
{
public:
NS_DECL_ISUPPORTS
NS_DECL_NSISTREAMLISTENER
NS_DECL_NSIREQUESTOBSERVER
TestListener(char *);
virtual ~TestListener();
private:
char *mFilename;
FILE *mFile;
};
NS_IMPL_ISUPPORTS(TestListener,
nsIStreamListener,
nsIRequestObserver)
TestListener::TestListener(char *filename)
: mFilename(filename)
, mFile(nullptr)
{
}
TestListener::~TestListener()
{
}
NS_IMETHODIMP
TestListener::OnStartRequest(nsIRequest *req, nsISupports *ctx)
{
printf("OnStartRequest\n");
mFile = fopen(mFilename, "w");
if (!mFile)
return NS_ERROR_FAILURE;
return NS_OK;
}
NS_IMETHODIMP
TestListener::OnStopRequest(nsIRequest *req, nsISupports *ctx, nsresult status)
{
printf("OnStopRequest: status=%x\n", status);
if (mFile)
fclose(mFile);
return NS_OK;
}
NS_IMETHODIMP
TestListener::OnDataAvailable(nsIRequest *req, nsISupports *ctx,
nsIInputStream *is,
uint64_t offset, uint32_t count)
{
printf("OnDataAvailable: offset=%llu count=%u\n", offset, count);
if (!mFile) return NS_ERROR_FAILURE;
char buf[128];
nsresult rv;
uint32_t nread = 0;
while (count) {
uint32_t amount = std::min<uint32_t>(count, sizeof(buf));
rv = is->Read(buf, amount, &nread);
if (NS_FAILED(rv)) return rv;
fwrite(buf, nread, 1, mFile);
count -= nread;
}
return NS_OK;
}
nsresult TestMCTransport(const char *filename)
{
nsresult rv = NS_OK;
nsCOMPtr<nsITransport> transport;
#ifdef USE_CREATE_INSTANCE
transport = do_CreateInstance(
"@mozilla.org/network/memory-cache-transport;1", &rv);
if (NS_FAILED(rv))
return rv;
#else
nsCOMPtr<nsICacheService> serv(do_GetService(kCacheServiceCID, &rv));
if (NS_FAILED(rv)) return rv;
rv = serv->CreateSession("TestMCTransport",
nsICache::STORE_IN_MEMORY, true,
&session);
if (NS_FAILED(rv)) return rv;
rv = session->OpenCacheEntry(nsDependentCString(filename),
nsICache::ACCESS_READ_WRITE,
nsICache::BLOCKING,
&desc);
if (NS_FAILED(rv)) return rv;
rv = desc->MarkValid();
if (NS_FAILED(rv)) return rv;
rv = desc->GetTransport(getter_AddRefs(transport));
if (NS_FAILED(rv)) return rv;
#endif
nsCOMPtr<nsIOutputStream> os;
rv = transport->OpenOutputStream(0, (uint32_t) -1, 0, getter_AddRefs(os));
if (NS_FAILED(rv)) return rv;
char *out = PR_smprintf("%s.out", filename);
nsCOMPtr<nsIStreamListener> listener = new TestListener(out);
if (!listener)
return NS_ERROR_OUT_OF_MEMORY;
nsCOMPtr<nsIRequest> req;
rv = transport->AsyncRead(listener, nullptr, 0, (uint32_t) -1, 0, getter_AddRefs(req));
if (NS_FAILED(rv)) return rv;
FILE *file = fopen(filename, "r");
if (!file)
return NS_ERROR_FILE_NOT_FOUND;
char buf[256];
uint32_t count, total=0;
while ((count = fread(buf, 1, sizeof(buf), file)) > 0) {
printf("writing %u bytes\n", count);
total += count;
rv = os->Write(buf, count, &count);
if (NS_FAILED(rv)) return rv;
// process an event
PLEvent *event = nullptr;
gEventQ->GetEvent(&event);
if (event) gEventQ->HandleEvent(event);
}
printf("wrote %u bytes\n", total);
return rv;
}
int main(int argc, char **argv)
{
nsresult rv;
if (argc < 2) {
printf("usage: %s filename\n", argv[0]);
return -1;
}
nsCOMPtr<nsIEventQueueService> eqs =
do_GetService(kEventQueueServiceCID, &rv);
if (NS_FAILED(rv)) {
printf("failed to create event queue service: rv=%x\n", rv);
return -1;
}
rv = eqs->CreateMonitoredThreadEventQueue();
if (NS_FAILED(rv)) {
printf("failed to create monitored event queue: rv=%x\n", rv);
return -1;
}
rv = eqs->GetThreadEventQueue(NS_CURRENT_THREAD, &gEventQ);
if (NS_FAILED(rv)) {
printf("failed to get thread event queue: %x\n", rv);
return -1;
}
rv = TestMCTransport(argv[1]);
printf("TestMCTransport returned %x\n", rv);
gEventQ->ProcessPendingEvents();
#ifndef USE_CREATE_INSTANCE
NS_IF_RELEASE(desc);
NS_IF_RELEASE(session);
#endif
return 0;
}

View File

@@ -1,48 +0,0 @@
function getCacheService()
{
var nsCacheService = Components.classes["@mozilla.org/network/cache-service;1"];
var service = nsCacheService.getService(Components.interfaces.nsICacheService);
return service;
}
function createCacheSession(clientID, storagePolicy, streamable)
{
var service = getCacheService();
var nsICache = Components.interfaces.nsICache;
var session = service.createSession(clientID, storagePolicy, streamable);
return session;
}
function openCacheEntry(clientID, url)
{
var nsICache = Components.interfaces.nsICache;
var session = createCacheSession(clientID, nsICache.STORE_ANYWHERE, false);
var entry = session.openCacheEntry(url, nsICache.ACCESS_READ_WRITE);
return entry;
}
function wrapString(str)
{
var nsISupportsCString = Components.interfaces.nsISupportsCString;
var factory = Components.classes["@mozilla.org/supports-cstring;1"];
var wrapper = factory.createInstance(nsISupportsCString);
wrapper.data = str;
return wrapper;
}
function test()
{
var data = wrapString("javascript");
var entry = openCacheEntry("javascript", "theme:button");
entry.cacheElement = data;
entry.markValid();
entry.close();
var newEntry = openCacheEntry("javascript", "theme:button");
if (newEntry.cacheElement === data)
print("object cache works.");
else
print("object cache failed.");
}
test();

View File

@@ -22,8 +22,8 @@ Cu.import("resource://gre/modules/Services.jsm");
const kNS_OFFLINECACHEUPDATESERVICE_CONTRACTID =
"@mozilla.org/offlinecacheupdate-service;1";
const kNS_CACHESERVICE_CONTRACTID =
"@mozilla.org/network/cache-service;1";
const kNS_CACHESTORAGESERVICE_CONTRACTID =
"@mozilla.org/netwerk/cache-storage-service;1";
const kNS_APPLICATIONCACHESERVICE_CONTRACTID =
"@mozilla.org/network/application-cache-service;1";
@@ -85,9 +85,10 @@ function init_http_server() {
}
function clean_app_cache() {
let cache_service = Cc[kNS_CACHESERVICE_CONTRACTID].
getService(Ci.nsICacheService);
cache_service.evictEntries(Ci.nsICache.STORE_OFFLINE);
let cache_service = Cc[kNS_CACHESTORAGESERVICE_CONTRACTID].
getService(Ci.nsICacheStorageService);
let storage = cache_service.appCacheStorage(LoadContextInfo.default, null);
storage.asyncEvictStorage(null);
}
function do_app_cache(manifestURL, pageURL) {

View File

@@ -6,7 +6,6 @@
#include "AsyncFaviconHelpers.h"
#include "nsICacheService.h"
#include "nsICacheEntry.h"
#include "nsICachingChannel.h"
#include "nsIAsyncVerifyRedirectCallback.h"

View File

@@ -11,7 +11,6 @@
#include "nsCOMArray.h"
#include "nsCOMPtr.h"
#include "nsICacheService.h"
#include "nsIDOMDocument.h"
#include "nsIObserver.h"
#include "nsIObserverService.h"

View File

@@ -15,8 +15,6 @@
#include "nsIApplicationCacheChannel.h"
#include "nsIApplicationCacheService.h"
#include "nsICache.h"
#include "nsICacheService.h"
#include "nsICacheSession.h"
#include "nsICachingChannel.h"
#include "nsIContent.h"
#include "mozilla/dom/Element.h"

View File

@@ -11,7 +11,6 @@
#include "nsAutoPtr.h"
#include "nsCOMArray.h"
#include "nsCOMPtr.h"
#include "nsICacheService.h"
#include "nsIChannelEventSink.h"
#include "nsIDOMDocument.h"
#include "nsIDOMNode.h"

View File

@@ -18,9 +18,6 @@
#include "nsIApplicationCacheContainer.h"
#include "nsIApplicationCacheChannel.h"
#include "nsIApplicationCacheService.h"
#include "nsICache.h"
#include "nsICacheService.h"
#include "nsICacheSession.h"
#include "nsICachingChannel.h"
#include "nsIContent.h"
#include "nsIDocShell.h"