コード例 #1
0
bool WorkbenchPlugin::GetDataPath(Poco::Path& path)
{
  QFileInfo fileInfo = bundleContext->getDataFile("");
  path.assign(fileInfo.absolutePath().toStdString() + '/');
  return fileInfo.isWritable();
}
コード例 #2
0
ファイル: berryBundleLoader.cpp プロジェクト: AGrafmint/MITK
void
BundleLoader::InstallLibraries(IBundle::Pointer bundle, bool copy)
{
  std::vector<std::string> libraries;
  this->ListLibraries(bundle, libraries);

  std::vector<std::string>::iterator iter;
  for (iter = libraries.begin(); iter != libraries.end(); ++iter)
  {
    if (iter->empty()) continue;

    //BERRY_INFO << "Testing CodeCache for: " << *iter << std::endl;

    std::size_t separator = iter->find_last_of("/");
    std::string libFileName = *iter;
    if (separator != std::string::npos)
      libFileName = iter->substr(separator+1);

    if (!m_CodeCache->HasLibrary(libFileName))
    {
      std::string libDir = "";
      if (separator != std::string::npos)
          libDir += iter->substr(0, separator);

      // Check if we should copy the dll (from a ZIP file for example)
      if (copy)
      {
        //TODO This copies all files which start with *iter to the
        // plugin cache. This is necessary for Windows, for example,
        // where a .dll file is accompanied by a set of other files.
        // This should be extended to check for the right dll files, since
        // it would be possible (and a good idea anyway) to put multiple
        // versions of the same library in the ZIP file, targeting different
        // compilers for example.
        std::vector<std::string> files;
        bundle->GetStorage().List(libDir, files);
        for (std::vector<std::string>::iterator fileName = files.begin();
             fileName != files.end(); ++fileName)
        {
          std::size_t size = std::min<std::size_t>(libFileName.size(), fileName->size());
          if (fileName->compare(0, size, libFileName) != 0) continue;

          std::istream* istr = bundle->GetResource(libDir + *fileName);
          m_CodeCache->InstallLibrary(*iter, *istr);
          delete istr;
        }
      }
      else
      {
        Poco::Path bundlePath = bundle->GetStorage().GetPath();
        bundlePath.append(Poco::Path::forDirectory(libDir));

        // On Windows, we set the path environment variable to include
        // the path to the library, so the loader can find it. We do this
        // programmatically because otherwise, a user would have to edit
        // a batch file every time he adds a new plugin from outside the
        // build system.
        #ifdef BERRY_OS_FAMILY_WINDOWS
        std::string pathEnv = Poco::Environment::get("PATH", "");
        if (!pathEnv.empty()) pathEnv += ";";
        pathEnv += bundlePath.toString();
        Poco::Environment::set("PATH", pathEnv);
        #endif

        m_CodeCache->InstallLibrary(libFileName, bundlePath);
      }
    }
  }
}
コード例 #3
0
void FileSystemRouteHandler::handleRequest(Poco::Net::HTTPServerRequest& request,
        Poco::Net::HTTPServerResponse& response)
{
    Poco::Path dataFolder(ofToDataPath("",true));
    Poco::Path documentRoot(ofToDataPath(_parent.getSettings().getDocumentRoot(),true));

    std::string dataFolderString = dataFolder.toString();
    std::string documentRootString = documentRoot.toString();

    // doc root validity check
    if(_parent.getSettings().getRequireDocumentRootInDataFolder() &&
            (documentRootString.length() < dataFolderString.length() ||
             documentRootString.substr(0,dataFolderString.length()) != dataFolderString))
    {
        ofLogError("ServerDefaultRouteHandler::handleRequest") << "Document Root is not a sub directory of the data folder.";
        response.setStatusAndReason(Poco::Net::HTTPResponse::HTTP_INTERNAL_SERVER_ERROR);
        _parent.handleRequest(request,response);
        return;
    }

    // check path

    Poco::URI uri(request.getURI());
    std::string path = uri.getPath(); // just get the path

    // make paths absolute
    if(path.empty())
    {
        path = "/";
    }

    Poco::Path requestPath = documentRoot.append(path).makeAbsolute();

    // add the default index if no filename is requested
    if(requestPath.getFileName().empty())
    {
        requestPath.append(_parent.getSettings().getDefaultIndex()).makeAbsolute();
    }

    std::string requestPathString = requestPath.toString();

    // double check path safety (not needed?)
    if((requestPathString.length() < documentRootString.length() ||
            requestPathString.substr(0,documentRootString.length()) != documentRootString))
    {
        ofLogError("ServerDefaultRouteHandler::handleRequest") << "Requested document not inside DocumentFolder.";
        response.setStatusAndReason(Poco::Net::HTTPResponse::HTTP_NOT_FOUND);
        _parent.handleRequest(request,response);
        return;
    }

    ofFile file(requestPathString); // use it to parse file name parts

    try
    {
//        ofx::Media::MediaTypeMap mediaMap;
//        Poco::Net::MediaType mediaType = mediaMap.getMediaTypeForSuffix(file.getExtension());

        std::string mediaTypeString = "application/octet-stream";
        std::string ext = file.getExtension();


        if(ext == "json")
        {
            mediaTypeString = "application/json";
        }
        else if(ext == "html")
        {
            mediaTypeString = "text/html";
        }
        else if(ext == "jpg" || ext == "jpeg")
        {
            mediaTypeString = "image/jpeg";
        }
        else if(ext == "png")
        {
            mediaTypeString = "image/png";
        }
        else if(ext == "js")
        {
            mediaTypeString = "application/javascript";
        }
        else if(ext == "css")
        {
            mediaTypeString = "text/css";
        }
        else if(ext == "xml")
        {
            mediaTypeString = "application/xml";
        }
        else if(ext == "ico")
        {
            mediaTypeString = "image/x-icon";
        }

        response.sendFile(file.getAbsolutePath(), mediaTypeString); // will throw exceptions
        return;
    }
    catch (const Poco::FileNotFoundException& ex)
    {
        ofLogError("ServerDefaultRouteHandler::handleRequest") << ex.displayText();
        response.setStatusAndReason(Poco::Net::HTTPResponse::HTTP_NOT_FOUND);
        _parent.handleRequest(request,response);
    }
    catch (const Poco::OpenFileException& ex)
    {
        ofLogError("ServerDefaultRouteHandler::handleRequest") << ex.displayText();
        response.setStatusAndReason(Poco::Net::HTTPResponse::HTTP_INTERNAL_SERVER_ERROR);
        _parent.handleRequest(request,response);
    }
    catch (const exception& ex)
    {
        ofLogError("ServerDefaultRouteHandler::handleRequest") << "Unknown server error: " << ex.what();
        response.setStatusAndReason(Poco::Net::HTTPResponse::HTTP_INTERNAL_SERVER_ERROR);
        _parent.handleRequest(request,response);
    }
}
コード例 #4
0
ファイル: MUI.cpp プロジェクト: subwolf/ofxMightyUI
void mui_init(){
	#if TARGET_OS_IPHONE
	if( mui::MuiConfig::detectRetina ){
		ofAppiOSWindow * w = ofAppiOSWindow::getInstance();
		if( w->isRetinaEnabled() ){
			mui::MuiConfig::scaleFactor = 2;
			mui::MuiConfig::useRetinaAssets = true;
		}
	}
	#endif
	//TODO: allow retina in osx too!
	
	Poco::Path appPath;
	#if TARGET_OS_IPHONE
		// http://www.cocoabuilder.com/archive/cocoa/193451-finding-out-executable-location-from-c-program.html
		CFBundleRef bundle = CFBundleGetMainBundle();
		CFURLRef    url  = CFBundleCopyExecutableURL(bundle); // CFBundleCopyResourcesDirectoryURL(bundle);
		CFURLRef absolute = CFURLCopyAbsoluteURL(url);
		CFStringRef path  = CFURLCopyFileSystemPath(url, kCFURLPOSIXPathStyle);
		CFIndex    maxLength = CFStringGetMaximumSizeOfFileSystemRepresentation(path);
		char        *result = (char*)malloc(maxLength);
		
		if(result) {
			if(!CFStringGetFileSystemRepresentation(path,result, maxLength)) {
				free(result);
				result = NULL;
			}
		}
		
		CFRelease(path);
		CFRelease(url);
		CFRelease(absolute);
		appPath = Poco::Path(result);
		appPath = appPath.parent();
	#elif TARGET_OS_MAC
		// http://www.cocoabuilder.com/archive/cocoa/193451-finding-out-executable-location-from-c-program.html
		CFBundleRef bundle = CFBundleGetMainBundle();
		CFURLRef    url  = CFBundleCopyExecutableURL(bundle); // CFBundleCopyResourcesDirectoryURL(bundle);
		CFURLRef absolute = CFURLCopyAbsoluteURL(url);
		CFStringRef path  = CFURLCopyFileSystemPath(url, kCFURLPOSIXPathStyle);
		CFIndex    maxLength = CFStringGetMaximumSizeOfFileSystemRepresentation(path);
		char        *result = (char*)malloc(maxLength);
		
		if(result) {
			if(!CFStringGetFileSystemRepresentation(path,result, maxLength)) {
				free(result);
				result = NULL;
			}
		}
		
		CFRelease(path);
		CFRelease(url);
		CFRelease(absolute);
		appPath = Poco::Path(result);
		appPath = appPath.parent().parent().pushDirectory("Resources");
	
		if( mui::MuiConfig::detectRetina ){
			ofAppGLFWWindow * window = dynamic_cast<ofAppGLFWWindow*>(ofGetWindowPtr());
			if( window != NULL ){
				mui::MuiConfig::scaleFactor = window->getPixelScreenCoordScale();
			}
		}
	#else
		appPath = Poco::Path(ofToDataPath("", true));
	#endif
	
	mui::MuiConfig::dataPath = appPath.absolute();
}
コード例 #5
0
ファイル: main.cpp プロジェクト: thejoker010/FastCraft
int main(int argc, char *argv[]) {
	std::string BuildVer(BUILD_VERSION);
	
	cout<<"FastCraft Minecraft Server"<<"\n";
	cout<<"Version "<<BUILD_VERSION<<(BuildVer.compare("") == 0 ? "" : "-")<<FC_VERSION<<" for Minecraft "<<FC_SUPPORTED_MINCRAFTVERSION<<"\n"<<std::endl;

	Poco::Path pathRoot(argv[0]); 
	pathRoot.setFileName(""); //Remove filename

	pathRoot.pushDirectory("Server");
	Poco::File fileRootDirectory(pathRoot.toString());
	if (!fileRootDirectory.exists()) {
		try {
			fileRootDirectory.createDirectories();
		}catch(Poco::FileException& ex) {
			cout<<"Unable to create server directory ("<<ex.message()<<")"<<std::endl;
		}
	}else{
		if ((!fileRootDirectory.canRead()) || (!fileRootDirectory.canWrite())) {
			cout<<"Unable to read or write FastCraft root directory"<<std::endl;
			Thread::sleep(3000);
			return 0;
		}
	}
	std::vector<MinecraftServer*> vpServer(0);
	std::vector<Poco::File>		  vFileList(0);

	fileRootDirectory.list(vFileList);
	if (vFileList.empty()) {
		cout<<"No server configurations found!"<<std::endl;
		Thread::sleep(3000);
		return 0;
	}

	Poco::Data::SQLite::Connector::registerConnector(); //Startup sqlite engine
	Constants::init(); //load constants

	MinecraftServer* pServer;
	Poco::Path pathTemp;
	int x;

	//Start all server
	for (x=0;x<=vFileList.size()-1;x++) {
		if (!vFileList[x].isDirectory()) {continue;} //Skip files

		if(!pathTemp.tryParse(vFileList[x].path())) {
			cout<<"Illegal path!"<<std::endl;
			Thread::sleep(3000);
			return 0;
		}

		try {
			cout<<"Starting "<<pathTemp[pathTemp.depth()]<<"\n";
			pathTemp.pushDirectory(pathTemp[pathTemp.depth()]);
			pathTemp.setFileName("");
			pServer = new MinecraftServer(pathTemp[pathTemp.depth()-1],pathTemp);
		}catch(Poco::RuntimeException& ex) {
			cout<<"Unable to start server ("<<ex.message()<<")"<<std::endl;
			Thread::sleep(3000);
			return 0;
		}
		vpServer.push_back(pServer);
		pathTemp.clear();
	}

	cout<<"Loading done!\n";

	bool fSomethingRuns = false;	
	while(1) {
		Thread::sleep(1000);

		//Check if there is at least one server that runs
		fSomethingRuns=false;
		for (x=0;x<=vpServer.size()-1;x++) {
			if (vpServer[x]->isRunning()) {
				fSomethingRuns=true;
				break;
			}
		}
		if (!fSomethingRuns) {break;}
	}

	Poco::Data::SQLite::Connector::unregisterConnector();
	return 1;
}
コード例 #6
0
void DebugBreakpointManager::RestoreState(const Poco::Path& path)
{
  try
  {
    Poco::XML::DOMParser parser;

    Poco::FileInputStream reader(path.toString());
    Poco::XML::InputSource source(reader);

    //source.setSystemId(baseDir);
    Poco::XML::Document* doc = parser.parse(&source);
    Poco::XML::Element* breakpoints = doc->documentElement();

    if (breakpoints)
    {
      // restore object breakpoints
      Poco::XML::NodeList* elementList = breakpoints->getElementsByTagName(
          OBJECT_TAG);
      for (std::size_t i = 0; i < elementList->length(); i++)
      {
        Poco::XML::Element* elem =
            dynamic_cast<Poco::XML::Element*> (elementList->item(i));

        if (!elem->hasAttribute(ID_ATTR))
          continue;

        const std::string& attr = elem->getAttribute(ID_ATTR);

        int traceId = 0;
        try
        {
          traceId = Poco::NumberParser::parse(attr);
        } catch (const Poco::SyntaxException& e)
        {
          BERRY_WARN << e.displayText();
        }

        DebugUtil::GetBreakpointManager()->AddObjectBreakpoint(traceId);
      }
      elementList->release();

      // restore smartpointer breakpoints
      elementList = breakpoints->getElementsByTagName(SMARTPOINTER_TAG);
      for (std::size_t i = 0; i < elementList->length(); i++)
      {
        Poco::XML::Element* elem =
            dynamic_cast<Poco::XML::Element*> (elementList->item(i));

        if (!elem->hasAttribute(ID_ATTR))
          continue;

        const std::string& attr = elem->getAttribute(ID_ATTR);

        int spId = 0;
        try
        {
          spId = Poco::NumberParser::parse(attr);
        } catch (const Poco::SyntaxException& e)
        {
          BERRY_WARN << e.displayText();
        }

        DebugUtil::GetBreakpointManager()->AddSmartpointerBreakpoint(spId);
      }
      elementList->release();
    }

    doc->release();
  } catch (Poco::XML::SAXParseException& e)
  {
    BERRY_WARN << e.displayText();
  }
  catch (Poco::FileNotFoundException& /*e*/)
  {

  }
  catch (Poco::FileException& e)
  {
    BERRY_WARN << e.displayText();
  }
}
コード例 #7
0
ファイル: Utils.cpp プロジェクト: gnimmel/ofxMissing
string getCurrentWorkingDirectory() {
	Poco::Path p;
	return p.current();
}
コード例 #8
0
void FileSystemRoute::handleRequest(ServerEventArgs& evt)
{
    Poco::Path dataFolder(ofToDataPath("", true));
    Poco::Path documentRoot(ofToDataPath(getSettings().getDocumentRoot(), true));

    std::string dataFolderString = dataFolder.toString();
    std::string documentRootString = documentRoot.toString();

    // Document root validity check.
    if (_settings.getRequireDocumentRootInDataFolder() &&
       (documentRootString.length() < dataFolderString.length() ||
        documentRootString.substr(0, dataFolderString.length()) != dataFolderString))
    {
        ofLogError("FileSystemRoute::handleRequest") << "Document Root is not a sub directory of the data folder.";
        evt.getResponse()   .setStatusAndReason(Poco::Net::HTTPResponse::HTTP_INTERNAL_SERVER_ERROR);
        handleErrorResponse(evt);
        return;
    }

    // check path

    Poco::URI uri(evt.getRequest().getURI());
    std::string path = uri.getPath(); // just get the path

    // make paths absolute
    if (path.empty())
    {
        path = "/";
    }

    Poco::Path requestPath = documentRoot.append(path).makeAbsolute();

    // add the default index if no filename is requested
    if (requestPath.getFileName().empty())
    {
        requestPath.append(getSettings().getDefaultIndex()).makeAbsolute();
    }

    std::string requestPathString = requestPath.toString();

    // double check path safety (not needed?)
    if ((requestPathString.length() < documentRootString.length() ||
         requestPathString.substr(0, documentRootString.length()) != documentRootString))
    {
        ofLogError("FileSystemRoute::handleRequest") << "Requested document not inside DocumentFolder.";
        evt.getResponse().setStatusAndReason(Poco::Net::HTTPResponse::HTTP_NOT_FOUND);
        handleErrorResponse(evt);
        return;
    }

    ofFile file(requestPathString); // use it to parse file name parts
    std::string mediaTypeString = MediaTypeMap::getDefault()->getMediaTypeForPath(file.path()).toString();

    try
    {
        // TODO: this is where we would begin to work honoring
        /// Accept-Encoding:gzip, deflate, sdch
        evt.getResponse().sendFile(file.getAbsolutePath(), mediaTypeString);
        return;
    }
    catch (const Poco::FileNotFoundException& exc)
    {
        ofLogError("FileSystemRoute::handleRequest") << exc.displayText();
        evt.getResponse().setStatusAndReason(Poco::Net::HTTPResponse::HTTP_NOT_FOUND);
        handleErrorResponse(evt);
        return;
    }
    catch (const Poco::OpenFileException& exc)
    {
        ofLogError("FileSystemRoute::handleRequest") << exc.displayText();
        evt.getResponse().setStatusAndReason(Poco::Net::HTTPResponse::HTTP_INTERNAL_SERVER_ERROR);
        handleErrorResponse(evt);
        return;
    }
    catch (const std::exception& exc)
    {
        ofLogError("FileSystemRoute::handleRequest") << "Unknown server error: " << exc.what();
        evt.getResponse().setStatusAndReason(Poco::Net::HTTPResponse::HTTP_INTERNAL_SERVER_ERROR);
        handleErrorResponse(evt);
        return;
    }
}
コード例 #9
0
Poco::Net::MediaType MediaTypeMap::getMediaTypeForPath(const Poco::Path& path) const
{
    Poco::File file(path);

    if (file.exists() && file.isDirectory())
    {
        return Poco::Net::MediaType("inode/directory");
    }
    else
    {
        FileExtensionConstIterator iter = _fileExtensionToMediaTypeMap.find(Poco::UTF8::toLower(path.getExtension()));

        if (iter != _fileExtensionToMediaTypeMap.end())
        {
            return (*iter).second;
        }
        else
        {
            return _defaultMediaType;
        }
    }
}
コード例 #10
0
ファイル: ZipTest.cpp プロジェクト: beneon/MITK
std::string ZipTest::getTestFile(const std::string& testFile)
{
	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(testFile);
	Poco::File aFile(result.toString());
	if (!aFile.exists() || (aFile.exists() && !aFile.isFile()))
		throw Poco::FileNotFoundException("Didn't find " + testFile);
	
	return result.toString();
}
コード例 #11
0
ファイル: XplDevice.cpp プロジェクト: zeroping/xPLsdk-poco
void XplDevice::LoadConfig()
{

    poco_trace ( devLog, "loading config for  "  + GetCompleteId() );
    
    Poco::Path p = GetConfigFileLocation();

    PropertyFileConfiguration* cfgp;
    try{
        cfgp =  new PropertyFileConfiguration(p.toString());
    } catch (Poco::FileException e) {
        poco_debug ( devLog, "Failed to parse  " + p.toString() );
        cfgp = (new PropertyFileConfiguration());
    }
    m_configStore = cfgp;
        
    m_bConfigRequired = true;
  
    
    AbstractConfiguration::Keys itemKeys;
    m_configStore->keys(itemKeys);
    for ( AbstractConfiguration::Keys::iterator iter = itemKeys.begin(); iter != itemKeys.end(); ++iter )
    {
        poco_debug ( devLog, " item: " + *iter );
    }
    
    
    
    if ( m_configStore->hasProperty ( "instanceId" ) )
    {
        //looks like we really have a config
        poco_debug ( devLog, "found instance ID" );
        m_bConfigRequired = false;
        SetInstanceId ( m_configStore->getString ( "instanceId" ) );
        
        if ( m_configStore->hasProperty ( "configItems" )) {
            AbstractConfiguration::Keys confItemKeys;
            m_configStore->keys("configItems", confItemKeys);
            poco_debug ( devLog, "found " + NumberFormatter::format(confItemKeys.size()) + "keys" );
            for ( AbstractConfiguration::Keys::iterator iter = confItemKeys.begin(); iter != confItemKeys.end(); ++iter )
            {
                if(m_configStore->hasProperty ( "configItems."+(*iter)+".numValues" )){
                    // we have a config item entry with the required parts, but should only restore it if it matches a programatically-added configitem.
                    AutoPtr<XplConfigItem> cfgItem = GetConfigItem(*iter);
                    if (cfgItem.get()== NULL){
                        poco_warning ( devLog, "Found a config item for name " + *iter + ", but no programatically-created config item exists with that name" );
                        continue;
                    }
                    poco_trace ( devLog, "Config item: " + *iter );
                    int numValues = m_configStore->getInt ( "configItems."+(*iter)+".numValues");
                    
                    for (int i= 0; i<numValues; i++) {
                        poco_trace( devLog, "Value " );
                        string valname = "configItems."+(*iter)+".value" + NumberFormatter::format(i);
                        if(m_configStore->hasProperty (valname) ){
                            cfgItem->AddValue(m_configStore->getString ( valname ));
                        }
                    }
                }
            }
            
        }
    }
  
// 	// If the config data was read ok, then configure this device.
	if( !m_bConfigRequired )
	{
    // Configure the XplDevice
    Configure();
    m_bConfigRequired = false;

        // Set the config event
		//SetEvent( m_hConfig );
//     m_hConfig.notifyAsync(NULL, m_hConfig);
	}
}
コード例 #12
0
ファイル: utils.cpp プロジェクト: drunner/drunner
 bool fileexists(const Poco::Path& name)
 {
    struct stat buffer;
    return (stat (name.toString().c_str(), &buffer) == 0);
 }
コード例 #13
0
void ofxRemoteUIServer::updateServer(float dt){

	timeCounter += dt;
	broadcastTime += dt;
	timeSinceLastReply  += dt;

	if(readyToSend){
		if (timeCounter > updateInterval){
			timeCounter = 0.0f;
			//vector<string> changes = scanForUpdatedParamsAndSync(); //sends changed params to client
			//cout << "ofxRemoteUIServer: sent " << ofToString(changes.size()) << " updates to client" << endl;
			//sendUpdateForParamsInList(changes);
		}
	}

	//let everyone know I exist and which is my port, every now and then
	if(broadcastTime > OFXREMOTEUI_BORADCAST_INTERVAL){
		if(doBroadcast){
			broadcastTime = 0.0f;
			if (computerName.size() == 0){
				#ifdef OF_AVAILABLE
					Poco::Environment e;
					computerName = e.nodeName();

					char pathbuf[2048];
					uint32_t  bufsize = sizeof(pathbuf);
					#ifdef TARGET_OSX
						_NSGetExecutablePath(pathbuf, &bufsize);
						Poco::Path p = Poco::Path(pathbuf);
						binaryName = p[p.depth()];
					#endif
					#ifdef TARGET_WIN32						
						GetModuleFileNameA( NULL, pathbuf, bufsize ); //no iea why, but GetModuleFileName() is not defined?
						Poco::Path p = Poco::Path(pathbuf);
						binaryName = p[p.depth()];
					#endif
				#endif
			}
			ofxOscMessage m;
			m.addIntArg(port); //0
			m.addStringArg(computerName); //1
			m.addStringArg(binaryName);	//2
			broadcastSender.sendMessage(m);
		}
	}

	while( oscReceiver.hasWaitingMessages() ){// check for waiting messages from client

		ofxOscMessage m;
		oscReceiver.getNextMessage(&m);
		if (!readyToSend){ // if not connected, connect to our friend so we can talk back
			connect(m.getRemoteIp(), port + 1);
		}

		DecodedMessage dm = decode(m);
		RemoteUIServerCallBackArg cbArg; // to notify our "delegate"
		cbArg.host = m.getRemoteIp();
		switch (dm.action) {

			case HELO_ACTION: //if client says hi, say hi back
				sendHELLO();
				if(callBack != NULL){
					cbArg.action = CLIENT_CONNECTED;
					callBack(cbArg);
				}
				if(verbose_) cout << "ofxRemoteUIServer: " << m.getRemoteIp() << " says HELLO!"  << endl;
				onScreenNotifications.addNotification("CONNECTED (" + cbArg.host +  ")!");
				break;

			case REQUEST_ACTION:{ //send all params to client
				if(verbose_) cout << "ofxRemoteUIServer: " << m.getRemoteIp() << " sends REQU!"  << endl;
				vector<string>paramsList = getAllParamNamesList();
				syncAllParamsToPointers();
				sendUpdateForParamsInList(paramsList);
				sendREQU(true); //once all send, confirm to close the REQU
			}
				break;

			case SEND_PARAM_ACTION:{ //client is sending us an updated val
				if(verbose_) cout << "ofxRemoteUIServer: " << m.getRemoteIp() << " sends SEND!"  << endl;
				updateParamFromDecodedMessage(m, dm);
				if(callBack != NULL){
					cbArg.action = CLIENT_UPDATED_PARAM;
					cbArg.paramName = dm.paramName;
					cbArg.param = params[dm.paramName];  //copy the updated param to the callbakc arg
					callBack(cbArg);
				}
			}
				break;

			case CIAO_ACTION:{
				if(verbose_) cout << "ofxRemoteUIServer: " << m.getRemoteIp() << " says CIAO!" << endl;
				sendCIAO();
				onScreenNotifications.addNotification("DISCONNECTED (" + cbArg.host +  ")!");
				if(callBack != NULL){
					cbArg.action = CLIENT_DISCONNECTED;
					callBack(cbArg);
				}
				clearOscReceiverMsgQueue();
				readyToSend = false;
			}break;

			case TEST_ACTION: // we got a request from client, lets bounce back asap.
				sendTEST();
				//if(verbose)cout << "ofxRemoteUIServer: " << m.getRemoteIp() << " says TEST!" << endl;
				break;

			case PRESET_LIST_ACTION: //client wants us to send a list of all available presets
				presetNames = getAvailablePresets();
				if (presetNames.size() == 0){
					presetNames.push_back(OFXREMOTEUI_NO_PRESETS);
				}
				sendPREL(presetNames);
				break;

			case SET_PRESET_ACTION:{ // client wants to set a preset
				//presetNames = getAvailablePresets();
				string presetName = m.getArgAsString(0);
				vector<string> missingParams = loadFromXML(string(OFXREMOTEUI_PRESET_DIR) + "/" + presetName + ".xml");
				if(verbose_) cout << "ofxRemoteUIServer: setting preset: " << presetName << endl;
				sendSETP(presetName);
				sendMISP(missingParams);
				if(callBack != NULL){
					cbArg.action = CLIENT_DID_SET_PRESET;
					cbArg.msg = presetName;
					callBack(cbArg);
				}
				onScreenNotifications.addNotification("SET PRESET to '" + string(OFXREMOTEUI_PRESET_DIR) + "/" + presetName + ".xml'");
			}break;

			case SAVE_PRESET_ACTION:{ //client wants to save current xml as a new preset
				string presetName = m.getArgAsString(0);
				if(verbose_) cout << "ofxRemoteUIServer: saving NEW preset: " << presetName << endl;
				saveToXML(string(OFXREMOTEUI_PRESET_DIR) + "/" + presetName + ".xml");
				sendSAVP(presetName);
				onScreenNotifications.addNotification("SAVED PRESET to '" + string(OFXREMOTEUI_PRESET_DIR) + "/" + presetName + ".xml'");
				if(callBack != NULL){
					cbArg.action = CLIENT_SAVED_PRESET;
					cbArg.msg = presetName;
					callBack(cbArg);
				}
			}break;

			case DELETE_PRESET_ACTION:{
				string presetName = m.getArgAsString(0);
				if(verbose_) cout << "ofxRemoteUIServer: DELETE preset: " << presetName << endl;
				deletePreset(presetName);
				sendDELP(presetName);
				onScreenNotifications.addNotification("DELETED PRESET '" + string(OFXREMOTEUI_PRESET_DIR) + "/" + presetName + ".xml'");
				if(callBack != NULL){
					cbArg.action = CLIENT_DELETED_PRESET;
					cbArg.msg = presetName;
					callBack(cbArg);
				}
			}break;

			case SAVE_CURRENT_STATE_ACTION:{
				if(verbose_) cout << "ofxRemoteUIServer: SAVE CURRENT PARAMS TO DEFAULT XML: " << endl;
				saveToXML(OFXREMOTEUI_SETTINGS_FILENAME);
				onScreenNotifications.addNotification("SAVED CONFIG to default XML");
				sendSAVE(true);
				if(callBack != NULL){
					cbArg.action = CLIENT_SAVED_STATE;
					callBack(cbArg);
				}
			}break;

			case RESET_TO_XML_ACTION:{
				if(verbose_) cout << "ofxRemoteUIServer: RESET TO XML: " << endl;
				restoreAllParamsToInitialXML();
				sendRESX(true);
				onScreenNotifications.addNotification("RESET CONFIG TO SERVER-LAUNCH XML values");
				if(callBack != NULL){
					cbArg.action = CLIENT_DID_RESET_TO_XML;
					callBack(cbArg);
				}
			}break;

			case RESET_TO_DEFAULTS_ACTION:{
				if(verbose_) cout << "ofxRemoteUIServer: RESET TO DEFAULTS: " << endl;
				restoreAllParamsToDefaultValues();
				sendRESD(true);
				onScreenNotifications.addNotification("RESET CONFIG TO DEFAULTS (source defined values)");
				if(callBack != NULL){
					cbArg.action = CLIENT_DID_RESET_TO_DEFAULTS;
					callBack(cbArg);
				}
			}break;

			default: cout << "ofxRemoteUIServer::update >> ERR!" <<endl; break;
		}
	}
}
コード例 #14
0
ファイル: TskL01Extract.cpp プロジェクト: robjoyce/sleuthkit
/*
 *   If containerFile is NULL, then we don't use that as a source for paths and we set the parent ID to 0.
 */
int TskL01Extract::extractFiles(TskFile * containerFile /*= NULL*/)
{
    static const std::string MSG_PREFIX = "TskL01Extract::extractFiles : ";
    
    try
    {
        m_containerFile = containerFile;

        if (m_archivePath.empty())
        {
            throw TskException(MSG_PREFIX + "No path to archive provided.");
        }

        std::string L01Path = TskUtilities::toUTF8(m_archivePath);
        if (m_containerFile != NULL)
        {
            L01Path = m_containerFile->getPath();
        }

        //m_db.addImageInfo((int)m_img_info->itype, m_img_info->sector_size);
        m_db.addImageName(L01Path.c_str());

        if (openContainer() != 0)
        {
            return -1;
        }

        if (m_imgInfo == NULL)
        {
            throw TskException(MSG_PREFIX +"Images not open yet");
        }

		// Create a map of directory names to file ids to use to 
		// associate files/directories with the correct parent.
		std::map<std::string, uint64_t> directoryMap;

        std::vector<ArchivedFile>::iterator it = m_archivedFiles.begin();
        for (; it != m_archivedFiles.end(); ++it)
        {
            Poco::Path path(it->path);
            Poco::Path parent = it->path.parent();
            std::string name;

            if (path.isDirectory())
            {
                name = path[path.depth() - 1];
            }
            else
            {
                name = path[path.depth()];
            }

            // Determine the parent id of the file.
            uint64_t parentId = 0;
            if (path.depth() == 0 || path.isDirectory() && path.depth() == 1)
            {
                // This file or directory lives at the root so our parent id
                // is the containing file id (if a containing file was provided).
                if (m_containerFile != NULL)
                {
                    parentId = m_containerFile->getId();
                }
            }
            else
            {
                // We are not at the root so we need to lookup the id of our
                // parent directory.
                std::map<std::string, uint64_t>::const_iterator pos;
                pos = directoryMap.find(parent.toString());

                if (pos == directoryMap.end())
                {
                    //error!
                    std::stringstream msg;
                    msg << "extractFiles: parent ID not mapped for " << it->path.toString();
                    LOGERROR(msg.str());
                }
                else
                {
                    parentId = pos->second;
                }
            }

            // Store some extra details about the derived (i.e, extracted) file.
            std::stringstream details;  ///@todo anything here?

            std::string fullpath = "";
            if (m_containerFile != NULL)
            {
                fullpath.append(m_containerFile->getFullPath());
            }
            fullpath.append("\\");
            fullpath.append(path.toString());

            uint64_t fileId;
            if (m_db.addDerivedFileInfo(name,
                parentId,
                path.isDirectory(),
                it->size,
                details.str(), 
                static_cast<int>(it->ctime),
                static_cast<int>(it->crtime),
                static_cast<int>(it->atime),
                static_cast<int>(it->mtime),
                fileId, fullpath) == -1) 
            {
                    std::wstringstream msg;
                    msg << L"addDerivedFileInfo failed for name="
                        << name.c_str();
                    LOGERROR(msg.str());
            }

            if (path.isDirectory())
            {
                directoryMap[path.toString()] = fileId;
            }
            else
            {
                // For file nodes, recreate file locally
                // Will save zero-length files
                if (saveFile(fileId, *it) == 0)
                {
                    // Schedule
                    m_db.updateFileStatus(fileId, TskImgDB::IMGDB_FILES_STATUS_READY_FOR_ANALYSIS);
                    TskServices::Instance().getScheduler().schedule(Scheduler::FileAnalysis, fileId, fileId);
                }
            }
        }

    }
    catch (TskException &ex)
    {
        std::ostringstream msg;
        msg << MSG_PREFIX << "TskException: " << ex.message();
        LOGERROR(msg.str());
        return -1;
    }
    catch (std::exception &ex)
    {
        std::ostringstream msg;
        msg << MSG_PREFIX << "std::exception: " << ex.what();
        LOGERROR(msg.str());
        return -1;
    }
    catch (...)
    {
        LOGERROR(MSG_PREFIX + "unrecognized exception");
        return -1;
    }

    return 0; //success
}
コード例 #15
0
ファイル: Util.hpp プロジェクト: aqxavier/online
 inline
 void removeFile(const Poco::Path& path, const bool recursive = false)
 {
     removeFile(path.toString(), recursive);
 }
コード例 #16
0
	InsufficientPrivileges(const Poco::Path& path) :
		Exception("Insufficient privileges for [" + path.toString() + "]"),
		path(path)
	{}
コード例 #17
0
ファイル: berryDebugUtil.cpp プロジェクト: robotdm/MITK
void DebugUtil::RestoreState()
{
    Poco::Path path;
    if (!GetPersistencePath(path)) return;

    path.setFileName(DEBUG_UTIL_XML);

    try
    {
        Poco::XML::DOMParser parser;

        Poco::FileInputStream reader(path.toString());
        Poco::XML::InputSource source(reader);

        //source.setSystemId(baseDir);
        Poco::XML::Document* doc = parser.parse(&source);
        Poco::XML::Element* debugutil = doc->documentElement();

        if (debugutil)
        {
            // restore traced objects
            Poco::XML::NodeList* elementList = debugutil->getElementsByTagName(TRACEOBJECT_TAG);
            for (std::size_t i = 0; i < elementList->length(); i++)
            {
                Poco::XML::Element* elem =
                    dynamic_cast<Poco::XML::Element*> (elementList->item(static_cast<unsigned long>(i)));

                if (!elem->hasAttribute(ID_ATTR)) continue;

                const std::string& attr = elem->getAttribute(ID_ATTR);

                int traceId = 0;
                try
                {
                    traceId = Poco::NumberParser::parse(attr);
                }
                catch (const Poco::SyntaxException& e)
                {
                    BERRY_WARN << e.displayText();
                }

                DebugUtil::TraceObject(traceId);
            }
            elementList->release();

            // restore traced classes
            elementList = debugutil->getElementsByTagName(TRACECLASS_TAG);
            for (std::size_t i = 0; i < elementList->length(); i++)
            {
                Poco::XML::Element* elem =
                    dynamic_cast<Poco::XML::Element*> (elementList->item(static_cast<unsigned long>(i)));

                if (!elem->hasAttribute(NAME_ATTR)) continue;

                const std::string& traceClass = elem->getAttribute(NAME_ATTR);
                if (!traceClass.empty())
                    DebugUtil::TraceClass(traceClass);
            }
            elementList->release();
        }

        doc->release();
    }
    catch (Poco::XML::SAXParseException& e)
    {
        BERRY_WARN << e.displayText();
    }
    catch (Poco::FileNotFoundException&)
    {

    }
    catch (Poco::FileException& e)
    {
        BERRY_WARN << e.displayText();
    }

    // restore BreakpointManager
    path.setFileName(DebugBreakpointManager::BREAKPOINTS_XML);
    GetBreakpointManager()->RestoreState(path);
}
コード例 #18
0
void DirectoryWatcherManager::addPath(const Poco::Path& path,
                                      bool listExistingItemsOnStart,
                                      bool sortAlphaNumeric,
                                      AbstractPathFilter* pFilter,
                                      int eventMask,
                                      int scanInterval)
{

    if (isWatching(path))
    {
        Poco::Exception exc("Already Watching Exception", path.toString());
        ofNotifyEvent(events.onScanError, exc, this);
        return;
    }

    try
    {
        Poco::File file(path);

        if (!file.exists())
        {
            Poco::FileNotFoundException exc(path.toString());
            throw exc;
        }

        DirectoryWatcherPtr watcher = DirectoryWatcherPtr(new DirectoryWatcher(path.toString(),
                                                                               eventMask,
                                                                               scanInterval));

        watcher->itemAdded += Poco::priorityDelegate(this, &DirectoryWatcherManager::onItemAdded, OF_EVENT_ORDER_AFTER_APP);
        watcher->itemRemoved += Poco::priorityDelegate(this, &DirectoryWatcherManager::onItemRemoved, OF_EVENT_ORDER_AFTER_APP);
        watcher->itemModified += Poco::priorityDelegate(this, &DirectoryWatcherManager::onItemModified, OF_EVENT_ORDER_AFTER_APP);
        watcher->itemMovedFrom += Poco::priorityDelegate(this, &DirectoryWatcherManager::onItemMovedFrom, OF_EVENT_ORDER_AFTER_APP);
        watcher->itemMovedTo += Poco::priorityDelegate(this, &DirectoryWatcherManager::onItemMovedTo, OF_EVENT_ORDER_AFTER_APP);
        watcher->scanError += Poco::priorityDelegate(this, &DirectoryWatcherManager::onScanError, OF_EVENT_ORDER_AFTER_APP);

        mutex.lock();

        if(pFilter)
        {
            filterList[path] = pFilter;
        }

        watchList[path] = watcher;

        mutex.unlock();

        if (listExistingItemsOnStart)
        {
            std::vector<Poco::File> files;
            
            DirectoryUtils::list(file, files, sortAlphaNumeric, pFilter);

            std::vector<Poco::File>::iterator iter = files.begin();

            while(iter != files.end())
            {
                DirectoryWatcher::DirectoryEvent event(*iter, DirectoryWatcher::DW_ITEM_ADDED);
                ofNotifyEvent(events.onItemAdded,event,this);
                ++iter;
            }
        }
    }
    catch (const Poco::FileNotFoundException& exc)
    {
        ofNotifyEvent(events.onScanError, exc, this);
    }
}
コード例 #19
0
ファイル: FsEvent.cpp プロジェクト: gitter-badger/Rocket.CMS
FsEvent::FsEvent(const FsEvent::Type& type, const Poco::Path& file1Path)
	: type(type), file1Path(file1Path.toString()) {
}