Exemplo n.º 1
0
/**
 * Atomically save \a doc to specified name. Prior to saving, back up
 * of old config data is created, and only then data is saved.
 */
bool AtomicXmlFile::saveDocument(const QDomDocument& doc) const
{
	if (!saveDocument(doc, tempFileName())) {
		qWarning("AtomicXmlFile::saveDocument(): Unable to save '%s'. Possibly drive is full.",
		         qPrintable(tempFileName()));
		return false;
	}

	if (QFile::exists(backupFileName()))
		QFile::remove(backupFileName());

	if (QFile::exists(fileName_)) {
		if (!QFile::rename(fileName_, backupFileName())) {
			qWarning("AtomicXmlFile::saveDocument(): Unable to rename '%s' to '%s'.",
			         qPrintable(fileName_), qPrintable(backupFileName()));
			return false;
		}
	}

	if (!QFile::rename(tempFileName(), fileName_)) {
		qWarning("AtomicXmlFile::saveDocument(): Unable to rename '%s' to '%s'.",
		         qPrintable(tempFileName()), qPrintable(fileName_));
		return false;
	}

	return true;
}
Exemplo n.º 2
0
void DiffDialog::callExternalDiff(const QString& extdiff, OrgKdeCervisia5CvsserviceCvsserviceInterface* service,
                                  const QString& fileName, const QString &revA,
                                  const QString &revB)
{
    QString extcmdline = extdiff;
    extcmdline += ' ';

    // create suffix for temporary file (used QFileInfo to remove path from file name)
    const QString suffix = '-' + QFileInfo(fileName).fileName();

    QDBusReply<QDBusObjectPath> job;
    if (!revA.isEmpty() && !revB.isEmpty())
    {
        // We're comparing two revisions
        QString revAFilename = tempFileName(suffix+QString("-")+revA);
        QString revBFilename = tempFileName(suffix+QString("-")+revB);

        // download the files for revision A and B
        job = service->downloadRevision(fileName, revA, revAFilename,
                                                revB, revBFilename);
        if( !job.isValid() )
            return;

        extcmdline += KShell::quoteArg(revAFilename);
        extcmdline += ' ';
        extcmdline += KShell::quoteArg(revBFilename);
    }
    else
    {
        // We're comparing to a file, and perhaps one revision
        QString revAFilename = tempFileName(suffix+QString("-")+revA);
        job = service->downloadRevision(fileName, revA, revAFilename);
        if( !job.isValid() )
            return;

        extcmdline += KShell::quoteArg(revAFilename);
        extcmdline += ' ';
        extcmdline += KShell::quoteArg(QFileInfo(fileName).absoluteFilePath());
    }

    ProgressDialog dlg(this, "Diff", service->service(),job, "diff");
    if( dlg.execute() )
    {
        // call external diff application
        KProcess proc;
        proc.setShellCommand(extcmdline);
        proc.startDetached();
    }
}
Exemplo n.º 3
0
SAWYER_EXPORT std::string
PodFormatter::toNroff(const ParserResult &parsed) {
    // Generate POD documentation into a temporary file
    TempFile tmpfile(tempFileName(".pod"));
    parsed.emit(tmpfile.stream, sharedFromThis());
    tmpfile.stream.close();

    std::string cmd = "pod2man"
                      " --center='" + escapeSingleQuoted(chapterName_) + "'"
                      " --date='" + escapeSingleQuoted(dateString_) + "'"
                      " --name='" + escapeSingleQuoted(pageName_) + "'"
                      " --release='" + escapeSingleQuoted(versionString_) + "'"
                      " --section='" + escapeSingleQuoted(chapterNumber_) + "'"
                      " " + tmpfile.name;

    FILE *f = popen(cmd.c_str(), "r");
    if (!f) {
#include <Sawyer/WarningsOff.h>                         // suppress strerror unsafe warning from Microsoft C++
        throw std::runtime_error(std::string("cannot run command: ") + strerror(errno) + "\ncommand: " + cmd);
#include <Sawyer/WarningsRestore.h>
    }
    
    std::string result;
    while (1) {
        std::string line = readOneLine(f);
        if (line.empty())
            break;
        result += line;
    }

    if (-1 == Sawyer::pclose(f))
        throw std::runtime_error("command failed: " + cmd);

    return result;
}
Exemplo n.º 4
0
/// Passes the results of a test to the test suite callback function
/// @param record Indicates whether or note the results of the test should be recorded to the results tree ctrl if the test was successful
/// @param startTime The time when the test was started
/// @param testName Name of the test
/// @param success Indicates the success/failure of the test
/// @param fileName Name of the file where the test occurred
/// @param lineNumber Line number in the file where the test occurred
bool TestSuite::Test(bool record, wxLongLong startTime, const wxChar* testName, bool success, char* fileName, size_t lineNumber)
{
    //------Last Checked------//
    // - Dec 2, 2004
           
    // Calculate the time to execute the test (in seconds)
    wxLongLong span = ::wxGetLocalTimeMillis() - startTime;
    double executionTime = ((double)span.ToLong()) / 1000.0;

    // If the test suite isn't being executed, bail out
    if (!IsExecuted())
        return (false);

    // Update the success or failure of the test
    if (success)
        m_passed++;
    else
        m_failed++;

    wxCHECK(testName != NULL, false);
    wxCHECK(fileName != NULL, false);
    wxCHECK(m_testSuiteCallback != NULL, false);

    // Create a temp string used for the filename (since it's ANSI and we want it this to work on Unicode builds)
    wxString tempFileName(fileName);

    // Send the results of the test to the callback
    return (m_testSuiteCallback(this, testName, success, tempFileName, lineNumber, record, executionTime, m_clientData));
}
Exemplo n.º 5
0
QFile::FileError QLCFixtureDef::saveXML(const QString& fileName)
{
    QFile::FileError error;

    if (fileName.isEmpty() == true)
        return QFile::OpenError;

    QString tempFileName(fileName);
    tempFileName += ".temp";
    QFile file(tempFileName);
    if (file.open(QIODevice::WriteOnly) == false)
        return file.error();

    QXmlStreamWriter doc(&file);
    doc.setAutoFormatting(true);
    doc.setAutoFormattingIndent(1);
    doc.setCodec("UTF-8");
    QLCFile::writeXMLHeader(&doc, KXMLQLCFixtureDefDocument, author());

    doc.writeTextElement(KXMLQLCFixtureDefManufacturer, m_manufacturer);
    doc.writeTextElement(KXMLQLCFixtureDefModel, m_model);
    doc.writeTextElement(KXMLQLCFixtureDefType, m_type);

    /* Channels */
    QListIterator <QLCChannel*> chit(m_channels);
    while (chit.hasNext() == true)
        chit.next()->saveXML(&doc);

    /* Modes */
    QListIterator <QLCFixtureMode*> modeit(m_modes);
    while (modeit.hasNext() == true)
        modeit.next()->saveXML(&doc);

    /* End the document and close all the open elements */
    error = QFile::NoError;
    doc.writeEndDocument();
    file.close();

    // Save to actual requested file name
    QFile currFile(fileName);
    if (currFile.exists() && !currFile.remove())
    {
        qWarning() << "Could not erase" << fileName;
        return currFile.error();
    }
    if (!file.rename(fileName))
    {
        qWarning() << "Could not rename" << tempFileName << "to" << fileName;
        return file.error();
    }

    return error;
}
Exemplo n.º 6
0
void CSimpleAppUi::ConstructContainerL()
    {
	TRect boundingRect=ClientRect(); // make toolband stretch to the screen width by default
    iContainer=new(ELeave) CTestContainer;
    iContainer->ConstructL();

	ReduceRect(boundingRect);
	iContainer->SetRect(boundingRect);	
    //vmTFileName tempFileName(Application()->BitmapStoreName());
	TFileName tempFileName(KTBmpAnimMBMFilePath);
	iContainer->SetAppFileName(tempFileName);
	iContainer->DrawNow();
    }
Exemplo n.º 7
0
/**
 * Tries to load \a doc from config file, or if that fails, from a back up.
 */
bool AtomicXmlFile::loadDocument(QDomDocument* doc) const
{
	Q_ASSERT(doc);

	QStringList fileNames;
	fileNames << tempFileName()
	          << fileName_
	          << backupFileName();

	foreach(QString fileName, fileNames)
		if (loadDocument(doc, fileName))
			return true;

	return false;
}
Exemplo n.º 8
0
SAWYER_EXPORT void
PodFormatter::emit(const ParserResult &parsed) {
    // Generate POD documentation into a temporary file.  Since perldoc doesn't support the "name" property, but rather
    // uses the file name, we create a temporary directory and place a POD file inside with the name we want.
    TempDir tmpdir(tempFileName());
    std::string fileName = tmpdir.name + pageName_ + ".pod";
    {
        std::ofstream stream(fileName.c_str());
        parsed.emit(stream, sharedFromThis());
    }

    std::string cmd = "perldoc "
                      " -o man"
                      " -w 'center:" + escapeSingleQuoted(chapterName_) + "'"
                      " -w 'date:" + escapeSingleQuoted(dateString_) + "'"
                      // " -w 'name:" + escapeSingleQuoted(pageName_) + "'"
                      " -w 'release:" + escapeSingleQuoted(versionString_) + "'"
                      " -w 'section:" + escapeSingleQuoted(chapterNumber_) + "'"
                      " " + fileName;
    system(cmd.c_str());
}
Exemplo n.º 9
0
//----------------------------------------------------------------------------
void correctEmptyFileExt(const wxString& ext, wxString & fileName)
{
    wxFileName tempFileName(fileName);
    if (tempFileName.GetExt().IsEmpty())
        fileName += "." + ext;
}
Exemplo n.º 10
0
/**
 * @return returns temporary directory name.
 */
std::string digidoc::util::File::tempDirectory()
{
    return tempFileName() + PATH_DELIMITER;
}
Exemplo n.º 11
0
DWORD CSoundManager::OnRunPlaylist(DWORD size, void *param)
{
	VERIFY_MESSAGE_SIZE(size, sizeof(IHashString*));

	IHashString *fileName = (IHashString*)param;
	IDTOOBJECTMAP::iterator plIter;	

	if (fileName)
	{
		// convert to lowercase hashstring
		StdString szFileName = fileName->GetString();
		szFileName.tolower();
		CHashString tempFileName(szFileName);

		if (m_pCurrentPlaylist)
		{
			m_pCurrentPlaylist->Stop();
		}

		IDTOOBJECTMAP *objMap = GetObjectMap(&m_hsPlaylistTypeName);
		bool found = false;
		if (objMap != NULL)
		{
			plIter = objMap->find(tempFileName.GetUniqueID());

			if (plIter != objMap->end())
			{
				found = true;
			}
		}

		if (!found)
		{

			// not in map... try to load and check again
			LOADFILEEXTPARAMS lfep;
			lfep.fileName = (TCHAR*) tempFileName.GetString();
			lfep.bInternalLoad = true;
			static DWORD msgHash_LoadFileByExtension = CHashString(_T("LoadFileByExtension")).GetUniqueID();
			m_ToolBox->SendMessage(msgHash_LoadFileByExtension, sizeof(LOADFILEEXTPARAMS), &lfep);
			
			objMap = GetObjectMap(&m_hsPlaylistTypeName);
			if (objMap != NULL)
			{
				plIter = objMap->find(tempFileName.GetUniqueID());
				if (plIter != objMap->end())
				{
					found = true;
				}
			}

			if (!found)
			{
				m_ToolBox->Log(LOGWARNING, _T("Sound manager: could not open playlist file %s\n"), tempFileName.GetString());
				return MSG_NOT_HANDLED;
			}
		}
		
		m_pCurrentPlaylist = dynamic_cast<ISoundObject *>(plIter->second);
		if (m_pCurrentPlaylist != NULL)
		{
			m_pCurrentPlaylist->Play();
		}
		else
		{
			m_ToolBox->Log(LOGWARNING, _T("Dynamic cast failed for CMusicPlayList in %s at line %d\n"),
				__FILE__, __LINE__);
			return MSG_NOT_HANDLED;
		}		
	}

	return MSG_HANDLED_STOP;
}
Exemplo n.º 12
0
void
PRDocument::DoSave()
{

	// Validate pointers.
	
	ValidateThis_();
	ValidateObject_(mRFMap);
	ValidateObject_(mFile);

	// Ensure that memory allocations succeed.
	
	StCriticalSection crit;

	// Finalize any pending actions while resource file is still open.

	PostAction(nil);

 	// Make a name for temporary file using base string provided by caller and a time stamp.
	
	LStr255 tempFileName(STR_FileTitles, str_TempSwapFile);
	if (tempFileName.Length() > 20)
		tempFileName[(UInt8)0] = 20;
	
	UInt32 time;
	::GetDateTime(&time);
	LStr255 tempFileNumber((SInt32) time);
	tempFileName += tempFileNumber;

	// Find Temporary Items folder on source file's volume and create temp file there.

	FSSpec documentSpec;
	mFile->GetSpecifier(documentSpec);

	SInt16 theVRef;
	SInt32 theDirID;
	OSErr theErr = ::FindFolder(documentSpec.vRefNum, kTemporaryFolderType,
					kCreateFolder, &theVRef, &theDirID);
	
	// JWW - The volume might not be what we asked, especially if it's on OS X...
	// ...and on OS X, it looks like FindFolder returns an error, so don't throw
	if ((theErr != noErr) || (theVRef != documentSpec.vRefNum))
	{
		// ...and in that case, just use the document folder instead why not?
		theVRef = documentSpec.vRefNum;
		theDirID = documentSpec.parID;
	}

	FSSpec tempFileSpec;
	theErr = ::FSMakeFSSpec(theVRef, theDirID, tempFileName, &tempFileSpec);
	if ((theErr != noErr) && (theErr != fnfErr))
		ThrowOSErr_(theErr);

	try {


		if (mIsFlattened)
		{
			// Make a copy of the file.
		
			SaveCDEFs();							//* 2.1.2: BUG FIX #370

			FSSpec unflattenedSpec;
			mUnflattenedFile->GetSpecifier(unflattenedSpec);

			mUnflattenedFile->CloseResourceFork();	//ugh! required for saving on remote volumes
			::FSpDelete(&tempFileSpec);
			ThrowIfOSErr_(::FileCopy(unflattenedSpec.vRefNum, unflattenedSpec.parID,
								unflattenedSpec.name,
								tempFileSpec.vRefNum, tempFileSpec.parID, nil, tempFileName,
								nil, 0, true));

			// Open temp file and make changes.

			LFile tempFile(tempFileSpec);
			OpenResourceFile(&tempFile);
			mRFMap->SetMainFile(&tempFile);
			RawSave(tempFileSpec, documentSpec);
			
			// Save is done. Now swap files back.
			//
			// With flat files, we'll copy the temp resource fork into the
			// original file's flattened data fork.
			
			SInt16	srcRefNum;
			SInt16	destRefNum;

			StPointerBlock	buffer(bigCopyBuffSize, false, false);
			if (not buffer.IsValid())
			{
				StPointerBlock	smallBuffer(minCopyBuffSize, true, false);
				buffer.Adopt(smallBuffer.Release());
			}

			tempFile.CloseResourceFork();
			mFile->CloseDataFork();
			
			srcRefNum = tempFile.OpenResourceFork(fsRdPerm);
			destRefNum = mFile->OpenDataFork(fsRdWrPerm);

			ThrowIfOSErr_(::CopyFork(srcRefNum, destRefNum, buffer, ::GetPtrSize(buffer)));
			
			// The Save is done.  Now swap the temp and unflattened files.  This fixes
			// bug WB1-42415 where some changes to a flattened ppob file were overwritten
			// unless you closed and reopened the flat ppob after each save.
			tempFile.CloseResourceFork();
			ThrowIfOSErr_(::FSpExchangeFiles(&unflattenedSpec, &tempFileSpec));
			
			::FSpDelete(&tempFileSpec);		// deletes old document

		}
		else
		{
			// Make a copy of the file.
		
			SaveCDEFs();							//* 2.1.2: BUG FIX #370

			mFile->CloseResourceFork();				//ugh! required for saving on remote volumes
			::FSpDelete(&tempFileSpec);
			ThrowIfOSErr_(::FileCopy(documentSpec.vRefNum, documentSpec.parID, documentSpec.name,
								tempFileSpec.vRefNum, tempFileSpec.parID, nil, tempFileName,
								nil, 0, true));

			// Open temp file and make changes.

			LFile tempFile(tempFileSpec);
			OpenResourceFile(&tempFile);
			mRFMap->SetMainFile(&tempFile);
			RawSave(tempFileSpec, documentSpec);
			
			// Save is done. Now swap files back.

			tempFile.CloseResourceFork();
			ThrowIfOSErr_(::FSpExchangeFiles(&documentSpec, &tempFileSpec));
			::FSpDelete(&tempFileSpec);		// deletes old document
		}
	}
	catch (...) {
	
		// Get rid of temp file.

		::FSpDelete(&tempFileSpec);
		
		if (mIsFlattened)
		{
			// Reopen (untouched) main document.
			
			OpenResourceFile(mUnflattenedFile);
			mRFMap->SetMainFile(mUnflattenedFile);
		}
		else
		{
			// Reopen (untouched) main document.
			
			OpenResourceFile(mFile);
			mRFMap->SetMainFile(mFile);
		}

		// Rethrow exception so it gets reported.

		#if SKIPOMPARSE				// grrr-
			throw;
		#endif
	}

	if (mIsFlattened)
	{
		// Reopen (untouched) main document.
		
		OpenResourceFile(mUnflattenedFile);
		mRFMap->SetMainFile(mUnflattenedFile);
	}
	else
	{
		// Reopen (untouched) main document.
		
		OpenResourceFile(mFile);
		mRFMap->SetMainFile(mFile);
	}

}
Exemplo n.º 13
0
QFile::FileError App::saveXML(const QString& fileName)
{
    QString tempFileName(fileName);
    tempFileName += ".temp";
    QFile file(tempFileName);
    if (file.open(QIODevice::WriteOnly) == false)
        return file.error();

    QXmlStreamWriter doc(&file);
    doc.setAutoFormatting(true);
    doc.setAutoFormattingIndent(1);
    doc.setCodec("UTF-8");

    doc.writeStartDocument();
    doc.writeDTD(QString("<!DOCTYPE %1>").arg(KXMLQLCWorkspace));

    doc.writeStartElement(KXMLQLCWorkspace);
    doc.writeAttribute("xmlns", QString("%1%2").arg(KXMLQLCplusNamespace).arg(KXMLQLCWorkspace));

    /* Currently active context */
    doc.writeAttribute(KXMLQLCWorkspaceWindow, m_contextManager->currentContext());

    /* Creator information */
    doc.writeStartElement(KXMLQLCCreator);
    doc.writeTextElement(KXMLQLCCreatorName, APPNAME);
    doc.writeTextElement(KXMLQLCCreatorVersion, APPVERSION);
    doc.writeTextElement(KXMLQLCCreatorAuthor, QLCFile::currentUserName());
    doc.writeEndElement();

    /* Write engine components to the XML document */
    m_doc->saveXML(&doc);

    /* Write virtual console to the XML document */
    m_virtualConsole->saveXML(&doc);

    /* Write Simple Desk to the XML document */
    //SimpleDesk::instance()->saveXML(&doc);

    doc.writeEndElement(); // close KXMLQLCWorkspace

    /* End the document and close all the open elements */
    doc.writeEndDocument();
    file.close();

    // Save to actual requested file name
    QFile currFile(fileName);
    if (currFile.exists() && !currFile.remove())
    {
        qWarning() << "Could not erase" << fileName;
        return currFile.error();
    }
    if (!file.rename(fileName))
    {
        qWarning() << "Could not rename" << tempFileName << "to" << fileName;
        return file.error();
    }

    /* Set the file name for the current Doc instance and
       set it also in an unmodified state. */
    setFileName(fileName);
    m_doc->resetModified();

    return QFile::NoError;
}
Exemplo n.º 14
0
// Main Method
int main(int argc, char** argv) {
  // Set up a handler for any signals so that we always shutdown gracefully
  struct sigaction sigIntHandler;
  sigIntHandler.sa_handler = my_signal_handler;
  sigemptyset(&sigIntHandler.sa_mask);
  sigIntHandler.sa_flags = 0;

  sigaction(SIGINT, &sigIntHandler, NULL);

  // Setup the component factories
  cli_factory = new CommandLineInterpreterFactory;
  uuid_factory = new uuidComponentFactory;
  zmq_factory = new ZmqComponentFactory;
  logging_factory = new LoggingComponentFactory;
  mongo_factory = new MongoComponentFactory;

  ObjectListFactory ofactory;
  ObjectFactory objfactory;

  // Set up our command line interpreter
  cli = cli_factory->get_command_line_interface(argc, argv);

  // Allow for wait on startup, if configured
  if (cli->opt_exist("-wait")) {
    std::string wait_time_string = cli->get_opt("-wait");
    int wait_time = std::stoi(wait_time_string, NULL);
    // Accept input on the command line in seconds, convert to microseconds
    usleep(wait_time * 1000000);
  }

  // Set up logging
  std::string initFileName;

  // See if we have a command line setting for the log file
  const char * env_logging_file = std::getenv("CRAZYIVAN_LOGGING_CONF");
  if (env_logging_file) {
    std::string tempFileName(env_logging_file);
    initFileName = tempFileName;
  } else if (cli->opt_exist("-log-conf")) {
    initFileName = cli->get_opt("-log-conf");
  } else {
    initFileName = "log4cpp.properties";
  }

  // This reads the logging configuration file
  logging = logging_factory->get_logging_interface(initFileName);

  // Set up the logging submodules for each category
  start_logging_submodules();

  // Set up the UUID Generator
  uid = uuid_factory->get_uuid_interface();

  std::string service_id = "Clyman";

  // Set up our configuration manager with the CLI
  config = new ConfigurationManager(cli, service_id);

  // Start up the Kafka Producer
  kafka = new KafkaClient();

  // The configuration manager will  look at any command line arguments,
  // configuration files, and Consul connections to try and determine the
  // correct configuration for the service

  // The configuration manager will  look at any command line arguments,
  // configuration files, and Consul connections to try and determine the
  // correct configuration for the service
  bool config_success = false;
  bool config_tried = false;
  int config_attempts = 0;
  // If we fail configuration, we should sleep for 5 seconds and try again
  while (!config_success) {
    if (config_attempts > 50) {
      main_logging->error("Max Config Attempts failed, exiting");
      shutdown();
      exit(1);
    }
    if (config_tried) {
      main_logging->error("Configuration Failed, trying again in 5 seconds");
      usleep(5000000);
    } else {
      config_tried = true;
    }
    try {
      config_success = config->configure();
    }
    catch (std::exception& e) {
      main_logging->error("Exception encountered during Configuration");
    }
  }

  // Set up the Mongo Connection
  std::string DBConnStr = config->get_mongoconnstr();
  std::string DBName = config->get_dbname();
  std::string DBHeaderCollection = config->get_dbheadercollection();
  if (!(DBConnStr.empty() || DBName.empty() \
    || DBHeaderCollection.empty())) {
    try {
      mongo = mongo_factory->get_mongo_interface(DBConnStr, \
        DBName, DBHeaderCollection);
      main_logging->debug("Connected to Mongo");
    }
    catch (std::exception& e) {
      main_logging->error("Exception encountered during Mongo Startup");
      main_logging->error(e.what());
      shutdown();
      exit(1);
    }
  } else {
    main_logging->error("Insufficient Mongo Connection Information");
    shutdown();
    exit(1);
  }

  // Connect to the inbound ZMQ Admin
  std::string ib_zmq_connstr = config->get_ibconnstr();
  if (!(ib_zmq_connstr.empty())) {
    zmqi = zmq_factory->get_zmq_inbound_interface(ib_zmq_connstr, REQ_RESP);
    main_logging->info("ZMQ Socket Open, opening request loop");
  } else {
    main_logging->error("No IB ZMQ Connection String Supplied");
    shutdown();
    exit(1);
  }

  // Main Request Loop

  while (true) {
    std::string resp_str = "";
    rapidjson::Document d;
    protoObj3::Obj3List new_proto;

    // Convert the OMQ message into a string to be passed on the event
    char * req_ptr = zmqi->crecv();
    if (!req_ptr) continue;
    main_logging->debug("Conversion to C String performed with result: ");
    main_logging->debug(req_ptr);

    // Trim the string recieved
    std::string recvd_msg(req_ptr);
    std::string clean_string;

    std::string new_error_message = "";

    // Parsing logic - JSON
    if (config->get_formattype() == JSON_FORMAT) {
      response_message = ofactory.build_json_object_list();
      int final_closing_char = recvd_msg.find_last_of("}");
      int first_opening_char = recvd_msg.find_first_of("{");
      clean_string = \
        recvd_msg.substr(first_opening_char, final_closing_char+1);
      main_logging->debug("Input String Cleaned");
      main_logging->debug(clean_string);

      try {
        d.Parse<rapidjson::kParseStopWhenDoneFlag>(clean_string.c_str());
        if (d.HasParseError()) {
          main_logging->error("Parsing Error: ");
          main_logging->error(GetParseError_En(d.GetParseError()));
          response_message->set_error_code(TRANSLATION_ERROR);
          new_error_message.assign(GetParseError_En(d.GetParseError()));
        } else {inbound_message = ofactory.build_object_list(d);}
      }
      // Catch a possible error and write to logs
      catch (std::exception& e) {
        main_logging->error("Exception occurred while parsing document:");
        main_logging->error(e.what());
      }
    // Parsing logic - Protocol Buffers
    } else if (config->get_formattype() == PROTO_FORMAT) {
      response_message = ofactory.build_proto_object_list();
      clean_string = trim(recvd_msg);
      main_logging->debug("Input String Cleaned");
      main_logging->debug(clean_string);

      try {
        new_proto.ParseFromString(clean_string);
        inbound_message = ofactory.build_object_list(new_proto);
      } catch (std::exception& e) {
        main_logging->error("Exception occurred while parsing bytes:");
        main_logging->error(e.what());
        response_message->set_error_code(TRANSLATION_ERROR);
        new_error_message.assign(e.what());
      }
    }

      // Determine the Transaction ID
      UuidContainer id_container;
      id_container.id = "";
      if (config->get_transactionidsactive() && inbound_message) {
        // Get an existing transaction ID
        std::string existing_trans_id = \
          inbound_message->get_transaction_id();
        // If no transaction ID is sent in, generate a new one
        if (existing_trans_id.empty()) {
          try {
            id_container = uid->generate();
            if (!id_container.err.empty()) {
              main_logging->error(id_container.err);
            }
            inbound_message->set_transaction_id(id_container.id);
          }
          catch (std::exception& e) {
            main_logging->error("Exception encountered in UUID Generation");
            main_logging->error(e.what());
            shutdown();
            exit(1);
          }
        }
        main_logging->debug("Transaction ID: ");
        main_logging->debug(inbound_message->get_transaction_id());
      }

      bool shutdown_needed = false;

      // Core application logic
      if (inbound_message) {
        try {
          // Object Creation
          if (inbound_message->get_msg_type() == OBJ_CRT) {
            main_logging->info("Processing Object Creation Message");
            for (int i = 0; i < inbound_message->num_objects(); i++) {
              // Create a new Obj3 to add to the return list
              ObjectInterface *resp_element = objfactory.build_object();

              // Create the Obj3 document for Mongo
              AOSSL::MongoBufferInterface *bson = mongo_factory->get_mongo_buffer();
              inbound_message->get_object(i)->to_bson(bson);
              MongoResponseInterface *resp = mongo->create_document(bson);
              delete bson;

              // Add the key into the new obj3
              resp_element->set_key(resp->get_value());
              // Add the new obj3 to the response list
              response_message->add_object(resp_element);
              delete resp;
            }

          // Object Update
          } else if (inbound_message->get_msg_type() == OBJ_UPD || \
            inbound_message->get_msg_type() == OBJ_LOCK || \
            inbound_message->get_msg_type() == OBJ_UNLOCK ||
            inbound_message->get_msg_type() == OBJ_OVERWRITE) {
            main_logging->info("Processing Object Update Message");
            for (int i = 0; i < inbound_message->num_objects(); i++) {
              // Build a query bson to pass to the update_by_query
              AOSSL::MongoBufferInterface *query_bson = mongo_factory->get_mongo_buffer();
              AOSSL::MongoBufferInterface *bson = mongo_factory->get_mongo_buffer();
              std::string msg_key = inbound_message->get_object(i)->get_key();
              bool execute_query = true;
              if (msg_key.empty() && \
                !(inbound_message->get_object(i)->get_name().empty() && \
                  inbound_message->get_object(i)->get_scene().empty())) {
                    std::string name_key = "name";
                    std::string scene_key = "scene";
                    query_bson->add_string(name_key, inbound_message->get_object(i)->get_name());
                    query_bson->add_string(scene_key, inbound_message->get_object(i)->get_scene());
              } else if (!(msg_key.empty())) {
                query_bson->add_oid(msg_key);
              }
              // Add an owner query if object locking is active
              if (config->get_locking_active()) {
                std::string owner_key = "owner";
                // If we have a lock message, then look for an empty owner
                if (inbound_message->get_msg_type() == OBJ_LOCK) {
                  std::string owner_search = "";
                  query_bson->add_string(owner_key, owner_search);
                // Otherwise, look for a matching owner to the input
                } else {
                  std::string owner_search = inbound_message->get_object(i)->get_owner();
                  query_bson->add_string(owner_key, owner_search);
                }
              }
              if (inbound_message->get_msg_type() == OBJ_OVERWRITE) {
                // Build the BSON Update
                main_logging->debug("Overwriting BSON Object");
                inbound_message->get_object(i)->to_bson_update(bson);
              } else {
                // Load the current doc from the database
                rapidjson::Document resp_doc;
                MongoResponseInterface *resp = mongo->load_document(msg_key);
                if (resp) {
                  std::string mongo_resp_str = resp->get_value();
                  main_logging->debug("Document loaded from Mongo");
                  main_logging->debug(mongo_resp_str);
                  resp_doc.Parse(mongo_resp_str.c_str());
                  ObjectInterface *resp_obj = objfactory.build_object(resp_doc);
                  // Save the resulting object
                  if (inbound_message->get_op_type() == APPEND) {
                    // Apply the object message as changes to the DB Object
                    resp_obj->merge(inbound_message->get_object(i));
                    // Update the object in case of unlock to have no owner before saving
                    if (inbound_message->get_msg_type() == OBJ_UNLOCK) {
                      std::string new_owner = "";
                      resp_obj->set_owner(new_owner);
                    }
                    resp_obj->to_bson_update(bson);
                  } else {
                    // Update the object in case of unlock to have no owner before saving
                    if (inbound_message->get_msg_type() == OBJ_UNLOCK) {
                      std::string new_owner = "";
                      inbound_message->get_object(0)->set_owner(new_owner);
                    }
                    inbound_message->get_object(0)->to_bson_update(true, false, bson);
                  }
                  response_message->add_object(resp_obj);
                  delete resp;
                } else {
                  main_logging->error("Document not found in Mongo");
                  response_message->set_error_code(NOT_FOUND);
                  new_error_message = "Object not Found";
                  response_message->set_error_message(new_error_message);
                  execute_query = false;
                }
              }

              // Actually execute the  Mongo update
              AOSSL::MongoBufferInterface *response_buffer = NULL;
              bool send_update = false;
              if (execute_query) {
                response_buffer = mongo->update_single_by_query(query_bson, bson);
                // Look at the response buffer to ensure that a single document
                // was matched and updated
                std::string mdc_key = "modifiedCount";
                std::string mtc_key = "matchedCount";
                int num_modified = response_buffer->get_int(mdc_key);
                int num_matched = response_buffer->get_int(mtc_key);
                if (num_matched == 0) {
                  main_logging->error("Document not found in Mongo");
                  response_message->set_error_code(NOT_FOUND);
                  new_error_message = "Object not Found";
                  response_message->set_error_message(new_error_message);
                } else if (num_modified == 0) {
                  main_logging->error("Document found in Mongo, but update failed");
                  response_message->set_error_code(LOCK_EXISTS_ERROR);
                  new_error_message = "Object locked by another device";
                  response_message->set_error_message(new_error_message);
                } else {
                  // Updates were successful in Mongo, so send via streams
                  send_update = true;
                }
              }
              // Send an update on the Kafka 'dvs' topic
              if ((inbound_message->get_msg_type() == OBJ_OVERWRITE || \
                inbound_message->get_msg_type() == OBJ_UPD) && send_update) {
                  kafka->send(inbound_message->get_object(i)->to_transform_json(), config->get_kafkabroker());
              }
              delete query_bson;
              delete bson;
            }

          // Object Retrieve
          } else if (inbound_message->get_msg_type() == OBJ_GET) {
            main_logging->info("Processing Object Get Message");
            for (int i = 0; i < inbound_message->num_objects(); i++) {
              // Pull down and parse the value from Mongo
              rapidjson::Document resp_doc;
              MongoResponseInterface *resp = mongo->load_document(\
                inbound_message->get_object(i)->get_key());
              if (resp) {
                std::string mongo_resp_str = resp->get_value();
                main_logging->debug("Document loaded from Mongo");
                main_logging->debug(mongo_resp_str);
                resp_doc.Parse(mongo_resp_str.c_str());

                // Create a new Obj3 and add to the return list
                ObjectInterface *resp_obj = objfactory.build_object(resp_doc);
                response_message->add_object(resp_obj);
                delete resp;
              } else {
                main_logging->error("Document not found in Mongo");
                response_message->set_error_code(NOT_FOUND);
                new_error_message = "Object not Found";
                response_message->set_error_message(new_error_message);
              }
            }

          // Object Query
          } else if (inbound_message->get_msg_type() == OBJ_QUERY) {
            main_logging->info("Processing Object Batch Query Message");
            batch_query(inbound_message, response_message, mongo);

          // Object Delete
          } else if (inbound_message->get_msg_type() == OBJ_DEL) {
            main_logging->info("Processing Object Deletion Message");
            for (int i = 0; i < inbound_message->num_objects(); i++) {
              ObjectInterface *resp_element = objfactory.build_object();
              resp_element->set_key(\
                inbound_message->get_object(i)->get_key());
              mongo->delete_document(\
                inbound_message->get_object(i)->get_key());
              response_message->add_object(resp_element);
            }

          // Ping
          } else if (inbound_message->get_msg_type() == PING) {
            main_logging->info("Ping Message Recieved");

          // Kill
          } else if (inbound_message->get_msg_type() == KILL) {
            main_logging->info("Shutting Down");
            shutdown_needed = true;

          // Invalid Message Type
          } else {
            response_message->set_error_code(BAD_MSG_TYPE_ERROR);
            new_error_message = "Unknown Message Type";
            response_message->set_error_message(new_error_message);
          }
        // Exception during processing
        } catch (std::exception& e) {
          main_logging->error("Exception encountered during Processing");
          main_logging->error(e.what());
          response_message->set_error_code(PROCESSING_ERROR);
          new_error_message.assign(e.what());
          response_message->set_error_message(new_error_message);
        }
        response_message->set_msg_type(inbound_message->get_msg_type());
      }

      // Convert the response object to a message
      main_logging->debug("Building Response");
      std::string application_response;
      response_message->to_msg_string(application_response);

      // Send the response via ZMQ
      main_logging->info("Sending Response");
      main_logging->info(application_response);
      zmqi->send(application_response);

      // Cleanup
      if (response_message) {
        delete response_message;
        response_message = NULL;
      }
      if (inbound_message) {
        delete inbound_message;
        inbound_message = NULL;
      }

      // If we recieved a shutdown message, then we cleanup and exit
      if (shutdown_needed) {shutdown(); exit(1);}
  }
  return 0;
}
Exemplo n.º 15
0
MStatus preview(const MArgList& args,bool useVertexColor)
{
	//单实例先清除
	if(MaterialSet::getSingletonPtr())
		MaterialSet::getSingletonPtr()->clear();

	char tempPath[MAX_PATH];
	GetTempPath(MAX_PATH, tempPath);
	std::string tempFileName(tempPath);
	ExportOptions::instance().m_outFilePath = tempFileName.c_str();
	tempFileName += "\\";
	tempFileName += _T("maya.mz");

	ExportOptions::instance().m_outFile = tempFileName.c_str();

	ExportOptions::instance().clipList.clear();
	MTime kTimeMin   = MAnimControl::animationStartTime();		//整个场景的起始帧
	MTime kTimeMax   = MAnimControl::animationEndTime();		//整个场景的结束帧

	clipInfo clip;
	clip.name = "Animation";
	clip.startFrame = (int)kTimeMin.value();
	clip.endFrame = (int)kTimeMax.value();
	clip.stepFrame = 1;
	ExportOptions::instance().clipList.push_back(clip);
	ExportOptions::instance().exportAnims = true;
	ExportOptions::instance().exportVertexColour = useVertexColor;

	/*BindPoseTool bindPoseTool;
	bindPoseTool.GoIntoBindPose();*/

	MWriter writer;
	writer.read();
	MStatus status = writer.write();

#ifdef RELEASEDEBUG
#define DLL_NAME "MayaPreview_rd.exe"
#elif _DEBUG
#define DLL_NAME "MayaPreview_d.exe"
#else
#define DLL_NAME "MayaPreview.exe"
#endif

	if(status == MS::kSuccess)
	{
		HWND hWnd = FindWindowEx(0,0,0,"MayaPreview");
		//if(hWnd)
		//{
		//	SendMessage(hWnd,WM_CLOSE,0,0);
		//	hWnd = 0;
		//}
		if(!hWnd)
		{
			static const std::string tMaxProgramName("Maya.exe");
			char path[257];
			GetModuleFileName(GetModuleHandle(tMaxProgramName.c_str()),path,256);
			std::string parentPath(path);
			parentPath.erase(parentPath.size() - tMaxProgramName.size(), tMaxProgramName.size());
			std::string previewProgramPath(parentPath + "preview\\" + DLL_NAME); 
			
			if(!ShellExecute(0,"open",previewProgramPath.c_str(),"","",SW_SHOW))
			{

				MessageBox(0,previewProgramPath.c_str(),"Can't Find MayaPreview Program",0);
				return MS::kFailure;
			}			
			hWnd = FindWindowEx(0,0,0,"MayaPreview");
			DWORD tick = GetTickCount();
			while(!hWnd)
			{
				DWORD tickNow = GetTickCount();
				if(tickNow - tick > 3000)break;
				Sleep(1);
				hWnd = FindWindowEx(0,0,0,"MayaPreview");
			}
		}
		if(hWnd)
		{
			SendMessage(hWnd,WM_USER + 128,0,0);
			SetActiveWindow(hWnd);
			SetForegroundWindow(hWnd);
			BringWindowToTop(hWnd);
		}
	}
	/*bindPoseTool	.UndoGoIntoBindPose();*/

	return MS::kSuccess;
}