Exemplo n.º 1
0
static MetaDataResult::Tag tryReadPluginMetaDataFromCacheFile(const QString& canonicalPluginPath, RawPluginMetaData& result)
{
    QJsonDocument jsonDocument;
    if (readMetaDataFromCacheFile(jsonDocument) != ReadResult::Success)
        return MetaDataResult::NotAvailable;

    QJsonArray array = jsonDocument.array();
    QDateTime pluginLastModified = QFileInfo(canonicalPluginPath).lastModified();
    for (QJsonArray::const_iterator i = array.constBegin(); i != array.constEnd(); ++i) {
        QJsonValue item = *i;
        if (!item.isObject()) {
            cacheFile()->remove();
            return MetaDataResult::NotAvailable;
        }

        QJsonObject object = item.toObject();
        if (object.value(QStringLiteral("path")).toString() == canonicalPluginPath) {
            QString timestampString = object.value(QStringLiteral("timestamp")).toString();
            if (timestampString.isEmpty()) {
                cacheFile()->remove();
                return MetaDataResult::NotAvailable;
            }
            QDateTime timestamp = QDateTime::fromString(timestampString);
            if (timestamp < pluginLastModified) {
                // Out of date data for this plugin => remove it from the file.
                array.removeAt(i.i);
                writeToCacheFile(array);
                return MetaDataResult::NotAvailable;
            }

            if (object.contains(QLatin1String("unloadable")))
                return MetaDataResult::Unloadable;

            // Match.
            result.name = object.value(QStringLiteral("name")).toString();
            result.description = object.value(QStringLiteral("description")).toString();
            result.mimeDescription = object.value(QStringLiteral("mimeDescription")).toString();
            if (result.mimeDescription.isEmpty()) {
                // Only the mime description is mandatory.
                // Don't trust in the cache file if it is empty.
                cacheFile()->remove();
                return MetaDataResult::NotAvailable;
            }

            return MetaDataResult::Available;
        }
    }

    return MetaDataResult::NotAvailable;
}
Exemplo n.º 2
0
void SloxFolderManager::readFolders()
{
  kdDebug() << k_funcinfo << endl;

  QFile f( cacheFile() );
  if ( !f.open( IO_ReadOnly ) ) {
    kdDebug() << "Unable to open '" << cacheFile() << "'" << endl;
    requestFolders();
    return;
  }

  QDomDocument doc;
  doc.setContent( &f );

  mFolders.clear();

  QDomNodeList nodes = doc.elementsByTagName( "D:prop" );
  for( uint i = 0; i < nodes.count(); ++i ) {
    QDomElement element = nodes.item(i).toElement();
    QString id = "-1", parentId = "-1"; // OX default folder
    bool def = false;
    QString name, type;
    QDomNode n;
    for( n = element.firstChild(); !n.isNull(); n = n.nextSibling() ) {
      QDomElement e = n.toElement();
      QString tag = e.tagName();
      QString value = e.text();
      if ( tag == "ox:object_id" ) id = value;
      else if ( tag == "ox:folder_id" ) parentId = value;
      else if ( tag == "ox:title" ) name = value;
      else if ( tag == "ox:module" ) type = value;
      else if ( tag == "ox:defaultfolder" ) def = (value == "true");
    }
    if ( id != "-1" && parentId != "-1" ) {
      SloxFolder *folder = new SloxFolder( id, parentId, type, name, def );
      mFolders[id] = folder;
      kdDebug() << k_funcinfo << "Found folder: " << folder->name() << endl;
    }
  }

  // add top-level system folders that are not contained in the folder listing
  SloxFolder *folder = new SloxFolder( "1", "0", "unbound", i18n("Private Folder") );
  mFolders[folder->id()] = folder;
  folder = new SloxFolder( "2", "0", "unbound", i18n("Public Folder") );
  mFolders[folder->id()] = folder;
  folder = new SloxFolder( "3", "0", "unbound", i18n("Shared Folder") );
  mFolders[folder->id()] = folder;
  folder = new SloxFolder( "4", "0", "unbound", i18n("System Folder") );
  mFolders[folder->id()] = folder;
}
Exemplo n.º 3
0
void tst_qmldiskcache::fileSelectors()
{
    QQmlEngine engine;

    QTemporaryDir tempDir;
    QVERIFY(tempDir.isValid());

    const QString testFilePath = tempDir.path() + "/test.qml";
    {
        QFile f(testFilePath);
        QVERIFY2(f.open(QIODevice::WriteOnly), qPrintable(f.errorString()));
        f.write(QByteArrayLiteral("import QtQml 2.0\nQtObject { property int value: 42 }"));
    }

    const QString selector = QStringLiteral("testSelector");
    const QString selectorPath = tempDir.path() + "/+" + selector;
    const QString selectedTestFilePath = selectorPath + "/test.qml";
    {
        QVERIFY(QDir::root().mkpath(selectorPath));
        QFile f(selectorPath + "/test.qml");
        QVERIFY2(f.open(QIODevice::WriteOnly), qPrintable(f.errorString()));
        f.write(QByteArrayLiteral("import QtQml 2.0\nQtObject { property int value: 100 }"));
    }

    {
        QQmlComponent component(&engine, testFilePath);
        QScopedPointer<QObject> obj(component.create());
        QVERIFY(!obj.isNull());
        QCOMPARE(obj->property("value").toInt(), 42);

        QFile cacheFile(testFilePath + "c");
        QVERIFY2(cacheFile.exists(), qPrintable(cacheFile.fileName()));
    }

    QQmlFileSelector qmlSelector(&engine);
    qmlSelector.setExtraSelectors(QStringList() << selector);

    engine.clearComponentCache();

    {
        QQmlComponent component(&engine, testFilePath);
        QScopedPointer<QObject> obj(component.create());
        QVERIFY(!obj.isNull());
        QCOMPARE(obj->property("value").toInt(), 100);

        QFile cacheFile(selectedTestFilePath + "c");
        QVERIFY2(cacheFile.exists(), qPrintable(cacheFile.fileName()));
    }
}
Exemplo n.º 4
0
//-------------------------------------------------------------------------
nsresult
DataStruct::WriteCache(nsISupports* aData, uint32_t aDataLen)
{
  // Get a new path and file to the temp directory
  nsCOMPtr<nsIFile> cacheFile ( getter_AddRefs(GetFileSpec(mCacheFileName)) );
  if (cacheFile) {
    // remember the file name
    if (!mCacheFileName) {
      nsXPIDLCString fName;
      cacheFile->GetNativeLeafName(fName);
      mCacheFileName = nsCRT::strdup(fName);
    }

    // write out the contents of the clipboard
    // to the file
    //uint32_t bytes;
    nsCOMPtr<nsIOutputStream> outStr;

    NS_NewLocalFileOutputStream(getter_AddRefs(outStr),
                                cacheFile);

    if (!outStr) return NS_ERROR_FAILURE;

    void* buff = nullptr;
    nsPrimitiveHelpers::CreateDataFromPrimitive ( mFlavor.get(), aData, &buff, aDataLen );
    if ( buff ) {
      uint32_t ignored;
      outStr->Write(reinterpret_cast<char*>(buff), aDataLen, &ignored);
      nsMemory::Free(buff);
      return NS_OK;
    }
  }
  return NS_ERROR_FAILURE;
}
Exemplo n.º 5
0
void TestGeoDataPack::saveKMLToCache()
{
    GeoDataParser parser( GeoData_KML );
    
    QByteArray array( content.toUtf8() );
    QBuffer buffer( &array );
    buffer.open( QIODevice::ReadOnly );
    if ( !parser.read( &buffer ) ) {
        qWarning( "Could not parse data!" );
        QFAIL( "Could not parse data!" );
        return;
    }
    GeoDocument* document = parser.releaseDocument();
    QVERIFY( document );
    qDebug() << " parse Timer " << timer.elapsed();
    GeoDataDocument *dataDocument = static_cast<GeoDataDocument*>( document );
    QString path = QString( "%1/%2.cache" );
    path = path.arg( QCoreApplication::applicationDirPath() );
    path = path.arg( QString( "KMLTest" ) );

    QFile cacheFile( path );
    if ( cacheFile.open( QIODevice::WriteOnly ) ) {
        QDataStream stream ( &cacheFile );
        dataDocument->pack( stream );
        cacheFile.close();
        qDebug( "Saved kml document to cache: %s", path.toLatin1().data() );
    }
    qDebug() << "write Timer " << timer.elapsed();
    delete document;
}
Exemplo n.º 6
0
void *DDiskImageAbstract::Fopen(const char *filename,const char *mode)
{
  diskError=false;
  void *ret=NULL;
  DEBUG_OUT<<"Fopen("<<filename<<")...\n";
  if(!diskMounted) {
    std::cerr<<"DDiskImageAbstract::load no disk in drive!\n";
    diskError=true;
    return NULL;
  }
  if(noFileSystem) {
    std::cerr<<"DDiskImageAbstract::fopen Non-DOS Disk!\n";
    return NULL;
  }
  const char *thename=SearchForFirst(filename);
  if(!thename) {
    std::cerr<<"DDiskImageAbstract::fopen SearchForFirst returned NULL!\n";
    return NULL;
  }
  DDirEntry *aFile=SearchForFirstFile(thename);
  if(!aFile) {
    std::cerr<<"DDiskImageAbstract::fopen SearchForFirstFile returned NULL!\n";
    return NULL;
  }
  cacheFile(aFile);
  aFile->curSeek=0;
  return (void *)aFile;
}
Exemplo n.º 7
0
/** \fn OSDImageCache::SaveToDisk(const OSDImageCacheValue*)
 *  \brief Saves OSD image data to disk cache.
 *
 *   Item is not written to the memory cache, i.e., it stays as
 *   property of the client.
 *
 *  \param value The cached OSD image to save.
 */
void OSDImageCache::SaveToDisk(const OSDImageCacheValue *value)
{
    if (InFileCache(value->GetKey()))
        return;

    QDir dir(MythContext::GetConfDir() + "/osdcache/");
    if (!dir.exists() && !dir.mkdir(dir.path()))
    {
        VERBOSE(VB_IMPORTANT, LOC_ERR + "Creating osdcache directory failed.");
        return;
    }

    QFile cacheFile(dir.path() + "/" + value->GetKey());
    if (!cacheFile.open(IO_WriteOnly | IO_Truncate))
    {
        VERBOSE(VB_IMPORTANT, LOC_ERR + "Creating osdcache file failed.");
        return;
    }

    uint32_t imwidth  = value->m_imagesize.width();
    uint32_t imheight = value->m_imagesize.height();
    uint     yuv_size = imwidth * imheight * 3 / 2;

    QDataStream stream(&cacheFile);
    stream << imwidth << imheight;   
    stream.writeRawBytes((const char*)value->m_yuv, yuv_size);
    stream.writeRawBytes((const char*)value->m_alpha, imwidth * imheight);
    cacheFile.close();
}
Exemplo n.º 8
0
void GrooveRequest::post()
{
    QString cacheKey = generateCacheKey();

    if (cacheKey.length()) {
        qDebug() << Q_FUNC_INFO << "Possibly cached request";
        QString cachePath = QDesktopServices::storageLocation(QDesktopServices::CacheLocation) + "/libgroove/cache/api/" + cacheKey;
        QFile cacheFile(cachePath);
        if (cacheFile.open(QIODevice::ReadOnly)) {
            qDebug() << Q_FUNC_INFO << "Definitely cached request";
            QByteArray response = cacheFile.readAll();
            processData(response);
            return;
        }
    }

    m_request.setHeader(m_request.ContentTypeHeader, "application/json");

    QJson::Serializer serializer;

    qDebug() << Q_FUNC_INFO << "Posting to: " << m_request.url();
    qDebug() << Q_FUNC_INFO << serializer.serialize(buildRequest());

    QNetworkReply *reply = m_client->networkManager()->post(m_request, serializer.serialize(buildRequest()));
    connect(reply, SIGNAL(error(QNetworkReply::NetworkError)), SIGNAL(error(QNetworkReply::NetworkError)));
    connect(reply, SIGNAL(finished()), SLOT(onFinished()));
}
Exemplo n.º 9
0
int GccCommand::execute()
{
    if (arguments().contains(QLatin1String("-dumpmachine")))
        m_cacheFile = QLatin1String(Mer::Constants::GCC_DUMPMACHINE);
    else if (arguments().contains(QLatin1String("-dumpversion")))
        m_cacheFile = QLatin1String(Mer::Constants::GCC_DUMPVERSION);

    if (!m_cacheFile.isEmpty())
            m_cacheFile.prepend(sdkToolsPath() + QDir::separator());

    if (QFile::exists(m_cacheFile)) {
        QFile cacheFile(m_cacheFile);
        if (!cacheFile.open(QIODevice::ReadOnly)) {
            return 1;
        }
        fprintf(stdout, "%s", cacheFile.readAll().constData());
        fflush(stdout);
        return 0;
    }

    return 1;
//TODO: remote command to cache ?
    /*
    // hack for gcc when querying pre-defined macros and header paths
    QRegExp rx(QLatin1String("\\bgcc\\b.*\\B-\\B"));
    const bool queryPredefinedMacros = rx.indexIn(completeCommand) != -1;
    if (queryPredefinedMacros)
        completeCommand.append(QLatin1String(" < /dev/null"));
    */
}
Exemplo n.º 10
0
void ObjectCache::notifyObjectCompiled(llvm::Module const* _module, llvm::MemoryBufferRef _object)
{
	Guard g{x_cacheMutex};

	// Only in "on" and "write" mode
	if (g_mode != CacheMode::on && g_mode != CacheMode::write)
		return;

	// TODO: Disabled because is not thread-safe.
	// if (g_listener)
		// g_listener->stateChanged(ExecState::CacheWrite);

	auto&& id = _module->getModuleIdentifier();
	llvm::SmallString<256> cachePath{getVersionedCacheDir()};
	if (auto err = llvm::sys::fs::create_directories(cachePath))
	{
		DLOG(cache) << "Cannot create cache dir " << cachePath.str().str() << " (error: " << err.message() << "\n";
		return;
	}

	llvm::sys::path::append(cachePath, id);

	DLOG(cache) << id << ": write\n";
	std::error_code error;
	llvm::raw_fd_ostream cacheFile(cachePath, error, llvm::sys::fs::F_None);
	cacheFile << _object.getBuffer();
}
	void CacheBasedLanguageModel::Load(const std::string file)
	{
		//file format
		//age || n-gram 
		//age || n-gram || n-gram || n-gram || ...
		//....
		//each n-gram is a sequence of n words (no matter of n)
		//
		//there is no limit on the size of n
		//
		//entries can be repeated, but the last entry overwrites the previous
		
		
		VERBOSE(2,"Loading data from the cache file " << file << std::endl);
		InputFileStream cacheFile(file);
		
		std::string line;
		int age;
		std::vector<std::string> words;
		
		while (getline(cacheFile, line)) {
			std::vector<std::string> vecStr = TokenizeMultiCharSeparator( line , "||" );
			if (vecStr.size() >= 2) {
				age = Scan<int>(vecStr[0]);
				vecStr.erase(vecStr.begin());
				Update(vecStr,age);
			} else {
				TRACE_ERR("ERROR: The format of the loaded file is wrong: " << line << std::endl);
				CHECK(false);
			}
		}
		IFVERBOSE(2) Print();
	}
Exemplo n.º 12
0
void TestGeoDataPack::saveCitiesToCache()
{
    GeoDataParser parser( GeoData_KML );
    
    QFile citiesFile( CITIES_PATH );
    citiesFile.open( QIODevice::ReadOnly );
    if ( !parser.read( &citiesFile ) ) {
        qWarning( "Could not parse data!" );
        QFAIL( "Could not parse data!" );
        return;
    }
    GeoDocument* document = parser.releaseDocument();
    QVERIFY( document );
    qDebug() << "read Timer " << timer.elapsed();
    GeoDataDocument *dataDocument = static_cast<GeoDataDocument*>( document );
    QString path = QString( "%1/%2.cache" );
    path = path.arg( QCoreApplication::applicationDirPath() );
    path = path.arg( QString( "CitiesTest" ) );

    QFile cacheFile( path );
    if ( cacheFile.open( QIODevice::WriteOnly ) ) {
        QDataStream stream ( &cacheFile );
        dataDocument->pack( stream );
        cacheFile.close();
        qDebug( "Saved kml document to cache: %s", path.toLatin1().data() );
    }
    QVERIFY( cacheFile.size() > 0 );
    qDebug() << "write Timer " << timer.elapsed();
    delete document;
}
Exemplo n.º 13
0
void tst_qmldiskcache::cacheResources()
{
    const QString cacheDirectory = QStandardPaths::writableLocation(QStandardPaths::CacheLocation);
    QVERIFY(QDir::root().mkpath(cacheDirectory));

    const QString qmlCacheDirectory = cacheDirectory + QLatin1String("/qmlcache/");
    QVERIFY(QDir(qmlCacheDirectory).removeRecursively());
    QVERIFY(QDir::root().mkpath(qmlCacheDirectory));
    QVERIFY(QDir(qmlCacheDirectory).entryList(QDir::NoDotAndDotDot).isEmpty());


    QQmlEngine engine;

    {
        CleanlyLoadingComponent component(&engine, QUrl("qrc:/test.qml"));
        QScopedPointer<QObject> obj(component.create());
        QVERIFY(!obj.isNull());
        QCOMPARE(obj->property("value").toInt(), 20);
    }

    const QStringList entries = QDir(qmlCacheDirectory).entryList(QDir::NoDotAndDotDot | QDir::Files);
    QCOMPARE(entries.count(), 1);

    QDateTime cacheFileTimeStamp;

    {
        QFile cacheFile(qmlCacheDirectory + QLatin1Char('/') + entries.constFirst());
        QVERIFY2(cacheFile.open(QIODevice::ReadOnly), qPrintable(cacheFile.errorString()));
        QV4::CompiledData::Unit unit;
        QVERIFY(cacheFile.read(reinterpret_cast<char *>(&unit), sizeof(unit)) == sizeof(unit));

        cacheFileTimeStamp = QFileInfo(cacheFile.fileName()).lastModified();

        QDateTime referenceTimeStamp = QFileInfo(":/test.qml").lastModified();
        if (!referenceTimeStamp.isValid())
            referenceTimeStamp = QFileInfo(QCoreApplication::applicationFilePath()).lastModified();
        QCOMPARE(qint64(unit.sourceTimeStamp), referenceTimeStamp.toMSecsSinceEpoch());
    }

    waitForFileSystem();

    {
        CleanlyLoadingComponent component(&engine, QUrl("qrc:///test.qml"));
        QScopedPointer<QObject> obj(component.create());
        QVERIFY(!obj.isNull());
        QCOMPARE(obj->property("value").toInt(), 20);
    }

    {
        const QStringList entries = QDir(qmlCacheDirectory).entryList(QDir::NoDotAndDotDot | QDir::Files);
        QCOMPARE(entries.count(), 1);

        QCOMPARE(QFileInfo(qmlCacheDirectory + QLatin1Char('/') + entries.constFirst()).lastModified().toMSecsSinceEpoch(), cacheFileTimeStamp.toMSecsSinceEpoch());
    }
}
Exemplo n.º 14
0
static void writeToCacheFile(const QJsonArray& array)
{
    OwnPtr<QFile> file = cacheFile();
    if (!file->open(QFile::WriteOnly | QFile::Truncate)) {
        // It should never but let's be pessimistic, it is the file system after all.
        qWarning("Cannot write into plugin meta data cache file: %s\n", qPrintable(file->fileName()));
        return;
    }

    // Don't care about write error here. We will detect it later.
    file->write(QJsonDocument(array).toJson());
}
Exemplo n.º 15
0
/** \fn OSDImageCache::Get(const QString&,bool)
 *  \brief Returns OSD image data from cache.
 *
 *   This also removes the image from the cache so it won't be deleted
 *   while in use. The deletion of the taken item becomes responsibility
 *   of the client. Returns NULL if item with the given key is not found.
 *
 *  \param key The key for this image.
 *  \param useFile If true, also check the disk cache.
 */
OSDImageCacheValue *OSDImageCache::Get(const QString &key, bool useFile)
{
    QMutexLocker locker(&m_cacheLock);
    OSDImageCacheValue* item = m_imageCache.find(key);
    if (item)
    {
        m_memHits++;
        return m_imageCache.take(key);
    }

    if (!useFile || !InFileCache(key))
    {
        m_misses++;
        return NULL;
    }

    QDir dir(MythContext::GetConfDir() + "/osdcache/");
    QFile cacheFile(dir.path() + "/" + key);
    cacheFile.open(IO_ReadOnly);
    uint32_t imwidth  = 0;
    uint32_t imheight = 0;

    QDataStream stream(&cacheFile);
    stream >> imwidth >> imheight;   

    uint yuv_size = imwidth * imheight * 3 / 2;
    uint tot_size = (sizeof(imwidth) * 2) + yuv_size + (imwidth * imheight);

    if (cacheFile.size() != tot_size)
    {
        VERBOSE(VB_IMPORTANT, LOC_ERR + key + " wrong cache file size!"
                << cacheFile.size() << " != " << tot_size);
        return NULL;
    }

    unsigned char *yuv = new unsigned char[yuv_size];
    unsigned char *alpha = new unsigned char[imwidth * imheight];
    stream.readRawBytes((char*)yuv,   yuv_size);
    stream.readRawBytes((char*)alpha, imwidth * imheight);
    cacheFile.close();

    OSDImageCacheValue* value = 
        new OSDImageCacheValue(
            key,
            yuv, yuv,
            yuv + (imwidth * imheight),
            yuv + (imwidth * imheight * 5 / 4),
            alpha, QRect(0, 0, imwidth, imheight));

    m_diskHits++;
    return value;
}
void SloxFolderManager::slotResult( KJob *job )
{
  kDebug() ;

  if ( job->error() ) {
    static_cast<KIO::Job*>(job)->ui()->showErrorMessage();
  } else {
    kDebug() <<" success, writing to" << cacheFile();
    QFile f( cacheFile() );
    if ( !f.open( QIODevice::WriteOnly ) ) {
      kDebug() <<"Unable to open '" << cacheFile() <<"'";
      return;
    }
    QTextStream stream ( &f );
    stream << mDownloadJob->response();
    f.close();
    readFolders();
  }

  mDownloadJob = 0;
  emit foldersUpdated();
}
Exemplo n.º 17
0
void Document::cache()
{
	if (m_cache_outdated) {
		m_cache_outdated = false;
		DocumentWriter* writer = new DocumentWriter;
		writer->setFileName(g_cache_path + m_cache_filename);
		writer->setType(m_filename.section(QLatin1Char('.'), -1));
		writer->setRichText(m_rich_text);
		writer->setCodePage(m_codepage);
		writer->setDocument(m_text->document()->clone());
		emit cacheFile(writer);
	}
}
Exemplo n.º 18
0
void SloxFolderManager::slotResult( KIO::Job *job )
{
  kdDebug() << k_funcinfo << endl;

  if ( job->error() ) {
    job->showErrorDialog( 0 );
  } else {
    kdDebug() << k_funcinfo << " success, writing to " << cacheFile() << endl;
    QFile f( cacheFile() );
    if ( !f.open( IO_WriteOnly ) ) {
      kdDebug() << "Unable to open '" << cacheFile() << "'" << endl;
      return;
    }
    QTextStream stream ( &f );
    stream << mDownloadJob->response();
    f.close();
    readFolders();
  }

  mDownloadJob = 0;
  emit foldersUpdated();
}
Exemplo n.º 19
0
/**
 * Put the given file in a cache, so that subsequent reads becomes faster.
 * There is no need to uncache files later, as this happens automatically.
 */
Datum cache_file(PG_FUNCTION_ARGS)
{
	if ( PG_ARGISNULL(0) )
		ereport(ERROR, (errcode( ERRCODE_RAISE_EXCEPTION ),	errmsg("NULL argument not allowed")));

	int64 id = PG_GETARG_INT64(0);

	// WARNING:
	// Do not use any postgres functionality within this macro
	// It will cause a resource leak.
	HANDLE_EXCEPTIONS(cacheFile(id));

	PG_RETURN_NULL();
}
Exemplo n.º 20
0
//-------------------------------------------------------------------------
nsresult
DataStruct::ReadCache(nsISupports** aData, uint32_t* aDataLen)
{
  // if we don't have a cache filename we are out of luck
  if (!mCacheFileName)
    return NS_ERROR_FAILURE;

  // get the path and file name
  nsCOMPtr<nsIFile> cacheFile ( getter_AddRefs(GetFileSpec(mCacheFileName)) );
  bool exists;
  if ( cacheFile && NS_SUCCEEDED(cacheFile->Exists(&exists)) && exists ) {
    // get the size of the file
    int64_t fileSize;
    int64_t max32 = 0xFFFFFFFF;
    cacheFile->GetFileSize(&fileSize);
    if (fileSize > max32)
      return NS_ERROR_OUT_OF_MEMORY;

    uint32_t size = uint32_t(fileSize);
    // create new memory for the large clipboard data
    nsAutoArrayPtr<char> data(new char[size]);
    if ( !data )
      return NS_ERROR_OUT_OF_MEMORY;
      
    // now read it all in
    nsCOMPtr<nsIInputStream> inStr;
    NS_NewLocalFileInputStream( getter_AddRefs(inStr),
                                cacheFile);
    
    if (!cacheFile) return NS_ERROR_FAILURE;

    nsresult rv = inStr->Read(data, fileSize, aDataLen);

    // make sure we got all the data ok
    if (NS_SUCCEEDED(rv) && *aDataLen == size) {
      nsPrimitiveHelpers::CreatePrimitiveForData ( mFlavor.get(), data, fileSize, aData );
      return *aData ? NS_OK : NS_ERROR_FAILURE;
    }

    // zero the return params
    *aData    = nullptr;
    *aDataLen = 0;
  }

  return NS_ERROR_FAILURE;
}
Exemplo n.º 21
0
ULONG DDiskImageAbstract::Fread(void *ptr,ULONG sizelem,ULONG n,void *fp)
{
  if(!fp) return 0;
  if(!ptr) return 0;
  DDirEntry *f=(DDirEntry *)fp;
  if(!f->data) cacheFile(fp);
  if(!f->data) return 0;  // we tried...
  BYTE *p=(BYTE *)ptr;
  ULONG rsize=sizelem*n;
  //if(w) *w<<"Going to fread "<<rsize<<"\n";
  if(!rsize) return 0;
  for(ULONG t=0;t<rsize;t++) {
    p[t]=f->data[f->curSeek+t];
  }
  f->curSeek+=rsize;
  return n;
  // TODO: Check that we actually read that much and return accordingly
}
Exemplo n.º 22
0
void GeoEngine::saveTileToDisk(QUrl url, QByteArray dat)
{
    //ne sauve pas une image vide
    if(dat.size()==0)
        return;
    TuileParams params = extractParamsFromUrl(url.toString());
    QFileInfo fileinfo = convertTileToFileInfo(params);

    QDir dir(fileinfo.absolutePath());
    if(!dir.exists())
        dir.mkpath(dir.path());

    QFile cacheFile(fileinfo.filePath());
    cacheFile.open(QIODevice::WriteOnly);
    cacheFile.write(dat);
    cacheFile.close();

}
Exemplo n.º 23
0
static ReadResult::Tag readMetaDataFromCacheFile(QJsonDocument& result)
{
    OwnPtr<QFile> file = cacheFile();
    if (!file->open(QFile::ReadOnly))
        return ReadResult::Empty;
    QByteArray data = file->readAll();
    if (data.isEmpty())
        return ReadResult::Empty;

    QJsonParseError error;
    result = QJsonDocument::fromJson(data, &error);
    if (error.error != QJsonParseError::NoError || !result.isArray()) {
        // Corrupted file.
        file->remove();
        return ReadResult::Error;
    }

    return ReadResult::Success;
}
Exemplo n.º 24
0
void SoupNetworkSession::clearCache(const String& cacheDirectory)
{
    CString cachePath = fileSystemRepresentation(cacheDirectory);
    GUniquePtr<char> cacheFile(g_build_filename(cachePath.data(), "soup.cache2", nullptr));
    if (!g_file_test(cacheFile.get(), G_FILE_TEST_IS_REGULAR))
        return;

    GUniquePtr<GDir> dir(g_dir_open(cachePath.data(), 0, nullptr));
    if (!dir)
        return;

    while (const char* name = g_dir_read_name(dir.get())) {
        if (!g_str_has_prefix(name, "soup.cache") && !stringIsNumeric(name))
            continue;

        GUniquePtr<gchar> filename(g_build_filename(cachePath.data(), name, nullptr));
        if (g_file_test(filename.get(), G_FILE_TEST_IS_REGULAR))
            g_unlink(filename.get());
    }
}
Exemplo n.º 25
0
void tst_qmldiskcache::recompileAfterDirectoryChange()
{
    QQmlEngine engine;
    TestCompiler testCompiler(&engine);

    QVERIFY(testCompiler.tempDir.isValid());

    QVERIFY(QDir(testCompiler.tempDir.path()).mkdir("source1"));
    testCompiler.init(testCompiler.tempDir.path() + QLatin1String("/source1"));

    {
        const QByteArray contents = QByteArrayLiteral("import QtQml 2.0\n"
                                                      "QtObject {\n"
                                                       "    property int blah: 42;\n"
                                                       "}");

        testCompiler.clearCache();
        QVERIFY2(testCompiler.compile(contents), qPrintable(testCompiler.lastErrorString));
        QVERIFY2(testCompiler.verify(), qPrintable(testCompiler.lastErrorString));
        testCompiler.closeMapping();
    }

    const QDateTime initialCacheTimeStamp = QFileInfo(testCompiler.cacheFilePath).lastModified();

    QDir(testCompiler.tempDir.path()).rename(QStringLiteral("source1"), QStringLiteral("source2"));
    waitForFileSystem();

    testCompiler.init(testCompiler.tempDir.path() + QLatin1String("/source2"));

    {
        CleanlyLoadingComponent component(&engine, testCompiler.testFilePath);
        QScopedPointer<QObject> obj(component.create());
        QVERIFY(!obj.isNull());
        QCOMPARE(obj->property("blah").toInt(), 42);
    }

    QFile cacheFile(testCompiler.cacheFilePath);
    QVERIFY2(cacheFile.exists(), qPrintable(cacheFile.fileName()));
    QVERIFY(QFileInfo(testCompiler.cacheFilePath).lastModified() > initialCacheTimeStamp);
}
Exemplo n.º 26
0
QIcon SlothThumbnailCache::addToCache(const QString &path, const QPixmap &pixmap,
                                      const QSize &size,
                                      Qt::AspectRatioMode aspectRatio /* Qt::IgnoreAspectRatio */) {
    QString randstr = Utils::randomString(20);
    QString cacheFilePath = FileUtils::combine(this->cacheDir(size), randstr);

    QFile indexFile(this->iconCacheIndexFile(size));
    QFile cacheFile(cacheFilePath);

    if(!indexFile.open(QIODevice::Append) || !cacheFile.open(QIODevice::WriteOnly))
        return QIcon();

    QTextStream appendIndexFile(&indexFile);
    appendIndexFile << randstr + "=" + QDir::cleanPath(path) + "\n";

    pixmap.scaled(size, aspectRatio).save(&cacheFile, "PNG");

    indexFile.close();
    cacheFile.close();

    return QIcon(cacheFilePath);
}
Exemplo n.º 27
0
void GrooveRequest::onFinished()
{
    QNetworkReply *reply = qobject_cast<QNetworkReply *>(sender());
    if (GROOVE_VERIFY(reply, "search returned without a QNetworkReply")) return;

    if (!reply->error()) {
        QByteArray response = reply->readAll();

        bool success = processData(response);

        // don't cache if there was a fault code
        if (success) {
            QString cacheKey = generateCacheKey();

            // TODO: codeshare with GrooveStream so we don't reinvent caching like this
            if (cacheKey.length()) {
                qDebug() << Q_FUNC_INFO << "Cached a " << response.size() << " byte response with cache key " << cacheKey;
                QString cachePath = QDesktopServices::storageLocation(QDesktopServices::CacheLocation) + "/libgroove/cache/api/";
                QDir dir;
                if (!dir.mkpath(cachePath)) {
                } else {
                    cachePath += cacheKey;
                    QFile cacheFile(cachePath);
                    if (!cacheFile.open(QIODevice::WriteOnly)) {
                        qDebug() << Q_FUNC_INFO << "Cannot open cache file! " << cacheFile.errorString();
                    } else {
                        cacheFile.write(response);
                    }
                }
            }
        }
    } else {
        qDebug() << Q_FUNC_INFO << "Not emitting for failed RPC";
        return;
    }

    qDebug() << Q_FUNC_INFO << "Destroying response";
    deleteLater();
}
Exemplo n.º 28
0
void TestGeoDataPack::loadCitiesFromCache()
{
    GeoDataDocument *cacheDocument = new GeoDataDocument();
    QString path = QString( "%1/%2.cache" );
    path = path.arg( QCoreApplication::applicationDirPath() );
    path = path.arg( QString( "CitiesTest" ) );

    QFile cacheFile( path );
    if ( cacheFile.open( QIODevice::ReadOnly ) ) {
        QDataStream stream ( &cacheFile );
        cacheDocument->unpack( stream );
        cacheFile.close();
        qDebug( "Loaded kml document from cache: %s", path.toLatin1().data() );
    }
    QVERIFY( cacheDocument );
    qDebug() << "read Timer " << timer.elapsed();

    GeoDataParser parser( GeoData_KML );
    QFile citiesFile( CITIES_PATH );
    citiesFile.open( QIODevice::ReadOnly );
    if ( !parser.read( &citiesFile ) ) {
        qWarning( "Could not parse data!" );
        QFAIL( "Could not parse data!" );
        return;
    }
    GeoDocument* document = parser.releaseDocument();
    QVERIFY( document );
    qDebug() << "parse Timer " << timer.elapsed();

// commented out as it timeouts the test on build.kde.org
//    GeoDataDocument *dataDocument = static_cast<GeoDataDocument*>( document );
//    QVERIFY( compareDocuments( cacheDocument, dataDocument ) );
//    qDebug() << "compare Timer " << timer.elapsed();

    delete cacheDocument;
//    delete dataDocument;
}
bool DocumentationPlugin::loadCachedIndex(IndexBox *index, DocumentationCatalogItem *item)
{
    QString cacheName = locateLocal("data", QString("kdevdocumentation/index/cache_") + item->cacheVersion() + item->text(0));
    QFile cacheFile(cacheName);
    if (!cacheFile.open(IO_ReadOnly))
        return false;

    kdDebug() << "Using cached index for item: " << item->text(0) << endl;
    
    QTextStream str(&cacheFile);
    str.setEncoding(QTextStream::Unicode);
    QString cache = str.read();
    QStringList cacheList = QStringList::split("\n", cache, true);
    QString ver = cacheList.first();
    if (ver != CACHE_VERSION)
    {
        kdDebug() << "Wrong cache version: " << ver << endl;
        return false;
    }
    QStringList::const_iterator it = cacheList.begin();
    it++;
    QString s[3]; int c = 0;
    for (; it != cacheList.end(); ++it)
    {
        s[c] = *it;
        if (c == 2)
        {
            IndexItemProto *ii = new IndexItemProto(this, item, index, s[0], s[1]);
            ii->addURL(KURL(s[2]));
            c = 0;
        }
        else c++;
    }
    cacheFile.close();
    
    return true;
}
void DocumentationPlugin::cacheIndex(DocumentationCatalogItem *item)
{
    kdDebug() << "Creating index cache for " << item->text(0) << endl;
    
    QString cacheName = locateLocal("data", QString("kdevdocumentation/index/cache_") + item->text(0));
    QFile cacheFile(cacheName);
    if (!cacheFile.open(IO_WriteOnly))
        return;
    
    QTextStream str(&cacheFile);
    str.setEncoding(QTextStream::Unicode);
    str << CACHE_VERSION << endl;

    QValueList<IndexItemProto*> catalogIndexes = indexes[item];
    for (QValueList<IndexItemProto*>::const_iterator it = catalogIndexes.constBegin();
        it != catalogIndexes.constEnd(); ++it)
    {
        str << (*it)->text() << endl;
        str << (*it)->description() << endl;
        str << (*it)->url().url() << endl;
    }
   
    cacheFile.close();
}