/*!
    \reimp
*/
QIODevice *QNetworkDiskCache::prepare(const QNetworkCacheMetaData &metaData)
{
#if defined(QNETWORKDISKCACHE_DEBUG)
    qDebug() << "QNetworkDiskCache::prepare()" << metaData.url();
#endif
    Q_D(QNetworkDiskCache);
    if (!metaData.isValid() || !metaData.url().isValid() || !metaData.saveToDisk())
        return 0;

    if (d->cacheDirectory.isEmpty()) {
        qWarning() << "QNetworkDiskCache::prepare() The cache directory is not set";
        return 0;
    }

    foreach (const QNetworkCacheMetaData::RawHeader &header, metaData.rawHeaders()) {
        if (header.first.toLower() == "content-length") {
            const qint64 size = header.second.toLongLong();
            if (size > (maximumCacheSize() * 3)/4)
                return 0;
            break;
        }
    }
    QScopedPointer<QCacheItem> cacheItem(new QCacheItem);
    cacheItem->metaData = metaData;

    QIODevice *device = 0;
    if (cacheItem->canCompress()) {
        cacheItem->data.open(QBuffer::ReadWrite);
        device = &(cacheItem->data);
    } else {
        QString templateName = d->tmpCacheFileName();
        QT_TRY {
            cacheItem->file = new QTemporaryFile(templateName, &cacheItem->data);
        } QT_CATCH(...) {
            cacheItem->file = 0;
        }
        if (!cacheItem->file || !cacheItem->file->open()) {
            qWarning() << "QNetworkDiskCache::prepare() unable to open temporary file";
            cacheItem.reset();
            return 0;
        }
        cacheItem->writeHeader(cacheItem->file);
        device = cacheItem->file;
    }
    d->inserting[device] = cacheItem.take();
    return device;
}
/*!
    adds \a offset using key \a key. \a itemType is the type of the structure,
    where offset points to.
    Only acceptable separator for key is '/'.

    doesn't check, if the item is already in the cache.
*/
bool HbSharedCache::add(ItemType itemType, const QString &key, int offset)
{
    bool added = false;
    if (offset >= 0) {
        QString cacheKey(key);
        if (cacheKey.at(0) == ':') {
            //use only filename as a key.
            int index = cacheKey.lastIndexOf('/');
            if (index >= 0) {
                cacheKey = cacheKey.right((cacheKey.size() - 1) - index);
            }
        }
        try {
            CacheItem cacheItem(cacheKey, offset);
            HbVector<CacheItem> &vector = itemCache(itemType);
            HbCacheLocker locker(*Semaphore);
            vector.append(cacheItem);
            added = true;
        } catch (std::exception &) {

        }
    }
    return added;
}