Exemple #1
0
	void URLToFileURLCallback(const char* url, char* buffer, int bufferLength)
	{
		strncpy(buffer, url, bufferLength);
		buffer[bufferLength - 1] = '\0';

		try
		{
			string newURL = url;
			string path = URLUtils::URLToPath(newURL);
			if (path != newURL)
				newURL = URLUtils::PathToFileURL(path);

			strncpy(buffer, newURL.c_str(), bufferLength);
			buffer[bufferLength - 1] = '\0';
		}
		catch (ValueException& e)
		{
			SharedString ss = e.DisplayString();
			Logger* log = Logger::Get("UI.URL");
			log->Error("Could not convert %s to a path: %s", url, ss->c_str());
		}
		catch (...)
		{
			Logger* log = Logger::Get("UI.URL");
			log->Error("Could not convert %s to a path", url);
		}
	}
Exemple #2
0
	char* PreprocessURLCallback(const char* url, KeyValuePair* headers, char** mimeType)
	{
		Logger* logger = Logger::Get("UI.URL");

		KObjectRef scope = new StaticBoundObject();
		KObjectRef kheaders = new StaticBoundObject();
		while (headers->key)
		{
			kheaders->SetString(headers->key, headers->value);
			headers++;
		}

		try
		{
			AutoPtr<PreprocessData> result = 
				Script::GetInstance()->Preprocess(url, scope);
			*mimeType = strdup(result->mimeType.c_str());
			return strdup(result->data->Pointer());
		}
		catch (ValueException& e)
		{
			logger->Error("Error in preprocessing: %s", e.ToString().c_str());
		}
		catch (...)
		{
			logger->Error("Unknown Error in preprocessing");
		}

		return NULL;
	}
int main(int argc, char ** argv) {
	try {
		Appender errApp("Error.log", Level::ERROR, false);
		Appender debugApp("Debug.log", Level::DEBUG, true);
		Appender * dynApp = new Appender("Dynamic.log", Level::INFO, false);
		try {
			Appender badApp("Error.log", Level::ERROR, false);
		} catch ( exception & e ) {
			cout << "Correctly failed to open two appenders to one file." << endl;
		}
		logger1.Error("This should show up for all Appenders");
		delete dynApp;
		logger1.Error("This should only be in Error and Debug");
		logger2.Info("This should only be in debug");
		Appender::enableConsole(Level::INFO);
		logger1.Info("This should show up on the console.");
		logger2.Debug("This should only be in the debug log");
		fLogger.Info("Entering Foo");
		foo();
		fLogger.Info("Exiting foo.");
		Appender::enableConsole(Level::DEBUG);
		logger2.Debug("This will be in the console.");
		logger1.fDebug("%s - %i", "format test", 42);
		Appender::disableConsole();
		logger2.Debug("This will not be on the console.");
		logger1.Error("Exiting");
	} catch ( exception & e ) {
		cerr << "Unhandled exception: ";
		cerr << e.what() << endl;
		cerr << "Exiting." << endl;
		return 1;
	}
	return 0;
}
Exemple #4
0
	void MonkeyBinding::Callback(const ValueList &args, SharedValue result)
	{
		SharedKObject event = args.at(1)->ToObject();
		std::string url_value = event->Get("url")->ToString();
		
		std::vector< std::pair< std::pair< VectorOfPatterns,VectorOfPatterns >,std::string> >::iterator iter = scripts.begin();
		while(iter!=scripts.end())
		{
			std::pair< std::pair< VectorOfPatterns,VectorOfPatterns >, std::string> e = (*iter++);
			VectorOfPatterns include = e.first.first;
			VectorOfPatterns exclude = e.first.second;

			if (Matches(exclude,url_value))
			{
				continue;
			}
			if (Matches(include,url_value))
			{
				// I got a castle in brooklyn, that's where i dwell 
				try
				{
					SharedKMethod eval = event->Get("scope")->ToObject()->Get("window")->ToObject()->Get("eval")->ToMethod();
#ifdef DEBUG
					std::cout << ">>> loading user script for " << url_value << std::endl;
#endif
					eval->Call(Value::NewString(e.second));
				}
				catch (ValueException &ex)
				{
					Logger* logger = Logger::Get("Monkey");
					SharedString ss = ex.DisplayString();
					int line = -1;

					if (ex.GetValue()->IsObject() &&
						ex.GetValue()->ToObject()->Get("line")->IsNumber())
					{
						line = ex.GetValue()->ToObject()->Get("line")->ToInt();
					}
					logger->Error(
						"Exception generated evaluating user script for %s "
						"(line %i): %s", url_value.c_str(), line, ss->c_str());
				}
				catch (std::exception &ex)
				{
					Logger* logger = Logger::Get("Monkey");
					logger->Error("Exception generated evaluating user script for %s, Exception: %s",url_value.c_str(),ex.what());
				}
			}
		}
	}
Exemple #5
0
int IRC::message_loop()
{
	char buffer[4096];
	int ret_len;

	PRINTD("ENTER IRC::message_loop()");

	if (!connected)
	{
		while (!connected && connecting)
		{
#ifdef WIN32
			Sleep(1);
#else
			sleep(1);
#endif
		}
	}

	int rc = 0;

	while (connected)
	{
		ret_len=recv(irc_socket, buffer, 4095, 0);
		if (ret_len==SOCKET_ERROR || !ret_len)
		{
			rc = 1;
			break;
		}
		buffer[ret_len]='\0';
		try
		{
			split_to_replies(buffer);
		}
		catch(std::exception &e)
		{
			Logger logger = Logger::GetRootLogger();
			logger.Error("ERROR DISPATCHING IRC RECEIVE BUFFER. Error=%s", e.what());
		}
		catch(...)
		{
			Logger logger = Logger::GetRootLogger();
			logger.Error("UNKNOWN EXCEPTION IN IRC RECEIVE THREAD...");
		}
	}

	PRINTD("EXIT IRC::message_loop() => " << rc);
	return rc;
}
	int IRCClientBinding::Callback(char *irc_command, char* param, irc_reply_data* data, void* conn, void *pd)
	{
		PRINTD("IRC Received: " << param)
		
		IRCClientBinding *binding = (IRCClientBinding*)pd;
		if (!binding->callback.isNull())
		{
			ValueList args;
			args.push_back(irc_command ? Value::NewString(irc_command) : Value::Null);
			args.push_back(param ? Value::NewString(param) : Value::Null);
			args.push_back(data->target ? Value::NewString(data->target): Value::Null);
			args.push_back(data->nick ? Value::NewString(data->nick): Value::Null);

			try
			{
				binding->host->InvokeMethodOnMainThread(binding->callback,args,false);
			}
			catch(std::exception &e)
			{
				Logger* logger = Logger::Get("Network.IRC");
				logger->Error("Caught exception dispatching IRC callback: %s, Error: %s", irc_command, e.what());
			}
		}
		return 0;
	}
Exemple #7
0
	bool FileStream::Close()
	{
		try
		{
			if (this->stream)
			{
				Poco::FileOutputStream* fos = dynamic_cast<Poco::FileOutputStream*>(this->stream);
				if (fos)
				{
					fos->flush();
				}
				this->stream->close();
				delete this->stream;
				this->stream = NULL;
				return true;
			}
		}
		catch (Poco::Exception& exc)
		{
			Logger* logger = Logger::Get("Filesystem.FileStream");
			logger->Error("Error in close. Exception: %s",exc.displayText().c_str());
			throw ValueException::FromString(exc.displayText());
		}

		return false;
	}
//
// Handler
//
INT_32 FnArrayElement::Handler(CDT            * aArguments,
                               const UINT_32    iArgNum,
                               CDT            & oCDTRetVal,
                               Logger         & oLogger)
{
	// Only 2 args allowed
	if (iArgNum != 2)
	{
		oLogger.Emerg("Usage: ARRAY_ELEMENT(index, array)");
		return -1;
	}

	// Second argument *MUST* be an ARRAY
	if (aArguments[0].GetType() != CDT::ARRAY_VAL)
	{
		oLogger.Error("Second argument MUST be ARRAY");
		return -1;
	}

	// Element index
	const UINT_32 iElement = aArguments[1].GetInt();
	if (aArguments[0].Size() <= iElement)
	{
		oCDTRetVal = CDT();
		return 0;
	}

	// Return element
	oCDTRetVal = aArguments[0][iElement];

return 0;
}
Exemple #9
0
	void FileStream::Read(const ValueList& args, SharedValue result)
	{
		if(!this->stream)
		{
			Logger* logger = Logger::Get("Filesystem.FileStream");
			logger->Error("Error in read. FileStream must be opened before calling read");
			throw ValueException::FromString("FileStream must be opened before calling read");
		}

		try
		{
			std::stringstream ostr;

			Poco::FileInputStream* fis = dynamic_cast<Poco::FileInputStream*>(this->stream);
			if(!fis)
			{
				Logger* logger = Logger::Get("Filesystem.FileStream");
				logger->Error("Error in read. FileInputStream is null");
				throw ValueException::FromString("FileStream must be opened for reading before calling read");
			}
			
			char buf[4096];
			int count = 0;

			while(!fis->eof())
			{
				fis->read((char*)&buf,4095);
				std::streamsize len = fis->gcount();
				if (len>0)
				{
					buf[len]='\0';
					count+=len;
					ostr << buf;
				}
				else break;
			}

			result->SetObject(new Blob(ostr.str().c_str(),count));
		}
		catch (Poco::Exception& exc)
		{
			Logger* logger = Logger::Get("Filesystem.FileStream");
			logger->Error("Error in read. Exception: %s",exc.displayText().c_str());
			throw ValueException::FromString(exc.displayText());
		}
	}
Exemple #10
0
    std::string TiURLToPath(const std::string& tiURL)
    {
        try
        {
            Poco::URI inURI = Poco::URI(tiURL);

            if (inURI.getScheme() != "ti")
            {
                return tiURL;
            }

            std::string host(inURI.getHost());
            SharedApplication app = Host::GetInstance()->GetApplication();
            std::string path(app->GetComponentPath(host));

            if (path.empty())
            {
                throw ValueException::FromString("Could not find component "+host);
            }

            std::vector<std::string> segments;
            inURI.getPathSegments(segments);

            for (size_t i = 0; i < segments.size(); i++)
            {
                path = FileUtils::Join(path.c_str(), segments[i].c_str(), NULL);
            }
            return path;
        }
        catch (ValueException& e)
        {
            SharedString ss = e.DisplayString();
            Logger* log = Logger::Get("URLUtils");
            log->Error("Could not convert %s to a path: %s", tiURL.c_str(), ss->c_str());
        }
        catch (...)
        {
            Logger* log = Logger::Get("URLUtils");
            log->Error("Could not convert %s to a path", tiURL.c_str());
        }
        return tiURL;
    }
Exemple #11
0
	void UIModule::LoadUIJavascript(JSContextRef context)
	{
		std::string module_path = GetPath();
		std::string js_path = FileUtils::Join(module_path.c_str(), "ui.js", NULL);
		try
		{
			KJSUtil::EvaluateFile(context, (char*) js_path.c_str());
		}
		catch (kroll::ValueException &e)
		{
			SharedString ss = e.DisplayString();
			Logger* logger = Logger::Get("UIModule");
			logger->Error("Error loading %s: %s",js_path.c_str(),(*ss).c_str());
		}
		catch (...)
		{
			Logger* logger = Logger::Get("UIModule");
			logger->Error("Unexpected error loading %s",js_path.c_str());
		}
	}
Exemple #12
0
	bool FileStream::Open(FileStreamMode mode, bool binary, bool append)
	{
		// close the prev stream if needed
		this->Close();

		try
		{
			std::ios::openmode flags = (std::ios::openmode) 0;
			bool output = false;
			if (binary)
			{
				flags|=std::ios::binary;
			}
			if (mode == MODE_APPEND)
			{
				flags|=std::ios::out|std::ios::app;
				output = true;
			}
			else if (mode == MODE_WRITE)
			{
				flags |= std::ios::out|std::ios::trunc;
				output = true;
			}
			else if (mode == MODE_READ)
			{
				flags |= std::ios::in;
			}

#ifdef DEBUG
			Logger* logger = Logger::Get("Filesystem.FileStream");
			logger->Debug("FILE OPEN FLAGS = %d, binary=%d, mode=%d, append=%d",flags,binary,(int)mode,append);
#endif
			if (output)
			{
				this->stream = new Poco::FileOutputStream(this->filename,flags);
#ifndef OS_WIN32
				chmod(this->filename.c_str(),S_IRUSR|S_IWUSR|S_IRGRP|S_IROTH);
#endif		
			}
			else
			{
				this->stream = new Poco::FileInputStream(this->filename,flags);
			}
			return true;
		}
		catch (Poco::Exception& exc)
		{
			Logger* logger = Logger::Get("Filesystem.FileStream");
			logger->Error("Error in open. Exception: %s",exc.displayText().c_str());
			throw ValueException::FromString(exc.displayText());
		}
	}
Exemple #13
0
int IRC::start(char* server, int port, char* nick, char* user, char* name, char* pass)
{
	#ifdef WIN32
	HOSTENT* resolv;
	#else
	hostent* resolv;
	#endif
	sockaddr_in rem;

	if (connected)
		return 1;

	irc_socket=socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
	if (irc_socket==INVALID_SOCKET)
	{
		return 1;
	}
	resolv=gethostbyname(server);
	if (!resolv)
	{
		closesocket(irc_socket);
		return 1;
	}
	memcpy(&rem.sin_addr, resolv->h_addr, 4);
	rem.sin_family=AF_INET;
	rem.sin_port=htons(port);

	connecting = true;

	if (connect(irc_socket, (const sockaddr*)&rem, sizeof(rem))==SOCKET_ERROR)
	{
#ifdef WIN32
		Logger logger = Logger::GetRootLogger();
		logger.Error("Failed to connect: %s", WSAGetLastError());
#endif
		connecting = false;
		closesocket(irc_socket);
		return 1;
	}

	cur_nick=new char[strlen(nick)+1];
	strcpy(cur_nick, nick);

	send("PASS %s\r\n", pass);
	send("NICK %s\r\n", cur_nick);
	send("USER %s * 0 :%s\r\n", user, name);

	connected=true;
	connecting=false;

	return 0;
}
	void Win32TrayItem::HandleDoubleLeftClick()
	{
		try
		{
			this->FireEvent(Event::DOUBLE_CLICKED);
		}
		catch (ValueException& e)
		{
			Logger* logger = Logger::Get("UI.Win32TrayItem");
			SharedString ss = e.DisplayString();
			logger->Error("Tray icon double left click callback failed: %s", ss->c_str());
		}
	}
    void RubyEvaluator::Evaluate(const ValueList& args, KValueRef result)
    {
        args.VerifyException("evaluate", "s s s o");
        
        //const char *mimeType = args.GetString(0).c_str();
        std::string name = args.GetString(1);
        std::string code = args.GetString(2);
        global_object = args.GetObject(3);

        VALUE ctx = this->GetContext(global_object);

        VALUE rargs = rb_ary_new();
        rb_ary_push(rargs, ctx);
        rb_ary_push(rargs, rb_str_new2(code.c_str()));

        int error;
        VALUE returnValue = rb_protect(reval_do_call, rargs, &error);
        RubyEvaluator::ContextToGlobal(ctx, global_object);

        if (error != 0)
        {
            std::string error("An error occured while parsing Ruby (");
            error += name;
            error += "): ";

            // Display a stringified version of the exception.
            VALUE exception = rb_gv_get("$!");
            KValueRef v = RubyUtils::ToKrollValue(exception);
            SharedString ss = v->DisplayString();
            error.append(ss->c_str());

            // Try to make a nice backtrace for the user.
            VALUE backtrace = rb_funcall(exception,
                rb_intern("backtrace"), 0);
            VALUE rBacktraceString = rb_funcall(backtrace,
                rb_intern("join"), 1, rb_str_new2("\n"));
            if (TYPE(rBacktraceString) == T_STRING)
            {
                error.append("\n");
                error.append(StringValuePtr(rBacktraceString));
            }

            Logger *logger = Logger::Get("Ruby");
            logger->Error(error);

            result->SetUndefined();
            return;
        }

        result->SetValue(RubyUtils::ToKrollValue(returnValue));
    }
Exemple #16
0
    std::string AppURLToPath(const std::string& inURL)
    {
        try
        {
            Poco::URI inURI = Poco::URI(inURL);
            if (inURI.getScheme() != "app")
            {
                return inURL;
            }

            std::string appURL(NormalizeAppURL(inURL));
            inURI = Poco::URI(appURL);

            SharedApplication app = Host::GetInstance()->GetApplication();
            std::string path(app->GetResourcesPath());

            std::vector<std::string> segments;
            inURI.getPathSegments(segments);
            for (size_t i = 0; i < segments.size(); i++)
            {
                path = FileUtils::Join(path.c_str(), segments[i].c_str(), NULL);
            }
            return path;
        }
        catch (ValueException& e)
        {
            SharedString ss = e.DisplayString();
            Logger* log = Logger::Get("URLUtils");
            log->Error("Could not convert %s to a path: %s", inURL.c_str(), ss->c_str());
        }
        catch (...)
        {
            Logger* log = Logger::Get("URLUtils");
            log->Error("Could not convert %s to a path", inURL.c_str());
        }

        return inURL;
    }
Exemple #17
0
	void FileStream::ReadLine(const ValueList& args, SharedValue result)
	{
		if(! this->stream)
		{
			Logger* logger = Logger::Get("Filesystem.FileStream");
			logger->Error("Error in readLine. FileStream must be opened before calling read");
			throw ValueException::FromString("FileStream must be opened before calling readLine");
		}

		try
		{
			Poco::FileInputStream* fis = dynamic_cast<Poco::FileInputStream*>(this->stream);
			if(!fis)
			{
				Logger* logger = Logger::Get("Filesystem.FileStream");
				logger->Error("Error in readLine. FileInputStream is null");
				throw ValueException::FromString("FileStream must be opened for reading before calling readLine");
			}

			if(fis->eof())
			{
				// close the file
				result->SetNull();
			}
			else
			{
				std::string line;
				std::getline(*fis, line);
				result->SetObject(new Blob((std::string)line));
			}
		}
		catch (Poco::Exception& exc)
		{
			Logger* logger = Logger::Get("Filesystem.FileStream");
			logger->Error("Error in readLine. Exception: %s",exc.displayText().c_str());
			throw ValueException::FromString(exc.displayText());
		}
	}
Exemple #18
0
int init(void) {
    iniFile = (char*) SendMessage(plugin.hwndWinampParent, WM_WA_IPC, 0, IPC_GETINIFILE);
    if (! mlOrgConfig.LoadConfiguration(iniFile)) {
        logger.Error("ml_org::init()", "could not load configuration");
        return 1;
    }

    logger.SetLogLevel(mlOrgConfig.m_logLevel);
    logger.SetLogfile(mlOrgConfig.m_logfile);

    // Grab ahold of the window function pointer so we can do our own thang
    // when someone presses the "Organize Media Library" menu item
    mlWndproc = (WNDPROC) SetWindowLongPtr(plugin.hwndLibraryParent,
                                           GWLP_WNDPROC, (LONG) winproc);
    if (mlWndproc == 0) {
        int error = GetLastError();
        sprintf(tmp, "could not get window func ptr (%d)", error);
        logger.Error("ml_org::init()", tmp);
        return error;
    }

    logger.Info("ml_org::init()", "plugin initialized");
    return 0;
}
	void WorkerContext::PostMessage(const ValueList &args, SharedValue result)
	{
		Logger *logger = Logger::Get("WorkerContext");
		logger->Debug("PostMessage called");
		try
		{
			Poco::ScopedLock<Poco::Mutex> lock(mutex);
			messages.push_back(args.at(0));
			SendQueuedMessages();
		}
		catch(std::exception &e)
		{
			logger->Error("Error calling onmessage for worker. Error = %s",e.what());
		}
	}
Exemple #20
0
	static void FireEventCallback(KMethodRef callback, AutoPtr<Event> event,
		bool synchronous, KObjectRef thisObject)
	{
		try
		{
			RunOnMainThread(callback, thisObject,
				ValueList(Value::NewObject(event)), synchronous);
		}
		catch (ValueException& e)
		{
			Logger* logger = Logger::Get("KEventObject");
			SharedString ss = e.DisplayString();
			logger->Error("Exception caught during event callback (target=[%s]): %s",
				event->target->GetType().c_str(), ss->c_str());
		}
	}
	void Win32TrayItem::HandleLeftClick()
	{
		if (callback.isNull())
			return;

		try
		{
			ValueList args;
			callback->Call(args);
		}
		catch (ValueException& e)
		{
			Logger* logger = Logger::Get("UI.Win32TrayItem");
			SharedString ss = e.DisplayString();
			logger->Error("Tray icon callback failed: %s", ss->c_str());
		}
	}
void TrayClickedCallback(GtkStatusIcon *status_icon, gpointer data)
{
    TrayItemGtk* item = static_cast<TrayItemGtk*>(data);
    KMethodRef cb = item->GetCallback();

    if (cb.isNull())
        return;

    try {
        ValueList args;
        cb->Call(args);

    } catch (ValueException& e) {
        Logger* logger = Logger::Get("UI.TrayItemGtk");
        SharedString ss = e.DisplayString();
        logger->Error("Tray icon callback failed: %s", ss->c_str());
    }
}
Exemple #23
0
	void FileStream::Write(char *text, int size)
	{
		try
		{
			Poco::FileOutputStream* fos = dynamic_cast<Poco::FileOutputStream*>(this->stream);
			if(!fos)
			{
				throw ValueException::FromString("FileStream must be opened for writing before calling write");
			}

			fos->write(text, size);
		}
		catch (Poco::Exception& exc)
		{
			Logger* logger = Logger::Get("Filesystem.FileStream");
			logger->Error("Error in write. Exception: %s",exc.displayText().c_str());
			throw ValueException::FromString(exc.displayText());
		}
	}
	JavascriptModuleInstance::JavascriptModuleInstance(Host* host, std::string path, std::string dir, std::string name) :
		Module(host, dir.c_str(), name.c_str(), "0.1"),
		path(path)
	{
		this->context = JSGlobalContextCreate(NULL);
		this->global = JSContextGetGlobalObject(context);
		KJSUtil::RegisterGlobalContext(global, context);
		KJSUtil::ProtectGlobalContext(context);

		try
		{
			this->Run();
		}
		catch (ValueException& e)
		{
			SharedString ss = e.GetValue()->DisplayString();
			Logger *logger = Logger::Get("Javascript");
			logger->Error("Could not execute %s because %s", path.c_str(), (*ss).c_str());
		}
	}
    JavaScriptModuleInstance::JavaScriptModuleInstance(Host* host, std::string path, std::string dir, std::string name) :
        Module(host, dir.c_str(), name.c_str(), "0.1"),
        path(path),
        context(0)
    {
        this->context = KJSUtil::CreateGlobalContext();
        KJSUtil::ProtectGlobalContext(context);

        try
        {
            this->Run();
        }
        catch (ValueException& e)
        {
            SharedString ss = e.GetValue()->DisplayString();
            Logger *logger = Logger::Get("JavaScript");
            logger->Error("Could not execute %s because %s", path.c_str(), (*ss).c_str());
        }

        instanceContexts.push_back(this->context);
    }
Exemple #26
0
	std::string URLToPath(std::string& url)
	{
		Poco::URI inURI = Poco::URI(url);
		try
		{
			if (inURI.getScheme() == "ti")
			{
				return TiURLToPath(url);
			}
			else if (inURI.getScheme() == "app")
			{
				return AppURLToPath(url);
			}
		}
		catch (ValueException& e)
		{
			SharedString ss = e.DisplayString();
			Logger* log = Logger::Get("URLUtils");
			log->Error("Could not convert %s to a path: %s", url.c_str(), ss->c_str());
		}
		return url;
	}
Exemple #27
0
    std::string URLToPath(const std::string& url)
    {
        Poco::URI inURI = Poco::URI(url);
        try
        {
            if (url == BlankPageURL())
            {
                return BlankURLToFilePath();
            }
            if (inURI.getScheme() == "ti")
            {
                return TiURLToPath(url);
            }
            else if (inURI.getScheme() == "app")
            {
                return AppURLToPath(url);
            }
            else if (inURI.getScheme().empty())
            {
                // There is no scheme for this URL, so we have to/ guess at this point if
                // it's a path or a relative app:// URL. If a file can be found, assume thi
                // is a file path.
                if (FileUtils::IsFile(url))
                    return url;

                // Otherwise treat this like an app:// URL relative to the root.
                std::string newURL("app://");
                newURL.append(url);
                return AppURLToPath(newURL);
            }
        }
        catch (ValueException& e)
        {
            SharedString ss = e.DisplayString();
            Logger* log = Logger::Get("URLUtils");
            log->Error("Could not convert %s to a path: %s", url.c_str(), ss->c_str());
        }
        return url;
    }
	Worker::~Worker()
	{
		Poco::ScopedLock<Poco::Mutex> lock(mutex);
		if (!this->stopped)
		{
			this->stopped=true;
			this->condition.signal();
		}
		if (this->thread.isRunning())
		{
			try
			{
				this->thread.join();
			}
			catch (Poco::Exception& e)
			{
				Logger *logger = Logger::Get("Worker");
				logger->Error(
					"Exception while try to join with thread: %s",
					e.displayText().c_str());
			}
		}
		delete this->adapter;
	}
Exemple #29
0
//
// Handler
//
INT_32 FnAvg::Handler(CDT            * aArguments,
                      const UINT_32    iArgNum,
                      CDT            & oCDTRetVal,
                      Logger         & oLogger)
{
	// Need at least 2 args
	if (iArgNum < 2)
	{
		oLogger.Emerg("Usage: AVG(data1, data2, ..., dataN, '[aAgGhHqQ]')");
		return -1;
	}

	// First Arg 1: destination type
	const STLW::string & sWhat = aArguments[iArgNum - 1].GetString();
	if (sWhat.length() == 0)
	{
		oLogger.Error("Last argument should be 'a', 'A', 'g', 'G', 'h', 'H', 'q' or 'Q', but is `%s`", sWhat.c_str());
		return -1;
	}

	// http://en.wikipedia.org/wiki/Average
	switch (sWhat[0])
	{
		// Arithmetic
		case 'A':
		case 'a':
			{
				W_FLOAT  dSum = 0.0;
				for(INT_32 iPos = iArgNum - 2; iPos >= 0 ; --iPos)
				{
					dSum += aArguments[iPos].GetFloat();
				}
				oCDTRetVal = dSum / (iArgNum - 1);
			}
			break;

		// Geometric
		case 'G':
		case 'g':
			{
				W_FLOAT  dSum = 1.0;
				for(INT_32 iPos = iArgNum - 2; iPos >= 0 ; --iPos)
				{
					dSum *= aArguments[iPos].GetFloat();
				}
				oCDTRetVal = pow(dSum, 1.0 / (iArgNum - 1));
			}
			break;

		// Harmonic
		case 'H':
		case 'h':
			{
				W_FLOAT  dSum = 0.0;
				for(INT_32 iPos = iArgNum - 2; iPos >= 0 ; --iPos)
				{
					const W_FLOAT dTMP = aArguments[iPos].GetFloat();
					if (dTMP == 0.0) { dSum = 0; break; }
					dSum += 1.0 / dTMP;
				}
				oCDTRetVal = 1.0 * (iArgNum - 1) / dSum;
			}
			break;

		// Quadratic
		case 'Q':
		case 'q':
			{
				W_FLOAT  dSum = 0.0;
				for(INT_32 iPos = iArgNum - 1; iPos >= 0 ; --iPos)
				{
					const W_FLOAT dTMP = aArguments[iPos].GetFloat();
					dSum += dTMP * dTMP;
				}
				oCDTRetVal = sqrt(dSum / (iArgNum - 1));
			}
			break;

		default:
			oLogger.Error("Last argument should be 'a', 'A', 'g', 'G', 'h', 'H', 'q' or 'Q', but is `%s`", sWhat.c_str());
			return -1;
	}

return 0;
}
	void AsyncCopy::Run(void* data)
	{
		START_KROLL_THREAD;

		Logger* logger = Logger::Get("Filesystem.AsyncCopy");

		AsyncCopy* ac = static_cast<AsyncCopy*>(data);
		std::vector<std::string>::iterator iter = ac->files.begin();
		Poco::Path to(ac->destination);
		Poco::File tof(to.toString());

		logger->Debug("Job started: dest=%s, count=%i", ac->destination.c_str(), ac->files.size());
		if (!tof.exists())
		{
			tof.createDirectory();
		}
		int c = 0;
		while (!ac->stopped && iter!=ac->files.end())
		{
			bool err_copy = false;
			std::string file = (*iter++);
			c++;

			logger->Debug("File: path=%s, count=%i\n", file.c_str(), c);
			try
			{
				Poco::Path from(file);
				Poco::File f(file);
				if (f.isDirectory())
				{
					ac->Copy(from,to);
				}
				else
				{
					Poco::Path dest(to,from.getFileName());
					ac->Copy(from,dest);
				}
				logger->Debug("File copied");

				KValueRef value = Value::NewString(file);
				ValueList args;
				args.push_back(value);
				args.push_back(Value::NewInt(c));
				args.push_back(Value::NewInt(ac->files.size()));
				args.push_back(Value::NewBool(true));
				RunOnMainThread(ac->callback, args, false);

				logger->Debug("Callback executed");
			}
			catch (ValueException &ex)
			{
				err_copy = true;
				SharedString ss = ex.DisplayString();
				logger->Error(std::string("Error: ") + *ss + " for file: " + file);
			}
			catch (Poco::Exception &ex)
			{
				err_copy = true;
				logger->Error(std::string("Error: ") + ex.displayText() + " for file: " + file);
			}
			catch (std::exception &ex)
			{
				err_copy = true;
				logger->Error(std::string("Error: ") + ex.what() + " for file: " + file);
			}
			catch (...)
			{
				err_copy = true;
				logger->Error(std::string("Unknown error during copy: ") + file);
			}
			try
			{
				if(err_copy)
				{
					KValueRef value = Value::NewString(file);
					ValueList args;
					args.push_back(value);
					args.push_back(Value::NewInt(c));
					args.push_back(Value::NewInt(ac->files.size()));
					args.push_back(Value::NewBool(false));
					RunOnMainThread(ac->callback, args, false);
				}
			}
			catch(...)
			{
				err_copy = true;
				logger->Error(std::string("Unknown error during copy: ") + file);
			}

		}
		ac->Set("running",Value::NewBool(false));
		ac->stopped = true;

		logger->Debug(std::string("Job finished"));

		END_KROLL_THREAD;
	}