void Image::write(const boost::filesystem::path &pfname)
{
  if(data::filename_is_png(pfname))
  {
    if(image_png_supports_bpp(m_b))
    {
      image_png_save(pfname.generic_string(), m_w, m_h, m_b, m_data);
    }
    else
    {
      std::ostringstream str;
      str << '\'' << pfname << "': bit depth " << m_b << " not supported in PNG";
      BOOST_THROW_EXCEPTION(std::runtime_error(str.str()));
    }
  }
  else if(data::filename_is_jpeg(pfname))
  {
    if(image_jpeg_supports_bpp(m_b))
    {
      image_jpeg_save(pfname.generic_string(), m_w, m_h, m_b, m_data);
    }
    else
    {
      std::ostringstream str;
      str << '\'' << pfname << "': bit depth " << m_b << " not supported in JPEG";
      BOOST_THROW_EXCEPTION(std::runtime_error(str.str()));
    }
  }
  else
  {
    std::ostringstream str;
    str << "unknown image type: " << pfname;
    BOOST_THROW_EXCEPTION(std::runtime_error(str.str()));
  }
}
EditorColorScheme::EditorColorScheme(fs::path path) : path(path)
{
	try {
		boost::property_tree::read_json(path.generic_string(), pt);
		_name = QString::fromStdString(pt.get<std::string>("name"));
		_index = pt.get<int>("index");
	} catch (const std::exception & e) {
		PRINTB("Error reading color scheme file '%s': %s", path.generic_string() % e.what());
		_name = "";
		_index = 0;
	}
}
Example #3
0
Status FTDCFileWriter::open(const boost::filesystem::path& file) {
    if (_archiveStream.is_open()) {
        return {ErrorCodes::FileAlreadyOpen, "FTDCFileWriter is already open."};
    }

    _archiveFile = file;

    // Ideally, we create a file from scratch via O_CREAT but there is not portable way via C++
    // iostreams to do this.
    _archiveStream.open(_archiveFile.c_str(),
                        std::ios_base::out | std::ios_base::binary | std::ios_base::app);

    if (!_archiveStream.is_open()) {
        return Status(ErrorCodes::FileNotOpen,
                      "Failed to open archive file " + file.generic_string());
    }

    // Set internal size tracking to reflect the current file size
    _size = boost::filesystem::file_size(file);

    _sizeInterim = 0;

    _interimFile = FTDCUtil::getInterimFile(file);
    _interimTempFile = FTDCUtil::getInterimTempFile(file);

    _compressor.reset();

    return Status::OK();
}
Example #4
0
GTEST_TEST_F(ReadFile, write) {
	ASSERT_FALSE(kFilePath.empty());

	static const byte data[5] = { 0x12, 0x34, 0x56, 0x78, 0x90 };

	// Create the input file

	boost::filesystem::ofstream testFile(kFilePath, std::ofstream::binary);

	testFile.write(reinterpret_cast<const char *>(data), ARRAYSIZE(data));
	testFile.flush();
	ASSERT_FALSE(testFile.fail());

	testFile.close();

	// Read the file with our ReadFile class

	Common::ReadFile file(kFilePath.generic_string());
	ASSERT_TRUE(file.isOpen());

	EXPECT_EQ(file.size(), ARRAYSIZE(data));

	byte readData[ARRAYSIZE(data)];
	const size_t readCount = file.read(readData, sizeof(readData));
	EXPECT_EQ(readCount, ARRAYSIZE(readData));

	file.close();
	ASSERT_FALSE(file.isOpen());

	// Compare

	for (size_t i = 0; i < ARRAYSIZE(data); i++)
		EXPECT_EQ(readData[i], data[i]) << "At index " << i;
}
Example #5
0
inline void save(Archive& ar,
    const boost::filesystem::path& p,
    const unsigned int /*version*/) {
    std::string s;
    s = p.generic_string();
    ar & boost::serialization::make_nvp("path", s);
}
Example #6
0
std::shared_ptr<rett> createAny(const boost::filesystem::path & libpath, const std::string & methodName)
{
#ifdef VCMI_ANDROID
	// android currently doesn't support loading libs dynamically, so the access to the known libraries
	// is possible only via specializations of this template
	throw std::runtime_error("Could not resolve ai library " + libpath.generic_string());
#else
	typedef void(* TGetAIFun)(std::shared_ptr<rett> &);
	typedef void(* TGetNameFun)(char *);

	char temp[150];

	TGetAIFun getAI = nullptr;
	TGetNameFun getName = nullptr;

#ifdef VCMI_WINDOWS
	HMODULE dll = LoadLibraryW(libpath.c_str());
	if (dll)
	{
		getName = (TGetNameFun)GetProcAddress(dll, "GetAiName");
		getAI = (TGetAIFun)GetProcAddress(dll, methodName.c_str());
	}
#else // !VCMI_WINDOWS
	void *dll = dlopen(libpath.string().c_str(), RTLD_LOCAL | RTLD_LAZY);
	if (dll)
	{
		getName = (TGetNameFun)dlsym(dll, "GetAiName");
		getAI = (TGetAIFun)dlsym(dll, methodName.c_str());
	}
#endif // VCMI_WINDOWS

	if (!dll)
	{
		logGlobal->error("Cannot open dynamic library (%s). Throwing...", libpath.string());
		throw std::runtime_error("Cannot open dynamic library");
	}
	else if(!getName || !getAI)
	{
		logGlobal->error("%s does not export method %s", libpath.string(), methodName);
#ifdef VCMI_WINDOWS
		FreeLibrary(dll);
#else
		dlclose(dll);
#endif
		throw std::runtime_error("Cannot find method " + methodName);
	}

	getName(temp);
	logGlobal->info("Loaded %s", temp);

	std::shared_ptr<rett> ret;
	getAI(ret);
	if(!ret)
		logGlobal->error("Cannot get AI!");

	return ret;
#endif //!VCMI_ANDROID
}
bool is_it_done( 
    const bfs::path& filepath, 
    size_map_t&      sizes ) {
    bs::error_code ec;
    if ( bfs::is_regular_file( filepath, ec ) &&
            ec == err::success &&
            ( sizes.count( filepath.generic_string() ) == 0 ||
              sizes[filepath.generic_string()] != bfs::file_size( filepath ) ) ) {
        return false;
    }
    else if ( bfs::is_directory( filepath, ec ) && ec == err::success ) {
        for ( bfs::directory_iterator iter( filepath ), end_iter; iter != end_iter; iter++ ) {
            if ( !is_it_done( iter->path(), sizes ) ) {
                return false;
            }
        }
    }
    return true;
}
	void IParser::beginParsing(boost::filesystem::path path){
		std::ifstream open(path.generic_string(),std::ios_base::binary);
		m_size = boost::filesystem::file_size(path);
		m_readPosition = 0;
		m_buffer = new char[m_size];
		open.read(m_buffer,m_size);
		open.close();

		m_document = DataDocumentPtr(new DataDocument);
	}
Example #9
0
        void
        writeNode(xercesc::DOMNode&              node,
                  const boost::filesystem::path& file,
                  const WriteParameters&         params)
        {
          Platform xmlplat;

          xercesc::LocalFileFormatTarget target(String(file.generic_string()));

          write_target(node, target, params);
        }
Example #10
0
		void ZipArchiveImpl::AddFolder(const bfs::path& path, const bfs::path& archive_path)
		{
			++m_Info.folderCount;

			zip_fileinfo fileinfo;
			fileinfo.internal_fa = 0;
#ifdef _WIN32
			fileinfo.external_fa = ::GetFileAttributesW(path.native().c_str());
#else
			{
				struct stat path_stat;
				if (::stat(path.native().c_str(), &path_stat) == 0)
				{
					fileinfo.external_fa = path_stat.st_mode;
				}
			}
#endif
			fileinfo.dosDate = 0;
			// Read the time from the filesystem and convert it
			auto fsTime = bfs::last_write_time(path);
			auto posixTime = boost::posix_time::from_time_t(fsTime);
			auto tm = boost::posix_time::to_tm(posixTime);

			/* TODO: this is how to get the time for a physfs file
			boost::posix_time::ptime posixTime;
			auto milisPastEpoc = PHYSFS_getLastModTime(path.generic_string().c_str());
			if (milisPastEpoc >= 0)
			time = boost::posix_time::ptime(boost::gregorian::date(1970, 1, 1), boost::posix_time::milliseconds(milisPastEpoc));
			else
			time = boost::posix_time::second_clock::local_time();
			*/

			fileinfo.tmz_date.tm_hour = tm.tm_hour;
			fileinfo.tmz_date.tm_min = tm.tm_min;
			fileinfo.tmz_date.tm_sec = tm.tm_sec;
			fileinfo.tmz_date.tm_year = tm.tm_year;
			fileinfo.tmz_date.tm_mon = tm.tm_mon;
			fileinfo.tmz_date.tm_mday = tm.tm_mday;

			auto r = zipOpenNewFileInZip(m_File, (archive_path.generic_string() + "/").c_str(),
				&fileinfo,
				nullptr, 0,
				nullptr, 0,
				nullptr,
				Z_DEFLATED,
				Z_BEST_SPEED);

			zipCloseFileInZip(m_File);

			for (bfs::directory_iterator it(path), end = bfs::directory_iterator(); it != end; ++it)
			{
				AddPath(it->path(), archive_path / it->path().filename());
			}
		}
Example #11
0
void Attribute::setLink(const boost::filesystem::path &l)
{  
  _link = l.generic_string();
  
  assert(name != _link);
  
  data = NULL;
  _m = Mat();
  dims = 0;
  size.resize(0);
}
Example #12
0
inline void png_read_and_convert_image(const boost::filesystem::path& path,Image& im) {
#if defined (_WIN32)
    boost::filesystem::path::string_type path_native = path.native();
    FILE* file = _wfopen(path_native.c_str(), L"rb");
    gil::png_read_and_convert_image(file,im);
    fclose(file);
#else
    std::string filename = path.generic_string();
    png_read_and_convert_image(filename.c_str(),im);
#endif
}
Example #13
0
void hashFile(const boost::filesystem::path& path, Hash& algorithm)
{
    std::ifstream fileStream(path.generic_string(), std::ios::binary);
    if(fileStream.is_open()) {
        while(!fileStream.eof()) {
            char buffer[4096];
            fileStream.read(buffer, 4096);
            int bytesRead = fileStream.gcount();
            algorithm.add(buffer, bytesRead);
        }
    }
}
Example #14
0
Status FTDCFileReader::open(const boost::filesystem::path& file) {
    _stream.open(file.c_str(), std::ios_base::in | std::ios_base::binary);
    if (!_stream.is_open()) {
        return Status(ErrorCodes::FileStreamFailed, "Failed to open file " + file.generic_string());
    }

    _fileSize = boost::filesystem::file_size(file);

    _file = file;

    return Status::OK();
}
Example #15
0
boost::optional<ModuleTemplate> ModuleTemplateInstance::CreateFromPath(boost::filesystem::path const& path)
{
    #ifdef _WIN32
        HMODULE syshandle = LoadLibrary(path.generic_string().c_str());
    #else // Posix
        void* syshandle = dlopen(path.generic_string().c_str(), RTLD_LAZY);
    #endif

    if (!syshandle)
        return boost::none;

    InternalHandleType handle(syshandle, [](void* handle)
    {
        #ifdef _WIN32
            FreeLibrary((HMODULE)handle);
        #else // Posix
            dlclose(handle);
        #endif
    });

    #ifdef _WIN32
        unwrap_function<ModuleCreateFunction>::function_ptr const function =
            (unwrap_function<ModuleCreateFunction>::function_ptr)GetProcAddress(syshandle, CREATE_MODULE_FUNCTION_NAME);

    #else // Posix

        // Silences "warning: dereferencing type-punned pointer will break strict-aliasing rules" warnings according to:
        // http://en.wikipedia.org/wiki/Dynamic_loading
        union { unwrap_function<ModuleCreateFunction>::function_ptr function; void* raw; } alias;
        alias.raw = dlsym(syshandle, CREATE_MODULE_FUNCTION_NAME);
        unwrap_function<ModuleCreateFunction>::function_ptr function = alias.function;
    #endif

    if (!function)
        return boost::none;

    return boost::make_optional(ModuleTemplate(
        new ModuleTemplateInstance(std::move(handle), function)));
}
Example #16
0
model hydrator::hydrate(const boost::filesystem::path& p) const {
    const auto gs(p.generic_string());
    BOOST_LOG_SEV(lg, debug) << "Parsing file: " << gs;
    boost::filesystem::ifstream s(p);

    if (s.fail()) {
        BOOST_LOG_SEV(lg, error) << failed_to_open_file << ": " << gs;
        BOOST_THROW_EXCEPTION(hydration_error(failed_to_open_file + gs));
    }

    try {
        auto r(hydrate(s));
        r.name(p.stem().generic_string());
        BOOST_LOG_SEV(lg, debug) << "Parsed file successfully.";
        return r;
    } catch(boost::exception& e) {
        const auto s(p.generic_string());
        BOOST_LOG_SEV(lg, error) << "Failed to parse file: " << s;
        e << error_in_file(s);
        throw;
    }
}
Example #17
0
model json_hydrator::hydrate(const boost::filesystem::path& p) const {
    const auto gs(p.generic_string());
    BOOST_LOG_SEV(lg, debug) << "Parsing JSON file: " << gs;
    boost::filesystem::ifstream s(p);

    if (s.fail()) {
        BOOST_LOG_SEV(lg, error) << failed_to_open_file << ": " << gs;
        BOOST_THROW_EXCEPTION(hydration_error(failed_to_open_file + gs));
    }

    const auto r(hydrate(s));
    BOOST_LOG_SEV(lg, debug) << "Parsed JSON file successfully.";
    return r;
}
Example #18
0
void set_config_path(libconfig::Config& configuration, 
    const boost::filesystem::path& config_path)
{
    // Ignore error if unable to read config file.
    try
    {
        // libconfig is ANSI/MBCS on Windows - no Unicode support.
        // This translates the path from Unicode to a "generic" path in
        // ANSI/MBCS, which can result in failures.
        configuration.readFile(config_path.generic_string().c_str());
    }
    catch (const libconfig::FileIOException&) {}
    catch (const libconfig::ParseException&) {}
}
void add_file_sizes( 
    const bfs::path& filepath, 
    size_map_t&      sizes ) {
    bs::error_code ec;
    if ( bfs::is_regular_file( filepath, ec ) &&
            ec == err::success ) {
        sizes[filepath.generic_string()] = bfs::file_size( filepath );
    }
    else if ( bfs::is_directory( filepath, ec ) && ec == err::success ) {
        for ( bfs::directory_iterator iter( filepath ), end_iter; iter != end_iter; iter++ ) {
            add_file_sizes( iter->path(), sizes );
        }
    }
}
Example #20
0
        Document
        createDocument(const boost::filesystem::path& file,
                       const ParseParameters&         params)
        {
          Platform xmlplat;

          xercesc::LocalFileInputSource source(String(file.generic_string()));

          xercesc::XercesDOMParser parser;
          setup_parser(parser, params);
          read_source(parser, source);

          return Document(parser.adoptDocument(), true);
        }
Example #21
0
int add_file(ff7::lgp::Archive& ar, fs::path const& path)
{
  int added{};

  if (is_directory(path)) {
    for (auto it = rec_it(path); it != rec_it(); ++it)
      if (is_regular_file(it->path())) {
        ar[it->path().generic_string()] = ff7::lgp::make_file(it->path().string());
        ++added;
      }
  
  } else if (is_regular_file(path)) {
    ar[path.generic_string()] = ff7::lgp::make_file(path.string());
    ++added;
  }
  return added;
}
Example #22
0
bool
Extract::extractSingle(const bfs::path& itemName,
                       std::ostream & os)
{
    unsigned char buf[BP_TAR_BUF_SIZE];
    bool success = false;

    struct archive * a = (struct archive *) m_state;;
    struct archive_entry * ae = NULL;

    if (a == NULL) return false;
    
    while (!(archive_read_next_header(a, &ae))) {
        const char * pn = archive_entry_pathname(ae);

        // and what if it IS null?
        if (pn != NULL && strlen(pn) > 0 &&
            !itemName.generic_string().compare(std::string(pn)))
        {
            // key off the tar header for file type
            unsigned int type = archive_entry_filetype(ae);

            if (AE_IFREG == type) {
                size_t sz;
                while ((sz = archive_read_data(a, (void *) buf,
                                               BP_TAR_BUF_SIZE)) > 0)
                {
                    os.write((const char *) buf, sz);
                }
                success = true;
            } else {
                // I don't know how to extract entries other than
                // regular files
            }
            break;
        }
    }

    // now we'll close and re-open the archive with touching m_data
    archive_read_finish((struct archive *) m_state);
    m_state = NULL;
    init();
    
    return success;
}
Example #23
0
StatusWith<std::unique_ptr<FTDCFileManager>> FTDCFileManager::create(
    const FTDCConfig* config,
    const boost::filesystem::path& path,
    FTDCCollectorCollection* collection,
    Client* client) {
    const boost::filesystem::path dir = boost::filesystem::absolute(path);

    if (!boost::filesystem::exists(dir)) {
        // Create the directory
        boost::system::error_code ec;
        boost::filesystem::create_directories(dir, ec);
        if (ec) {
            return {ErrorCodes::NonExistentPath,
                    str::stream() << "\'" << dir.generic_string()
                                  << "\' could not be created: " << ec.message()};
        }
    }

    auto mgr =
        std::unique_ptr<FTDCFileManager>(new FTDCFileManager(config, dir, std::move(collection)));

    // Enumerate the metrics files
    auto files = mgr->scanDirectory();

    // Recover the interim file
    auto interimDocs = mgr->recoverInterimFile();

    // Open the archive file for writing
    auto swFile = mgr->generateArchiveFileName(path, terseUTCCurrentTime());
    if (!swFile.isOK()) {
        return swFile.getStatus();
    }

    Status s = mgr->openArchiveFile(client, swFile.getValue(), interimDocs);
    if (!s.isOK()) {
        return s;
    }

    // Rotate as needed after we appended interim data to the archive file
    mgr->trimDirectory(files);

    return {std::move(mgr)};
}
 /** ssaxファイルを読み込む */
 SsMotion::Ptr loadSsax(const fs::path& ssaxPath, SsPlayerConverterResultCode& resultCode)
 {
     SsaxLoader::ResultCode result;
     SsMotion::Ptr motion = SsaxLoader::load(ssaxPath.generic_string(), &result);
     switch (result)
     {
         case SsaxLoader::SUCCESS:
             resultCode = SSPC_SUCCESS;
             break;
             
         case SsaxLoader::XML_PARSE_ERROR:
             resultCode = SSPC_SSAX_PARSE_FAILED;
             break;
             
         default:
             break;
     }
     return motion;
 }
adobe::dictionary_t parse_input_dictionary(const bfs::path& input_path) {
    std::string path_str(input_path.generic_string());
    std::ifstream input_stream(path_str.c_str());
    adobe::array_t token_stream;
    adobe::virtual_machine_t vm;

    if (!adobe::expression_parser(input_stream, adobe::line_position_t("input_dictionary"))
             .is_expression(token_stream))
        return adobe::dictionary_t();

    vm.evaluate(token_stream);

    const adobe::dictionary_t result(vm.back().cast<adobe::dictionary_t>());

    vm.pop_back();

    std::cout << "--" << std::endl
              << "Initializing sheet with the following input dictionary: " << adobe::begin_asl_cel
              << result << adobe::end_asl_cel << std::endl << "--" << std::endl;

    return result;
}
Example #26
0
std::string UpdateFetcher::ReadSQLUpdate(boost::filesystem::path const& file) const
{
    std::ifstream in(file.c_str());
    if (!in.is_open())
    {
        TC_LOG_FATAL("sql.updates", "Failed to open the sql update \"%s\" for reading! "
                     "Stopping the server to keep the database integrity, "
                     "try to identify and solve the issue or disable the database updater.",
                     file.generic_string().c_str());

        throw UpdateException("Opening the sql update failed!");
    }

    auto update = [&in]  {
        std::ostringstream ss;
        ss << in.rdbuf();
        return ss.str();
    }();

    in.close();
    return update;
}
    sheet_tracker(const bfs::path& sheet_path, const bfs::path& input_path)
        : callbacks_m(adobe::bind_to_sheet(sheet_m)) {
        //  attach the VM to the sheet.
        sheet_m.machine_m.set_variable_lookup(boost::bind(&adobe::sheet_t::get, &sheet_m, _1));

        std::string sheet_path_str(sheet_path.generic_string());
        std::ifstream sheet_stream(sheet_path_str.c_str());

        callbacks_m.add_cell_proc_m = boost::bind(&sheet_tracker::add_cell_trap, boost::ref(*this),
                                                  callbacks_m.add_cell_proc_m, _1, _2, _3, _4);
        callbacks_m.add_interface_proc_m =
            boost::bind(&sheet_tracker::add_interface_trap, boost::ref(*this),
                        callbacks_m.add_interface_proc_m, _1, _2, _3, _4, _5, _6);

        if (!sheet_stream.is_open())
            std::cerr << "Could not open \"" << sheet_path_str << "\"!\n";

        // set up adam sheet
        adobe::parse(sheet_stream, adobe::line_position_t("property model sheet"), callbacks_m);

        sheet_m.set(parse_input_dictionary(input_path));

        sheet_m.update();
    }
Example #28
0
void FileSourceProvider::fillSourceFields(const boost::filesystem::path& source, SourceId::Builder& builder)
{
    builder.set_value(source.generic_string())
           .set_uniquePresentation(getUniquePresentationString(source))
           .set_externalElements(getExternalElements(source));
}
Example #29
0
std::string inclusion_expander::
to_inclusion_directive(const boost::filesystem::path& p) const {
    std::ostringstream ss;
    ss << double_quote << p.generic_string() << double_quote;
    return ss.str();
}
Example #30
0
double Match::match(fs::path path1, fs::path path2)
{
	Mat img1 = imread(path1.generic_string());
	Mat img2 = imread(path2.generic_string());
	return match(&img1, &img2);
}