⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 graphbuilderaiml.cpp

📁 AIML的实现
💻 CPP
📖 第 1 页 / 共 4 页
字号:
void GraphBuilderAIML::parseConfigurationFile(const String &fileName)
//	throw(XMLErrorException &, FileNotFoundException &, Exception &)
{
	LOG_BOT_METHOD("void GraphBuilderAIML::parseConfigurationFile(const String &fileName)");
	logging("<Input> file: " + String(fileName));
	
	if(!exists(fileName))
	{
		String fileNotFoundMsg = "File:" + fileName + " was not found";
		throw FileNotFoundExceptionImpl(fileNotFoundMsg.c_str());
	}

	try 
	{
		if(m_doConfigurationValidation && (!m_configurationSchema.empty()) && !(m_commonTypesSchema.empty()))
		{
			String SchemaLoc = "http://aitools.org/programd/4.5 " + m_commonTypesSchema + 
					            " http://aitools.org/programd/4.5/bot-configuration " + m_configurationSchema;

			m_configurationParser->setDoSchema(true);
			m_configurationParser->setDoValidation(true);    // optional.
			m_configurationParser->setDoNamespaces(true);    // optional
			m_configurationParser->setExternalSchemaLocation(SchemaLoc.c_str());
		}
		else
		{
			m_configurationParser->setDoSchema(false);
			m_configurationParser->setDoValidation(false);    // optional.
			m_configurationParser->setDoNamespaces(false);    // optional
		}
	
		m_configurationParser->parse(fileName.c_str());
	}
	catch (const XMLException& toCatch) 
	{
		Transcode message(toCatch.getMessage());
		String msg("XMLException: " + message.getString());
		logging(msg);
		throw ExceptionImpl(msg.c_str());
	}
	catch (const SAXParseException& toCatch) 
	{
		Transcode message(toCatch.getMessage());
		String msg("SAXParseException: " + message.getString());
		logging(msg);
		throw ExceptionImpl(msg.c_str());
	}
}

void GraphBuilderAIML::parsePropertiesFile(const char *const fileName)
	throw(XMLErrorException &, FileNotFoundException &, Exception &)
{
	try
	{
		LOG_BOT_METHOD("void GraphBuilderAIML::parsePropertiesFile(const char *const fileName)");
		logging("<Input> file: " + String(fileName));

		parseConfigurationFile(fileName);
	}
	catch(exception &e)
	{
		throw ExceptionImpl(e.what());
	}
}

void GraphBuilderAIML::parseSentenceSplitterFile(const char *const fileName)
	throw(XMLErrorException &, FileNotFoundException &, Exception &)
{
	try
	{
		LOG_BOT_METHOD("void GraphBuilderAIML::parseSentenceSplitterFile(const char *const fileName)");
		logging("<Input> file: " + String(fileName));

		parseConfigurationFile(fileName);
	}
	catch(exception &e)
	{
		throw ExceptionImpl(e.what());
	}
}

void GraphBuilderAIML::setSentenceSplitter(const char *const splitter)
	throw(Exception &)
{
	try
	{
		m_sentenceSplitters += splitter;
	}
	catch(exception &e)
	{
		throw ExceptionImpl(e.what());
	}
}

int GraphBuilderAIML::getSize() const
	throw(Exception &)
{
	try
	{
		return m_size;
	}
	catch(exception &e)
	{
		throw ExceptionImpl(e.what());
	}

}

void GraphBuilderAIML::setSize(const unsigned int newSize)
//	throw(Exception &)
{
	m_size = newSize;
}

StringPimpl GraphBuilderAIML::getVersion() const
	throw(Exception &)
{
	try
	{
		return ".9871";
	}
	catch(exception &e)
	{
		throw ExceptionImpl(e.what());
	}
}

void GraphBuilderAIML::setCallBacks(CallBacks *callBacks)
	throw(Exception &)
{
	try
	{
		m_callBacks = callBacks;
	}
	catch(exception &e)
	{
		throw ExceptionImpl(e.what());
	}
}

void GraphBuilderAIML::storeGossip(const char * const gossip)
	throw(Exception &)
{
	try
	{
		m_callBacks->storeGossip(gossip);
	}
	catch(exception &e)
	{
		throw ExceptionImpl(e.what());
	}
}

CallBacks &GraphBuilderAIML::getCallBacks()
	throw(Exception &)
{
	try
	{
		return *m_callBacks;
	}
	catch(exception &e)
	{
		throw ExceptionImpl(e.what());
	}
}

StringPimpl GraphBuilderAIML::getId() const
	throw(Exception &)
{
	try
	{
		return m_id.c_str();
	}
	catch(exception &e)
	{
		throw ExceptionImpl(e.what());
	}
}

void GraphBuilderAIML::setId(const char * const id)
	throw(Exception &)
{
	try
	{
		m_id = id;
	}
	catch(exception &e)
	{
		throw ExceptionImpl(e.what());
	}
}

StringPimpl GraphBuilderAIML::checkedInfiniteLoopGetResponse(const StringPimpl &userInput, bool keepPreviousUserInput)
	throw(RecursionException &, Exception &)
{
	try
	{
		String userInputString(userInput.c_str());
		typedef VectorString::const_iterator CI;

		for(CI it = m_previousSrai.begin(); it != m_previousSrai.end(); ++it)
		{
			if(userInputString == *it)
			{
				logging("Infinite Recursion detected");
				throw RecursionExceptionImpl("Infinite Recursion detected");
			}
		}

		m_previousSrai.push_back(userInputString);

		/*
		 * Save the stars and then restore them
		 * after the call.  The reason is that 
		 * this can be called recursively through
		 * srai and we want to restore the stars 
		 * after each of those calls.
		 */
		VectorString m_tempStar = m_star; 
		VectorString m_tempThatStar = m_thatStar;
		VectorString m_tempTopicStar = m_topicStar;
		
		StringPimpl response = getResponseInternal(userInputString.c_str(), keepPreviousUserInput);
		
		/*
		 * Now restore the stars to before us 
		 * calling getrepsonse.
		 */
		m_star = m_tempStar;
		m_thatStar = m_tempThatStar;
		m_topicStar = m_tempTopicStar;

		return response;
	}
	catch(exception &e)
	{
		throw ExceptionImpl(e.what());
	}
}

void GraphBuilderAIML::removeCustomTagLibrary(const char * const library)
	throw(FileNotFoundException &, Exception &)
{
	///@todo put this into the adt
	typedef map<String, CustomTagWithDelete>::iterator I;
	I it = m_customTags.find(library);

	if(it != m_customTags.end())
	{
		CustomTagWithDelete &tag = it->second;
		(tag.m_deleteFunc)(tag.m_customTags);

		///@todo fix this, cannot remove the lib right now.
		//There's a dep on the GraphBuilder shared_ptr to 
		//the dll
		//FreeLibrary(tag.m_dllHandle);

		m_customTags.erase(library);
	}
	else
	{
		String msg("Cannot find library to remove:" + String(library));
		throw ExceptionImpl(msg.c_str());
	}
}

void GraphBuilderAIML::addCustomTagLibrary(const char * const library)
	throw(FileNotFoundException &, Exception &)
{
#ifdef _WIN32
	HINSTANCE hinstLib; 
	EntryPointfuncPtr func;
	ExitPointfuncPtr deleteFunc;	
	BOOL fRunTimeLinkSuccess = FALSE; 
 
    // Get a handle to the DLL module. 
	String lib(library);
	lib += ".dll";
    hinstLib = LoadLibrary(lib.c_str()); 
 
    // If the handle is valid, try to get the function address.
    if (hinstLib != NULL) 
    { 
        func = (EntryPointfuncPtr)GetProcAddress(hinstLib, "rebeccaAIMLLoadCustomTags"); 
        deleteFunc = (ExitPointfuncPtr)GetProcAddress(hinstLib, "rebeccaAIMLRemoveCustomTags"); 
		
		if(func == NULL)
		{
			throw ExceptionImpl("rebeccaAIMLLoadCustomTags C function not found in the library");
		}

		if(deleteFunc == NULL)
		{
			throw ExceptionImpl("rebeccaAIMLRemoveCustomTags C function not found in the library");
		}

        // The addresses are valid, call the function.
        fRunTimeLinkSuccess = TRUE;
		
		//Add the tag to the vector of custom tags
		CustomTagWithDelete tag;
		tag.m_customTags = (func) ();
		tag.m_deleteFunc = deleteFunc;
		tag.m_dllHandle = hinstLib;
		m_customTags[library] = tag;
		//m_customTags.push_back(tag); 
    }
   	else 
	{
		throw ExceptionImpl("The library is not a valid dll or shared object");
	}	
#else 
	
	//I am assuming Unix or Linux by default
	//if not windows
	void *handle;
	String lib("lib");
    lib	+= library;
	lib += ".so";	
	handle = dlopen(lib.c_str(), RTLD_LAZY);
	EntryPointfuncPtr func;
	ExitPointfuncPtr deleteFunc;
	char * error;
	if(handle)
	{
		func = (EntryPointfuncPtr)dlsym(handle, "rebeccaAIMLLoadCustomTags");	
		error = dlerror();

		if(error != NULL)
		{
			throw ExceptionImpl("rebeccaAIMLLoadCustomTags C function not found in the library");
		}

		deleteFunc = (ExitPointfuncPtr)dlsym(handle, "rebeccaAIMLRemoveCustomTags");
		error = dlerror();

		if(error != NULL)
		{
			throw ExceptionImpl("rebeccaAIMLRemoveCustomTags C function not found in the library");
		}

		CustomTagWithDelete tag;
		tag.m_customTags = (func) ();
		tag.m_deleteFunc = deleteFunc;
		tag.m_dllHandle = handle;
		m_customTags[library] = tag;
	}
	else
	{
		throw ExceptionImpl("The library is not a valid dll or shared object");		
	}
	
#endif

}

StringPimpl GraphBuilderAIML::callSystemCommand(const char * const command)
	throw(Exception &)
{
	LOG_BOT_METHOD("GraphBuilderAIML::callSystemCommand(const char * const command)");
	String commandString(command);
#ifdef _WIN32

	STARTUPINFO si;
	SECURITY_ATTRIBUTES sa;
	SECURITY_DESCRIPTOR sd;
	PROCESS_INFORMATION pi;
	HANDLE read_pipe, write_pipe;
	sa.nLength = sizeof(SECURITY_ATTRIBUTES);
	sa.bInheritHandle = TRUE;
	int fd, create;
	OSVERSIONINFO osv;
	osv.dwOSVersionInfoSize = sizeof(osv);
	
	GetVersionEx(&osv);

	if (osv.dwPlatformId == VER_PLATFORM_WIN32_NT)
	{
		InitializeSecurityDescriptor(&sd, SECURITY_DESCRIPTOR_REVISION);
		SetSecurityDescriptorDacl(&sd, TRUE, NULL, FALSE);
		sa.lpSecurityDescriptor = &sd;
	}
	else
	{
		/* Pipe will use ACLs from default descriptor */
		sa.lpSecurityDescriptor = NULL;
	}

	/* Create a new pipe with system's default buffer size */
	if (!CreatePipe(&read_pipe, &write_pipe, &sa, 0))
	{
		//error 
		return StringPimpl();
	}
	

	GetStartupInfo(&si);

	/* Sets the standard output handle for the process to the
	   handle specified in hStdOutput */
	si.dwFlags = STARTF_USESTDHANDLES | STARTF_USESHOWWINDOW;

	si.hStdOutput = write_pipe;
	si.hStdError  = (HANDLE) _get_osfhandle (2);
	si.wShowWindow = SW_HIDE;
	string cmd("cmd.exe /c \"");
	cmd += commandString;
	cmd += "\"";
	char *commandLine = strdup(cmd.c_str());
	create = CreateProcess(
		NULL,				// The full path of app to launch
		commandLine, // Command line parameters
		NULL,					// Default process security attributes
		NULL,					// Default thread security attributes
		TRUE,					// Inherit handles from the parent
		0,						// Normal priority
		NULL,					// Use the same environment as the parent
		NULL,					// Use app's directory as current
		&si,					// Startup Information
		&pi);					// Process information stored upon return

	if (!create)
	{
		//error
		return StringPimpl();
	}

	/* Associates a file descriptor with the stdout pipe */
	fd = _open_osfhandle((intptr_t)read_pipe, _O_BINARY);

	/* Close the handle that we're not going to use */
	CloseHandle(write_pipe);

	if (!fd)
	{
		//error
		return StringPimpl();
	}
	
	FILE *file = 0;

	/* Open the pipe stream using its file descriptor */
	file = fdopen(fd, "r");

	if(!file)
	{
		//error
		return StringPimpl();
	}

	if (commandLine)
		free(commandLine);

	int pid = (int)pi.hProcess;
	char c = 0;
	string returnString;
	while (c != EOF)
	{
		c = (char)getc(file);
		
		if(isascii(c))
		{
			returnString += c;
		}
	}

	/* Close the pipe once it's not needed anymore */
	fclose(file);
	return returnString.c_str();

#else

	FILE *file;
	file = popen(commandString.c_str(), "r");
	char c = 0;
	string returnString;
	while (c != EOF)
	{
		c = (char)getc(file);

		if(isascii(c))
		{
			returnString += c;
		}
	}

	fclose(file);
	return returnString.c_str();
#endif

}





} //end of namespace impl
} //end of namespace rebecca

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -