Qt 4.8
Public Slots | Public Functions | Protected Functions | List of all members
QNetworkDiskCache Class Reference

The QNetworkDiskCache class provides a very basic disk cache. More...

#include <qnetworkdiskcache.h>

Inheritance diagram for QNetworkDiskCache:
QAbstractNetworkCache QObject

Public Slots

void clear ()
 Reimplemented Function More...
 
- Public Slots inherited from QAbstractNetworkCache
virtual void clear ()=0
 Removes all items from the cache. More...
 
- Public Slots inherited from QObject
void deleteLater ()
 Schedules this object for deletion. More...
 

Public Functions

QString cacheDirectory () const
 Returns the location where cached files will be stored. More...
 
qint64 cacheSize () const
 Reimplemented Function More...
 
QIODevicedata (const QUrl &url)
 Reimplemented Function More...
 
QNetworkCacheMetaData fileMetaData (const QString &fileName) const
 Returns the QNetworkCacheMetaData for the cache file fileName. More...
 
void insert (QIODevice *device)
 Reimplemented Function More...
 
qint64 maximumCacheSize () const
 Returns the current maximum size in bytes for the disk cache. More...
 
QNetworkCacheMetaData metaData (const QUrl &url)
 Reimplemented Function More...
 
QIODeviceprepare (const QNetworkCacheMetaData &metaData)
 Reimplemented Function More...
 
 QNetworkDiskCache (QObject *parent=0)
 Creates a new disk cache. More...
 
bool remove (const QUrl &url)
 Reimplemented Function More...
 
void setCacheDirectory (const QString &cacheDir)
 Sets the directory where cached files will be stored to cacheDir. More...
 
void setMaximumCacheSize (qint64 size)
 Sets the maximum size of the disk cache to be size in bytes. More...
 
void updateMetaData (const QNetworkCacheMetaData &metaData)
 Reimplemented Function More...
 
 ~QNetworkDiskCache ()
 Destroys the cache object. More...
 
- Public Functions inherited from QAbstractNetworkCache
virtual ~QAbstractNetworkCache ()
 Destroys the cache. More...
 
- Public Functions inherited from QObject
bool blockSignals (bool b)
 If block is true, signals emitted by this object are blocked (i.e., emitting a signal will not invoke anything connected to it). More...
 
const QObjectListchildren () const
 Returns a list of child objects. More...
 
bool connect (const QObject *sender, const char *signal, const char *member, Qt::ConnectionType type=Qt::AutoConnection) const
 
bool disconnect (const char *signal=0, const QObject *receiver=0, const char *member=0)
 
bool disconnect (const QObject *receiver, const char *member=0)
 
void dumpObjectInfo ()
 Dumps information about signal connections, etc. More...
 
void dumpObjectTree ()
 Dumps a tree of children to the debug output. More...
 
QList< QByteArraydynamicPropertyNames () const
 Returns the names of all properties that were dynamically added to the object using setProperty(). More...
 
virtual bool event (QEvent *)
 This virtual function receives events to an object and should return true if the event e was recognized and processed. More...
 
virtual bool eventFilter (QObject *, QEvent *)
 Filters events if this object has been installed as an event filter for the watched object. More...
 
template<typename T >
findChild (const QString &aName=QString()) const
 Returns the child of this object that can be cast into type T and that is called name, or 0 if there is no such object. More...
 
template<typename T >
QList< T > findChildren (const QString &aName=QString()) const
 Returns all children of this object with the given name that can be cast to type T, or an empty list if there are no such objects. More...
 
template<typename T >
QList< T > findChildren (const QRegExp &re) const
 
bool inherits (const char *classname) const
 Returns true if this object is an instance of a class that inherits className or a QObject subclass that inherits className; otherwise returns false. More...
 
void installEventFilter (QObject *)
 Installs an event filter filterObj on this object. More...
 
bool isWidgetType () const
 Returns true if the object is a widget; otherwise returns false. More...
 
void killTimer (int id)
 Kills the timer with timer identifier, id. More...
 
virtual const QMetaObjectmetaObject () const
 Returns a pointer to the meta-object of this object. More...
 
void moveToThread (QThread *thread)
 Changes the thread affinity for this object and its children. More...
 
QString objectName () const
 
QObjectparent () const
 Returns a pointer to the parent object. More...
 
QVariant property (const char *name) const
 Returns the value of the object's name property. More...
 
Q_INVOKABLE QObject (QObject *parent=0)
 Constructs an object with parent object parent. More...
 
void removeEventFilter (QObject *)
 Removes an event filter object obj from this object. More...
 
void setObjectName (const QString &name)
 
void setParent (QObject *)
 Makes the object a child of parent. More...
 
bool setProperty (const char *name, const QVariant &value)
 Sets the value of the object's name property to value. More...
 
void setUserData (uint id, QObjectUserData *data)
 
bool signalsBlocked () const
 Returns true if signals are blocked; otherwise returns false. More...
 
int startTimer (int interval)
 Starts a timer and returns a timer identifier, or returns zero if it could not start a timer. More...
 
QThreadthread () const
 Returns the thread in which the object lives. More...
 
QObjectUserDatauserData (uint id) const
 
virtual ~QObject ()
 Destroys the object, deleting all its child objects. More...
 

Protected Functions

virtual qint64 expire ()
 Cleans the cache so that its size is under the maximum cache size. More...
 
- Protected Functions inherited from QAbstractNetworkCache
 QAbstractNetworkCache (QObject *parent=0)
 Constructs an abstract network cache with the given parent. More...
 
 QAbstractNetworkCache (QAbstractNetworkCachePrivate &dd, QObject *parent)
 
- Protected Functions inherited from QObject
virtual void childEvent (QChildEvent *)
 This event handler can be reimplemented in a subclass to receive child events. More...
 
virtual void connectNotify (const char *signal)
 This virtual function is called when something has been connected to signal in this object. More...
 
virtual void customEvent (QEvent *)
 This event handler can be reimplemented in a subclass to receive custom events. More...
 
virtual void disconnectNotify (const char *signal)
 This virtual function is called when something has been disconnected from signal in this object. More...
 
 QObject (QObjectPrivate &dd, QObject *parent=0)
 
int receivers (const char *signal) const
 Returns the number of receivers connected to the signal. More...
 
QObjectsender () const
 Returns a pointer to the object that sent the signal, if called in a slot activated by a signal; otherwise it returns 0. More...
 
int senderSignalIndex () const
 
virtual void timerEvent (QTimerEvent *)
 This event handler can be reimplemented in a subclass to receive timer events for the object. More...
 

Additional Inherited Members

- Signals inherited from QObject
void destroyed (QObject *=0)
 This signal is emitted immediately before the object obj is destroyed, and can not be blocked. More...
 
- Static Public Functions inherited from QObject
static bool connect (const QObject *sender, const char *signal, const QObject *receiver, const char *member, Qt::ConnectionType=Qt::AutoConnection)
 Creates a connection of the given type from the signal in the sender object to the method in the receiver object. More...
 
static bool connect (const QObject *sender, const QMetaMethod &signal, const QObject *receiver, const QMetaMethod &method, Qt::ConnectionType type=Qt::AutoConnection)
 
static bool disconnect (const QObject *sender, const char *signal, const QObject *receiver, const char *member)
 Disconnects signal in object sender from method in object receiver. More...
 
static bool disconnect (const QObject *sender, const QMetaMethod &signal, const QObject *receiver, const QMetaMethod &member)
 
static uint registerUserData ()
 
static QString tr (const char *sourceText, const char *comment=0, int n=-1)
 
static QString trUtf8 (const char *sourceText, const char *comment=0, int n=-1)
 
- Static Public Variables inherited from QObject
static const QMetaObject staticMetaObject
 This variable stores the meta-object for the class. More...
 
- Protected Variables inherited from QObject
QScopedPointer< QObjectDatad_ptr
 
- Static Protected Variables inherited from QObject
static const QMetaObject staticQtMetaObject
 

Detailed Description

The QNetworkDiskCache class provides a very basic disk cache.

Since
4.5
Attention
Module: QtNetwork

QNetworkDiskCache stores each url in its own file inside of the cacheDirectory using QDataStream. Files with a text MimeType are compressed using qCompress. Each cache file starts with "cache_" and ends in ".cache". Data is written to disk only in insert() and updateMetaData().

Currently you can not share the same cache files with more then one disk cache.

QNetworkDiskCache by default limits the amount of space that the cache will use on the system to 50MB.

Note you have to set the cache directory before it will work.

A network disk cache can be enabled by:

QNetworkDiskCache *diskCache = new QNetworkDiskCache(this);
diskCache->setCacheDirectory("cacheDir");
manager->setCache(diskCache);

When sending requests, to control the preference of when to use the cache and when to use the network, consider the following:

// do a normal request (preferred from network, as this is the default)
QNetworkRequest request(QUrl(QString("http://qt.nokia.com")));
manager->get(request);
// do a request preferred from cache
QNetworkRequest request2(QUrl(QString("http://qt.nokia.com")));
manager->get(request2);

To check whether the response came from the cache or from the network, the following can be applied:

void replyFinished(QNetworkReply *reply) {
qDebug() << "page from cache?" << fromCache.toBool();
}

Definition at line 56 of file qnetworkdiskcache.h.

Constructors and Destructors

◆ QNetworkDiskCache()

QNetworkDiskCache::QNetworkDiskCache ( QObject parent = 0)
explicit

Creates a new disk cache.

The parent argument is passed to QAbstractNetworkCache's constructor.

Definition at line 111 of file qnetworkdiskcache.cpp.

113 {
114 }
QAbstractNetworkCache(QObject *parent=0)
Constructs an abstract network cache with the given parent.

◆ ~QNetworkDiskCache()

QNetworkDiskCache::~QNetworkDiskCache ( )

Destroys the cache object.

This does not clear the disk cache.

Definition at line 119 of file qnetworkdiskcache.cpp.

120 {
122  QHashIterator<QIODevice*, QCacheItem*> it(d->inserting);
123  while (it.hasNext()) {
124  it.next();
125  delete it.value();
126  }
127 }
double d
Definition: qnumeric_p.h:62
#define it(className, varName)
The QNetworkDiskCache class provides a very basic disk cache.
#define Q_D(Class)
Definition: qglobal.h:2482

Functions

◆ cacheDirectory()

QString QNetworkDiskCache::cacheDirectory ( ) const

Returns the location where cached files will be stored.

Definition at line 132 of file qnetworkdiskcache.cpp.

Referenced by expire(), QNetworkDiskCachePrivate::prepareLayout(), and QNetworkDiskCachePrivate::tmpCacheFileName().

133 {
134  Q_D(const QNetworkDiskCache);
135  return d->cacheDirectory;
136 }
double d
Definition: qnumeric_p.h:62
The QNetworkDiskCache class provides a very basic disk cache.
#define Q_D(Class)
Definition: qglobal.h:2482

◆ cacheSize()

qint64 QNetworkDiskCache::cacheSize ( ) const
virtual

Reimplemented Function

Implements QAbstractNetworkCache.

Definition at line 169 of file qnetworkdiskcache.cpp.

170 {
171 #if defined(QNETWORKDISKCACHE_DEBUG)
172  qDebug() << "QNetworkDiskCache::cacheSize()";
173 #endif
174  Q_D(const QNetworkDiskCache);
175  if (d->cacheDirectory.isEmpty())
176  return 0;
177  if (d->currentCacheSize < 0) {
178  QNetworkDiskCache *that = const_cast<QNetworkDiskCache*>(this);
179  that->d_func()->currentCacheSize = that->expire();
180  }
181  return d->currentCacheSize;
182 }
double d
Definition: qnumeric_p.h:62
The QNetworkDiskCache class provides a very basic disk cache.
#define Q_D(Class)
Definition: qglobal.h:2482
Q_CORE_EXPORT void qDebug(const char *,...)
virtual qint64 expire()
Cleans the cache so that its size is under the maximum cache size.

◆ clear

void QNetworkDiskCache::clear ( )
slot

Reimplemented Function

Definition at line 584 of file qnetworkdiskcache.cpp.

585 {
586 #if defined(QNETWORKDISKCACHE_DEBUG)
587  qDebug() << "QNetworkDiskCache::clear()";
588 #endif
590  qint64 size = d->maximumCacheSize;
591  d->maximumCacheSize = 0;
592  d->currentCacheSize = expire();
593  d->maximumCacheSize = size;
594 }
double d
Definition: qnumeric_p.h:62
The QNetworkDiskCache class provides a very basic disk cache.
#define Q_D(Class)
Definition: qglobal.h:2482
Q_CORE_EXPORT void qDebug(const char *,...)
__int64 qint64
Definition: qglobal.h:942
virtual qint64 expire()
Cleans the cache so that its size is under the maximum cache size.

◆ data()

QIODevice * QNetworkDiskCache::data ( const QUrl url)
virtual

Reimplemented Function

Implements QAbstractNetworkCache.

Definition at line 404 of file qnetworkdiskcache.cpp.

Referenced by QCacheItem::read(), updateMetaData(), and QCacheItem::writeCompressedData().

405 {
406 #if defined(QNETWORKDISKCACHE_DEBUG)
407  qDebug() << "QNetworkDiskCache::data()" << url;
408 #endif
411  if (!url.isValid())
412  return 0;
413  if (d->lastItem.metaData.url() == url && d->lastItem.data.isOpen()) {
414  buffer.reset(new QBuffer);
415  buffer->setData(d->lastItem.data.data());
416  } else {
417  QScopedPointer<QFile> file(new QFile(d->cacheFileName(url)));
418  if (!file->open(QFile::ReadOnly | QIODevice::Unbuffered))
419  return 0;
420 
421  if (!d->lastItem.read(file.data(), true)) {
422  file->close();
423  remove(url);
424  return 0;
425  }
426  if (d->lastItem.data.isOpen()) {
427  // compressed
428  buffer.reset(new QBuffer);
429  buffer->setData(d->lastItem.data.data());
430  } else {
431  buffer.reset(new QBuffer);
432  // ### verify that QFile uses the fd size and not the file name
433  qint64 size = file->size() - file->pos();
434  const uchar *p = 0;
435 #if !defined(Q_OS_WINCE) && !defined(Q_OS_INTEGRITY) && !defined(Q_OS_SYMBIAN)
436  p = file->map(file->pos(), size);
437 #endif
438  if (p) {
439  buffer->setData((const char *)p, size);
440  file.take()->setParent(buffer.data());
441  } else {
442  buffer->setData(file->readAll());
443  }
444  }
445  }
446  buffer->open(QBuffer::ReadOnly);
447  return buffer.take();
448 }
double d
Definition: qnumeric_p.h:62
bool isValid() const
Returns true if the URL is valid; otherwise returns false.
Definition: qurl.cpp:4303
T * data() const
Returns the value of the pointer referenced by this object.
void setData(const QByteArray &data)
Sets the contents of the internal buffer to be data.
Definition: qbuffer.cpp:315
bool open(OpenMode openMode)
Reimplemented Function
Definition: qbuffer.cpp:338
T * take()
Returns the value of the pointer referenced by this object.
The QNetworkDiskCache class provides a very basic disk cache.
The QBuffer class provides a QIODevice interface for a QByteArray.
Definition: qbuffer.h:57
#define Q_D(Class)
Definition: qglobal.h:2482
The QScopedPointer class stores a pointer to a dynamically allocated object, and deletes it upon dest...
Q_CORE_EXPORT void qDebug(const char *,...)
unsigned char uchar
Definition: qglobal.h:994
__int64 qint64
Definition: qglobal.h:942
void reset(T *other=0)
Deletes the existing object it is pointing to if any, and sets its pointer to other.
The QFile class provides an interface for reading from and writing to files.
Definition: qfile.h:65

◆ expire()

qint64 QNetworkDiskCache::expire ( )
protectedvirtual

Cleans the cache so that its size is under the maximum cache size.

Returns the current size of the cache.

When the current size of the cache is greater than the maximumCacheSize() older cache files are removed until the total size is less then 90% of maximumCacheSize() starting with the oldest ones first using the file creation date to determine how old a cache file is.

Subclasses can reimplement this function to change the order that cache files are removed taking into account information in the application knows about that QNetworkDiskCache does not, for example the number of times a cache is accessed.

Note: cacheSize() calls expire if the current cache size is unknown.

See also
maximumCacheSize(), fileMetaData()

Definition at line 528 of file qnetworkdiskcache.cpp.

Referenced by cacheSize(), clear(), and setMaximumCacheSize().

529 {
531  if (d->currentCacheSize >= 0 && d->currentCacheSize < maximumCacheSize())
532  return d->currentCacheSize;
533 
534  if (cacheDirectory().isEmpty()) {
535  qWarning() << "QNetworkDiskCache::expire() The cache directory is not set";
536  return 0;
537  }
538 
539  // close file handle to prevent "in use" error when QFile::remove() is called
540  d->lastItem.reset();
541 
544 
546  qint64 totalSize = 0;
547  while (it.hasNext()) {
548  QString path = it.next();
549  QFileInfo info = it.fileInfo();
550  QString fileName = info.fileName();
551  if (fileName.endsWith(CACHE_POSTFIX)) {
552  cacheItems.insert(info.created(), path);
553  totalSize += info.size();
554  }
555  }
556 
557  int removedFiles = 0;
558  qint64 goal = (maximumCacheSize() * 9) / 10;
560  while (i != cacheItems.constEnd()) {
561  if (totalSize < goal)
562  break;
563  QString name = i.value();
564  QFile file(name);
565  qint64 size = file.size();
566  file.remove();
567  totalSize -= size;
568  ++removedFiles;
569  ++i;
570  }
571 #if defined(QNETWORKDISKCACHE_DEBUG)
572  if (removedFiles > 0) {
573  qDebug() << "QNetworkDiskCache::expire()"
574  << "Removed:" << removedFiles
575  << "Kept:" << cacheItems.count() - removedFiles;
576  }
577 #endif
578  return totalSize;
579 }
The QMultiMap class is a convenience QMap subclass that provides multi-valued maps.
Definition: qcontainerfwd.h:59
double d
Definition: qnumeric_p.h:62
static mach_timebase_info_data_t info
#define it(className, varName)
QDateTime created() const
Returns the date and time when the file was created.
Definition: qfileinfo.cpp:1278
QMap< Key, T >::iterator insert(const Key &key, const T &value)
Inserts a new item with the key key and a value of value.
Definition: qmap.h:982
The QNetworkDiskCache class provides a very basic disk cache.
QString fileName() const
Returns the name of the file, excluding the path.
Definition: qfileinfo.cpp:726
The QDirIterator class provides an iterator for directory entrylists.
Definition: qdiriterator.h:54
The QString class provides a Unicode character string.
Definition: qstring.h:83
#define Q_D(Class)
Definition: qglobal.h:2482
Q_CORE_EXPORT void qDebug(const char *,...)
static bool isEmpty(const char *str)
const char * name
Q_CORE_EXPORT void qWarning(const char *,...)
__int64 qint64
Definition: qglobal.h:942
const_iterator constBegin() const
Returns a const STL-style iterator pointing to the first item in the map.
Definition: qmap.h:374
int count(const Key &key, const T &value) const
Returns the number of items with key key and value value.
Definition: qmap.h:1071
static const char *const filters[3]
The QMap::const_iterator class provides an STL-style const iterator for QMap and QMultiMap.
Definition: qmap.h:301
const_iterator constEnd() const
Returns a const STL-style iterator pointing to the imaginary item after the last item in the map...
Definition: qmap.h:380
qint64 size() const
Returns the file size in bytes.
Definition: qfileinfo.cpp:1248
The QFile class provides an interface for reading from and writing to files.
Definition: qfile.h:65
const T & value() const
Returns the current item&#39;s value.
Definition: qmap.h:325
QString cacheDirectory() const
Returns the location where cached files will be stored.
bool endsWith(const QString &s, Qt::CaseSensitivity cs=Qt::CaseSensitive) const
Returns true if the string ends with s; otherwise returns false.
Definition: qstring.cpp:3796
The QFileInfo class provides system-independent file information.
Definition: qfileinfo.h:60
static QString fileName(const QString &fileUrl)
#define CACHE_POSTFIX
qint64 maximumCacheSize() const
Returns the current maximum size in bytes for the disk cache.

◆ fileMetaData()

QNetworkCacheMetaData QNetworkDiskCache::fileMetaData ( const QString fileName) const

Returns the QNetworkCacheMetaData for the cache file fileName.

If fileName is not a cache file QNetworkCacheMetaData will be invalid.

Definition at line 384 of file qnetworkdiskcache.cpp.

Referenced by metaData().

385 {
386 #if defined(QNETWORKDISKCACHE_DEBUG)
387  qDebug() << "QNetworkDiskCache::fileMetaData()" << fileName;
388 #endif
389  Q_D(const QNetworkDiskCache);
390  QFile file(fileName);
391  if (!file.open(QFile::ReadOnly))
392  return QNetworkCacheMetaData();
393  if (!d->lastItem.read(&file, false)) {
394  file.close();
396  that->removeFile(fileName);
397  }
398  return d->lastItem.metaData;
399 }
double d
Definition: qnumeric_p.h:62
The QNetworkDiskCache class provides a very basic disk cache.
bool removeFile(const QString &file)
Put all of the misc file removing into one function to be extra safe.
#define Q_D(Class)
Definition: qglobal.h:2482
Q_CORE_EXPORT void qDebug(const char *,...)
The QFile class provides an interface for reading from and writing to files.
Definition: qfile.h:65
static QString fileName(const QString &fileUrl)
The QNetworkCacheMetaData class provides cache information.

◆ insert()

void QNetworkDiskCache::insert ( QIODevice device)
virtual

Reimplemented Function

Implements QAbstractNetworkCache.

Definition at line 238 of file qnetworkdiskcache.cpp.

Referenced by updateMetaData().

239 {
240 #if defined(QNETWORKDISKCACHE_DEBUG)
241  qDebug() << "QNetworkDiskCache::insert()" << device;
242 #endif
244  QHash<QIODevice*, QCacheItem*>::iterator it = d->inserting.find(device);
245  if (it == d->inserting.end()) {
246  qWarning() << "QNetworkDiskCache::insert() called on a device we don't know about" << device;
247  return;
248  }
249 
250  d->storeItem(it.value());
251  delete it.value();
252  d->inserting.erase(it);
253 }
double d
Definition: qnumeric_p.h:62
#define it(className, varName)
The QNetworkDiskCache class provides a very basic disk cache.
T & value() const
Returns a modifiable reference to the current item&#39;s value.
Definition: qhash.h:348
#define Q_D(Class)
Definition: qglobal.h:2482
Q_CORE_EXPORT void qDebug(const char *,...)
Q_CORE_EXPORT void qWarning(const char *,...)
The QHash::iterator class provides an STL-style non-const iterator for QHash and QMultiHash.
Definition: qhash.h:330

◆ maximumCacheSize()

qint64 QNetworkDiskCache::maximumCacheSize ( ) const

Returns the current maximum size in bytes for the disk cache.

See also
setMaximumCacheSize()

Definition at line 488 of file qnetworkdiskcache.cpp.

Referenced by expire(), and prepare().

489 {
490  Q_D(const QNetworkDiskCache);
491  return d->maximumCacheSize;
492 }
double d
Definition: qnumeric_p.h:62
The QNetworkDiskCache class provides a very basic disk cache.
#define Q_D(Class)
Definition: qglobal.h:2482

◆ metaData()

QNetworkCacheMetaData QNetworkDiskCache::metaData ( const QUrl url)
virtual

Reimplemented Function

Implements QAbstractNetworkCache.

Definition at line 368 of file qnetworkdiskcache.cpp.

Referenced by QCacheItem::canCompress(), prepare(), QCacheItem::read(), and QCacheItem::writeHeader().

369 {
370 #if defined(QNETWORKDISKCACHE_DEBUG)
371  qDebug() << "QNetworkDiskCache::metaData()" << url;
372 #endif
374  if (d->lastItem.metaData.url() == url)
375  return d->lastItem.metaData;
376  return fileMetaData(d->cacheFileName(url));
377 }
double d
Definition: qnumeric_p.h:62
QNetworkCacheMetaData fileMetaData(const QString &fileName) const
Returns the QNetworkCacheMetaData for the cache file fileName.
The QNetworkDiskCache class provides a very basic disk cache.
#define Q_D(Class)
Definition: qglobal.h:2482
Q_CORE_EXPORT void qDebug(const char *,...)

◆ prepare()

QIODevice * QNetworkDiskCache::prepare ( const QNetworkCacheMetaData metaData)
virtual

Reimplemented Function

Implements QAbstractNetworkCache.

Definition at line 187 of file qnetworkdiskcache.cpp.

Referenced by updateMetaData().

188 {
189 #if defined(QNETWORKDISKCACHE_DEBUG)
190  qDebug() << "QNetworkDiskCache::prepare()" << metaData.url();
191 #endif
193  if (!metaData.isValid() || !metaData.url().isValid() || !metaData.saveToDisk())
194  return 0;
195 
196  if (d->cacheDirectory.isEmpty()) {
197  qWarning() << "QNetworkDiskCache::prepare() The cache directory is not set";
198  return 0;
199  }
200 
201  foreach (QNetworkCacheMetaData::RawHeader header, metaData.rawHeaders()) {
202  if (header.first.toLower() == "content-length") {
203  qint64 size = header.second.toInt();
204  if (size > (maximumCacheSize() * 3)/4)
205  return 0;
206  break;
207  }
208  }
209  QScopedPointer<QCacheItem> cacheItem(new QCacheItem);
210  cacheItem->metaData = metaData;
211 
212  QIODevice *device = 0;
213  if (cacheItem->canCompress()) {
214  cacheItem->data.open(QBuffer::ReadWrite);
215  device = &(cacheItem->data);
216  } else {
217  QString templateName = d->tmpCacheFileName();
218  QT_TRY {
219  cacheItem->file = new QTemporaryFile(templateName, &cacheItem->data);
220  } QT_CATCH(...) {
221  cacheItem->file = 0;
222  }
223  if (!cacheItem->file || !cacheItem->file->open()) {
224  qWarning() << "QNetworkDiskCache::prepare() unable to open temporary file";
225  cacheItem.reset();
226  return 0;
227  }
228  cacheItem->writeHeader(cacheItem->file);
229  device = cacheItem->file;
230  }
231  d->inserting[device] = cacheItem.take();
232  return device;
233 }
double d
Definition: qnumeric_p.h:62
bool isValid() const
Returns true if the URL is valid; otherwise returns false.
Definition: qurl.cpp:4303
bool isValid() const
Returns true if this network cache meta data has attributes that have been set otherwise false...
The QTemporaryFile class is an I/O device that operates on temporary files.
T1 first
Definition: qpair.h:65
The QNetworkDiskCache class provides a very basic disk cache.
T2 second
Definition: qpair.h:66
The QString class provides a Unicode character string.
Definition: qstring.h:83
#define Q_D(Class)
Definition: qglobal.h:2482
QChar * data()
Returns a pointer to the data stored in the QString.
Definition: qstring.h:710
QUrl url() const
Returns the URL this network cache meta data is referring to.
The QScopedPointer class stores a pointer to a dynamically allocated object, and deletes it upon dest...
RawHeaderList rawHeaders() const
Returns a list of all raw headers that are set in this meta data.
Q_CORE_EXPORT void qDebug(const char *,...)
QNetworkCacheMetaData metaData(const QUrl &url)
Reimplemented Function
Q_CORE_EXPORT void qWarning(const char *,...)
__int64 qint64
Definition: qglobal.h:942
#define QT_CATCH(A)
Definition: qglobal.h:1537
virtual bool open(OpenMode mode)
Opens the device and sets its OpenMode to mode.
Definition: qiodevice.cpp:570
The QIODevice class is the base interface class of all I/O devices in Qt.
Definition: qiodevice.h:66
bool saveToDisk() const
Returns is this cache should be allowed to be stored on disk.
#define QT_TRY
Definition: qglobal.h:1536
qint64 maximumCacheSize() const
Returns the current maximum size in bytes for the disk cache.

◆ remove()

bool QNetworkDiskCache::remove ( const QUrl url)
virtual

Reimplemented Function

Implements QAbstractNetworkCache.

Definition at line 319 of file qnetworkdiskcache.cpp.

320 {
321 #if defined(QNETWORKDISKCACHE_DEBUG)
322  qDebug() << "QNetworkDiskCache::remove()" << url;
323 #endif
325 
326  // remove is also used to cancel insertions, not a common operation
327  QHashIterator<QIODevice*, QCacheItem*> it(d->inserting);
328  while (it.hasNext()) {
329  it.next();
330  QCacheItem *item = it.value();
331  if (item && item->metaData.url() == url) {
332  delete item;
333  d->inserting.remove(it.key());
334  return true;
335  }
336  }
337 
338  if (d->lastItem.metaData.url() == url)
339  d->lastItem.reset();
340  return d->removeFile(d->cacheFileName(url));
341 }
double d
Definition: qnumeric_p.h:62
#define it(className, varName)
The QNetworkDiskCache class provides a very basic disk cache.
#define Q_D(Class)
Definition: qglobal.h:2482
QUrl url() const
Returns the URL this network cache meta data is referring to.
Q_CORE_EXPORT void qDebug(const char *,...)
QNetworkCacheMetaData metaData

◆ setCacheDirectory()

void QNetworkDiskCache::setCacheDirectory ( const QString cacheDir)

Sets the directory where cached files will be stored to cacheDir.

QNetworkDiskCache will create this directory if it does not exists.

Prepared cache items will be stored in the new cache directory when they are inserted.

See also
QDesktopServices::CacheLocation

Definition at line 148 of file qnetworkdiskcache.cpp.

149 {
150 #if defined(QNETWORKDISKCACHE_DEBUG)
151  qDebug() << "QNetworkDiskCache::setCacheDirectory()" << cacheDir;
152 #endif
154  if (cacheDir.isEmpty())
155  return;
156  d->cacheDirectory = cacheDir;
157  QDir dir(d->cacheDirectory);
158  d->cacheDirectory = dir.absolutePath();
159  if (!d->cacheDirectory.endsWith(QLatin1Char('/')))
160  d->cacheDirectory += QLatin1Char('/');
161 
162  d->dataDirectory = d->cacheDirectory + DATA_DIR + QString::number(CACHE_VERSION) + QLatin1Char('/');
163  d->prepareLayout();
164 }
static QString number(int, int base=10)
This is an overloaded member function, provided for convenience. It differs from the above function o...
Definition: qstring.cpp:6448
The QDir class provides access to directory structures and their contents.
Definition: qdir.h:58
double d
Definition: qnumeric_p.h:62
The QNetworkDiskCache class provides a very basic disk cache.
#define DATA_DIR
#define Q_D(Class)
Definition: qglobal.h:2482
Q_CORE_EXPORT void qDebug(const char *,...)
#define CACHE_VERSION
bool isEmpty() const
Returns true if the string has no characters; otherwise returns false.
Definition: qstring.h:704
The QLatin1Char class provides an 8-bit ASCII/Latin-1 character.
Definition: qchar.h:55

◆ setMaximumCacheSize()

void QNetworkDiskCache::setMaximumCacheSize ( qint64  size)

Sets the maximum size of the disk cache to be size in bytes.

If the new size is smaller then the current cache size then the cache will call expire().

See also
maximumCacheSize()

Definition at line 501 of file qnetworkdiskcache.cpp.

502 {
504  bool expireCache = (size < d->maximumCacheSize);
505  d->maximumCacheSize = size;
506  if (expireCache)
507  d->currentCacheSize = expire();
508 }
double d
Definition: qnumeric_p.h:62
The QNetworkDiskCache class provides a very basic disk cache.
#define Q_D(Class)
Definition: qglobal.h:2482
virtual qint64 expire()
Cleans the cache so that its size is under the maximum cache size.

◆ updateMetaData()

void QNetworkDiskCache::updateMetaData ( const QNetworkCacheMetaData metaData)
virtual

Reimplemented Function

Implements QAbstractNetworkCache.

Definition at line 453 of file qnetworkdiskcache.cpp.

454 {
455 #if defined(QNETWORKDISKCACHE_DEBUG)
456  qDebug() << "QNetworkDiskCache::updateMetaData()" << metaData.url();
457 #endif
458  QUrl url = metaData.url();
459  QIODevice *oldDevice = data(url);
460  if (!oldDevice) {
461 #if defined(QNETWORKDISKCACHE_DEBUG)
462  qDebug() << "QNetworkDiskCache::updateMetaData(), no device!";
463 #endif
464  return;
465  }
466 
467  QIODevice *newDevice = prepare(metaData);
468  if (!newDevice) {
469 #if defined(QNETWORKDISKCACHE_DEBUG)
470  qDebug() << "QNetworkDiskCache::updateMetaData(), no new device!" << url;
471 #endif
472  return;
473  }
474  char data[1024];
475  while (!oldDevice->atEnd()) {
476  qint64 s = oldDevice->read(data, 1024);
477  newDevice->write(data, s);
478  }
479  delete oldDevice;
480  insert(newDevice);
481 }
void insert(QIODevice *device)
Reimplemented Function
The QUrl class provides a convenient interface for working with URLs.
Definition: qurl.h:61
QIODevice * data(const QUrl &url)
Reimplemented Function
virtual bool atEnd() const
Returns true if the current read and write position is at the end of the device (i.e.
Definition: qiodevice.cpp:711
QUrl url() const
Returns the URL this network cache meta data is referring to.
qint64 read(char *data, qint64 maxlen)
Reads at most maxSize bytes from the device into data, and returns the number of bytes read...
Definition: qiodevice.cpp:791
Q_CORE_EXPORT void qDebug(const char *,...)
__int64 qint64
Definition: qglobal.h:942
qint64 write(const char *data, qint64 len)
Writes at most maxSize bytes of data from data to the device.
Definition: qiodevice.cpp:1342
The QIODevice class is the base interface class of all I/O devices in Qt.
Definition: qiodevice.h:66
QIODevice * prepare(const QNetworkCacheMetaData &metaData)
Reimplemented Function

The documentation for this class was generated from the following files: