<commit_before>/*!
 * \file bpel-attributes.c
 *
 * \brief Functions for Petri nets (implementation)
 *
 * This file implements the classes and functions defined in bpel-attributes.h.
 *
 * \author
 *          - responsible: Niels Lohmann <nlohmann@informatik.hu-berlin.de>
 *          - last changes of: \$Author: reinert $
 *
 * \date
 *          - created: 2005/10/18
 *          - last changed: \$Date: 2005/12/01 15:00:02 $
 *
 * \note    This file is part of the tool BPEL2oWFN and was created during the
 *          project "Tools4BPEL" at the Humboldt-Universit� zu Berlin. See
 *          http://www.informatik.hu-berlin.de/top/forschung/projekte/tools4bpel
 *          for details.
 *
 * \version \$Revision: 1.8 $
 *
 */

#include "bpel-attributes.h" // ...
#include "bpel-syntax.h" // K_PROCESS ...
#include "debug.h" // trace() ...

/********************************************
 * implementation of attributeManager CLASS
 ********************************************/

/*!
 * contructor
 */
attributeManager::attributeManager()
{
  this->scannerResult.clear();
  this->attributeDB.clear();
  this->nodeId = 0;
  initAttributeDB();
}

/*!
 *
 */
kc::casestring attributeManager::read(kc::integer elementId, std::string attributeName)
{
  // "cast" Kimwitu++ to C++
  unsigned int elementIdInt = elementId->value;

  //trace(attributeName + "=" + intToString(elementIdInt) + "\n");

  std::string result;

  if(scannerResult[elementIdInt][attributeName].empty())
  {
    // no attribute-value given
    result = "";
  }
  else
  {
    result = scannerResult[elementIdInt][attributeName];
  }

  return kc::mkcasestring(result.c_str());
}

/*!
 *
 */
kc::integer attributeManager::nextId()
{
  this->nodeId++;
  return kc::mkinteger(this->nodeId);
}

/*!
 *
 */
void attributeManager::define(kc::casestring attributeName, kc::casestring attributeValue)
{
  scannerResult[this->nodeId][attributeName->name] = attributeValue->name;
/*  trace(TRACE_DEBUG,attributeName->name);
  trace(TRACE_DEBUG,"=");
  trace(TRACE_DEBUG,attributeValue->name);
  trace(TRACE_DEBUG,"\n");
*/
}

/*!
 * to initialize the attributeDB
 */
void attributeManager::initAttributeDB()
{
	/*
	 *  [activity-id][attribute-name][optional][tagged][content type][default content]
	 *
	 * 	[optional] -> true <optional attribute> | false <mandotory attribute>
	 * 	[tagged] -> true | false
	 * 	[content type] -> 0 <not empty> | 1 <yes | no>
	 */

	// process
	this->attributeDB[K_PROCESS][A__NAME] = new attributeDBData(false, false, 0);
	this->attributeDB[K_PROCESS][A__TARGET_NAMESPACE] = new attributeDBData(false, false, 0);
	this->attributeDB[K_PROCESS][A__QUERY_LANGUAGE] = new attributeDBData(true, false, 0);
	this->attributeDB[K_PROCESS][A__EXPRESSION_LANGUAGE] = new attributeDBData(true, false, 0);
	this->attributeDB[K_PROCESS][A__SUPPRESS_JOIN_FAILURE] = new attributeDBData(true, false, 1);
	this->attributeDB[K_PROCESS][A__ENABLE_INSTANCE_COMPENSATION] = new attributeDBData(true, false, 1);
	this->attributeDB[K_PROCESS][A__ABSTRACT_PROCESS] = new attributeDBData(true, false, 1);
	this->attributeDB[K_PROCESS][A__XMLNS] = new attributeDBData(false, false, 0);

	// receive
	this->attributeDB[K_RECEIVE][A__PARTNER_LINK] = new attributeDBData(false, false, 0);
	this->attributeDB[K_RECEIVE][A__PORT_TYPE] = new attributeDBData(false, false, 0);
	this->attributeDB[K_RECEIVE][A__OPERATION] = new attributeDBData(false, false, 0);
	this->attributeDB[K_RECEIVE][A__VARIABLE] = new attributeDBData(true, false, 0);
	this->attributeDB[K_RECEIVE][A__CREATE_INSTANCE] = new attributeDBData(true, false, 1);
	//	standard-attributes
	this->attributeDB[K_RECEIVE][A__NAME] = new attributeDBData(true, false, 0);
	this->attributeDB[K_RECEIVE][A__JOIN_CONDITION] = new attributeDBData(true, false, 0);
	this->attributeDB[K_RECEIVE][A__SUPPRESS_JOIN_FAILURE] = new attributeDBData(true, false, 1);

	// reply
	this->attributeDB[K_REPLY][A__PARTNER_LINK] = new attributeDBData(false, false, 0);
	this->attributeDB[K_REPLY][A__PORT_TYPE] = new attributeDBData(false, false, 0);
	this->attributeDB[K_REPLY][A__OPERATION] = new attributeDBData(false, false, 0);
	this->attributeDB[K_REPLY][A__VARIABLE] = new attributeDBData(true, false, 0);
	this->attributeDB[K_REPLY][A__FAULT_NAME] = new attributeDBData(true, false, 0);
	//	standard-attributes
	this->attributeDB[K_REPLY][A__NAME] = new attributeDBData(true, false, 0);
	this->attributeDB[K_REPLY][A__JOIN_CONDITION] = new attributeDBData(true, false, 0);
	this->attributeDB[K_REPLY][A__SUPPRESS_JOIN_FAILURE] = new attributeDBData(true, false, 1);

	// invoke
	this->attributeDB[K_REPLY][A__PARTNER_LINK] = new attributeDBData(false, false, 0);
	this->attributeDB[K_REPLY][A__PORT_TYPE] = new attributeDBData(false, false, 0);
	this->attributeDB[K_REPLY][A__OPERATION] = new attributeDBData(false, false, 0);
	this->attributeDB[K_REPLY][A__INPUT_VARIABLE] = new attributeDBData(true, false, 0);
	this->attributeDB[K_REPLY][A__OUTPUT_VARIABLE] = new attributeDBData(true, false, 0);
	//	standard-attributes
	this->attributeDB[K_RECEIVE][A__NAME] = new attributeDBData(true, false, 0);
	this->attributeDB[K_RECEIVE][A__JOIN_CONDITION] = new attributeDBData(true, false, 0);
	this->attributeDB[K_RECEIVE][A__SUPPRESS_JOIN_FAILURE] = new attributeDBData(true, false, 1);

	// assign
	//	standard-attributes
	this->attributeDB[K_ASSIGN][A__NAME] = new attributeDBData(true, false, 0);
	this->attributeDB[K_ASSIGN][A__JOIN_CONDITION] = new attributeDBData(true, false, 0);
	this->attributeDB[K_ASSIGN][A__SUPPRESS_JOIN_FAILURE] = new attributeDBData(true, false, 1);

	// throw
	this->attributeDB[K_THROW][A__FAULT_NAME] = new attributeDBData(false, false, 0);
	this->attributeDB[K_THROW][A__FAULT_VARIABLE] = new attributeDBData(true, false, 0);
	//	standard-attributes
	this->attributeDB[K_RECEIVE][A__NAME] = new attributeDBData(true, false, 0);
	this->attributeDB[K_RECEIVE][A__JOIN_CONDITION] = new attributeDBData(true, false, 0);
	this->attributeDB[K_RECEIVE][A__SUPPRESS_JOIN_FAILURE] = new attributeDBData(true, false, 1);

	// wait
	this->attributeDB[K_WAIT][A__FOR] = new attributeDBData(false, false, 0);
	this->attributeDB[K_WAIT][A__UNTIL] = new attributeDBData(false, false, 0);
	//	standard-attributesTRACE_DEBUG,
	this->attributeDB[K_RECEIVE][A__NAME] = new attributeDBData(true, false, 0);
	this->attributeDB[K_RECEIVE][A__JOIN_CONDITION] = new attributeDBData(true, false, 0);
	this->attributeDB[K_RECEIVE][A__SUPPRESS_JOIN_FAILURE] = new attributeDBData(true, false, 1);

	// empty
	//	standard-attributes
	this->attributeDB[K_EMPTY][A__NAME] = new attributeDBData(true, false, 0);
	this->attributeDB[K_EMPTY][A__JOIN_CONDITION] = new attributeDBData(true, false, 0);
	this->attributeDB[K_EMPTY][A__SUPPRESS_JOIN_FAILURE] = new attributeDBData(true, false, 1);

	// terminate
	//	standard-attributes
	this->attributeDB[K_TERMINATE][A__NAME] = new attributeDBData(true, false, 0);
	this->attributeDB[K_TERMINATE][A__JOIN_CONDITION] = new attributeDBData(true, false, 0);
	this->attributeDB[K_TERMINATE][A__SUPPRESS_JOIN_FAILURE] = new attributeDBData(true, false, 1);

	// flow
	//	standard-attributes
	this->attributeDB[K_RECEIVE][A__NAME] = new attributeDBData(true, false, 0);
	this->attributeDB[K_RECEIVE][A__JOIN_CONDITION] = new attributeDBData(true, false, 0);
	this->attributeDB[K_RECEIVE][A__SUPPRESS_JOIN_FAILURE] = new attributeDBData(true, false, 1);

	// switch
	//	standard-attributes
	this->attributeDB[K_SWITCH][A__NAME] = new attributeDBData(true, false, 0);
	this->attributeDB[K_SWITCH][A__JOIN_CONDITION] = new attributeDBData(true, false, 0);
	this->attributeDB[K_SWITCH][A__SUPPRESS_JOIN_FAILURE] = new attributeDBData(true, false, 1);

	// while
	this->attributeDB[K_WHILE][A__CONDITION] = new attributeDBData(false, false, 0);
	//	standard-attributes
	this->attributeDB[K_WHILE][A__NAME] = new attributeDBData(true, false, 0);
	this->attributeDB[K_WHILE][A__JOIN_CONDITION] = new attributeDBData(true, false, 0);
	this->attributeDB[K_WHILE][A__SUPPRESS_JOIN_FAILURE] = new attributeDBData(true, false, 1);

	// sequence
	//	standard-attributes
	this->attributeDB[K_SEQUENCE][A__NAME] = new attributeDBData(true, false, 0);
	this->attributeDB[K_SEQUENCE][A__JOIN_CONDITION] = new attributeDBData(true, false, 0);
	this->attributeDB[K_SEQUENCE][A__SUPPRESS_JOIN_FAILURE] = new attributeDBData(true, false, 1);

	// pick
	this->attributeDB[K_PICK][A__CREATE_INSTANCE] = new attributeDBData(true, false, 1);
	//	standard-attributes
	this->attributeDB[K_PICK][A__NAME] = new attributeDBData(true, false, 0);
	this->attributeDB[K_PICK][A__JOIN_CONDITION] = new attributeDBData(true, false, 0);
	this->attributeDB[K_PICK][A__SUPPRESS_JOIN_FAILURE] = new attributeDBData(true, false, 1);

	// scope
	this->attributeDB[K_SCOPE][A__VARIABLE_ACCESS_SERIALIZABLE] = new attributeDBData(false, false, 1);
	//	standard-attributes
	this->attributeDB[K_SCOPE][A__NAME] = new attributeDBData(true, false, 0);
	this->attributeDB[K_SCOPE][A__JOIN_CONDITION] = new attributeDBData(true, false, 0);
	this->attributeDB[K_SCOPE][A__SUPPRESS_JOIN_FAILURE] = new attributeDBData(true, false, 1);

	// compensate
	this->attributeDB[K_COMPENSATE][A__SCOPE] = new attributeDBData(true, false, 0);
	//	standard-attributes
	this->attributeDB[K_COMPENSATE][A__NAME] = new attributeDBData(true, false, 0);
	this->attributeDB[K_COMPENSATE][A__JOIN_CONDITION] = new attributeDBData(true, false, 0);
	this->attributeDB[K_COMPENSATE][A__SUPPRESS_JOIN_FAILURE] = new attributeDBData(true, false, 1);

}

/*!
 *
 */
bool attributeManager::isValidElement(unsigned int elementId, unsigned int activityId) {
	/// iterator for the embedded map
	std::map<std::string, std::string>::iterator scannerResultDataIterator;
	scannerResultDataIterator = this->scannerResult[elementId].begin();

	/// iteration loop about all xml-element attributes
	while(scannerResultDataIterator != this->scannerResult[elementId].end())
	{
		/// to tag all found accurate attributes
		if(isAttribute(activityId, (*scannerResultDataIterator).first))
		{
			trace(TRACE_VERY_DEBUG,(*scannerResultDataIterator).first + "\n");
			(this->attributeDB[activityId][(*scannerResultDataIterator).first])->setTag(true);
		}
		else
		{
			/* ignore
			 * 	- wrong spelling
			 *  - unknown attributes
			 *  */
		}
		++scannerResultDataIterator;
	}

	///
	if(!isAccurateCombinationOfAttributes(activityId))
	{
		return false;
	}

	///
	if(!checkAttributeContent(activityId))
	{
		//return false;
	}

	return true;
}

/*!
 *
 */
bool attributeManager::isAttribute(unsigned int activityId, std::string elementAttributeName)
{
	/// iterator for the embedded map
	std::map<std::string, attributeDBData*>::iterator attributeDBDataIterator;
	attributeDBDataIterator = this->attributeDB[activityId].begin();

	while(attributeDBDataIterator != attributeDB[activityId].end())
	{
		if(elementAttributeName.compare((*attributeDBDataIterator).first) == 0)
		{
			return true;
		}
		++attributeDBDataIterator;
	}
	return false;
}

/*!
 *
 */
bool attributeManager::isAccurateCombinationOfAttributes(unsigned int activityId)
{
	/// iterator for the embedded map
	std::map<std::string, attributeDBData*>::iterator attributeDBDataIterator;
	attributeDBDataIterator = this->attributeDB[activityId].begin();

	while(attributeDBDataIterator != attributeDB[activityId].end())
	{
		/// check of mandatory attribute
		if((!isOptional(activityId, (*attributeDBDataIterator).first) &&
			  !isTagged(activityId, (*attributeDBDataIterator).first)));
		{
			/* doesn't scanned mandatory attribute was found */
			trace(TRACE_DEBUG,"HALLO" + (*attributeDBDataIterator).first + "\n");
			return false;
		}

		/*blabla="naja"
		 * more checks are necessary
		 *	-
		 *
		 */

		++attributeDBDataIterator;
	}

	return true;
}

/*!
 *
 */
bool attributeManager::isOptional(unsigned int activityId, std::string attributeName)
{
	return (this->attributeDB[activityId][attributeName])->getOptional();
}

/*!
 *
 */
bool attributeManager::isTagged(unsigned int activityId, std::string attributeName)
{
	return (this->attributeDB[activityId][attributeName])->getTag();
}

/*!
 *
 */
bool attributeManager::checkAttributeContent(unsigned int activityId)
{
	return true;
}

/*!
 *
 * \param elementId
 * \param type
 */
void attributeManager::check(kc::integer elementId, unsigned int activityId)
{
//	trace("AttrM-ID: " + intToString(elementId->value) + "\n");
//	trace("Type: " + intToString(activityId) + "\n");

	if(!isValidElement(elementId->value, activityId))
	{
		//yyerror(string("+----------------------------------------- \n attributeManager: attribute error \n+----------------------------------------- \n ").c_str());
	}
}

/********************************************
 * implementation of attributeDBData CLASS
 ********************************************/

/*!
 *
 */
void attributeDBData::setOptional(bool val)
{
	this->optional = val;
}

/*!
 *
 */
void attributeDBData::setTag(bool val)
{
	this->tag = val;
}

/*!
 *
 */
void attributeDBData::setContentType(unsigned int val)
{
	this->contentType = val;
}

/*!
 *
 */
bool attributeDBData::getOptional()
{
	return this->optional;
}

/*!
 *
 */
bool attributeDBData::getTag(){
	return this->tag;
}

/*!
 *
 */
unsigned int attributeDBData::getContentType(){
	return this->contentType;
}

/*

	switch(activityId) {
		case K_PROCESS:
			{
				trace("PROCESS!!! \n");
				if(!isValidElement(elementId->value, activityId))
				{
				}
			}
			break;

		case K_RECEIVE:
			{
				trace("RECEIVE!!! \n");
				if(!isValidElement(elementId->value, activityId))
				{
					yyerror("FEHLER");
				}
			}
			break;

		case K_REPLY:
			{
				trace("REPLY!!!");
				if(!isValidElement(elementId->value, activityId))
				{
				}
			}
			break;

		case K_INVOKE:
			{
				trace("INVOKE!!!");
				if(!isValidElement(elementId->value, activityId))
				{
				}
			}
			break;

		case K_ASSIGN:
			{
				trace("ASSIGN!!!");
			}
			break;

		case K_THROW:
			{
				trace("THROW!!!");
			}
			break;

		case K_WAIT:
			{
				trace("WAIT!!!");
			}
			break;

		case K_EMPTY:
			{
				trace("EMPTY!!!");
			}
			break;

		case K_TERMINATE:
			{
				trace("TERMINATE!!!");
			}
			break;

	}

*/
<commit_msg>complete new attributeManager<commit_after>/*!
 * \file bpel-attributes.c
 *
 * \brief Functions for Petri nets (implementation)
 *
 * This file implements the classes and functions defined in bpel-attributes.h.
 *
 * \author
 *          - responsible: Niels Lohmann <nlohmann@informatik.hu-berlin.de>
 *          - last changes of: \$Author: reinert $
 *
 * \date
 *          - created: 2005/10/18
 *          - last changed: \$Date: 2005/12/02 15:59:40 $
 *
 * \note    This file is part of the tool BPEL2oWFN and was created during the
 *          project "Tools4BPEL" at the Humboldt-Universit� zu Berlin. See
 *          http://www.informatik.hu-berlin.de/top/forschung/projekte/tools4bpel
 *          for details.
 *
 * \version \$Revision: 1.9 $
 *
 */

#include "bpel-attributes.h"
#include "bpel-syntax.h"
#include "debug.h"

attributeManager::attributeManager()
{
  this->scannerResult.clear();
  this->nodeId = 0;
}

kc::casestring attributeManager::read(kc::integer elementId, std::string attributeName)
{
  // "cast" Kimwitu++ to C++
  unsigned int elementIdInt = elementId->value;

  std::string result;

  if(scannerResult[elementIdInt][attributeName].empty())
  {
    // no attribute-value given
    result = "";
  }
  else
  {
    result = scannerResult[elementIdInt][attributeName];
  }

  return kc::mkcasestring(result.c_str());
}

kc::integer attributeManager::nextId()
{
  this->nodeId++;
  return kc::mkinteger(this->nodeId);
}

void attributeManager::define(kc::casestring attributeName, kc::casestring attributeValue)
{
  scannerResult[this->nodeId][attributeName->name] = attributeValue->name;
}

void attributeManager::printCheckErrorMsg(std::string errorMsg)
{
	yyerror(string("[AttributeManager]: " + errorMsg + "\n").c_str());
}

void attributeManager::check(kc::integer elementId, unsigned int activityId)
{
	// "cast" Kimwitu++ to C++
  	unsigned int elementIdInt = elementId->value;
	/// iterator for the embedded map
    std::map<std::string, string>::iterator scannerResultDataIterator;

	switch(activityId) {
		case K_PROCESS:
			{
				trace(TRACE_DEBUG,"PROCESS!!! \n");

				bool nameFlag, targetNamespaceFlag;
				nameFlag = targetNamespaceFlag = true;

				scannerResultDataIterator = this->scannerResult[elementIdInt].begin();

				///
				while(scannerResultDataIterator != scannerResult[elementIdInt].end())
				{
					if(((*scannerResultDataIterator).first) == A__NAME)
					{
						nameFlag = false;
						trace(TRACE_DEBUG,(*scannerResultDataIterator).first + "\n");
					}
					else if(((*scannerResultDataIterator).first) == A__TARGET_NAMESPACE)
					{
						targetNamespaceFlag = false;
						trace(TRACE_DEBUG,(*scannerResultDataIterator).first + "\n");
					}
					++scannerResultDataIterator;
				}

				if(nameFlag)
				{
					printCheckErrorMsg("attribute " + A__NAME + "=\"" + T__NCNAME + "\" is missing");
				}
				else if(targetNamespaceFlag)
				{
					printCheckErrorMsg("attribute " + A__TARGET_NAMESPACE + "=\"" + T__ANYURI + "\" is missing");
				}

			}
			break;

		case K_RECEIVE:
			{
				trace(TRACE_DEBUG,"RECEIVE!!! \n");

				bool partnerLinkFlag, portTypeFlag, operationFlag;
				partnerLinkFlag = portTypeFlag = operationFlag = true;

				scannerResultDataIterator = this->scannerResult[elementIdInt].begin();

				///
				while(scannerResultDataIterator != scannerResult[elementIdInt].end())
				{
					if(((*scannerResultDataIterator).first) == A__PARTNER_LINK)
					{
						partnerLinkFlag = false;
						trace(TRACE_DEBUG,(*scannerResultDataIterator).first + "\n");
					}
					else if(((*scannerResultDataIterator).first) == A__PORT_TYPE)
					{
						portTypeFlag = false;
						trace(TRACE_DEBUG,(*scannerResultDataIterator).first + "\n");
					}
					else if(((*scannerResultDataIterator).first) == A__OPERATION)
					{
						operationFlag = false;
						trace(TRACE_DEBUG,(*scannerResultDataIterator).first + "\n");
					}
					++scannerResultDataIterator;
				}

				if(partnerLinkFlag)
				{
					printCheckErrorMsg("attribute " + A__PARTNER_LINK + "=\"" + T__NCNAME + "\" is missing");
				}
				else if(portTypeFlag)
				{
					printCheckErrorMsg("attribute " + A__PORT_TYPE + "=\"" + T__QNAME + "\" is missing");
				}
				else if(operationFlag)
				{
					printCheckErrorMsg("attribute " + A__OPERATION + "=\"" + T__NCNAME + "\" is missing");
				}
			}
			break;

		case K_REPLY:
			{
				trace(TRACE_DEBUG,"REPLY!!! \n");

				bool partnerLinkFlag, portTypeFlag, operationFlag;
				partnerLinkFlag = portTypeFlag = operationFlag = true;

				scannerResultDataIterator = this->scannerResult[elementIdInt].begin();

				///
				while(scannerResultDataIterator != scannerResult[elementIdInt].end())
				{
					if(((*scannerResultDataIterator).first) == A__PARTNER_LINK)
					{
						partnerLinkFlag = false;
						trace(TRACE_DEBUG,(*scannerResultDataIterator).first + "\n");
					}
					else if(((*scannerResultDataIterator).first) == A__PORT_TYPE)
					{
						portTypeFlag = false;
						trace(TRACE_DEBUG,(*scannerResultDataIterator).first + "\n");
					}
					else if(((*scannerResultDataIterator).first) == A__OPERATION)
					{
						operationFlag = false;
						trace(TRACE_DEBUG,(*scannerResultDataIterator).first + "\n");
					}
					++scannerResultDataIterator;
				}

				if(partnerLinkFlag)
				{
					printCheckErrorMsg("attribute " + A__PARTNER_LINK + "=\"" + T__NCNAME + "\" is missing");
				}
				else if(portTypeFlag)
				{
					printCheckErrorMsg("attribute " + A__PORT_TYPE + "=\"" + T__QNAME + "\" is missing");
				}
				else if(operationFlag)
				{
					printCheckErrorMsg("attribute " + A__OPERATION + "=\"" + T__NCNAME + "\" is missing");
				}
			}
			break;

		case K_INVOKE:
			{
				trace(TRACE_DEBUG,"INVOKE!!! \n");

				bool partnerLinkFlag, portTypeFlag, operationFlag;
				partnerLinkFlag = portTypeFlag = operationFlag = true;

				scannerResultDataIterator = this->scannerResult[elementIdInt].begin();

				///
				while(scannerResultDataIterator != scannerResult[elementIdInt].end())
				{
					if(((*scannerResultDataIterator).first) == A__PARTNER_LINK)
					{
						partnerLinkFlag = false;
						trace(TRACE_DEBUG,(*scannerResultDataIterator).first + "\n");
					}
					else if(((*scannerResultDataIterator).first) == A__PORT_TYPE)
					{
						portTypeFlag = false;
						trace(TRACE_DEBUG,(*scannerResultDataIterator).first + "\n");
					}
					else if(((*scannerResultDataIterator).first) == A__OPERATION)
					{
						operationFlag = false;
						trace(TRACE_DEBUG,(*scannerResultDataIterator).first + "\n");
					}
					++scannerResultDataIterator;
				}

				if(partnerLinkFlag)
				{
					printCheckErrorMsg("attribute " + A__PARTNER_LINK + "=\"" + T__NCNAME + "\" is missing");
				}
				else if(portTypeFlag)
				{
					printCheckErrorMsg("attribute " + A__PORT_TYPE + "=\"" + T__QNAME + "\" is missing");
				}
				else if(operationFlag)
				{
					printCheckErrorMsg("attribute " + A__OPERATION + "=\"" + T__NCNAME + "\" is missing");
				}
			}
			break;

		case K_ASSIGN:
			{
				trace(TRACE_DEBUG,"ASSIGN!!! \n");

				/* no mandatory attributes */

			}
			break;

		case K_THROW:
			{
				trace(TRACE_DEBUG,"THROW!!! \n");

				bool faultNameFlag;
				faultNameFlag = true;

				scannerResultDataIterator = this->scannerResult[elementIdInt].begin();

				///
				while(scannerResultDataIterator != scannerResult[elementIdInt].end())
				{
					if(((*scannerResultDataIterator).first) == A__FAULT_NAME)
					{
						faultNameFlag = false;
						trace(TRACE_DEBUG,(*scannerResultDataIterator).first + "\n");
					}
					++scannerResultDataIterator;
				}

				if(faultNameFlag)
				{
					printCheckErrorMsg("attribute " + A__FAULT_NAME + "=\"" + T__QNAME + "\" is missing");
				}

			}
			break;

		case K_WAIT:
			{
				trace(TRACE_DEBUG,"WAIT!!! \n");

				bool forFlag, untilFlag;
				forFlag = untilFlag = true;

				scannerResultDataIterator = this->scannerResult[elementIdInt].begin();

				///
				while(scannerResultDataIterator != scannerResult[elementIdInt].end())
				{
					if(((*scannerResultDataIterator).first) == A__FOR)
					{
						forFlag = false;
						trace(TRACE_DEBUG,(*scannerResultDataIterator).first + "\n");
					}
					else if(((*scannerResultDataIterator).first) == A__UNTIL)
					{
						untilFlag = false;
						trace(TRACE_DEBUG,(*scannerResultDataIterator).first + "\n");
					}
					++scannerResultDataIterator;
				}

				/// XOR
				if((forFlag && !untilFlag) || (!forFlag && untilFlag))
				{
					if(forFlag)
					{
						printCheckErrorMsg("attribute " + A__FOR + "=\"" + T__DURATION_EXPR + "\" is missing");
					}
					else if(untilFlag)
					{
						printCheckErrorMsg("attribute " + A__UNTIL + "=\"" + T__DEADLINE_EXPR + "\" is missing");
					}
				}
			}
			break;

		case K_EMPTY:
			{
				trace(TRACE_DEBUG,"EMPTY!!! \n");

				/* no mandatory attributes */

			}
			break;

		case K_TERMINATE:
			{
				trace(TRACE_DEBUG,"TERMINATE!!! \n");

				/* no mandatory attributes */

			}
			break;
		case K_SCOPE:
			{
				trace(TRACE_DEBUG,"SCOPE!!! \n");

				/* default attribute */

			}
			break;
		case K_COMPENSATE:
			{
				trace(TRACE_DEBUG,"COMPENSATE!!! \n");

				/* no mandatory attributes */

			}
			break;
		case K_PICK:
			{
				trace(TRACE_DEBUG,"PICK!!! \n");

				/* default attribute */
			}
			break;
		case K_SEQUENCE:
			{
				trace(TRACE_DEBUG,"SEQUENCE!!! \n");

				/* no mandatory attributes */

			}
			break;
		case K_SWITCH:
			{
				trace(TRACE_DEBUG,"SWITCH!!! \n");

				/* no mandatory attributes */

			}
			break;
		case K_WHILE:
			{
				trace(TRACE_DEBUG,"WHILE!!! \n");

				bool conditionFlag;
				conditionFlag = true;

				scannerResultDataIterator = this->scannerResult[elementIdInt].begin();

				///
				while(scannerResultDataIterator != scannerResult[elementIdInt].end())
				{
					if(((*scannerResultDataIterator).first) == A__CONDITION)
					{
						conditionFlag = false;
						trace(TRACE_DEBUG,(*scannerResultDataIterator).first + "\n");
					}
					++scannerResultDataIterator;
				}

				if(conditionFlag)
				{
					printCheckErrorMsg("attribute " + A__CONDITION + "=\"" + T__BOOLEAN_EXPR + "\" is missing");
				}

			}
			break;
	}

}
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: share.hxx,v $
 *
 *  $Revision: 1.3 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-07 22:31:55 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/
#include "uno/mapping.h"
#include <typeinfo>
#include <exception>
#include <cstddef>
namespace CPPU_CURRENT_NAMESPACE
{
void dummy_can_throw_anything( char const * );
// ----- following decl from libstdc++-v3/libsupc++/unwind-cxx.h and unwind.h

struct _Unwind_Exception
{
    unsigned exception_class __attribute__((__mode__(__DI__)));
    void * exception_cleanup;
    unsigned private_1 __attribute__((__mode__(__word__)));
    unsigned private_2 __attribute__((__mode__(__word__)));
} __attribute__((__aligned__));

struct __cxa_exception
{
    ::std::type_info *exceptionType;
    void (*exceptionDestructor)(void *);

    ::std::unexpected_handler unexpectedHandler;
    ::std::terminate_handler terminateHandler;

    __cxa_exception *nextException;

    int handlerCount;

    int handlerSwitchValue;
    const unsigned char *actionRecord;
    const unsigned char *languageSpecificData;
    void *catchTemp;
    void *adjustedPtr;

    _Unwind_Exception unwindHeader;
};

extern "C" void *__cxa_allocate_exception(
    std::size_t thrown_size ) throw();
extern "C" void __cxa_throw (
    void *thrown_exception, std::type_info *tinfo, void (*dest) (void *) ) __attribute__((noreturn));

struct __cxa_eh_globals
{
    __cxa_exception *caughtExceptions;
    unsigned int uncaughtExceptions;
};
extern "C" __cxa_eh_globals *__cxa_get_globals () throw();

//==================================================================================================
void raiseException(
    uno_Any * pUnoExc, uno_Mapping * pUno2Cpp );
//==================================================================================================
void fillUnoException(
    __cxa_exception * header, uno_Any *, uno_Mapping * pCpp2Uno );

inline char* adjustPointer( char* pIn, typelib_TypeDescription* pType )
{
    switch( pType->nSize )
    {
        case 1: return pIn + 3;
        case 2: return pIn + 2;
        case 3: return pIn + 1;
            // Huh ? perhaps a char[3] ? Though that would be a pointer
            // well, we have it anyway for symmetry
    }
    return pIn;
}

}
<commit_msg>INTEGRATION: CWS changefileheader (1.3.170); FILE MERGED 2008/03/28 16:30:35 rt 1.3.170.1: #i87441# Change license header to LPGL v3.<commit_after>/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2008 by Sun Microsystems, Inc.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * $RCSfile: share.hxx,v $
 * $Revision: 1.4 $
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/
#include "uno/mapping.h"
#include <typeinfo>
#include <exception>
#include <cstddef>
namespace CPPU_CURRENT_NAMESPACE
{
void dummy_can_throw_anything( char const * );
// ----- following decl from libstdc++-v3/libsupc++/unwind-cxx.h and unwind.h

struct _Unwind_Exception
{
    unsigned exception_class __attribute__((__mode__(__DI__)));
    void * exception_cleanup;
    unsigned private_1 __attribute__((__mode__(__word__)));
    unsigned private_2 __attribute__((__mode__(__word__)));
} __attribute__((__aligned__));

struct __cxa_exception
{
    ::std::type_info *exceptionType;
    void (*exceptionDestructor)(void *);

    ::std::unexpected_handler unexpectedHandler;
    ::std::terminate_handler terminateHandler;

    __cxa_exception *nextException;

    int handlerCount;

    int handlerSwitchValue;
    const unsigned char *actionRecord;
    const unsigned char *languageSpecificData;
    void *catchTemp;
    void *adjustedPtr;

    _Unwind_Exception unwindHeader;
};

extern "C" void *__cxa_allocate_exception(
    std::size_t thrown_size ) throw();
extern "C" void __cxa_throw (
    void *thrown_exception, std::type_info *tinfo, void (*dest) (void *) ) __attribute__((noreturn));

struct __cxa_eh_globals
{
    __cxa_exception *caughtExceptions;
    unsigned int uncaughtExceptions;
};
extern "C" __cxa_eh_globals *__cxa_get_globals () throw();

//==================================================================================================
void raiseException(
    uno_Any * pUnoExc, uno_Mapping * pUno2Cpp );
//==================================================================================================
void fillUnoException(
    __cxa_exception * header, uno_Any *, uno_Mapping * pCpp2Uno );

inline char* adjustPointer( char* pIn, typelib_TypeDescription* pType )
{
    switch( pType->nSize )
    {
        case 1: return pIn + 3;
        case 2: return pIn + 2;
        case 3: return pIn + 1;
            // Huh ? perhaps a char[3] ? Though that would be a pointer
            // well, we have it anyway for symmetry
    }
    return pIn;
}

}
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: xsec_framework.cxx,v $
 *
 *  $Revision: 1.1.1.1 $
 *
 *  last change: $Author: mt $ $Date: 2004-07-12 13:15:23 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (the "License"); You may not use this file
 *  except in compliance with the License. You may obtain a copy of the
 *  License at http://www.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/

#include <stdio.h>

#include <osl/mutex.hxx>
#include <osl/thread.h>
#include <cppuhelper/factory.hxx>

#ifndef _COM_SUN_STAR_LANG_XSINGLESERVICEFACTORY_HPP_
#include <com/sun/star/lang/XSingleServiceFactory.hpp>
#endif

#include <decryptorimpl.hxx>
#include <encryptorimpl.hxx>
#include <signaturecreatorimpl.hxx>
#include <signatureverifierimpl.hxx>
#include <saxeventkeeperimpl.hxx>
#include <xmlencryptiontemplateimpl.hxx>
#include <xmlsignaturetemplateimpl.hxx>

using namespace ::rtl;
using namespace ::cppu;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::lang;
using namespace ::com::sun::star::registry;

extern "C"
{
//==================================================================================================
void SAL_CALL component_getImplementationEnvironment(
    const sal_Char ** ppEnvTypeName, uno_Environment ** ppEnv )
{
    *ppEnvTypeName = CPPU_CURRENT_LANGUAGE_BINDING_NAME;
}

//==================================================================================================
sal_Bool SAL_CALL component_writeInfo(
    void * pServiceManager, void * pRegistryKey )
{
    if (pRegistryKey)
    {
        try
        {
            //Decryptor
            sal_Int32 nPos = 0;
            Reference< XRegistryKey > xNewKey(
                reinterpret_cast< XRegistryKey * >( pRegistryKey )->createKey( DecryptorImpl_getImplementationName() ) );
            xNewKey = xNewKey->createKey( OUString::createFromAscii( "/UNO/SERVICES" ) );

            const Sequence< OUString > & rSNL = DecryptorImpl_getSupportedServiceNames();
            const OUString * pArray = rSNL.getConstArray();
            for ( nPos = rSNL.getLength(); nPos--; )
                xNewKey->createKey( pArray[nPos] );

            //Encryptor
            xNewKey = reinterpret_cast< XRegistryKey * >( pRegistryKey )->createKey( EncryptorImpl_getImplementationName() );
            xNewKey = xNewKey->createKey( OUString::createFromAscii( "/UNO/SERVICES" ) );
            const Sequence< OUString > & rSNL2 = EncryptorImpl_getSupportedServiceNames();
            pArray = rSNL2.getConstArray();
            for ( nPos = rSNL2.getLength(); nPos--; )
                xNewKey->createKey( pArray[nPos] );

            //SignatureCreator
            xNewKey = reinterpret_cast< XRegistryKey * >( pRegistryKey )->createKey( SignatureCreatorImpl_getImplementationName() );
            xNewKey = xNewKey->createKey( OUString::createFromAscii( "/UNO/SERVICES" ) );
            const Sequence< OUString > & rSNL3 = SignatureCreatorImpl_getSupportedServiceNames();
            pArray = rSNL3.getConstArray();
            for ( nPos = rSNL3.getLength(); nPos--; )
                xNewKey->createKey( pArray[nPos] );

            //SignatureVerifier
            xNewKey = reinterpret_cast< XRegistryKey * >( pRegistryKey )->createKey( SignatureVerifierImpl_getImplementationName() );
            xNewKey = xNewKey->createKey( OUString::createFromAscii( "/UNO/SERVICES" ) );
            const Sequence< OUString > & rSNL4 = SignatureVerifierImpl_getSupportedServiceNames();
            pArray = rSNL4.getConstArray();
            for ( nPos = rSNL4.getLength(); nPos--; )
                xNewKey->createKey( pArray[nPos] );

            //SAXEventKeeper
            xNewKey = reinterpret_cast< XRegistryKey * >( pRegistryKey )->createKey( SAXEventKeeperImpl_getImplementationName() );
            xNewKey = xNewKey->createKey( OUString::createFromAscii( "/UNO/SERVICES" ) );
            const Sequence< OUString > & rSNL5 = SAXEventKeeperImpl_getSupportedServiceNames();
            pArray = rSNL5.getConstArray();
            for ( nPos = rSNL5.getLength(); nPos--; )
                xNewKey->createKey( pArray[nPos] );

            //XMLSignatureTemplateImpl
            xNewKey = reinterpret_cast< XRegistryKey * >( pRegistryKey )->createKey( XMLSignatureTemplateImpl::impl_getImplementationName() );
            xNewKey = xNewKey->createKey( OUString::createFromAscii( "/UNO/SERVICES" ) );
            const Sequence< OUString > & rSNL6 = XMLSignatureTemplateImpl::impl_getSupportedServiceNames();
            pArray = rSNL6.getConstArray();
            for ( nPos = rSNL6.getLength(); nPos--; )
                xNewKey->createKey( pArray[nPos] );

            // XMLEncryptionTemplateImpl
            xNewKey = reinterpret_cast< XRegistryKey * >( pRegistryKey )->createKey( XMLEncryptionTemplateImpl::impl_getImplementationName() );
            xNewKey = xNewKey->createKey( OUString::createFromAscii( "/UNO/SERVICES" ) );
            const Sequence< OUString > & rSNL7 = XMLEncryptionTemplateImpl::impl_getSupportedServiceNames();
            pArray = rSNL7.getConstArray();
            for ( nPos = rSNL7.getLength(); nPos--; )
                xNewKey->createKey( pArray[nPos] );

            return sal_True;
        }
        catch (InvalidRegistryException &)
        {
            OSL_ENSURE( sal_False, "### InvalidRegistryException!" );
        }
    }
    return sal_False;
}

//==================================================================================================
void * SAL_CALL component_getFactory(
    const sal_Char * pImplName, void * pServiceManager, void * pRegistryKey )
{
    void * pRet = 0;

    //Decryptor
    OUString implName = OUString::createFromAscii( pImplName );
    if ( pServiceManager && implName.equals(DecryptorImpl_getImplementationName()) )
    {
        Reference< XSingleServiceFactory > xFactory( createSingleFactory(
            reinterpret_cast< XMultiServiceFactory * >( pServiceManager ),
            OUString::createFromAscii( pImplName ),
            DecryptorImpl_createInstance, DecryptorImpl_getSupportedServiceNames() ) );

        if (xFactory.is())
        {
            xFactory->acquire();
            pRet = xFactory.get();
        }
    }

    //Encryptor
    if ( pServiceManager && implName.equals(EncryptorImpl_getImplementationName()) )
    {
        Reference< XSingleServiceFactory > xFactory( createSingleFactory(
            reinterpret_cast< XMultiServiceFactory * >( pServiceManager ),
            OUString::createFromAscii( pImplName ),
            EncryptorImpl_createInstance, EncryptorImpl_getSupportedServiceNames() ) );

        if (xFactory.is())
        {
            xFactory->acquire();
            pRet = xFactory.get();
        }
    }

    //SignatureCreator
    if ( pServiceManager && implName.equals(SignatureCreatorImpl_getImplementationName()) )
    {
        Reference< XSingleServiceFactory > xFactory( createSingleFactory(
            reinterpret_cast< XMultiServiceFactory * >( pServiceManager ),
            OUString::createFromAscii( pImplName ),
            SignatureCreatorImpl_createInstance, SignatureCreatorImpl_getSupportedServiceNames() ) );

        if (xFactory.is())
        {
            xFactory->acquire();
            pRet = xFactory.get();
        }
    }

    //SignatureVerifier
    if ( pServiceManager && implName.equals(SignatureVerifierImpl_getImplementationName()) )
    {
        Reference< XSingleServiceFactory > xFactory( createSingleFactory(
            reinterpret_cast< XMultiServiceFactory * >( pServiceManager ),
            OUString::createFromAscii( pImplName ),
            SignatureVerifierImpl_createInstance, SignatureVerifierImpl_getSupportedServiceNames() ) );

        if (xFactory.is())
        {
            xFactory->acquire();
            pRet = xFactory.get();
        }
    }

    //SAXEventKeeper
    if ( pServiceManager && implName.equals(SAXEventKeeperImpl_getImplementationName()) )
    {
        Reference< XSingleServiceFactory > xFactory( createSingleFactory(
            reinterpret_cast< XMultiServiceFactory * >( pServiceManager ),
            OUString::createFromAscii( pImplName ),
            SAXEventKeeperImpl_createInstance, SAXEventKeeperImpl_getSupportedServiceNames() ) );

        if (xFactory.is())
        {
            xFactory->acquire();
            pRet = xFactory.get();
        }
    }

    //XMLSignatureTemplate
    if ( pServiceManager && implName.equals( XMLSignatureTemplateImpl::impl_getImplementationName()) )
    {
        Reference< XSingleServiceFactory > xFactory = XMLSignatureTemplateImpl::impl_createFactory(
                reinterpret_cast< XMultiServiceFactory* >( pServiceManager ) ) ;

        if (xFactory.is())
        {
            xFactory->acquire();
            pRet = xFactory.get();
        }
    }

    //XMLEncryptionTemplate
    if ( pServiceManager && implName.equals( XMLEncryptionTemplateImpl::impl_getImplementationName()) )
    {
        Reference< XSingleServiceFactory > xFactory = XMLEncryptionTemplateImpl::impl_createFactory(
                reinterpret_cast< XMultiServiceFactory* >( pServiceManager ) ) ;

        if (xFactory.is())
        {
            xFactory->acquire();
            pRet = xFactory.get();
        }
    }

    return pRet;
}
}

<commit_msg>INTEGRATION: CWS ooo19126 (1.1.1.1.86); FILE MERGED 2005/09/05 17:01:47 rt 1.1.1.1.86.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: xsec_framework.cxx,v $
 *
 *  $Revision: 1.2 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-09 17:21:32 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

#include <stdio.h>

#include <osl/mutex.hxx>
#include <osl/thread.h>
#include <cppuhelper/factory.hxx>

#ifndef _COM_SUN_STAR_LANG_XSINGLESERVICEFACTORY_HPP_
#include <com/sun/star/lang/XSingleServiceFactory.hpp>
#endif

#include <decryptorimpl.hxx>
#include <encryptorimpl.hxx>
#include <signaturecreatorimpl.hxx>
#include <signatureverifierimpl.hxx>
#include <saxeventkeeperimpl.hxx>
#include <xmlencryptiontemplateimpl.hxx>
#include <xmlsignaturetemplateimpl.hxx>

using namespace ::rtl;
using namespace ::cppu;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::lang;
using namespace ::com::sun::star::registry;

extern "C"
{
//==================================================================================================
void SAL_CALL component_getImplementationEnvironment(
    const sal_Char ** ppEnvTypeName, uno_Environment ** ppEnv )
{
    *ppEnvTypeName = CPPU_CURRENT_LANGUAGE_BINDING_NAME;
}

//==================================================================================================
sal_Bool SAL_CALL component_writeInfo(
    void * pServiceManager, void * pRegistryKey )
{
    if (pRegistryKey)
    {
        try
        {
            //Decryptor
            sal_Int32 nPos = 0;
            Reference< XRegistryKey > xNewKey(
                reinterpret_cast< XRegistryKey * >( pRegistryKey )->createKey( DecryptorImpl_getImplementationName() ) );
            xNewKey = xNewKey->createKey( OUString::createFromAscii( "/UNO/SERVICES" ) );

            const Sequence< OUString > & rSNL = DecryptorImpl_getSupportedServiceNames();
            const OUString * pArray = rSNL.getConstArray();
            for ( nPos = rSNL.getLength(); nPos--; )
                xNewKey->createKey( pArray[nPos] );

            //Encryptor
            xNewKey = reinterpret_cast< XRegistryKey * >( pRegistryKey )->createKey( EncryptorImpl_getImplementationName() );
            xNewKey = xNewKey->createKey( OUString::createFromAscii( "/UNO/SERVICES" ) );
            const Sequence< OUString > & rSNL2 = EncryptorImpl_getSupportedServiceNames();
            pArray = rSNL2.getConstArray();
            for ( nPos = rSNL2.getLength(); nPos--; )
                xNewKey->createKey( pArray[nPos] );

            //SignatureCreator
            xNewKey = reinterpret_cast< XRegistryKey * >( pRegistryKey )->createKey( SignatureCreatorImpl_getImplementationName() );
            xNewKey = xNewKey->createKey( OUString::createFromAscii( "/UNO/SERVICES" ) );
            const Sequence< OUString > & rSNL3 = SignatureCreatorImpl_getSupportedServiceNames();
            pArray = rSNL3.getConstArray();
            for ( nPos = rSNL3.getLength(); nPos--; )
                xNewKey->createKey( pArray[nPos] );

            //SignatureVerifier
            xNewKey = reinterpret_cast< XRegistryKey * >( pRegistryKey )->createKey( SignatureVerifierImpl_getImplementationName() );
            xNewKey = xNewKey->createKey( OUString::createFromAscii( "/UNO/SERVICES" ) );
            const Sequence< OUString > & rSNL4 = SignatureVerifierImpl_getSupportedServiceNames();
            pArray = rSNL4.getConstArray();
            for ( nPos = rSNL4.getLength(); nPos--; )
                xNewKey->createKey( pArray[nPos] );

            //SAXEventKeeper
            xNewKey = reinterpret_cast< XRegistryKey * >( pRegistryKey )->createKey( SAXEventKeeperImpl_getImplementationName() );
            xNewKey = xNewKey->createKey( OUString::createFromAscii( "/UNO/SERVICES" ) );
            const Sequence< OUString > & rSNL5 = SAXEventKeeperImpl_getSupportedServiceNames();
            pArray = rSNL5.getConstArray();
            for ( nPos = rSNL5.getLength(); nPos--; )
                xNewKey->createKey( pArray[nPos] );

            //XMLSignatureTemplateImpl
            xNewKey = reinterpret_cast< XRegistryKey * >( pRegistryKey )->createKey( XMLSignatureTemplateImpl::impl_getImplementationName() );
            xNewKey = xNewKey->createKey( OUString::createFromAscii( "/UNO/SERVICES" ) );
            const Sequence< OUString > & rSNL6 = XMLSignatureTemplateImpl::impl_getSupportedServiceNames();
            pArray = rSNL6.getConstArray();
            for ( nPos = rSNL6.getLength(); nPos--; )
                xNewKey->createKey( pArray[nPos] );

            // XMLEncryptionTemplateImpl
            xNewKey = reinterpret_cast< XRegistryKey * >( pRegistryKey )->createKey( XMLEncryptionTemplateImpl::impl_getImplementationName() );
            xNewKey = xNewKey->createKey( OUString::createFromAscii( "/UNO/SERVICES" ) );
            const Sequence< OUString > & rSNL7 = XMLEncryptionTemplateImpl::impl_getSupportedServiceNames();
            pArray = rSNL7.getConstArray();
            for ( nPos = rSNL7.getLength(); nPos--; )
                xNewKey->createKey( pArray[nPos] );

            return sal_True;
        }
        catch (InvalidRegistryException &)
        {
            OSL_ENSURE( sal_False, "### InvalidRegistryException!" );
        }
    }
    return sal_False;
}

//==================================================================================================
void * SAL_CALL component_getFactory(
    const sal_Char * pImplName, void * pServiceManager, void * pRegistryKey )
{
    void * pRet = 0;

    //Decryptor
    OUString implName = OUString::createFromAscii( pImplName );
    if ( pServiceManager && implName.equals(DecryptorImpl_getImplementationName()) )
    {
        Reference< XSingleServiceFactory > xFactory( createSingleFactory(
            reinterpret_cast< XMultiServiceFactory * >( pServiceManager ),
            OUString::createFromAscii( pImplName ),
            DecryptorImpl_createInstance, DecryptorImpl_getSupportedServiceNames() ) );

        if (xFactory.is())
        {
            xFactory->acquire();
            pRet = xFactory.get();
        }
    }

    //Encryptor
    if ( pServiceManager && implName.equals(EncryptorImpl_getImplementationName()) )
    {
        Reference< XSingleServiceFactory > xFactory( createSingleFactory(
            reinterpret_cast< XMultiServiceFactory * >( pServiceManager ),
            OUString::createFromAscii( pImplName ),
            EncryptorImpl_createInstance, EncryptorImpl_getSupportedServiceNames() ) );

        if (xFactory.is())
        {
            xFactory->acquire();
            pRet = xFactory.get();
        }
    }

    //SignatureCreator
    if ( pServiceManager && implName.equals(SignatureCreatorImpl_getImplementationName()) )
    {
        Reference< XSingleServiceFactory > xFactory( createSingleFactory(
            reinterpret_cast< XMultiServiceFactory * >( pServiceManager ),
            OUString::createFromAscii( pImplName ),
            SignatureCreatorImpl_createInstance, SignatureCreatorImpl_getSupportedServiceNames() ) );

        if (xFactory.is())
        {
            xFactory->acquire();
            pRet = xFactory.get();
        }
    }

    //SignatureVerifier
    if ( pServiceManager && implName.equals(SignatureVerifierImpl_getImplementationName()) )
    {
        Reference< XSingleServiceFactory > xFactory( createSingleFactory(
            reinterpret_cast< XMultiServiceFactory * >( pServiceManager ),
            OUString::createFromAscii( pImplName ),
            SignatureVerifierImpl_createInstance, SignatureVerifierImpl_getSupportedServiceNames() ) );

        if (xFactory.is())
        {
            xFactory->acquire();
            pRet = xFactory.get();
        }
    }

    //SAXEventKeeper
    if ( pServiceManager && implName.equals(SAXEventKeeperImpl_getImplementationName()) )
    {
        Reference< XSingleServiceFactory > xFactory( createSingleFactory(
            reinterpret_cast< XMultiServiceFactory * >( pServiceManager ),
            OUString::createFromAscii( pImplName ),
            SAXEventKeeperImpl_createInstance, SAXEventKeeperImpl_getSupportedServiceNames() ) );

        if (xFactory.is())
        {
            xFactory->acquire();
            pRet = xFactory.get();
        }
    }

    //XMLSignatureTemplate
    if ( pServiceManager && implName.equals( XMLSignatureTemplateImpl::impl_getImplementationName()) )
    {
        Reference< XSingleServiceFactory > xFactory = XMLSignatureTemplateImpl::impl_createFactory(
                reinterpret_cast< XMultiServiceFactory* >( pServiceManager ) ) ;

        if (xFactory.is())
        {
            xFactory->acquire();
            pRet = xFactory.get();
        }
    }

    //XMLEncryptionTemplate
    if ( pServiceManager && implName.equals( XMLEncryptionTemplateImpl::impl_getImplementationName()) )
    {
        Reference< XSingleServiceFactory > xFactory = XMLEncryptionTemplateImpl::impl_createFactory(
                reinterpret_cast< XMultiServiceFactory* >( pServiceManager ) ) ;

        if (xFactory.is())
        {
            xFactory->acquire();
            pRet = xFactory.get();
        }
    }

    return pRet;
}
}

<|endoftext|>


<commit_before>//
//  handler.cpp
//  timedtracechecker
//
//  Created by Clement Poncelet on 28/08/13.
//  Copyright (c) 2013 Clement Poncelet. All rights reserved.
//

#include <base/handler.h>

//Version Management
void version(ostream &out)
{
    out << "Timed trace checker V0" << endl;
}

//From Antescofo by JL Giavitto
void error(const char *fmt, ...)
{
    va_list ap;
    va_start(ap, fmt);  // initialize va_list

    // So stdout and stderr appears correctly interleaved if redirected on the same io
    fflush(stdout);

    version(cerr);
    std::fprintf(stderr, "- Error: ");
    std::vfprintf(stderr, fmt, ap);
    std::fprintf(stderr, "\n");
    fflush(stderr);

    va_end(ap);

    exit(EXIT_FAILURE);
}

void usage(ostream &out)
{
    out << endl
    << "Usage : timedtracechecker -(V|T) ..." << endl
    << "  [mode] Other options depend of the mode" << endl
    << "  For Translation: Uppaal-trace, score and table are needed" << endl
    << "  For Verification: reference, the Antescofo output to test and the symbol table are needed" << endl
    << endl;

    out << "Modes: " << endl
    << " -T:  Translation, the trace (from Uppaal) will be translated according the options" << endl
    << " \n\t The T options are:" << endl
    << " --utrace(-u): The Uppaal relative trace to translate." << endl
    << " --score (-s): The mixed-score (the mixed-score corresponding to the tests) " << endl
    << " --rel: do not apply a tempo curve on input traces (relative input and reference trace)" << endl
    << " --treco: create an input trace that is a detected input trace (a result of recognition)"

    << "\n -V:  Verification, timed conformance: test if the real trace (--totest) is conformed to the reference trace (--ref)" << endl
    << " \n\t The V options are:" << endl
    << " --ref (-r): Reference trace (or expected [in physical time])." << endl
    << " --tempo: Checks tempo values too with time values."
    << " --totest: The real Antescofo output trace which has to be conformed to the ref" << endl

    << " \n\t Similar options are:" << endl
    << "    --table (-t): The symbols table that maps ref labels to Antescofo labels." << endl;

    out << "\nOthers options:" << endl
    << " --version (-v) :   current version" << endl
    << " --help (-h) :     print this help" << endl
    << endl;
}

bool check_and_complete_options()
{
    if (!symboltable)       error("option --table (-t) required");
    if(f_verif && f_tran)   error("one mode at the same time");

    if(f_tran)
    {
        run_mode = TRANSLAT;
        if (!scorename)       error("option --score (-s) required");
        if (!uppaaltrace)     error("option --utrace (-u) required");

        if(f_kind && !input_file)   error("option --kind need an input file with this option --tin");

    } else if(f_verif)
    {
        run_mode = VERIF;
        if (!reftrace)       error("option --ref (-r) required");
        if (!realtrace)      error("option --totest required");
    } else                   error("no mode given");

    return false;
}

void set_flag_options(int option_index)
{
    switch(option_index)
    {
        case 9:
            check_index_is("kind");
            //Latter other generation options
            //      TIN for now
            break;

            default:
            ; // nothing for (2,3 and 7)
    }
}

// ==========================================================================|
// Main
int perform(int argc, char *argv[]) {

    if (argc==1)
    {
        usage(std::cerr);
        return EXIT_FAILURE;
    }

    /// Parse command-line options
    int index = 0; // index of the current option
    int c;

    while ((c = getopt_long_only(argc, argv, "hvVTRr:s:t:e:u:a:k:i:p:", longoptions, &index)) != -1)
    {
        switch (c)
        {
            case 0:  // Value returned by the options that set a flag.
                set_flag_options(index);
                break;

            case 'h':
                usage(std::cout);
                exit(EXIT_SUCCESS);

            case 'v':
                version(std::cout);
                exit(EXIT_SUCCESS);

            case 'r':
                reftrace = optarg;
                break;

            case 's':
                scorename = optarg;
                break;

            case 't':
                symboltable = optarg;
                break;

            case 'u':
                uppaaltrace = optarg;
                break;

            case 'a':
                realtrace = optarg;
                break;

            case 'p':
                pathname = optarg;
                break;

            case 'i':
                input_file = optarg;
                break;

            case ':':
                //  missing option argument. Error already signaled by getopt
                error("Missing option argument");
                break;

            case '?':
                // unknown or ambiguous option  Error already signaled by getopt
                error("Warning: ambiguous option argument");
                break;

            default:
                // Do nothing for the options that are not flag-managed and without arguments
                ;
        }
    }

    if (check_and_complete_options())
        std::exit(EXIT_FAILURE);

    int ret = EXIT_FAILURE;
    switch (run_mode)
    {
            // Translation
        case TRANSLAT:
            assert(uppaaltrace && symboltable);
            ret = run_translation();
            break;

            // Verification
        case VERIF:
            assert(reftrace && realtrace && symboltable);
            ret = run_verification();
            break;

        case NONE: exit(EXIT_FAILURE);
    }

    //free ressources
    flush_files();

    std::cout << "finito. ||" << endl;
    exit(ret);
}

int run_translation()
{
    std::cout << "In translation: " << uppaaltrace << std::endl;

    string pathbase(uppaaltrace);
    unsigned long p = pathbase.find_last_of(".");
    pathbase.erase(pathbase.begin()+(long)p, pathbase.end());

    //link real symbols to model labels
    // and checks doublons
    assert(symboltable);
    Symbol_table_parser* symbol_parser;
    map <string, Symbol_phy*>* table;
    symbol_parser = new Symbol_table_parser(symboltable);
    table = symbol_parser->create_table();

    //include pitches chord and poss.
    assert(scorename);
    AntescofoScoreParser score_parser(scorename);
    score_parser.add_pitches(table);

    //Parse coVer trace
    UpppalSuiteParser CoVerParser(uppaaltrace, table);
    while(!CoVerParser.is_eof())
    {
        Trace* testcase = CoVerParser.parseATrace((bool)! f_rel);

        //test debbug
        //Show debug(std::cerr);
        //testcase->accept(&debug);

        if(!f_rel)
        {
         //   WRONG: We cannot loose the action changes ! (model specifications)
         //   TempoCurve* Curve = new Cover_TempoCurve(score_parser.get_score_tempo());
         //   testcase->modify(Curve);

        //TOTEST with tempo curves.
        // tin === treco ?
            TempoCurve* Curve = new TempoCurve(score_parser.get_score_tempo());
            testcase->modify(Curve);
        }

        ///> Input trace to input trace (Before Computing the ref. ! (i.e Cover))

        //TempoCurve Curve(120.0);
        //Cover_TempoCurve Curve(basename+".txt");
        //Equation and Sinus to explore [?] Equation_TempoCurve Curve(60, 4, -40, 100, -70);
        /*    TempoCurve* Curve;
            if(f_kind)
                Curve = new Input_Curve(input_file, score_parser.get_score_tempo());
            else
                Curve = new Random_TempoCurve(score_parser.get_score_tempo());

            testcase->modify(Curve);

            //We print the tempo curve created ::
            //GnuPlotTempoCurve* printcurve = new GnuPlotTempoCurve(pathbase);
            //t1.gettests()->accept(printcurve);

            delete Curve;
//          delete printcurve;
            std::cout << " ... " << endl;
        */

        //test debbug
        //const Testsuite* ts2 = t1.gettests();
        //ts2->accept(new PrintShow(std::cerr));

        // An uppaaltrace is several test cases
        // We give the path/base name of the future input/expected traces
        //      next <argument>.aaa.in are input files created
        //      and  <argument>.aaa.ref are expected files created
        // with aaa an numbers from 1 to N of test cases
        auto last_event = table->end();
        last_event--;
        Print_tin tinPrinter(pathname ? pathname : pathbase, CoVerParser.numberTrace());
        Print_tref trefPrinter(pathname ? pathname : pathbase, CoVerParser.numberTrace(), (last_event)->first);

        testcase->accept(&tinPrinter);  ///> print input trace
        if((bool)! f_rel)
        {
            Computation_Rel_To_Phy_Visitor* translator = new Computation_Rel_To_Phy_Visitor((bool)f_treco,
                                                                                score_parser.get_score_tempo());
            testcase->modify(translator); ///> translation of the reference if not relative
            delete translator;
        }
        testcase->accept(&trefPrinter); ///> print reference trace
    }

    std::cout << "We have " << CoVerParser.numberTrace() << " trace(s) " << std::endl;

    delete table;
    delete symbol_parser;

    return EXIT_SUCCESS;
}

int run_verification()
{
    std::cout << "... Verification on air ... " << std::endl;
    std::cout << "Is " << realtrace << endl
    << "conform to " << reftrace << endl;

    // Parsing of traces
    //ref
    ReferenceTraceParser ref_parser(reftrace);
    Trace* reference_trace = ref_parser.parse();

    //TODO print ref trace ?

    //real
    AntescofoOutputParser real_parser(realtrace);
    Trace* real_trace = real_parser.parse();

    //link symbols using the table_symbol
    Symbol_table_parser symbol_parser(symboltable);
    symbol_parser.link(reference_trace, real_trace);

    //Verification
    TimedConformanceChecker checker(reference_trace, real_trace, (bool)f_tempo);
    bool res = checker.check();

    //Print for debug
 //   Show* printer = new Show(cerr);
 //   reference_trace->accept(printer);
 //   real_trace->accept(printer);
 //   delete printer;

    /*
     unsigned long under = filename.find_last_of("_", filename.size());
     unsigned long size =  filename.find_last_of(".", filename.size()) - under;
     string fend = filename.substr(under, size);

     GnuPlotVerdict plotVerdict((*basename)+"/"+fend, CheckEngine->getExpt(), CheckEngine->getObtained());
     plotVerdict.plot();
     */

    //free
    delete reference_trace;
    delete real_trace;

    if(res) {
        std::cout << "\tChecked :: Test OK" << std::endl;
        return EXIT_SUCCESS;
    } else {
        std::cout << "\tError :: Test KO" << std::endl;
        return EXIT_FAILURE;
    }
}

void flush_files()
{
    //TODO add input trace file (curves)
    //if (input_file) delete input_file;
    //if(symboltable) {delete symboltable;}
    //if(pathname) delete pathname;
    //Mode T
    if(f_tran)
    {
    //    delete scorename;
    //    delete uppaaltrace;
    }

    //Mode V
    if(f_verif)
    {
    //    delete reftrace;
    //    delete realtrace;
    }
}
<commit_msg>usage update (path option)<commit_after>//
//  handler.cpp
//  timedtracechecker
//
//  Created by Clement Poncelet on 28/08/13.
//  Copyright (c) 2013 Clement Poncelet. All rights reserved.
//

#include <base/handler.h>

//Version Management
void version(ostream &out)
{
    out << "Timed trace checker V0" << endl;
}

//From Antescofo by JL Giavitto
void error(const char *fmt, ...)
{
    va_list ap;
    va_start(ap, fmt);  // initialize va_list

    // So stdout and stderr appears correctly interleaved if redirected on the same io
    fflush(stdout);

    version(cerr);
    std::fprintf(stderr, "- Error: ");
    std::vfprintf(stderr, fmt, ap);
    std::fprintf(stderr, "\n");
    fflush(stderr);

    va_end(ap);

    exit(EXIT_FAILURE);
}

void usage(ostream &out)
{
    out << endl
    << "Usage : rttm -<mode> [-<options>]" << endl
    << "  The <mode> is required, other options may depend of the choosen mode" << endl
    << "  For Translation (-T): the Uppaal-trace and the score are needed" << endl
    << "  For Verification (-V): the reference and the system's output (to test) are needed" << endl
    << endl;

    out << "Modes: " << endl
    << " -T:  Translation, the trace (from Uppaal) will be translated according to the options" << endl
    << " \n\t The T options are:" << endl
    << " --utrace(-u): The Uppaal relative trace to translate." << endl
    << " --score (-s): The mixed-score (the mixed-score corresponding to the tests) " << endl
    << " --rel:        Do not apply a tempo curve on input traces (keep input and reference traces relative)" << endl
    << " --treco:      Create an input trace that is a detected input trace (a recognition trace)"

    << "\n -V:  Verification, timed conformance: test if the real trace (--totest) is timely conformed to the reference trace (--ref)" << endl
    << " \n\t The V options are:" << endl
    << " --ref (-r):  The reference trace (or expected [in physical time])." << endl
    << " --tempo:     Checks tempo values too."
    << " --totest:    The system's output trace." << endl

    << " \n\t Similar options are:" << endl
    << "    --table (-t): The symbols table that maps reference's and system's labels." << endl;
    << "    --path (-p):  A path prefix for the outputed files." << endl;

    out << "\nOthers options:" << endl
    << " --version (-v):   current version" << endl
    << " --help (-h):      print this help" << endl
    << endl;
}

bool check_and_complete_options()
{
    if (!symboltable)       error("option --table (-t) required");
    if(f_verif && f_tran)   error("one mode at the same time");

    if(f_tran)
    {
        run_mode = TRANSLAT;
        if (!scorename)       error("option --score (-s) required");
        if (!uppaaltrace)     error("option --utrace (-u) required");

        if(f_kind && !input_file)   error("option --kind need an input file with this option --tin");

    } else if(f_verif)
    {
        run_mode = VERIF;
        if (!reftrace)       error("option --ref (-r) required");
        if (!realtrace)      error("option --totest required");
    } else                   error("no mode given");

    return false;
}

void set_flag_options(int option_index)
{
    switch(option_index)
    {
        case 9:
            check_index_is("kind");
            //Latter other generation options
            //      TIN for now
            break;

            default:
            ; // nothing for (2,3 and 7)
    }
}

// ==========================================================================|
// Main
int perform(int argc, char *argv[]) {

    if (argc==1)
    {
        usage(std::cerr);
        return EXIT_FAILURE;
    }

    /// Parse command-line options
    int index = 0; // index of the current option
    int c;

    while ((c = getopt_long_only(argc, argv, "hvVTRr:s:t:e:u:a:k:i:p:", longoptions, &index)) != -1)
    {
        switch (c)
        {
            case 0:  // Value returned by the options that set a flag.
                set_flag_options(index);
                break;

            case 'h':
                usage(std::cout);
                exit(EXIT_SUCCESS);

            case 'v':
                version(std::cout);
                exit(EXIT_SUCCESS);

            case 'r':
                reftrace = optarg;
                break;

            case 's':
                scorename = optarg;
                break;

            case 't':
                symboltable = optarg;
                break;

            case 'u':
                uppaaltrace = optarg;
                break;

            case 'a':
                realtrace = optarg;
                break;

            case 'p':
                pathname = optarg;
                break;

            case 'i':
                input_file = optarg;
                break;

            case ':':
                //  missing option argument. Error already signaled by getopt
                error("Missing option argument");
                break;

            case '?':
                // unknown or ambiguous option  Error already signaled by getopt
                error("Warning: ambiguous option argument");
                break;

            default:
                // Do nothing for the options that are not flag-managed and without arguments
                ;
        }
    }

    if (check_and_complete_options())
        std::exit(EXIT_FAILURE);

    int ret = EXIT_FAILURE;
    switch (run_mode)
    {
            // Translation
        case TRANSLAT:
            assert(uppaaltrace && symboltable);
            ret = run_translation();
            break;

            // Verification
        case VERIF:
            assert(reftrace && realtrace && symboltable);
            ret = run_verification();
            break;

        case NONE: exit(EXIT_FAILURE);
    }

    //free ressources
    flush_files();

    std::cout << "finito. ||" << endl;
    exit(ret);
}

int run_translation()
{
    std::cout << "In translation: " << uppaaltrace << std::endl;

    string pathbase(uppaaltrace);
    unsigned long p = pathbase.find_last_of(".");
    pathbase.erase(pathbase.begin()+(long)p, pathbase.end());

    //link real symbols to model labels
    // and checks doublons
    assert(symboltable);
    Symbol_table_parser* symbol_parser;
    map <string, Symbol_phy*>* table;
    symbol_parser = new Symbol_table_parser(symboltable);
    table = symbol_parser->create_table();

    //include pitches chord and poss.
    assert(scorename);
    AntescofoScoreParser score_parser(scorename);
    score_parser.add_pitches(table);

    //Parse coVer trace
    UpppalSuiteParser CoVerParser(uppaaltrace, table);
    while(!CoVerParser.is_eof())
    {
        Trace* testcase = CoVerParser.parseATrace((bool)! f_rel);

        //test debbug
        //Show debug(std::cerr);
        //testcase->accept(&debug);

        if(!f_rel)
        {
         //   WRONG: We cannot loose the action changes ! (model specifications)
         //   TempoCurve* Curve = new Cover_TempoCurve(score_parser.get_score_tempo());
         //   testcase->modify(Curve);

        //TOTEST with tempo curves.
        // tin === treco ?
            TempoCurve* Curve = new TempoCurve(score_parser.get_score_tempo());
            testcase->modify(Curve);
        }

        ///> Input trace to input trace (Before Computing the ref. ! (i.e Cover))

        //TempoCurve Curve(120.0);
        //Cover_TempoCurve Curve(basename+".txt");
        //Equation and Sinus to explore [?] Equation_TempoCurve Curve(60, 4, -40, 100, -70);
        /*    TempoCurve* Curve;
            if(f_kind)
                Curve = new Input_Curve(input_file, score_parser.get_score_tempo());
            else
                Curve = new Random_TempoCurve(score_parser.get_score_tempo());

            testcase->modify(Curve);

            //We print the tempo curve created ::
            //GnuPlotTempoCurve* printcurve = new GnuPlotTempoCurve(pathbase);
            //t1.gettests()->accept(printcurve);

            delete Curve;
//          delete printcurve;
            std::cout << " ... " << endl;
        */

        //test debbug
        //const Testsuite* ts2 = t1.gettests();
        //ts2->accept(new PrintShow(std::cerr));

        // An uppaaltrace is several test cases
        // We give the path/base name of the future input/expected traces
        //      next <argument>.aaa.in are input files created
        //      and  <argument>.aaa.ref are expected files created
        // with aaa an numbers from 1 to N of test cases
        auto last_event = table->end();
        last_event--;
        Print_tin tinPrinter(pathname ? pathname : pathbase, CoVerParser.numberTrace());
        Print_tref trefPrinter(pathname ? pathname : pathbase, CoVerParser.numberTrace(), (last_event)->first);

        testcase->accept(&tinPrinter);  ///> print input trace
        if((bool)! f_rel)
        {
            Computation_Rel_To_Phy_Visitor* translator = new Computation_Rel_To_Phy_Visitor((bool)f_treco,
                                                                                score_parser.get_score_tempo());
            testcase->modify(translator); ///> translation of the reference if not relative
            delete translator;
        }
        testcase->accept(&trefPrinter); ///> print reference trace
    }

    std::cout << "We have " << CoVerParser.numberTrace() << " trace(s) " << std::endl;

    delete table;
    delete symbol_parser;

    return EXIT_SUCCESS;
}

int run_verification()
{
    std::cout << "... Verification on air ... " << std::endl;
    std::cout << "Is " << realtrace << endl
    << "conform to " << reftrace << endl;

    // Parsing of traces
    //ref
    ReferenceTraceParser ref_parser(reftrace);
    Trace* reference_trace = ref_parser.parse();

    //TODO print ref trace ?

    //real
    AntescofoOutputParser real_parser(realtrace);
    Trace* real_trace = real_parser.parse();

    //link symbols using the table_symbol
    Symbol_table_parser symbol_parser(symboltable);
    symbol_parser.link(reference_trace, real_trace);

    //Verification
    TimedConformanceChecker checker(reference_trace, real_trace, (bool)f_tempo);
    bool res = checker.check();

    //Print for debug
 //   Show* printer = new Show(cerr);
 //   reference_trace->accept(printer);
 //   real_trace->accept(printer);
 //   delete printer;

    /*
     unsigned long under = filename.find_last_of("_", filename.size());
     unsigned long size =  filename.find_last_of(".", filename.size()) - under;
     string fend = filename.substr(under, size);

     GnuPlotVerdict plotVerdict((*basename)+"/"+fend, CheckEngine->getExpt(), CheckEngine->getObtained());
     plotVerdict.plot();
     */

    //free
    delete reference_trace;
    delete real_trace;

    if(res) {
        std::cout << "\tChecked :: Test OK" << std::endl;
        return EXIT_SUCCESS;
    } else {
        std::cout << "\tError :: Test KO" << std::endl;
        return EXIT_FAILURE;
    }
}

void flush_files()
{
    //TODO add input trace file (curves)
    //if (input_file) delete input_file;
    //if(symboltable) {delete symboltable;}
    //if(pathname) delete pathname;
    //Mode T
    if(f_tran)
    {
    //    delete scorename;
    //    delete uppaaltrace;
    }

    //Mode V
    if(f_verif)
    {
    //    delete reftrace;
    //    delete realtrace;
    }
}
<|endoftext|>


<commit_before>/*
				Copyright <SWGEmu>
		See file COPYING for copying conditions.*/

#include "server/zone/objects/tangible/pharmaceutical/VitalityPack.h"
#include "server/zone/objects/creature/CreatureObject.h"
#include "server/zone/objects/player/PlayerObject.h"
#include "server/zone/objects/scene/components/ObjectMenuComponent.h"
#include "server/zone/packets/object/ObjectMenuResponse.h"
#include "server/zone/managers/objectcontroller/ObjectController.h"
#include "server/zone/ZoneServer.h"
#include "server/zone/Zone.h"
#include "server/zone/objects/creature/ai/AiAgent.h"
#include "server/zone/objects/intangible/PetControlDevice.h"
#include "server/zone/managers/creature/PetManager.h"

void VitalityPackImplementation::fillAttributeList(AttributeListMessage* msg, CreatureObject* player){
	TangibleObjectImplementation::fillAttributeList(msg, player);

	msg->insertAttribute("power", effectiveness);

}

int VitalityPackImplementation::handleObjectMenuSelect(CreatureObject* player, byte selectedID) {

	if (player == NULL)
		return 0;

	if (!isASubChildOf(player))
		return 0;

	if (selectedID != 20)
		return TangibleObjectImplementation::handleObjectMenuSelect(player, selectedID);

	uint64 targetID = player->getTargetID();
	ZoneServer* server = player->getZoneServer();
	if (server == NULL)
		return 0;

	// Target must be a pet
	ManagedReference<TangibleObject*> target = server->getObject(targetID, true).castTo<TangibleObject*>();
	if (target == NULL || !target->isPet() ) {
		player->sendSystemMessage("You can only use this to restore vitality to pets");
		return 0;
	}

	ManagedReference<AiAgent*> pet = cast<AiAgent*>(target.get());
	if( pet == NULL )
		return 0;

	ManagedReference<PetControlDevice*> controlDevice = pet->getControlDevice().get().castTo<PetControlDevice*>();
	if( controlDevice == NULL )
		return 0;

	// Check pet type
	Locker crossLock(controlDevice, _this.getReferenceUnsafeStaticCast() );
	if( controlDevice->getPetType() == PetManager::FACTIONPET ){
		player->sendSystemMessage("You cannot use this to restore vitality to that type of pet");
		return 0;
	}

	// Check owner
	uint64 ownerID = pet->getCreatureLinkID();
	if ( ownerID != player->getObjectID()){
		player->sendSystemMessage("You cannot revitalize another player's pet");
		return 0;
	}

	// Check pet and player states
	if( pet->isInCombat() || pet->isDead() || pet->isIncapacitated() || player->isInCombat() || player->isDead() || player->isIncapacitated()){
		player->sendSystemMessage("You can't restore vitality to your pet right now");
		return 0;
	}

	// Check that some vitality has been lost
	if( controlDevice->getVitality() >= controlDevice->getMaxVitality() ){
		player->sendSystemMessage("Pet is already at maximum vitality");
		return 0;
	}

	// Calculate vitality loss
	int vitalityLost = controlDevice->getMaxVitality() - controlDevice->getVitality();
	int vitalityLoss = 1;

	if (effectiveness < 45){
		vitalityLoss += (vitalityLost / 9) + (vitalityLost / 13);
	} else if (effectiveness < 75) {
		vitalityLoss += (vitalityLost / 19) + (vitalityLost / 28);
	} else {
		vitalityLoss += (vitalityLost / 29) + (vitalityLost / 43);
	}

	vitalityLoss *= ((vitalityLost - 1) / effectiveness) + 1;

	if( vitalityLoss >= controlDevice->getMaxVitality() ){
		vitalityLoss = controlDevice->getMaxVitality() - 1;
	}

	// Reduce max vitality
	controlDevice->setMaxVitality( controlDevice->getMaxVitality() - vitalityLoss );

	// Restore vitality to new max
	controlDevice->setVitality( controlDevice->getMaxVitality() );

	// Use a charge
	decreaseUseCount();

	player->sendSystemMessage("You restore your pet to " + String::valueOf( controlDevice->getMaxVitality() ) +
							  " vitality but it permanently lost " + String::valueOf( vitalityLoss ) + " vitality." );

	return 0;

}
<commit_msg>[Fixed] stability issue<commit_after>/*
				Copyright <SWGEmu>
		See file COPYING for copying conditions.*/

#include "server/zone/objects/tangible/pharmaceutical/VitalityPack.h"
#include "server/zone/objects/creature/CreatureObject.h"
#include "server/zone/objects/player/PlayerObject.h"
#include "server/zone/objects/scene/components/ObjectMenuComponent.h"
#include "server/zone/packets/object/ObjectMenuResponse.h"
#include "server/zone/managers/objectcontroller/ObjectController.h"
#include "server/zone/ZoneServer.h"
#include "server/zone/Zone.h"
#include "server/zone/objects/creature/ai/AiAgent.h"
#include "server/zone/objects/intangible/PetControlDevice.h"
#include "server/zone/managers/creature/PetManager.h"

void VitalityPackImplementation::fillAttributeList(AttributeListMessage* msg, CreatureObject* player){
	TangibleObjectImplementation::fillAttributeList(msg, player);

	msg->insertAttribute("power", effectiveness);
}

int VitalityPackImplementation::handleObjectMenuSelect(CreatureObject* player, byte selectedID) {

	if (player == NULL)
		return 0;

	if (!isASubChildOf(player))
		return 0;

	if (selectedID != 20)
		return TangibleObjectImplementation::handleObjectMenuSelect(player, selectedID);

	uint64 targetID = player->getTargetID();
	ZoneServer* server = player->getZoneServer();
	if (server == NULL)
		return 0;

	// Target must be a pet
	ManagedReference<TangibleObject*> target = server->getObject(targetID, true).castTo<TangibleObject*>();
	if (target == NULL || !target->isPet()) {
		player->sendSystemMessage("You can only use this to restore vitality to pets");
		return 0;
	}

	ManagedReference<AiAgent*> pet = cast<AiAgent*>(target.get());
	if (pet == NULL)
		return 0;

	ManagedReference<PetControlDevice*> controlDevice = pet->getControlDevice().get().castTo<PetControlDevice*>();
	if (controlDevice == NULL)
		return 0;

	// Check pet type
	Locker crossLock(controlDevice, _this.getReferenceUnsafeStaticCast());

	if (controlDevice->getPetType() == PetManager::FACTIONPET) {
		player->sendSystemMessage("You cannot use this to restore vitality to that type of pet");
		return 0;
	}

	// Check owner
	uint64 ownerID = pet->getCreatureLinkID();
	if (ownerID != player->getObjectID()) {
		player->sendSystemMessage("You cannot revitalize another player's pet");
		return 0;
	}

	// Check pet and player states
	if (pet->isInCombat() || pet->isDead() || pet->isIncapacitated() || player->isInCombat() || player->isDead() || player->isIncapacitated()) {
		player->sendSystemMessage("You can't restore vitality to your pet right now");
		return 0;
	}

	// Check that some vitality has been lost
	if (controlDevice->getVitality() >= controlDevice->getMaxVitality()) {
		player->sendSystemMessage("Pet is already at maximum vitality");
		return 0;
	}

	// Calculate vitality loss
	int vitalityLost = controlDevice->getMaxVitality() - controlDevice->getVitality();
	int vitalityLoss = 1;

	if (effectiveness < 45) {
		vitalityLoss += (vitalityLost / 9) + (vitalityLost / 13);
	} else if (effectiveness < 75) {
		vitalityLoss += (vitalityLost / 19) + (vitalityLost / 28);
	} else {
		vitalityLoss += (vitalityLost / 29) + (vitalityLost / 43);
	}

	vitalityLoss *= ((vitalityLost - 1) / (effectiveness > 0 ? effectiveness : 1)) + 1;

	if (vitalityLoss >= controlDevice->getMaxVitality()) {
		vitalityLoss = controlDevice->getMaxVitality() - 1;
	}

	// Reduce max vitality
	controlDevice->setMaxVitality(controlDevice->getMaxVitality() - vitalityLoss);

	// Restore vitality to new max
	controlDevice->setVitality(controlDevice->getMaxVitality());

	// Use a charge
	decreaseUseCount();

	player->sendSystemMessage("You restore your pet to " + String::valueOf(controlDevice->getMaxVitality()) +
							  " vitality but it permanently lost " + String::valueOf(vitalityLoss) + " vitality.");

	return 0;

}
<|endoftext|>


<commit_before>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/browser/chromeos/cros/screen_lock_library.h"

#include "base/message_loop.h"
#include "base/string_util.h"
#include "chrome/browser/chrome_thread.h"
#include "chrome/browser/chromeos/cros/cros_library.h"

// Allows InvokeLater without adding refcounting. This class is a Singleton and
// won't be deleted until it's last InvokeLater is run.
DISABLE_RUNNABLE_METHOD_REFCOUNT(chromeos::ScreenLockLibraryImpl);

namespace chromeos {

ScreenLockLibraryImpl::ScreenLockLibraryImpl() {
  if (CrosLibrary::Get()->EnsureLoaded()) {
    Init();
  }
}

ScreenLockLibraryImpl::~ScreenLockLibraryImpl() {
  if (screen_lock_connection_) {
    chromeos::DisconnectScreenLock(screen_lock_connection_);
  }
}

void ScreenLockLibraryImpl::AddObserver(Observer* observer) {
  observers_.AddObserver(observer);
}

void ScreenLockLibraryImpl::RemoveObserver(Observer* observer) {
  observers_.RemoveObserver(observer);
}

void ScreenLockLibraryImpl::NotifyScreenLockRequested() {
  chromeos::NotifyScreenLockRequested();
}

void ScreenLockLibraryImpl::NotifyScreenLockCompleted() {
  chromeos::NotifyScreenLockCompleted();
}

void ScreenLockLibraryImpl::NotifyScreenUnlockRequested() {
  chromeos::NotifyScreenUnlockRequested();
}

void ScreenLockLibraryImpl::NotifyScreenUnlockCompleted() {
  chromeos::NotifyScreenUnlockCompleted();
}

void ScreenLockLibraryImpl::Init() {
  screen_lock_connection_ = chromeos::MonitorScreenLock(
      &ScreenLockedHandler, this);
}

void ScreenLockLibraryImpl::LockScreen() {
  // Make sure we run on UI thread.
  if (!ChromeThread::CurrentlyOn(ChromeThread::UI)) {
    ChromeThread::PostTask(
        ChromeThread::UI, FROM_HERE,
        NewRunnableMethod(this, &ScreenLockLibraryImpl::LockScreen));
    return;
  }
  FOR_EACH_OBSERVER(Observer, observers_, LockScreen(this));
}

void ScreenLockLibraryImpl::UnlockScreen() {
  // Make sure we run on UI thread.
  if (!ChromeThread::CurrentlyOn(ChromeThread::UI)) {
    ChromeThread::PostTask(
        ChromeThread::UI, FROM_HERE,
        NewRunnableMethod(this, &ScreenLockLibraryImpl::UnlockScreen));
    return;
  }
  FOR_EACH_OBSERVER(Observer, observers_, UnlockScreen(this));
}

void ScreenLockLibraryImpl::UnlockScreenFailed() {
  // Make sure we run on UI thread.
  if (!ChromeThread::CurrentlyOn(ChromeThread::UI)) {
    ChromeThread::PostTask(
        ChromeThread::UI, FROM_HERE,
        NewRunnableMethod(this, &ScreenLockLibraryImpl::UnlockScreenFailed));
    return;
  }
  FOR_EACH_OBSERVER(Observer, observers_, UnlockScreenFailed(this));
}

// static
void ScreenLockLibraryImpl::ScreenLockedHandler(void* object,
                                                ScreenLockEvent event) {
  ScreenLockLibraryImpl* self = static_cast<ScreenLockLibraryImpl*>(object);
  switch (event) {
    case chromeos::LockScreen:
      self->LockScreen();
      break;
    case chromeos::UnlockScreen:
      self->UnlockScreen();
      break;
    case chromeos::UnlockScreenFailed:
      self->UnlockScreenFailed();
      break;
    default:
      NOTREACHED();
  }
}

}  // namespace chromeos
<commit_msg>Use io thread to send dbus message.<commit_after>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/browser/chromeos/cros/screen_lock_library.h"

#include "base/message_loop.h"
#include "base/string_util.h"
#include "chrome/browser/chrome_thread.h"
#include "chrome/browser/chromeos/cros/cros_library.h"

// Allows InvokeLater without adding refcounting. This class is a Singleton and
// won't be deleted until it's last InvokeLater is run.
DISABLE_RUNNABLE_METHOD_REFCOUNT(chromeos::ScreenLockLibraryImpl);

namespace chromeos {

ScreenLockLibraryImpl::ScreenLockLibraryImpl() {
  if (CrosLibrary::Get()->EnsureLoaded()) {
    Init();
  }
}

ScreenLockLibraryImpl::~ScreenLockLibraryImpl() {
  if (screen_lock_connection_) {
    chromeos::DisconnectScreenLock(screen_lock_connection_);
  }
}

void ScreenLockLibraryImpl::AddObserver(Observer* observer) {
  observers_.AddObserver(observer);
}

void ScreenLockLibraryImpl::RemoveObserver(Observer* observer) {
  observers_.RemoveObserver(observer);
}

void ScreenLockLibraryImpl::NotifyScreenLockRequested() {
  // Make sure we run on IO thread.
  if (!ChromeThread::CurrentlyOn(ChromeThread::IO)) {
    ChromeThread::PostTask(
        ChromeThread::IO, FROM_HERE,
        NewRunnableMethod(this,
                          &ScreenLockLibraryImpl::NotifyScreenLockRequested));
    return;
  }
  chromeos::NotifyScreenLockRequested();
}

void ScreenLockLibraryImpl::NotifyScreenLockCompleted() {
  // Make sure we run on IO thread.
  if (!ChromeThread::CurrentlyOn(ChromeThread::IO)) {
    ChromeThread::PostTask(
        ChromeThread::IO, FROM_HERE,
        NewRunnableMethod(this,
                          &ScreenLockLibraryImpl::NotifyScreenLockCompleted));
    return;
  }
  chromeos::NotifyScreenLockCompleted();
}

void ScreenLockLibraryImpl::NotifyScreenUnlockRequested() {
  // Make sure we run on IO thread.
  if (!ChromeThread::CurrentlyOn(ChromeThread::IO)) {
    ChromeThread::PostTask(
        ChromeThread::IO, FROM_HERE,
        NewRunnableMethod(this,
                          &ScreenLockLibraryImpl::NotifyScreenUnlockRequested));
    return;
  }
  chromeos::NotifyScreenUnlockRequested();
}

void ScreenLockLibraryImpl::NotifyScreenUnlockCompleted() {
  // Make sure we run on IO thread.
  if (!ChromeThread::CurrentlyOn(ChromeThread::IO)) {
    ChromeThread::PostTask(
        ChromeThread::IO, FROM_HERE,
        NewRunnableMethod(this,
                          &ScreenLockLibraryImpl::NotifyScreenUnlockCompleted));
    return;
  }
  chromeos::NotifyScreenUnlockCompleted();
}

void ScreenLockLibraryImpl::Init() {
  screen_lock_connection_ = chromeos::MonitorScreenLock(
      &ScreenLockedHandler, this);
}

void ScreenLockLibraryImpl::LockScreen() {
  // Make sure we run on UI thread.
  if (!ChromeThread::CurrentlyOn(ChromeThread::UI)) {
    ChromeThread::PostTask(
        ChromeThread::UI, FROM_HERE,
        NewRunnableMethod(this, &ScreenLockLibraryImpl::LockScreen));
    return;
  }
  FOR_EACH_OBSERVER(Observer, observers_, LockScreen(this));
}

void ScreenLockLibraryImpl::UnlockScreen() {
  // Make sure we run on UI thread.
  if (!ChromeThread::CurrentlyOn(ChromeThread::UI)) {
    ChromeThread::PostTask(
        ChromeThread::UI, FROM_HERE,
        NewRunnableMethod(this, &ScreenLockLibraryImpl::UnlockScreen));
    return;
  }
  FOR_EACH_OBSERVER(Observer, observers_, UnlockScreen(this));
}

void ScreenLockLibraryImpl::UnlockScreenFailed() {
  // Make sure we run on UI thread.
  if (!ChromeThread::CurrentlyOn(ChromeThread::UI)) {
    ChromeThread::PostTask(
        ChromeThread::UI, FROM_HERE,
        NewRunnableMethod(this, &ScreenLockLibraryImpl::UnlockScreenFailed));
    return;
  }
  FOR_EACH_OBSERVER(Observer, observers_, UnlockScreenFailed(this));
}

// static
void ScreenLockLibraryImpl::ScreenLockedHandler(void* object,
                                                ScreenLockEvent event) {
  ScreenLockLibraryImpl* self = static_cast<ScreenLockLibraryImpl*>(object);
  switch (event) {
    case chromeos::LockScreen:
      self->LockScreen();
      break;
    case chromeos::UnlockScreen:
      self->UnlockScreen();
      break;
    case chromeos::UnlockScreenFailed:
      self->UnlockScreenFailed();
      break;
    default:
      NOTREACHED();
  }
}

}  // namespace chromeos
<|endoftext|>