Beispiel #1
0
TEST_P(DataTestWithSizeParam, StoreAndLoad) {
  TempFile file;
  randomData.StoreToFile(file.path());
  Data loaded_data = Data::LoadFromFile(file.path()).value();

  EXPECT_EQ(randomData, loaded_data);
}
Beispiel #2
0
  void remove_lines(std::string name, long int n) throw(Error_TempFile::open_file, Error_FileLines::open_file, Error_FileLines::read_file, Error_remove_lines::temporary_file, Error_TempFile::remove_file, std::ios_base::failure, std::bad_alloc) {

    // If n < 0 then the trailing n lines are removed, and
    // if n > 0 then the leading n lines are removed;
    // for n <> 0 the final line is always concluded with "\n";
    // if abs(n) is greater or equal than the number of lines in the file,
    // then the file becomes empty.

    if (n == 0)
      return;
    TempFile t;
    {
      FileLines f(name);
      if (n > 0)
	std::copy(f.begin() + n, f.end(), std::ostream_iterator<std::string>(t, "\n"));
      else {
	std::copy(f.begin(), f.begin() + std::max(f.size() + n, 0L), std::ostream_iterator<std::string>(t, "\n"));
      }
    }
    t.f().seekg(0);
    std::ofstream f(name.c_str());
    f << t.f().rdbuf();
    if (! t.f())
      throw Error_remove_lines::temporary_file("StreamHandling::remove_lines : Error when writing to temporary file " + t.name());
  }
//---------------------------------------------------------------------------
static bool parse(istream& in,const char* name,StringLookup& lookup,TempFile& facts,TempFile& strings,map<unsigned,unsigned>& subTypes)
   // Parse the input and store it into temporary files
{
   cerr << "Parsing " << name << "..." << endl;

   TurtleParser parser(in);
   map<string,unsigned> languages,types;

   // Read the triples
   try {
      string subject,predicate,object,objectSubType;
      Type::ID objectType;
      while (true) {
         try {
            if (!parser.parse(subject,predicate,object,objectType,objectSubType))
	    //Jyoti --Begin
	    /*cout<<"\n Subject:"<<subject;
            cout<<"\n Predicate:"<<predicate;
            cout<<"\n Object:"<<object<<"\n";*/
            //Jyoti --End
            
	       break;
         } catch (const TurtleParser::Exception& e) {
            cerr << e.message << endl;
            // recover...
            while (in.get()!='\n') ;
            continue;
         }
         // Construct IDs
         unsigned subjectId=lookup.lookupValue(strings,subject,Type::URI,0);
         unsigned predicateId=lookup.lookupPredicate(strings,predicate);
         unsigned subType=0;
         if (objectType==Type::CustomLanguage) {
            if (languages.count(objectSubType)) {
               subType=languages[objectSubType];
            } else {
               subType=languages[objectSubType]=lookup.lookupValue(strings,objectSubType,Type::Literal,0);
               subTypes[subType]=subType;
            }
         } else if (objectType==Type::CustomType) {
            if (types.count(objectSubType)) {
               subType=types[objectSubType];
            } else {
               subType=types[objectSubType]=lookup.lookupValue(strings,objectSubType,Type::URI,0);
               subTypes[subType]=subType;
            }
         }
         unsigned objectId=lookup.lookupValue(strings,object,objectType,subType);

         // And write the triple
         facts.writeId(subjectId);
         facts.writeId(predicateId);
         facts.writeId(objectId);
      }
   } catch (const TurtleParser::Exception&) {
      return false;
   }

   return true;
}
Beispiel #4
0
TEST_P(DataTestWithSizeParam, StoreDoesntChangeData) {
  Data data = randomData.copy();

  TempFile file;
  data.StoreToFile(file.path());

  EXPECT_EQ(randomData, data);
}
Beispiel #5
0
TEST_P(DataTestWithSizeParam, CheckLoadedData) {
  TempFile file;
  StoreData(randomData, file.path());

  Data data = Data::LoadFromFile(file.path()).value();

  EXPECT_EQ(randomData, data);
}
Beispiel #6
0
BEGIN_FIXTURE_TEST(ScriptObjectFixture, bug438633_JS_CompileFileHandle_empty)
{
    const char *script_filename = "empty temporary file";
    TempFile tempScript;
    FILE *script_stream = tempScript.open("temp-bug438633_JS_CompileFileHandle_empty");
    JS::CompileOptions options(cx);
    options.setFileAndLine(script_filename, 1);
    return tryScript(global, JS::Compile(cx, global, options, script_stream));
}
Beispiel #7
0
BEGIN_FIXTURE_TEST(ScriptObjectFixture, bug438633_JS_CompileFileHandleForPrincipals)
{
    TempFile tempScript;
    FILE *script_stream = tempScript.open("temp-bug438633_JS_CompileFileHandleForPrincipals");
    CHECK(fputs(code, script_stream) != EOF);
    CHECK(fseek(script_stream, 0, SEEK_SET) != EOF);
    JS::CompileOptions options(cx);
    options.setFileAndLine("temporary file", 1);
    return tryScript(global, JS::Compile(cx, global, options, script_stream));
}
Beispiel #8
0
static int plain_write(const char *path, const char *buf, size_t size, off_t offset,
        struct fuse_file_info *fi) {
    boost::mutex::scoped_lock lock(io_mutex);

    if (tempFiles.find(string(path)) == tempFiles.end())
        return -EACCES;

    TempFile* file = tempFiles.find(string(path))->second;
    return file->write(buf, size, offset);
};
static void verifyAssemblyUseListOrder(const Module &M) {
    TempFile F;
    if (F.init("ll"))
        report_fatal_error("failed to initialize assembly file");

    if (F.writeAssembly(M))
        report_fatal_error("failed to write assembly");

    LLVMContext Context;
    verifyAfterRoundTrip(M, F.readAssembly(Context));
}
Beispiel #10
0
static void verifyBitcodeUseListOrder(const Module &M) {
    TempFile F;
    if (F.init("bc"))
        report_fatal_error("failed to initialize bitcode file");

    if (F.writeBitcode(M))
        report_fatal_error("failed to write bitcode");

    LLVMContext Context;
    verifyAfterRoundTrip(M, F.readBitcode(Context));
}
Beispiel #11
0
BEGIN_FIXTURE_TEST(ScriptObjectFixture, bug438633_JS_CompileFile_empty)
{
    TempFile tempScript;
    static const char script_filename[] = "temp-bug438633_JS_CompileFile_empty";
    tempScript.open(script_filename);
    tempScript.close();
    JS::CompileOptions options(cx);
    options.setFileAndLine(script_filename, 1);
    JSScript *script = JS::Compile(cx, global, options, script_filename);
    tempScript.remove();
    return tryScript(global, script);
}
Beispiel #12
0
BEGIN_FIXTURE_TEST(ScriptObjectFixture, bug438633_JS_CompileFile)
{
    TempFile tempScript;
    static const char script_filename[] = "temp-bug438633_JS_CompileFile";
    FILE *script_stream = tempScript.open(script_filename);
    CHECK(fputs(code, script_stream) != EOF);
    tempScript.close();
    JS::CompileOptions options(cx);
    options.setFileAndLine(script_filename, 1);
    JSScript *script = JS::Compile(cx, global, options, script_filename);
    tempScript.remove();
    return tryScript(global, script);
}
Beispiel #13
0
static void report_cb(Fl_Widget*, void*) {
	String bug_tool = file_path("ede-bug-report");
	if(bug_tool.empty()) {
		alert(_("Unable to find ede-bug-report tool."
				" Please check if PATH variable contains directory where this tool was installed"));
		return;
	}

	collect_info_once();

	TempFile tmp;
	if(!tmp.create("/tmp/.ecrash-dump")) {
		alert(_("Unable to create temporary file: (%i) %s"), tmp.status(), strerror(tmp.status()));
		return;
	}

	/* close it since we need the file name */
	tmp.close();

	txt_buf->savefile(tmp.name());

	run_async("%s --gdb-dump %s", bug_tool.c_str(), tmp.name());

	/* wait some time until the file was read; dumb, I know :( */
	sleep(1);

	/* remove it */
	tmp.unlink();
}
Beispiel #14
0
TempFile* TempSpace::setupFile(size_t size)
{
	ISC_STATUS_ARRAY status_vector = {0};

	for (size_t i = 0; i < tempDirs->getCount(); i++)
	{
		TempFile* file = NULL;

		Firebird::PathName directory = (*tempDirs)[i];
		PathUtils::ensureSeparator(directory);

		for (size_t j = 0; j < tempFiles.getCount(); j++)
		{
			Firebird::PathName dirname, filename;
			PathUtils::splitLastComponent(dirname, filename, tempFiles[j]->getName());
			PathUtils::ensureSeparator(dirname);
			if (!directory.compare(dirname))
			{
				file = tempFiles[j];
				break;
			}
		}

		try
		{
			if (!file)
			{
				file = FB_NEW(pool) TempFile(pool, filePrefix, directory);
				tempFiles.add(file);
			}

			file->extend(size);
		}
		catch (const Firebird::system_error& ex)
		{
			ex.stuff_exception(status_vector);
			continue;
		}

		return file;
	}

	// no room in all directories
	Firebird::Arg::Gds status(isc_out_of_temp_space);
	status.append(Firebird::Arg::StatusVector(status_vector));
	iscLogStatus(NULL, status.value());
	status.raise();

	return NULL; // compiler silencer
}
Beispiel #15
0
static void collect_info_once(void) {
	if(info_was_collected)
		return;

	write_host_info();

	TempFile tmp;
	tmp.set_auto_delete(true);

	if(gdb_output_generate(pdetails->path, tmp))
		txt_buf->appendfile(tmp.name());

	info_was_collected = true;
}
Beispiel #16
0
TEST(ChomeProfileTest, OneLineLocalState_ReadUILocale)
{
	wstring location;
	ChomeProfileTest chromeProfile;
	TempFile tempFile;

	Application::GetExecutionLocation(location);
	location += L"Chrome\\CatalanUI_OneLineProfile\\User Data\\";
	location += L"/../User Data/Local State";
	CopyFile(location.c_str(), tempFile.GetFileName().c_str(), false);

	chromeProfile.SetPath(GetPathFromFullFileName(tempFile.GetFileName()));
	chromeProfile.SetUIRelPathAndFile(GetFileNameFromFullFileName(tempFile.GetFileName()));

	EXPECT_TRUE(chromeProfile.IsUiLocaleOk());
}
//---------------------------------------------------------------------------
void dumpFacts(ofstream& out,TempFile& rawFacts,const string& name)
// Dump the facts
{
    // Sort the facts
    TempFile sortedFacts(rawFacts.getBaseFile());
    Sorter::sort(rawFacts,sortedFacts,skipTriple,compareTriple,true);

    // Dump the facts
    {
        unlink("facts.sql");
        ofstream out("facts.sql");
        MemoryMappedFile in;
        in.open(sortedFacts.getFile().c_str());
        const Triple* triplesBegin=reinterpret_cast<const Triple*>(in.getBegin());
        const Triple* triplesEnd=reinterpret_cast<const Triple*>(in.getEnd());
        for (const Triple* iter=triplesBegin,*limit=triplesEnd; iter!=limit; ++iter)
            out << (*iter).subject << "\t" << (*iter).predicate << "\t" << (*iter).object << std::endl;
    }

    // And write the copy statement
    out << "drop schema if exists " << name << " cascade;" << endl;
    out << "create schema " << name << ";" << endl;
    out << "create table " << name << ".facts(subject int not null, predicate int not null, object int not null);" << endl;
    out << "copy " << name << ".facts from 'facts.sql';" << endl;

    // Create indices
    out << "create index facts_spo on " << name << ".facts (subject, predicate, object);" << endl;
    out << "create index facts_pso on " << name << ".facts (predicate, subject, object);" << endl;
    out << "create index facts_pos on " << name << ".facts (predicate, object, subject);" << endl;
}
void KwayMergeSort::WriteToTempFile(const vector<T> &lineBuffer) {


	TempFile *temp = new TempFile(_tempPath + _inFile);
	// write the contents of the current buffer to the temp file
	for (size_t i = 0; i < lineBuffer.size(); ++i) {

		temp->write(strlen(lineBuffer[i].c_str()), lineBuffer[i].c_str());
		temp->write(1, "\n");
	}

	temp->close();
	_vTempFileNames.push_back(temp->getFile());
	delete temp;

}
Beispiel #19
0
TEST(ChomeProfileTest, WriteUILocale)
{
	wstring location;
	ChomeProfileTest chromeProfile;
	TempFile tempFile;

	Application::GetExecutionLocation(location);
	location += L"Chrome\\SpanishUI_NoAcceptLanguage\\User Data\\";
	location += L"/../User Data/Local State";
	CopyFile(location.c_str(), tempFile.GetFileName().c_str(), false);
	
	chromeProfile.SetPath(GetPathFromFullFileName(tempFile.GetFileName()));
	chromeProfile.SetUIRelPathAndFile(GetFileNameFromFullFileName(tempFile.GetFileName()));

	chromeProfile.WriteUILocale();
	EXPECT_TRUE(chromeProfile.IsUiLocaleOk());	
}
Beispiel #20
0
TEST(ChomeProfileTest, OneLinePreferences_EsSpellChecker_SetCatalanAsSpellCheckerLanguage)
{
	wstring location;
	ChomeProfileTest chromeProfile;
	TempFile tempFile;

	Application::GetExecutionLocation(location);
	location += L"Chrome\\CatalanUI_OneLineProfile\\User Data\\";
	location += L"/../User Data/Default/Preferences";
	CopyFile(location.c_str(), tempFile.GetFileName().c_str(), false);
	chromeProfile.SetPath(GetPathFromFullFileName(tempFile.GetFileName()));
	chromeProfile.SetPreferencesRelPathAndFile(GetFileNameFromFullFileName(tempFile.GetFileName()));

	chromeProfile.SetCatalanAsSpellCheckerLanguage();
	chromeProfile.WriteSpellAndAcceptLanguages();
	EXPECT_TRUE(chromeProfile.IsSpellCheckerLanguageOk());
}
Beispiel #21
0
void
OutputMerge::addTempFile(TempFile& t)
{
    istream* f = t.forRead();
    mStreams.emplace_back(f);
    mIters.push_back(FileIter(*f));
    
    insertNext(mIters.size() - 1);
}
Beispiel #22
0
TEST(ChomeProfileTest, PrevLanguage_SetAcceptLanguages)
{
	wstring location, langcode;
	ChomeProfileTest chromeProfile;
	TempFile tempFile;

	Application::GetExecutionLocation(location);
	location += L"Chrome\\SpanishUI_AcceptLanguage_es_de_br\\User Data\\";
	location += L"/../User Data/Default/Preferences";
	CopyFile(location.c_str(), tempFile.GetFileName().c_str(), false);
	
	chromeProfile.SetPath(GetPathFromFullFileName(tempFile.GetFileName()));
	chromeProfile.SetPreferencesRelPathAndFile(GetFileNameFromFullFileName(tempFile.GetFileName()));

	chromeProfile.SetCatalanAsAcceptLanguages();
	chromeProfile.WriteSpellAndAcceptLanguages();
	chromeProfile.ReadAcceptLanguages(langcode);
	EXPECT_THAT(langcode, StrCaseEq(L"ca,es,de,br"));
}
void TripleBitBuilder::NTriplesParse(const char* subject,  const char* predicate, const char* object, TempFile& facts) {
	ID subjectID, objectID, predicateID;

	if (isStatementReification(object) == false && isStatementReification(predicate) == false) {
		if (preTable->getIDByPredicate(predicate, predicateID) == PREDICATE_NOT_BE_FINDED) {
			preTable->insertTable(predicate, predicateID);
		}


		if (uriTable->getIdByURI(subject, subjectID) == URI_NOT_FOUND)
			uriTable->insertTable(subject, subjectID);
		if (uriTable->getIdByURI(object, objectID) == URI_NOT_FOUND)
			uriTable->insertTable(object, objectID);

		facts.writeId(subjectID);
		facts.writeId(predicateID);
		facts.writeId(objectID);
	} else {
//		statementFile << subject << " : " << predicate << " : " << object << endl;
	}

}
Beispiel #24
0
bool Config::save(const char* fname) {
	E_ASSERT(fname != NULL);

	TempFile t;
	if(!t.create(".etmp.XXXXXX")) {
		errcode = CONF_ERR_FILE;
		return false;
	}

	/* so we could explicitly handle our options */
	t.set_no_close(true);
	t.set_auto_delete(false);

	FILE *f = t.fstream();

	SectionListIter sit = section_list.begin(), sit_end = section_list.end();
	unsigned int sz = section_list.size();
	EntryListIter eit;

	for (; sit != sit_end; ++sit, --sz) {
		fprintf(f, "[%s]\n", (*sit)->sname);

		for (eit = (*sit)->entry_list.begin(); eit != (*sit)->entry_list.end(); ++eit)
			fprintf(f, "%s=%s\n", (*eit)->key, (*eit)->value);

		/* prevent unneeded newline at the end of file */
		if(sz != 1)
			fprintf(f, "\n");
	}

	/* explicitly flush */
	fflush(f);
	t.close();

	E_ASSERT(t.name() && "Temporary name NULL. Report this as bug");

	if(rename(t.name(), fname) != 0) {
		E_WARNING("Unable to save to '%s'\n", fname);
		return false;
	} 

	chmod(fname, S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH);
	return true;
}
//---------------------------------------------------------------------------
bool readFacts(TempFile& out,const char* fileName)
// Read the facts table
{
    ifstream in(fileName);
    if (!in.is_open()) {
        cout << "unable to open " << fileName << endl;
        return false;
    }

    while (true) {
        Triple t;
        in >> t.subject >> t.predicate >> t.object;
        if (!in.good()) break;
        out.write(sizeof(t),reinterpret_cast<char*>(&t));
    }

    return true;
}
Beispiel #26
0
 void CreateWithCipher(const string &cipher, const TempFile &tempFile) {
     CryConfig cfg;
     cfg.SetCipher(cipher);
     CryConfigFile::create(tempFile.path(), std::move(cfg), "mypassword", SCrypt::TestSettings);
 }
Beispiel #27
0
 optional<CryConfigFile> Load(const string &password = "******") {
     return CryConfigFile::load(file.path(), password);
 }
Beispiel #28
0
 void Create(CryConfig cfg, const string &password = "******") {
     CryConfigFile::create(file.path(), std::move(cfg), password, SCrypt::TestSettings);
 }
Beispiel #29
0
bool gdb_output_generate(const char *path, TempFile &t, int pid) {
	E_RETURN_VAL_IF_FAIL(path != NULL, false);

	int      tfd = -1;
	TempFile scr;

	if(!scr.create("/tmp/.ecrash-script")) {
		E_WARNING(E_STRLOC ": Unable to create temporary file for debugger script: (%i) %s",
				scr.status(), strerror(scr.status()));
		return false;
	}

	if(!t.create("/tmp/.ecrash-output")) {
		E_WARNING(E_STRLOC ": Unable to create temporary file for debugger output: (%i) %s",
				t.status(), strerror(t.status()));
		return false;
	}

	tfd = t.handle();

	/* write script */
	::write(scr.handle(), "bt\nquit\n", 8);
	scr.set_auto_delete(true);
	scr.close();

	String gdb_path = file_path("gdb");
	if(gdb_path.empty()) {
		/* write straight to the file, so dialog could show it */
		write_str(tfd, "Unable to find gdb. Please install it first");

		/* see it as valid, so dialog could be shown */
		return true;
	}

	/*
	 * to find core file, we will try these strategies: first try to open 'core.PID' if
	 * we got PID (default on linux); if does not exists, try to open 'core'; everything is
	 * assumed current folder, whatever it was set
	 */
	bool   core_found = false;
	String core_path;
	if(pid > -1) {
		core_path.printf("%s.%i", CORE_FILE, pid);
		if(file_test(core_path.c_str(), FILE_TEST_IS_REGULAR))
			core_found = true;
	}

	if(!core_found) {
		core_path = CORE_FILE;
		if(file_test(core_path.c_str(), FILE_TEST_IS_REGULAR))
			core_found = true;
	}

	if(!core_found) {
		write_str(tfd, "Unable to find core file. Backtrace will not be done.");
		/* see it as valid, so dialog could be shown */
		return true;
	}

	pid_t gdb_pid = fork();

    if(gdb_pid == -1) {
		E_WARNING(E_STRLOC ": Unable to fork the process\n");
        return false;
    } else if(gdb_pid == 0) {
		/* child; redirect to the file */
        dup2(tfd, 1);
		t.close();

		::write(1, " ", 1);

        char* argv[8];
        argv[0] = (char*)gdb_path.c_str();
        argv[1] = (char*)"--quiet";
        argv[2] = (char*)"--batch";
        argv[3] = (char*)"-x";
        argv[4] = (char*)scr.name();
        argv[5] = (char*)path;
        argv[6] = (char*)core_path.c_str();
        argv[7] = 0;

        execvp(argv[0], argv);
        return false;
    } else {
        int status;

        if(waitpid(gdb_pid, &status, 0) != gdb_pid) {
			E_WARNING(E_STRLOC ": Failed to execute waitpid() properly\n");
            return false;
		}
    }

	file_remove(core_path.c_str());
	return true;
}
Beispiel #30
0
#include <edelib/TempFile.h>
#include <edelib/FileTest.h>
#include "UnitTest.h"

EDELIB_NS_USE

UT_FUNC(TempFileTest, "Test TempFile")
{
	TempFile t, t2, t3;

	UT_VERIFY(t.create("foo-temp.XXXXXX") == true);
	UT_VERIFY(t == true);

	UT_VERIFY(file_test(t.name(), FILE_TEST_IS_REGULAR | FILE_TEST_IS_WRITEABLE));

	t.unlink();
	UT_VERIFY(file_test(t.name(), FILE_TEST_IS_REGULAR) == false);

	UT_VERIFY(t2.create("baz-tmp") == true);
	UT_VERIFY(t2 == true);
	UT_VERIFY(file_test(t2.name(), FILE_TEST_IS_REGULAR | FILE_TEST_IS_WRITEABLE));
	UT_VERIFY(t2.fstream() != 0);
	t2.set_auto_delete(true);

	UT_VERIFY(t3.create("/this/file/should/not/exists") == false);
	UT_VERIFY(t3 == false);
}