Example #1
0
void XplDevice::SaveConfig()
{
    
    
    Poco::Path p = GetConfigFileLocation();
    poco_debug ( devLog, "saving config for  " + GetCompleteId() + " to " + p.toString());

    m_configStore->setString("vendorId", GetVendorId());
    m_configStore->setString("deviceId", GetDeviceId());
    m_configStore->setString("instanceId", GetInstanceId());

    
    if(m_configItems.size()) {
        m_configStore->setInt("configItems",m_configItems.size());
        for ( vector<AutoPtr<XplConfigItem> >::iterator iter = m_configItems.begin(); iter != m_configItems.end(); ++iter )
        {
            poco_debug ( devLog, "saving config item  " + (*iter)->GetName());
            m_configStore->setString("configItems." + (*iter)->GetName(), ""  );
            m_configStore->setString("configItems." + (*iter)->GetName() + ".numValues" , NumberFormatter::format((*iter)->GetNumValues())  );
            
            for (int vindex=0; vindex<(*iter)->GetNumValues(); vindex++) {
                m_configStore->setString("configItems." + (*iter)->GetName() + ".value" + NumberFormatter::format(vindex) , (*iter)->GetValue(vindex)  );
            }
        }
    }
    
    
    m_configStore->save(p.toString());
    poco_debug ( devLog, "saved to " + p.toString());
    
}
Example #2
0
   // recusively delete the path given. we do this manually to set the permissions to writable,
   // so that windows doesn't cause permission denied errors.
   cResult deltree(Poco::Path s)
   {
      drunner_assert(s.isDirectory(), "deltree: asked to delete a file: "+s.toString());
      cResult rval = kRNoChange;

      try
      {
         Poco::DirectoryIterator end;
         for (Poco::DirectoryIterator it(s); it != end; ++it)
            if (it->isFile())
               rval += delfile(it->path());
            else
            {
               Poco::Path subdir(it->path());
               subdir.makeDirectory();
               rval += deltree(subdir);
            }

         Poco::File f(s);
         f.setWriteable(true);
         f.remove();
         logmsg(kLDEBUG, "Deleted " + f.path());
      }
      catch (const Poco::Exception & e) {
         return cError("Couldn't delete " + s.toString() + " - " + e.what());
      }
      return kRSuccess;
   }
// ---
bool VSWAEImportContentWindow::validateDir (const QString& d)
{
	bool result = false;

	// Calculates the paths for everything: the basic dir, the definition file...
	// ...and the basic path received as parameter during the initialization.
	Poco::Path defPath;
	Poco::File defFile;
	Poco::File defDir (d.toStdString ());
	Poco::Path bPath (_basicPath.toStdString ());
	bool isDefDirADir = defDir.isDirectory (); // The directory has to be a dir (this is guarantte by the window, but just in case)
	if (isDefDirADir) 
	{
		defPath = Poco::Path (d.toStdString ());
		defFile = Poco::File ((d + QString (__PATH_SEPARATOR__) + 
			_name -> text () + QString (".xml")).toStdString ());
	}

	// If the directory is a directory, then it is needed to test whether the
	// directory is or not contained in the basic path received as parameter.
	bool isDefDirInBPath = false;
	if (isDefDirADir)
		isDefDirInBPath = ((defPath.toString () + std::string (__PATH_SEPARATOR__)).
			find (bPath.toString () + std::string (__PATH_SEPARATOR__)) != -1);

	// To determinate whether the dir is or not valid...
	result = !isDefDirADir || (isDefDirADir && isDefDirInBPath);

	return (result);
}
Example #4
0
    int CStatsUtil::DoImportGameStrings()
    {
        Poco::Path inpath(m_inputPath);
        Poco::Path outpath;
        
        if( m_outputPath.empty() )
            throw runtime_error("Output path unspecified!");

        if( utils::isFolder( m_outputPath ) )
        {
            outpath = Poco::Path(m_outputPath).makeAbsolute().makeDirectory();
            GameStats gstats( outpath.toString(), m_langconf );
            gstats.AnalyzeGameDir();
            gstats.ImportStrings( m_inputPath );
            gstats.WriteStrings();
        }
        else
        {
            outpath = Poco::Path(m_outputPath).makeAbsolute();

            if( ! m_flocalestr.empty() )
            {
                auto myloc = std::locale( m_flocalestr );
                pmd2::filetypes::WriteTextStrFile( outpath.toString(), utils::io::ReadTextFileLineByLine( m_inputPath, myloc ), myloc );
            }
            else
            {
                pmd2::filetypes::WriteTextStrFile( outpath.toString(), utils::io::ReadTextFileLineByLine(m_inputPath) );
            }
        }
        return 0;
    }
Example #5
0
/**
 * Sets the location of the module given an absolute or relative location.
 * For relative paths we look for the
 * module first in PROG_DIR, then MODULE_DIR, then the
 * current directory, and 
 * finally the system path. Will throw an exception if the module cannot 
 * be found.
 * @param location Absolute or relative path string for module.
 */
void TskModule::setPath(const std::string& location)
{
    if (location.empty()) 
    {
        throw TskException("TskModule::setPath: location is empty or missing.");
    }

    Poco::Path tempPath = location;

    if (!tempPath.isAbsolute())
    {
        // If this is a relative path, then see if we can find the
        // executable either in PROG_DIR, in MODULE_DIR, in the current directory,
        // or on the system path.        
        std::string pathsToSearch = GetSystemProperty(TskSystemProperties::PROG_DIR); 
        if (!pathsToSearch.empty())
            pathsToSearch += Poco::Path::pathSeparator();
        pathsToSearch += GetSystemProperty(TskSystemProperties::MODULE_DIR);
        if (!pathsToSearch.empty())
            pathsToSearch += Poco::Path::pathSeparator();
        pathsToSearch += ".";

        if (!Poco::Path::find(pathsToSearch, location, tempPath))
        {
            // if we didn't find them in the above paths, check on the path. 
            if (Poco::Environment::has("Path"))
            {
                std::string systemPath = Poco::Environment::get("Path");
            
                if (!systemPath.empty())
                {
                    Poco::Path::find(systemPath, location, tempPath);
                }
            }
        }
    }

    // Confirm existence of file at location.
    Poco::File moduleFile(tempPath);

    if (!moduleFile.exists())
    {
        std::stringstream msg;
        msg << "TskModule::setPath - Module not found: "
            << tempPath.toString().c_str();
        throw TskException(msg.str());
    }
    else {
        std::wstringstream msg;
        msg << L"TskModule::setPath - Module found at: "
            << tempPath.toString().c_str();
        LOGINFO(msg.str());
    }

    m_modulePath = tempPath.toString();
}
Example #6
0
      void CWidget::update(CWorkerTools::WorkerProgressFunc progressCallback, const std::string & widgetName, const std::string & downloadUrl)
      {
         YADOMS_LOG(information) << "Updating widget " << widgetName << " from " << downloadUrl;

         shared::CDataContainer callbackData;
         callbackData.set("widgetName", widgetName);
         callbackData.set("downloadUrl", downloadUrl);

         progressCallback(true, 0.0f, i18n::CClientStrings::UpdateWidgetUpdate, shared::CStringExtension::EmptyString, callbackData);
         /////////////////////////////////////////////
         //1. download package
         /////////////////////////////////////////////
         try
         {
            YADOMS_LOG(information) << "Downloading widget package";
            progressCallback(true, 0.0f, i18n::CClientStrings::UpdateWidgetDownload, shared::CStringExtension::EmptyString, callbackData);
            Poco::Path downloadedPackage = CWorkerTools::downloadPackage(downloadUrl, progressCallback, i18n::CClientStrings::UpdateWidgetDownload, 0.0, 90.0);
            YADOMS_LOG(information) << "Downloading widget package with sucess";



            /////////////////////////////////////////////
            //2. deploy package
            /////////////////////////////////////////////
            try
            {
               YADOMS_LOG(information) << "Deploy widget package " << downloadedPackage.toString();
               progressCallback(true, 90.0f, i18n::CClientStrings::UpdateWidgetDeploy, shared::CStringExtension::EmptyString, callbackData);
               Poco::Path widgetPath = CWorkerTools::deployWidgetPackage(downloadedPackage);

               YADOMS_LOG(information) << "Widget installed with success";
               progressCallback(true, 100.0f, i18n::CClientStrings::UpdateWidgetSuccess, shared::CStringExtension::EmptyString, callbackData);
            }
            catch (std::exception & ex)
            {
               //fail to extract package file
               YADOMS_LOG(error) << "Fail to deploy widget package : " << ex.what();
                progressCallback(false, 100.0f, i18n::CClientStrings::UpdateWidgetDeployFailed, ex.what(), callbackData);
            }


            //delete downloaded zip file
            Poco::File toDelete(downloadedPackage.toString());
            if (toDelete.exists())
               toDelete.remove();

         }
         catch (std::exception & ex)
         {
            //fail to download package
            YADOMS_LOG(error) << "Fail to download pwidget ackage : " << ex.what();
            progressCallback(false, 100.0f, i18n::CClientStrings::UpdateWidgetDownloadFailed, ex.what(), callbackData);
         }
      }
Example #7
0
    /**
     *    Creates a set of files that match the given pathPattern.
     *   
     *    The path may be give in either Unix, Windows or VMS syntax and
     *    is automatically expanded by calling Path::expand().
     *   
     *    The pattern may contain wildcard expressions even in intermediate
     *    directory names (e.g. /usr/include/<I>*</I> /<I>*</I>*.h).
     *   
     *    Note that, for obvious reasons, escaping characters in a pattern
     *    with a backslash does not work in Windows-style paths.
     *   
     *    Directories that for whatever reason cannot be traversed are
     *    ignored.
     *    
     *    It seems that whatever bug Poco had is fixed now. 
     *    So calling Poco::Glob::glob(pathPattern,files,options) inside.
     *
     *    @param pathPattern :: The search pattern 
     *    @param files :: The names of the files that match the pattern
     *    @param options :: Options
     */
void Glob::glob(const Poco::Path& pathPattern, std::set<std::string>& files, int options)
{
#ifdef _WIN32
  // There appears to be a bug in the glob for windows.
  // Putting case sensitive on then with reference to test testFindFileCaseSensitive()
  // in FileFinderTest on Windows it is able to find "CSp78173.Raw" as it should even
  // the case is wrong, but for some strange reason it then cannot find IDF_for_UNiT_TESTiNG.xMl!!!!
  // Hence the reason to circumvent this by this #ifdef
  Poco::Glob::glob(Poco::Path(pathPattern.toString()),files, Poco::Glob::GLOB_CASELESS);
#else
  Poco::Glob::glob(Poco::Path(pathPattern.toString()),files,options);
#endif
}
Example #8
0
   tempfolder::tempfolder(Poco::Path d) : mPath(d)
   {   // http://stackoverflow.com/a/10232761
      Poco::File f(d);

      if (f.exists() && kRSuccess != utils::deltree(d))
         die("Couldn't delete old stuff in temp directory: " + d.toString());

      f.createDirectories();
      logmsg(kLDEBUG, "Created " + d.toString());

#ifndef _WIN32
      if (chmod(d.toString().c_str(), S_777) != 0)
         die("Unable to change permissions on " + d.toString());
#endif
   }
Example #9
0
	void AsyncCopy::Copy(Poco::Path &src, Poco::Path &dest)
	{
		Logger* logger = Logger::Get("Filesystem.AsyncCopy");
		std::string srcString = src.toString();
		std::string destString = dest.toString();
		Poco::File from(srcString);
		bool isLink = from.isLink();

		logger->Debug("file=%s dest=%s link=%i", srcString.c_str(), destString.c_str(), isLink);
#ifndef OS_WIN32
		if (isLink)
		{
			char linkPath[PATH_MAX];
			ssize_t length = readlink(from.path().c_str(), linkPath, PATH_MAX);
			linkPath[length] = '\0';

			std::string newPath (dest.toString());
			const char *destPath = newPath.c_str();
			unlink(destPath); // unlink it first, fails in some OS if already there
			int result = symlink(linkPath, destPath);

			if (result == -1)
			{
				std::string err = "Copy failed: Could not make symlink (";
				err.append(destPath);
				err.append(") from ");
				err.append(linkPath);
				err.append(" : ");
				err.append(strerror(errno));
				throw kroll::ValueException::FromString(err);
			}
		}
#endif
		if (!isLink && from.isDirectory())
		{
			Poco::File d(dest.toString());
			if (!d.exists())
			{
				d.createDirectories();
			}
			std::vector<std::string> files;
			from.list(files);
			std::vector<std::string>::iterator i = files.begin();
			while(i!=files.end())
			{
				std::string fn = (*i++);
				Poco::Path sp(kroll::FileUtils::Join(src.toString().c_str(),fn.c_str(),NULL));
				Poco::Path dp(kroll::FileUtils::Join(dest.toString().c_str(),fn.c_str(),NULL));
				this->Copy(sp,dp);
			}
		}
		else if (!isLink)
		{
			// in this case it's a regular file
			Poco::File s(src.toString());
			s.copyTo(dest.toString().c_str());
		}
	}
Example #10
0
    int CStatsUtil::DoExportAll()
    {
        Poco::Path inpath(m_inputPath);
        Poco::Path outpath;
        
        if( m_outputPath.empty() )
        {
            outpath = inpath.absolute().makeParent().append(DefExportAllDir);
        }
        else
        {
            outpath = Poco::Path(m_outputPath).makeAbsolute();
        }

        GameStats gstats( m_inputPath, m_langconf );
        gstats.Load();

        //Test output path
        Poco::File fTestOut = outpath;
        if( ! fTestOut.exists() )
        {
            cout << "Created output directory \"" << fTestOut.path() <<"\"!\n";
            fTestOut.createDirectory();
        }
        gstats.ExportAll(outpath.toString());
        return 0;
    }
Example #11
0
    int CStatsUtil::DoExportGameScripts()
    {
        //Validate output + input paths
        Poco::Path inpath(m_inputPath);
        Poco::Path outpath;
        
        if( m_outputPath.empty() )
            outpath = inpath.absolute().makeParent().append(DefExportScriptsDir);
        else
            outpath = Poco::Path(m_outputPath).makeAbsolute();

        Poco::File fTestOut = outpath;
        if( ! fTestOut.exists() )
        {
            cout << "Created output directory \"" << fTestOut.path() <<"\"!\n";
            fTestOut.createDirectory();
        }
        else if( ! fTestOut.isDirectory() )
            throw runtime_error("CStatsUtil::DoExportGameScripts(): Output path is not a directory!");

        //Setup the script handler
        GameScripts scripts( inpath.absolute().toString() );

        //Convert to XML
        scripts.ExportScriptsToXML( outpath.toString() );

        return 0;
    }
Example #12
0
std::string mui::Helpers::muiPath( std::string path ){
	// pretty much copy&pasted from OF
	Poco::Path outputPath;
	Poco::Path inputPath(path);
	string strippedDataPath = mui::MuiConfig::dataPath.toString();
	strippedDataPath = ofFilePath::removeTrailingSlash(strippedDataPath);
	if (inputPath.toString().find(strippedDataPath) != 0) {
		outputPath = mui::MuiConfig::dataPath;
		outputPath.resolve(inputPath);
	} else {
		outputPath = inputPath;
	}
	
	if( !ofFile(outputPath.absolute().toString(), ofFile::Reference).exists() ){
		// maybe in the data dir?
		string dataFile = ofToDataPath(path, true);
		if( ofFile(dataFile,ofFile::Reference).exists() ){
			outputPath = Poco::Path(dataFile);
		}
	}
	
	if( mui::MuiConfig::logLevel <= OF_LOG_NOTICE ){
		cout << "loading path: " << outputPath.toString() << " || " << outputPath.absolute().toString() << " || " << path << endl;
	}
	return outputPath.absolute().toString();
}
Example #13
0
QStringList QtAssistantUtil::ExtractQCHFiles(const std::vector<IBundle::Pointer>& bundles)
{
  QStringList result;

  for (std::size_t i = 0; i < bundles.size(); ++i)
  {
    std::vector<std::string> resourceFiles;
    bundles[i]->GetStorage().List("resources", resourceFiles);
    bool qchFileFound = false;
    for (std::size_t j = 0; j < resourceFiles.size(); ++j)
    {
      QString resource = QString::fromStdString(resourceFiles[j]);
      if (resource.endsWith(".qch"))
      {
        qchFileFound = true;
        Poco::Path qchPath = bundles[i]->GetPath();
        qchPath.pushDirectory("resources");
        qchPath.setFileName(resourceFiles[j]);
        result << QString::fromStdString(qchPath.toString());
      }
    }

    if (qchFileFound)
    {
      registeredBundles.insert(QString::fromStdString(bundles[i]->GetSymbolicName()));
    }
  }

  return result;
}
Example #14
0
IBundleActivator*
BundleLoader::LoadActivator(BundleInfo& bundleInfo)
{
  Poco::Mutex::ScopedLock lock(m_Mutex);
  std::string activator = bundleInfo.m_Bundle->GetActivatorClass();

  if (activator == "") return new DefaultActivator();

  Poco::Path libPath = this->GetLibraryPathFor(bundleInfo.m_Bundle);
  std::string strLibPath(libPath.toString());

  BERRY_INFO(m_ConsoleLog) << "Loading activator library: " << strLibPath;
  try
  {
  /* retrieves only an empty string and its not required
#ifdef BERRY_OS_FAMILY_WINDOWS
    char cDllPath[512];
    GetDllDirectory(512, cDllPath);
    BERRY_INFO << "Dll Path: " << cDllPath << std::endl;
#endif
  */
    bundleInfo.m_ClassLoader->loadLibrary(strLibPath);
    return bundleInfo.m_ClassLoader->create(activator);
  }
  catch (Poco::LibraryLoadException exc)
  {
    BERRY_ERROR << "Could not create Plugin activator. Did you export the class \"" << activator << "\" ?\n"
                 << "  Exception displayText(): " << exc.displayText();
    exc.rethrow();
  }

  return 0;
}
Example #15
0
string getOFRelPath(string from){
    Poco::Path base(true);
    base.parse(from);

    Poco::Path path;
    path.parse( getOFRoot() );
    path.makeAbsolute();

    
    cout << "getOFRelPath " << base.toString() << " " << path.toString() << endl;
    
	string relPath;
	if (path.toString() == base.toString()){
		// do something.
	}

	int maxx = MAX(base.depth(), path.depth());
	for (int i = 0; i <= maxx; i++){

		bool bRunOut = false;
		bool bChanged = false;
		if (i <= base.depth() && i <= path.depth()){
			if (base.directory(i) == path.directory(i)){

			} else {
				bChanged = true;
			}
		} else {
			bRunOut = true;
		}
		if (bRunOut == true || bChanged == true){
			for (int j = i; j <= base.depth(); j++){
				relPath += "../";
			}
			for (int j = i; j <= path.depth(); j++){
				relPath += path.directory(j) + "/";
			}
			break;
		}
	}
    
    cout << relPath << " ---- " << endl;
    
    
    return relPath;
}
Example #16
0
   cResult makedirectory(Poco::Path d, mode_t mode)
   {
      Poco::File f(d);
      if (!f.exists())
      {
         if (!utils::fileexists(d.parent()))
            return cError("Parent directoy doesn't exist: " + d.parent().toString());
         f.createDirectory();
         logdbg("Created " + d.toString());
      }

#ifndef _WIN32
      if (chmod(d.toString().c_str(), mode) != 0)
         return cError("Unable to change permissions on " + d.toString());
#endif

      return kRSuccess;
   }
Example #17
0
/**
Common method used by all constructors. Creates a file containing the ASCII file
contents and 'remembers' the location of that file.
*/
void ScopedFile::doCreateFile(const std::string &fileContents,
                              const Poco::Path &fileNameAndPath) {
  m_filename = fileNameAndPath.toString();
  m_file.open(m_filename.c_str(), std::ios_base::out);
  if (!m_file.is_open()) {
    throw std::runtime_error("Cannot open " + m_filename);
  }
  m_file << fileContents;
  m_file.close();
}
Example #18
0
Poco::Path SharedMemoryTest::findDataFile(const std::string& afile)
{
	Poco::Path root;
	root.makeAbsolute();
	Poco::Path result;
	while (!Poco::Path::find(root.toString(), "data", result))
	{
		root.makeParent();
		if (root.toString().empty() || root.toString() == "/")
			throw Poco::FileNotFoundException("Didn't find data subdir");
	}
	result.makeDirectory();
	result.setFileName(afile);
	Poco::File aFile(result.toString());
	if (!aFile.exists() || (aFile.exists() && !aFile.isFile()))
		throw Poco::FileNotFoundException("Didn't find file " + afile);
	
	return result;
}
Example #19
0
	void Host::ReadModuleManifest(std::string& modulePath)
	{
		Poco::Path manifestPath(modulePath);
		Poco::Path moduleTopDir = manifestPath.parent();

		manifestPath = Poco::Path(FileUtils::Join(moduleTopDir.toString().c_str(), "manifest", NULL));

		Poco::File manifestFile(manifestPath);
		if (manifestFile.exists()) 
		{
			this->logger->Trace("Reading manifest for module: %s", manifestPath.toString().c_str());
			Poco::AutoPtr<Poco::Util::PropertyFileConfiguration> manifest = new Poco::Util::PropertyFileConfiguration(manifestFile.path());

			if (manifest->hasProperty("libpath")) 
			{
				std::string libPath = manifest->getString("libpath");
				Poco::StringTokenizer t(libPath, ",", Poco::StringTokenizer::TOK_TRIM);
	#if defined(OS_WIN32)
				std::string libPathEnv = "PATH";
	#elif defined(OS_OSX)
				std::string libPathEnv = "DYLD_LIBRARY_PATH";
	#elif defined(OS_LINUX)
				std::string libPathEnv = "LD_LIBRARY_PATH";
	#endif
				std::string newLibPath;

				if (Environment::has(libPathEnv)) 
				{
					newLibPath = Environment::get(libPathEnv);
				}

				for (size_t i = 0; i < t.count(); i++) 
				{
					std::string lib = t[i];
					newLibPath = FileUtils::Join(moduleTopDir.toString().c_str(), lib.c_str(), NULL) +
						KR_LIB_SEP + newLibPath;
				}

				this->logger->Debug("%s=%s", libPathEnv.c_str(), newLibPath.c_str());
				Environment::set(libPathEnv, newLibPath);
			}
		}
	}
    /**
     * Module initialization function. Optionally receives an output folder
     * path as the location for saving the files corresponding to interesting
     * file set hits. The default output folder path is a folder named for the
     * module in #MODULE_OUT_DIR#.
     *
     * @param args Optional output folder path.
     * @return TskModule::OK if an output folder is created, TskModule::FAIL
     * otherwise. 
     */
    TSK_MODULE_EXPORT TskModule::Status initialize(const char* arguments)
    {
        TskModule::Status status = TskModule::OK;

        const std::string MSG_PREFIX = "SaveInterestingFilesModule::initialize : ";
        try
        {
            Poco::Path outputDirPath;
            if (strlen(arguments) != 0)
            {
                outputDirPath = Poco::Path::forDirectory(arguments);
            }
            else
            {
                outputDirPath = Poco::Path::forDirectory(GetSystemProperty(TskSystemProperties::MODULE_OUT_DIR));
                outputDirPath.pushDirectory(name());
            }
            outputFolderPath = outputDirPath.toString();

            Poco::File(outputDirPath).createDirectory();
        }
        catch (TskException &ex)
        {
            status = TskModule::FAIL;
            outputFolderPath.clear();
            std::stringstream msg;
            msg << MSG_PREFIX << "TskException: " << ex.message();
            LOGERROR(msg.str());
        }
        catch (Poco::Exception &ex)
        {
            status = TskModule::FAIL;
            outputFolderPath.clear();
            std::stringstream msg;
            msg << MSG_PREFIX << "Poco::Exception: " << ex.displayText();
            LOGERROR(msg.str());
        }
        catch (std::exception &ex)
        {
            status = TskModule::FAIL;
            outputFolderPath.clear();
            std::stringstream msg;
            msg << MSG_PREFIX << "std::exception: " << ex.what();
            LOGERROR(msg.str());
        }
        catch (...)
        {
            status = TskModule::FAIL;
            outputFolderPath.clear();
            LOGERROR(MSG_PREFIX + "unrecognized exception");
        }

        return status;
    }
std::string EnggDiffractionViewQtGUI::guessGSASTemplatePath() const {
  // Inside the mantid installation target directory:
  // scripts/Engineering/template_ENGINX_241391_236516_North_and_South_banks.par
  Poco::Path templ =
      Mantid::Kernel::ConfigService::Instance().getInstrumentDirectory();
  templ = templ.makeParent();
  templ.append("scripts");
  templ.append("Engineering");
  templ.append("template_ENGINX_241391_236516_North_and_South_banks.par");
  return templ.toString();
}
Example #22
0
void ComputeApp::initialize(Application& self)
{
    Application::initialize(self);

    Poco::Path appPath = commandPath();
    appPath.setExtension("");
    appPath.setFileName("");
    exeDirectory = appPath.toString();

    loadConfiguration();
}
Example #23
0
void Converter::initialize( 
    const string_t& inputFolder, 
    const string_t& outputFolder,
    const string_t& mappingFolder )
{
    inputFolder_   = Poco::Path(inputFolder)
        .makeAbsolute()
        .makeDirectory()
        .toString();

    outputFolder_  = Poco::Path(outputFolder)
        .makeAbsolute()
        .makeDirectory()
        .toString();

    mappingFolder_ = Poco::Path(mappingFolder)
        .makeAbsolute()
        .makeDirectory()
        .toString();

    /// load font names which support all languages. these are generic unicode
    loadFontList(mappingFolder_ + "font-generic-unicode.txt", fontsAllCharSupport_);

    /// load fonts that should be ignore as they are discovered
    loadFontList(mappingFolder_ + "font-ignore-list.txt",     fontsToIgnore_);
    
    /// characters mapping for each available language
    FileFinder ff(true, mappingFolder_);
    auto files = ff.getFiles();
    auto dirs  = ff.getDirs();

    for (auto itd = dirs.begin(); itd != dirs.end(); ++itd) {
        Poco::Path langDir = Poco::Path(ff.getRootPath())
            .pushDirectory(*itd)
            .makeDirectory();

        loadKnownAsciiFonts(langDir.toString(), *itd);
        loadNamesMapping(langDir.toString() + "font-mapping-default.txt", *itd, false);
        loadNamesMapping(langDir.toString() + "font-mapping-user.txt", *itd, true);
    }
}
std::string EnggDiffractionViewQtGUI::guessDefaultFullCalibrationPath() const {
  // Inside the mantid installation target directory:
  // scripts/Engineering/ENGINX_full_pixel_calibration_vana194547_ceria193749.csv
  Poco::Path templ =
      Mantid::Kernel::ConfigService::Instance().getInstrumentDirectory();
  templ = templ.makeParent();
  templ.append("scripts");
  templ.append("Engineering");
  templ.append("calib");
  templ.append("ENGINX_full_pixel_calibration_vana194547_ceria193749.csv");
  return templ.toString();
}
Example #25
0
int countLoolKitProcesses()
{
    // Give polls in the lool processes time to time out etc
    Poco::Thread::sleep(POLL_TIMEOUT_MS*5);

    int result = 0;

    for (auto i = Poco::DirectoryIterator(std::string("/proc")); i != Poco::DirectoryIterator(); ++i)
    {
        try
        {
            Poco::Path procEntry = i.path();
            const std::string& fileName = procEntry.getFileName();
            int pid;
            std::size_t endPos = 0;
            try
            {
                pid = std::stoi(fileName, &endPos);
            }
            catch (const std::invalid_argument&)
            {
                pid = 0;
            }
            if (pid > 1 && endPos == fileName.length())
            {
                Poco::FileInputStream stat(procEntry.toString() + "/stat");
                std::string statString;
                Poco::StreamCopier::copyToString(stat, statString);
                Poco::StringTokenizer tokens(statString, " ");
                if (tokens.count() > 3 && tokens[1] == "(loolkit)")
                {
                    switch (tokens[2].c_str()[0])
                    {
                    case 'x':
                    case 'X': // Kinds of dead-ness.
                    case 'Z': // zombies
                        break; // ignore
                    default:
                        result++;
                        break;
                    }
                    // std::cout << "Process:" << pid << ", '" << tokens[1] << "'" << " state: " << tokens[2] << std::endl;
                }
            }
        }
        catch (const Poco::Exception&)
        {
        }
    }

    // std::cout << "Number of loolkit processes: " << result << std::endl;
    return result;
}
Example #26
0
Poco::Path XplDevice::GetConfigFileLocation() {
    Poco::Path p ( Poco::Path::home() );
    p.pushDirectory ( ".xPL" );
    File test = File(p);
    if (!test.exists()){
        poco_debug ( devLog, "dir doesn't exist:  " + p.toString() );
        test.createDirectory();
    }
    p.pushDirectory ( "xPLSDK_configs" );
    test = File(p);
    if (!test.exists()){
        poco_debug ( devLog, "dir doesn't exist:  " + p.toString() );
        test.createDirectory();
    }
    p.setFileName ( GetCompleteId() + ".conf" );
    test = File(p);
    if (!test.exists()){
        poco_debug ( devLog, "file doesn't exist:  " + p.toString() );
        test.createFile();
    }
    return p;
}
void DebugBreakpointManager::SaveState(const Poco::Path& path) const
{
  Poco::XML::Document* doc = new Poco::XML::Document();
  Poco::XML::Element* breakpoints = doc->createElement(BREAKPOINTS_TAG);
  doc->appendChild(breakpoints)->release();

  for (std::set<unsigned long>::const_iterator i = m_ObjectBreakpoints.begin(); i
      != m_ObjectBreakpoints.end(); ++i)
  {
    Poco::XML::Element* objectBreakpoint = doc->createElement(OBJECT_TAG);
    breakpoints->appendChild(objectBreakpoint)->release();
    std::stringstream ss;
    ss << *i;
    objectBreakpoint->setAttribute(ID_ATTR, ss.str());

    const Object* obj = DebugUtil::GetObject(*i);
    if (obj)
    {
      objectBreakpoint->setAttribute(CLASSNAME_ATTR, obj->GetClassName());

    }
  }

  for (Poco::HashMap<int, const Object*>::ConstIterator i =
      m_SmartPointerBreakpoints.begin(); i != m_SmartPointerBreakpoints.end(); ++i)
  {
    Poco::XML::Element* spBreakpoint = doc->createElement(SMARTPOINTER_TAG);
    breakpoints->appendChild(spBreakpoint)->release();
    std::stringstream ss;
    ss << i->first;
    spBreakpoint->setAttribute(ID_ATTR, ss.str());

    const Object* obj = i->second;
    if (i->second)
    {
      spBreakpoint->setAttribute(CLASSNAME_ATTR, obj->GetClassName());
      ss.clear();
      ss << obj->GetTraceId();
      spBreakpoint->setAttribute(OBJECTID_ATTR, ss.str());
    }
  }

  Poco::FileOutputStream writer(path.toString());
  Poco::XML::DOMWriter out;
  out.setOptions(3); //write declaration and pretty print
  out.writeNode(writer, doc);

  doc->release();
}
Example #28
0
const std::string OptionsPage::GenerateContent(const std::string &method, const std::map<std::string,QueryVar> &queryvars)
{
	std::string content("");
	std::string sql("");

	if(queryvars.find("formaction")!=queryvars.end() && (*queryvars.find("formaction")).second=="save" && ValidateFormPassword(queryvars))
	{
		Option option(m_db);
		option.ClearCache();
		std::vector<std::string> options;
		std::vector<std::string> oldvalues;
		std::vector<std::string> newvalues;
		CreateArgArray(queryvars,"option",options);
		CreateArgArray(queryvars,"oldvalue",oldvalues);
		CreateArgArray(queryvars,"value",newvalues);

		for(int i=0; i<options.size(); i++)
		{
			if(oldvalues[i]!=newvalues[i])
			{

				option.Set(options[i],newvalues[i]);

				// load new language immediately
				if(options[i]=="Language")
				{
					Poco::Path tdir;
					tdir.pushDirectory(global::basepath+"translations");
					tdir=tdir.makeAbsolute();
					tdir.setFileName(newvalues[i]);
					m_trans->LoadLocalizedTranslation(tdir.toString());
				}

				if(options[i]=="MessageDownloadMaxDaysBackward")
				{
					m_db->Execute("INSERT OR IGNORE\
								INTO tblMessageRequests (IdentityID, Day, RequestIndex, Found)\
								SELECT M.IdentityID, M.InsertDate, M.MessageIndex, 'true'\
								FROM tblMessage M\
								LEFT JOIN tblMessageRequests R\
									ON M.IdentityID=R.IdentityID\
									AND M.MessageIndex=R.RequestIndex\
									AND M.InsertDate=R.Day\
								WHERE R.IdentityID IS NULL\
								AND M.IdentityID IS NOT NULL\
								AND M.InsertDate >= date('now',(SELECT -MAX(OptionValue,0) FROM tblOption \
									WHERE Option='MessageDownloadMaxDaysBackward')||' days');");
				}
			}
Example #29
0
/**
 * Confirm that an executable file exists at location.
 */
void TskExecutableModule::setPath(const std::string& location)
{
    try
    {
        // Autogenerate filename extension if needed
        Poco::Path tempPath = location;
        if (tempPath.getExtension().empty())
        {
            std::string os = Poco::Environment::osName();
            if (os.find("Windows") != std::string::npos ||
                os.find("CYGWIN")  != std::string::npos ||
                os.find("MINGW")   != std::string::npos )
            {
                tempPath.setExtension("exe");
            }
            // Else we assume the user is on a platform that doesn't use executable extensions.
        }

        // Call our parent to validate the location.
        TskModule::setPath(tempPath.toString());

        m_name = Poco::Path(m_modulePath).getBaseName();

        // Verify that the file is executable.
        Poco::File exeFile(m_modulePath);

        if (!exeFile.canExecute())
        {
            std::wstringstream msg;
            msg << L"TskExecutableModule::setPath - File is not executable: "
                << m_modulePath.c_str();
            LOGERROR(msg.str());
            throw TskException("File is not executable.");
        }
    }
    catch (TskException& tskEx)
    {
        throw tskEx;
    }
    catch(std::exception& ex)
    {
        // Log a message and throw a framework exception.
        std::wstringstream msg;
        msg << "TskExecutableModule::setPath : " << ex.what();
        LOGERROR(msg.str());

        throw TskException("Failed to set location: " + m_modulePath);
    }
}
Example #30
0
/// Loads and registers plugin libraries
bool LoadPlugins (pI::BaseApplication& app) {

    std::string baseDir = app.FindPIBaseDir();

    if (baseDir.empty()) {
        return false;
    }

    Poco::Path pluginDir (baseDir);

#ifdef _DEBUG
    pluginDir.pushDirectory ("DistDebug");
#else
    pluginDir.pushDirectory ("DistRelease");
#endif

    app.LoadPluginLibrary (pluginDir.toString().c_str(), "CImg_pIns");
    app.LoadPluginLibrary (pluginDir.toString().c_str(), "FLLL_pIns");
    app.LoadPluginLibrary (pluginDir.toString().c_str(), "OpenCV_pIns");
    app.LoadPluginLibrary (pluginDir.toString().c_str(), "Freenect_pIns");

    app.RegisterPlugins();
    return true;
}