Exemple #1
0
bool DataManager::saveMap(Map map) {
    FileUtil util;
    util.addMapping(map);

    bool res = saveDatabaseTimeRecord(map);
    return res;
}
Exemple #2
0
void kill(OSCommandLine *oscommandline, OSnl2OS* nl2OS)
{
    FileUtil *fileUtil = NULL;
    fileUtil = new FileUtil();
    std::string osplOutput = "";
    OSSolverAgent* osagent = NULL;
    try
    {
        if (oscommandline->serviceLocation != "")
        {
            osagent = new OSSolverAgent(oscommandline->serviceLocation);

            if (oscommandline->osol == "")
            {
                // we need to construct the OSoL
                OSOption *osOption = NULL;
                osOption = new OSOption();
                // get a jobId if necessary
                if (oscommandline->jobID == "") throw ErrorClass("there is no JobID");
                //set the jobID
                osOption->setJobID( oscommandline->jobID);
                // now read the osOption object into a string
                OSoLWriter *osolWriter = NULL;
                osolWriter = new OSoLWriter();
                oscommandline->osol = osolWriter->writeOSoL( osOption);
                delete osOption;
                osOption = NULL;
                delete osolWriter;
                osolWriter = NULL;
            }

            osplOutput = osagent->kill(oscommandline->osol);

            if (oscommandline->osplOutputFile != "")
                fileUtil->writeFileFromString(oscommandline->osplOutputFile, osplOutput);
            else
                osoutput->OSPrint(ENUM_OUTPUT_AREA_main, ENUM_OUTPUT_LEVEL_summary, osplOutput);
            delete osagent;
            osagent = NULL;
        }
        else
        {
            delete osagent;
            osagent = NULL;
            throw ErrorClass("please specify service location (url)");
        }
        delete fileUtil;
        fileUtil = NULL;
    }
    catch (const ErrorClass& eclass)
    {
        reportErrors(oscommandline, eclass.errormsg, nl2OS);
        if (osagent != NULL)
            delete osagent;
        osagent = NULL;

        delete fileUtil;
        fileUtil = NULL;
    }
}//end kill
Exemple #3
0
/** Deal with the OSrL output generated by the call to one of the service methods
 */
void reportResults(OSCommandLine *oscommandline, std::string osrl, OSnl2OS* nl2OS)
{
    ostringstream outStr;

    if (oscommandline->osrlFile == "")
        oscommandline->osrlFile = oscommandline->nlFile + ".osrl";
    
    FileUtil* fileUtil = new FileUtil();
    fileUtil->writeFileFromString(oscommandline->osrlFile, osrl);
    
    if (oscommandline->browser != "")
    {
        std::string str = oscommandline->browser + "  "
                          + oscommandline->osrlFile;
        const char *ch = &str[0];
        std::system(ch);
    }

    // now put solution back to ampl

    OSosrl2ampl *solWriter = new OSosrl2ampl();

    try
    {
std::cout << osrl << std::endl << std::endl;
//        fileUtil->writeFileFromString(oscommandline->osrlFile, osrl);
        std::string::size_type pos1 = osrl.find( "error");
        if(pos1 == std::string::npos)
        {
            OSrLReader *osrlreader = new OSrLReader();
            OSResult *osresult = osrlreader->readOSrL( osrl);
            solWriter->writeSolFile(osrl, nl2OS->getASL("asl"), oscommandline->nlFile + ".sol");

            delete osrlreader;
            osrlreader = NULL;
        }
        else // there was an error
        {
            osoutput->OSPrint(ENUM_OUTPUT_AREA_main, ENUM_OUTPUT_LEVEL_error, osrl);
            solWriter->writeSolFile(osrl, nl2OS->getASL("asl"), oscommandline->nlFile + ".sol");
        }
        if (fileUtil != NULL)
            delete fileUtil;
        fileUtil = NULL;
    }
    catch(const ErrorClass& eclass)
    {
        outStr.str("");
        outStr.clear();
        outStr << "There was an error parsing the OSrL string" << endl << eclass.errormsg << endl << endl;
        osoutput->OSPrint(ENUM_OUTPUT_AREA_main, ENUM_OUTPUT_LEVEL_debug, outStr.str());
        if (fileUtil != NULL)
            delete fileUtil;
        fileUtil = NULL;
    }

}// reportResults
Exemple #4
0
void InvertedIndex::load(){
	FileUtil util;

	invertedIndexMap["000"] = util.readNonPositionalInvertedIndex("OUTPUT/inv_index/index.inv.000");
	invertedIndexMap["001"] = util.readNonPositionalInvertedIndex("OUTPUT/inv_index/index.inv.001");
	invertedIndexMap["002"] = util.readNonPositionalInvertedIndex("OUTPUT/inv_index/index.inv.002");
	invertedIndexMap["003"] = util.readNonPositionalInvertedIndex("OUTPUT/inv_index/index.inv.003");
	invertedIndexMap["004"] = util.readNonPositionalInvertedIndex("OUTPUT/inv_index/index.inv.004");

}
int main(int argC, char* argV[])
{
	WindowsErrorPopupBlocker();
	FileUtil *fileUtil = NULL;  
  	const char dirsep =  CoinFindDirSeparator();
	std::string osilFileNameWithPath;
	std::string osilFileName;
	std::string osil;
	std::string uploadResult;
	std::string actualServer;

	/* Replace this URL as needed */
	std::string defaultServer = "http://128.135.130.17:8080/os/servlet/OSFileUpload";

	try{
		if( argC == 1 || argC > 3 || argV[1] == "-?") 
			throw ErrorClass( "usage: OSFileUpload <filename> [<serverURL>]");
		fileUtil = new FileUtil(); 
		time_t start, finish, tmp;
		osilFileNameWithPath = argV[ 1];
		std::cout << "FILE NAME = " << argV[1] << std::endl;
		std::cout << "Read the file into a string" << std::endl; 
		osil = fileUtil->getFileAsString( osilFileNameWithPath.c_str() ); 
		OSSolverAgent* osagent = NULL;
		if (argC == 2)
			actualServer = defaultServer;
		else
			actualServer = argV[2];
		osagent = new OSSolverAgent(actualServer);

		// strip off just the file name
		// modify to into a file C:filename
		int index = osilFileNameWithPath.find_last_of( dirsep);
		int slength = osilFileNameWithPath.size();
		osilFileName = osilFileNameWithPath.substr( index + 1, slength) ;
		std::cout << std::endl << std::endl;
		std::cout << "Place remote synchronous call" << std::endl;

		start = time( &tmp);
		uploadResult = osagent->fileUpload(osilFileName, osil);
		finish = time( &tmp);
		std::cout << "File Upload took (seconds): "<< difftime(finish, start) << std::endl;
		std::cout << uploadResult << std::endl;

		if(fileUtil != NULL) delete fileUtil;
		return 0;
	}
	catch( const ErrorClass& eclass){
		std::cout << eclass.errormsg <<  std::endl;
		if(fileUtil != NULL) delete fileUtil;
		return 0;
	}
}
/**
 * Handle the getLocalPath message.
 */
void MessageHandler::handleFileGetLocalPath(
    WebViewMessage& message)
{
    FileUtil fileUtil;
    MAUtil::String path = fileUtil.getLocalPath();
    if (0 == path.length())
    {
        replyNull(message);
    }
    else
    {
        replyString(message, path);
    }
}
/**
 * Handle the file write message.
 */
void MessageHandler::handleFileWrite(WebViewMessage& message)
{
    FileUtil fileUtil;
    bool success = fileUtil.writeTextToFile(
                       message.getParam("filePath"),
                       message.getParam("data"));
    if (success)
    {
        replyBoolean(message, true);
    }
    else
    {
        replyString(message, false);
    }
}
/**
 * Handle the file read message.
 */
void MessageHandler::handleFileRead(WebViewMessage& message)
{
    FileUtil fileUtil;
    MAUtil::String inText;
    bool success = fileUtil.readTextFromFile(
                       message.getParam("filePath"),
                       inText);
    if (success)
    {
        replyString(message, inText);
    }
    else
    {
        replyNull(message);
    }
}
Exemple #9
0
int main(int argc, char **argv)
{
    WindowsErrorPopupBlocker();
    std::ostringstream outStr;
    OSnl2OS *nl2OS = new OSnl2OS();
    OSiLReader* osilreader = new OSiLReader(); 
    FileUtil *fileUtil = NULL;
    ostringstream echo_cl;

    // initialize the command line structure 

    OSCommandLine *oscommandline;// = new OSCommandLine();
    OSCommandLineReader *oscommandlinereader = new OSCommandLineReader();

    DefaultSolver *solverType  = NULL;
    char* stub = NULL;
    if (argc > 0) stub = argv[1];

    // getting the OSAmplClient_options into a std::string is a bit of a pain...
    char* temp = getenv("OSAmplClient_options");
    ostringstream temp2;
    std::string amplclient_options;
    if (temp != NULL)
    {
        temp2 << temp; 
        amplclient_options = temp2.str();
        std::cout << amplclient_options << std::endl;
    }
    else
//        amplclient_options = "";
        amplclient_options = "serviceMethod retrieve serviceLocation http://74.94.100.129:8080/OSServer/services/OSSolverService printLevel 4 jobID gus-10-apr-2013-0001";

    // this output must be held in abeyance  until the command line
    // has been processed and printLevel has been set...
#ifndef NDEBUG
    echo_cl << "HERE ARE THE AMPLCLIENT OPTIONS ";
    echo_cl << amplclient_options;
    echo_cl << endl << endl;

    echo_cl << "Try to open file ";
    echo_cl << stub << ".nl";
    echo_cl << endl;
#endif

    // Now read the command line
    try
    {
        oscommandline = oscommandlinereader->readCommandLine(amplclient_options);
    }

    catch (const ErrorClass& eclass)
    {
        reportErrors(oscommandline, eclass.errormsg, nl2OS);
        delete oscommandlinereader;
        oscommandlinereader = NULL;
        return 1;
    }

    if (stub) oscommandline->nlFile = stub;


    /** Deal with action items: -printLevel, -logFile, -filePrintLevel, --help, --version **/

    try
    {
        outStr.str("");
        outStr.clear();
        outStr << std::endl << "using print level " << oscommandline->printLevel << " for stdout" << std::endl;

        if (oscommandline->printLevel != DEFAULT_OUTPUT_LEVEL)
        {
            osoutput->SetPrintLevel("stdout", (ENUM_OUTPUT_LEVEL)oscommandline->printLevel);

#ifndef NDEBUG
            osoutput->OSPrint(ENUM_OUTPUT_AREA_main, ENUM_OUTPUT_LEVEL_trace, echo_cl.str());
#endif
            osoutput->OSPrint(ENUM_OUTPUT_AREA_main, ENUM_OUTPUT_LEVEL_info, outStr.str());
        }
#ifndef NDEBUG
        else
        {
            osoutput->OSPrint(ENUM_OUTPUT_AREA_main, ENUM_OUTPUT_LEVEL_trace, echo_cl.str());
            osoutput->OSPrint(ENUM_OUTPUT_AREA_main, ENUM_OUTPUT_LEVEL_debug, outStr.str());            
        }
#endif

        if (oscommandline->logFile != "")
        {
            int status = osoutput->AddChannel(oscommandline->logFile);
 
            switch(status)
            {
                case 0:
                    osoutput->OSPrint(ENUM_OUTPUT_AREA_main, ENUM_OUTPUT_LEVEL_info,
                        "Added channel " + oscommandline->logFile);
                    break;          
                case 1:
                    osoutput->OSPrint(ENUM_OUTPUT_AREA_main, ENUM_OUTPUT_LEVEL_info,
                        "Output channel " + oscommandline->logFile + " previously defined");
                    break;
                default:
                    throw ErrorClass("Could not add output channel " + oscommandline->logFile);
            }//end switch
            

            outStr.str("");
            outStr.clear();
            outStr << std::endl << "using print level " << oscommandline->filePrintLevel;
            outStr << " for " << oscommandline->logFile << std::endl;

            if (oscommandline->filePrintLevel != DEFAULT_OUTPUT_LEVEL)
            {
                osoutput->SetPrintLevel(oscommandline->logFile, (ENUM_OUTPUT_LEVEL)oscommandline->filePrintLevel);
            }
            else
            {
                osoutput->OSPrint(ENUM_OUTPUT_AREA_main, ENUM_OUTPUT_LEVEL_debug, outStr.str());            
            }
        }

        if (oscommandline->invokeHelp == true)
        {
            outStr.str("");
            outStr.clear();
            outStr << std::endl << std::endl << get_help() << std::endl;
            osoutput->OSPrint(ENUM_OUTPUT_AREA_main, ENUM_OUTPUT_LEVEL_always, outStr.str());

            delete oscommandlinereader;
            oscommandlinereader = NULL;
            return 0;
        }

        if (oscommandline->writeVersion == true)
        {
            outStr.str("");
            outStr.clear();
            outStr << std::endl << std::endl << OSgetVersionInfo() << std::endl;
            osoutput->OSPrint(ENUM_OUTPUT_AREA_main, ENUM_OUTPUT_LEVEL_always, outStr.str());

            delete oscommandlinereader;
            oscommandlinereader = NULL;
            return 0;
        }
    }
    catch (const ErrorClass& eclass)
    {
        reportErrors(oscommandline, eclass.errormsg, nl2OS);
        delete oscommandlinereader;
        oscommandlinereader = NULL;
        return 1;
    }

#ifndef NDEBUG
    outStr.str("");
    outStr.clear();
    
    outStr << "HERE ARE THE OPTION VALUES:" << endl;
    if(oscommandline->configFile != "") outStr << "Config file = " << oscommandline->configFile << endl;
    if(oscommandline->osilFile != "") outStr << "OSiL file = " << oscommandline->osilFile << endl;
    if(oscommandline->osolFile != "") outStr << "OSoL file = " << oscommandline->osolFile << endl;
    if(oscommandline->osrlFile != "") outStr << "OSrL file = " << oscommandline->osrlFile << endl;
    //if(oscommandline->insListFile != "") outStr << "Instruction List file = " << oscommandline->insListFile << endl;
    if(oscommandline->osplInputFile != "") outStr << "OSpL Input file = " << oscommandline->osplInputFile << endl;
    if(oscommandline->serviceMethod != "") outStr << "Service Method = " << oscommandline->serviceMethod << endl;
    if(oscommandline->mpsFile != "") outStr << "MPS File Name = " << oscommandline->mpsFile << endl;
    if(oscommandline->nlFile != "") outStr << "NL File Name = " << oscommandline->nlFile << endl;
    if(oscommandline->gamsControlFile != "") outStr << "gams Control File Name = " << oscommandline->gamsControlFile << endl;
    if(oscommandline->browser != "") outStr << "Browser Value = " << oscommandline->browser << endl;
    if(oscommandline->solverName != "") outStr << "Selected Solver = " << oscommandline->solverName << endl;
    if(oscommandline->serviceLocation != "") outStr << "Service Location = " << oscommandline->serviceLocation << endl;
    if(oscommandline->jobID != "") outStr << "Job ID = " << oscommandline->jobID << endl;
    if(oscommandline->printModel) outStr << "print model prior to solve/send" << endl;
    if(oscommandline->printRowNumberAsString != "") outStr << "print model row " << oscommandline->printRowNumberAsString << " prior to solve/send" << endl;
    outStr << "print level for stdout: " << oscommandline->printLevel << endl;
    if(oscommandline->logFile != "") 
    {
        outStr << "also send output to " << oscommandline->logFile << endl;
        outStr << "print level for file output: " << oscommandline->filePrintLevel << endl;
    }

    osoutput->OSPrint(ENUM_OUTPUT_AREA_main, ENUM_OUTPUT_LEVEL_debug, outStr.str());
#endif


    //convert solver name to lower case so there is no ambiguity
    unsigned int k;
    for (k = 0; k < oscommandline->solverName.length(); k++)
    {
        oscommandline->solverName[k] = (char)tolower(oscommandline->solverName[k]);
    }

    // now call the correct serviceMethod
    // solve is the default
    if (oscommandline->serviceMethod == "") oscommandline->serviceMethod = "solve";

    try
    {
        // for local use only the solve method is available
        if (oscommandline->serviceLocation == "")
            if (oscommandline->serviceMethod != "solve") 
                throw ErrorClass("No serviceLocation given. Only \'solve\' is available locally.");

        if (oscommandline->serviceMethod[0] == 's')
        {
            // for solve or send commands we must have an instance
            if (oscommandline->osil == "")
            {
                if (!findInstance(oscommandline, nl2OS))
                    throw ErrorClass("No instance could be found");
            }

            // write out the model or portion thereof, if directed by the user
            if (oscommandline->printModel == true)
            {
                if (oscommandline->osinstance == NULL)
                {
                    oscommandline->osinstance = osilreader->readOSiL(oscommandline->osil);
                }
                osoutput->OSPrint(ENUM_OUTPUT_AREA_main, ENUM_OUTPUT_LEVEL_always, 
                    oscommandline->osinstance->printModel());
            }
            else if (oscommandline->printRowNumberAsString != "")
            {
                if (oscommandline->osinstance == NULL)
                {
                    oscommandline->osinstance = osilreader->readOSiL(oscommandline->osil);
                }
                doPrintRow(oscommandline->osinstance, oscommandline->printRowNumberAsString);
            }

            // write the instance to an OSiL file, if directed by the user
            if (oscommandline->osilOutputFile != "")
            {
                fileUtil = new FileUtil();
                if (oscommandline->osil == "")
                {
                    OSiLWriter* osilwriter = new OSiLWriter(); 
                    oscommandline->osil = osilwriter->writeOSiL(oscommandline->osinstance);
                    delete osilwriter;
                    osilwriter = NULL;
                }
                fileUtil->writeFileFromString(oscommandline->osilOutputFile, oscommandline->osil);
                delete fileUtil;
                fileUtil = NULL;
            }

            // write the solver options to an OSoL file, if directed by the user
            if (oscommandline->osolOutputFile != "")
            {
                fileUtil = new FileUtil();
                if (oscommandline->osol != "" && oscommandline->osoption == NULL)
                    fileUtil->writeFileFromString(oscommandline->osolOutputFile, oscommandline->osol);
                else
                {
                    if (oscommandline->osoption == NULL)
                        oscommandline->osoption = new OSOption();
                    OSoLWriter* osolwriter = new OSoLWriter(); 
                    fileUtil->writeFileFromString(oscommandline->osolOutputFile, 
                        osolwriter->writeOSoL(oscommandline->osoption));
                    delete osolwriter;
                    osolwriter = NULL;
                }
                delete fileUtil;
                fileUtil = NULL;
            }

            // if no serviceLocation was given, do a local solve
            if (oscommandline->serviceLocation == "")
            {
                std::string osrl;
                if (oscommandline->osinstance != NULL)
                    if (oscommandline->osoption != NULL)
                        osrl = runSolver(oscommandline->solverName, oscommandline->osoption, oscommandline->osinstance);
                    else
                        osrl = runSolver(oscommandline->solverName, oscommandline->osol,     oscommandline->osinstance);
                else
                    if (oscommandline->osoption != NULL)
                        osrl = runSolver(oscommandline->solverName, oscommandline->osoption, oscommandline->osil);
                    else
                        osrl = runSolver(oscommandline->solverName, oscommandline->osol,     oscommandline->osil);
                reportResults(oscommandline, osrl, nl2OS);
            }
    
            // remote solve or send
            else
            {
                if (oscommandline->serviceMethod[1] == 'e')
                    send(oscommandline, nl2OS);
                else
                    solve(oscommandline, nl2OS);
            }
        }

        else //call one of the other methods
        {
            switch (oscommandline->serviceMethod[0])
            {
            case 'g':
                getJobID(oscommandline, nl2OS);
                break;
            case 'r':
                retrieve(oscommandline, nl2OS);
                break;
            case 'k':
                if (oscommandline->serviceMethod[1] == 'i')
                    kill(oscommandline, nl2OS);
                else
                    knock(oscommandline, nl2OS);
                break;
            default:
                break;
            }
        }

        // garbage collection
        if (osilreader != NULL)
            delete osilreader;
            oscommandline->osinstance = NULL;
        osilreader = NULL;
        delete oscommandlinereader;
        oscommandlinereader = NULL;
        delete fileUtil;
        fileUtil = NULL;

        if (nl2OS != NULL)
            delete nl2OS;
        nl2OS = NULL;

        return 0;
    }

    catch (const ErrorClass& eclass)
    {
        reportErrors(oscommandline, eclass.errormsg, nl2OS);
        if (osilreader != NULL)
            delete osilreader;
            oscommandline->osinstance = NULL;
        osilreader = NULL;
        delete oscommandlinereader;
        oscommandlinereader = NULL;
        delete fileUtil;
        fileUtil = NULL;

        if (nl2OS != NULL)
            delete nl2OS;
        nl2OS = NULL;
        return 1;
    }
}// end of main()
bool callServiceMethod(OSCommandLine* oscommandline)
{
	FileUtil *fileUtil = new FileUtil();
	try
    {
		bool result;
		OSServiceMethods *osservicemethods;
		osservicemethods = new OSServiceMethods(oscommandline);

		if (oscommandline->printModel) 
			oscommandline->osinstance->printModel();
		if (oscommandline->printRowNumberAsString != "")
			oscommandline->osinstance->printModel(atoi((oscommandline->printRowNumberAsString).c_str()));

		result = osservicemethods->executeServiceMethod(oscommandline);

		// deal with the output
		if (result == false) 
			throw ErrorClass(osservicemethods->resultString);
		else
		{
			if (oscommandline->serviceMethod == "getJobID")
			{
				std::cout << "The job ID generated by the system is:" << std::endl << std::endl;
				std::cout << osservicemethods->resultString << std::endl << std::endl;
				std::cout << "Be sure to make a record of this job ID for later." << std::endl;
				std::cout << "You will need it to retrieve the job or inquire into its status." << std::endl;
			}
			else if (oscommandline->serviceMethod == "solve" || oscommandline->serviceMethod == "retrieve")
			{
		        if (oscommandline->osrlFile != "")
				{
		            fileUtil->writeFileFromString(oscommandline->osrlFile, osservicemethods->resultString);
					if (oscommandline->browser != "")
					{
			            std::string str = oscommandline->browser + "  "
					                      + oscommandline->osrlFile;
		                const char *ch = &str[0];
				        std::system(ch);
		            }
                    std::cout <<  "\nSolve command executed. Please see " << oscommandline->osrlFile  << " for results." << std::endl;
				}
		        else
				{
		            std::cout << osservicemethods->resultString << std::endl;
				}
			}
			else if (oscommandline->serviceMethod == "kill" || oscommandline->serviceMethod == "knock")
			{
		        if (oscommandline->osplOutputFile != "")
				{
		            fileUtil->writeFileFromString(oscommandline->osplOutputFile, osservicemethods->resultString);
				}
		        else
				{
		            std::cout << osservicemethods->resultString << std::endl;
				}
			}
		}
		return 0;
    }
    catch (const ErrorClass& eclass)
    {
        OSResult *osresult = NULL;
        OSrLWriter *osrlwriter = NULL;
        osrlwriter = new OSrLWriter();
        osresult = new OSResult();
        osresult->setGeneralMessage(eclass.errormsg);
        osresult->setGeneralStatusType("error");
        std::string osrl = osrlwriter->writeOSrL(osresult);
        if (oscommandline->osrlFile != "")
        {
            fileUtil->writeFileFromString(oscommandline->osrlFile, osrl);
            if (oscommandline->browser != "")
            {
                std::string str = oscommandline->browser + "  "
                                  + oscommandline->osrlFile;
                const char *ch = &str[0];
                std::system(ch);
            }
        }
        else
        {
            std::cout << osrl << std::endl;
        }
        //catch garbage collection
        delete osresult;
        osresult = NULL;
        delete osrlwriter;
        osrlwriter = NULL;

        delete oscommandline;
        oscommandline = NULL;
        delete fileUtil;
        fileUtil = NULL;
        return 1;
    }
}
int main(int argc, char **argv)
{
    WindowsErrorPopupBlocker();
    char *stub;
    // set AMPL structures
    ASL *asl;
    asl = ASL_alloc(ASL_read_fg);
    stub = argv[1];
    jac0dim((char*)stub, (fint)strlen(stub));
    OSnl2osil *nl2osil = NULL;

    std::ostringstream outStr;
	std::cout << OSAmplClientVersionInfo();
	std::string osss;

	outStr << stub << " " << getenv("OSAmplClient_options");
    osss = outStr.str();

#ifdef DEBUG_AMPL_CLIENT
    std::cout << "Input String = " << osss << std::endl;
#endif

	FileUtil *fileUtil = NULL;
	OSCommandLine *oscommandline;
	oscommandline = new OSCommandLine();
	OSCommandLineReader *clreader;
	clreader = new OSCommandLineReader();

	//parse the command line items into a CommandLine object
    try
    {		
		oscommandline = clreader->readCommandLine(osss);
		if (oscommandline->serviceMethod == "")
			oscommandline->serviceMethod = "solve";
		oscommandline->convertSolverNametoLowerCase();

	}
    catch (const ErrorClass& eclass)
    {
        OSResult *osresult = NULL;
        osresult = new OSResult();
        osresult->setGeneralMessage(eclass.errormsg);
        osresult->setGeneralStatusType("error");
        OSrLWriter *osrlwriter = NULL;
        osrlwriter = new OSrLWriter();
        std::string osrl = osrlwriter->writeOSrL(osresult);
        if (oscommandline->osrlFile != "")
        {
            fileUtil->writeFileFromString(oscommandline->osrlFile, osrl);
            if (oscommandline->browser != "")
            {
                std::string str = oscommandline->browser + "  "
                                  + oscommandline->osrlFile;
                const char *ch = &str[0];
                std::system(ch);
            }
        }
        else
        {
            std::cout << osrl << std::endl;
        }
        //catch garbage collection
        delete osresult;
        osresult = NULL;
        delete osrlwriter;
        osrlwriter = NULL;
        delete fileUtil;
        fileUtil = NULL;
        delete oscommandline;
        oscommandline = NULL;
        delete clreader;
        clreader = NULL;
        return 1;
    }

#ifdef DEBUG_AMPL_CLIENT
	std::cout << oscommandline->list_options() << std::endl;
#endif

	// deal with "action items": help, quit, listOptions
	if (oscommandline->quit || oscommandline->invokeHelp || oscommandline->writeVersion || oscommandline->listOptions)
	{
		if (oscommandline->invokeHelp) 
			std::cout << std::endl << std::endl << get_AmplClient_help() << std::endl;
		if (oscommandline->listOptions) 
			std::cout << std::endl << std::endl << oscommandline->list_options() << std::endl;
        delete oscommandline;
        oscommandline = NULL;
        return 0;
	}

	// call service method
	bool result = callServiceMethod(oscommandline);
	if (result == true)
		return 0;
	else
		return 1;
}
Exemple #12
0
void knock(OSCommandLine *oscommandline, OSnl2OS* nl2OS)
{
    std::string osplOutput = "";
    OSSolverAgent* osagent = NULL;
    FileUtil *fileUtil = NULL;
    fileUtil = new FileUtil();
    try
    {
        if (oscommandline->serviceLocation != "")
        {
            osagent = new OSSolverAgent(oscommandline->serviceLocation);

            // if no OSpL file was given, make a default one
            if (oscommandline->osplInput == "")
            {
                std::ostringstream temp;
                temp << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" << 
                    "<ospl xmlns=\"os.optimizationservices.org\"\n" <<
                    "        xmlns:xs=\"http://www.w3.org/2001/XMLSchema\"\n" <<
                    "        xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n" <<
                    "        xsi:schemaLocation=\"os.optimizationservices.org\n" <<
                    "        http://www.optimizationservices.org/schemas/OSpL.xsd\">\n"<<
                    "     <processHeader>\n" <<
                    "          <request action=\"getAll\"/>\n" <<
                    "     </processHeader>\n" <<
                    "     <processData/>\n" <<
                    "</ospl>\n";              
                oscommandline->osplInput = temp.str();
           }

            // if a jobID was given on the command line, use it
            if(oscommandline->jobID != "") 
            {
                OSOption *osOption = NULL;
                if (oscommandline->osol == "")
                {
                    osOption = new OSOption();
                }
                else
                {
                    OSoLReader *osolReader = new OSoLReader();
                    try
                    {
                        osOption = osolReader->readOSoL(oscommandline->osol);
                        delete osolReader;
                        osolReader = NULL;
                    }
                    catch (const ErrorClass& eclass)
                    {
                        if (osolReader != NULL) delete osolReader;
                        osolReader = NULL;
                        throw ErrorClass(eclass.errormsg);
                    }
                }
                osOption->setJobID( oscommandline->jobID);
                OSoLWriter *osolWriter = new OSoLWriter();
                oscommandline->osol = osolWriter->writeOSoL( osOption);
                delete osOption;
                osOption = NULL;
                delete osolWriter;
                osolWriter = NULL;
            }

            osplOutput = osagent->knock(oscommandline->osplInput, oscommandline->osol);
            if (oscommandline->osplOutputFile != "")
                fileUtil->writeFileFromString(oscommandline->osplOutputFile,
                                              osplOutput);
            else
                osoutput->OSPrint(ENUM_OUTPUT_AREA_main, ENUM_OUTPUT_LEVEL_error, osplOutput);
            delete osagent;
        }
        else
        {
            delete osagent;
            throw ErrorClass("please specify service location (url)");
        }
        delete fileUtil;
        fileUtil = NULL;
    }
    catch (const ErrorClass& eclass)
    {
         reportErrors(oscommandline, eclass.errormsg, nl2OS);
        if (osagent != NULL)
            delete osagent;
        osagent = NULL;

        delete fileUtil;
        fileUtil = NULL;
    }
}//end knock
Exemple #13
0
int main( ){
	WindowsErrorPopupBlocker();
// test OS code samples here
	FileUtil *fileUtil = NULL; 
	fileUtil = new FileUtil();
	const char dirsep =  CoinFindDirSeparator();
 	// Set directory containing mps data files.
 	std::string dataDir;
   dataDir = dirsep == '/' ? "../data/" : "..\\data\\";
	cout << "Start Building the Model" << endl;
	try{
		// get the p0033 problem
		std::string osilFileName;
		osilFileName =  dataDir  +   "p0033.osil";
		std::cout << "Try to read a sample file" << std::endl;
		std::cout << "The file is: " ;
		std::cout <<  osilFileName << std::endl;
		std::string osil = fileUtil->getFileAsString( osilFileName.c_str() );
		OSiLReader *osilreader = NULL;
		osilreader = new OSiLReader(); 
		OSInstance *osinstance;
		osinstance = osilreader->readOSiL( osil);
		// done writing the model
		cout << "Done writing the Model" << endl;
		// now solve the model
		CoinSolver *solver  = NULL;
		solver = new CoinSolver();  
		solver->sSolverName ="cbc"; 
		solver->osinstance = osinstance;
		solver->buildSolverInstance();
		solver->osiSolver->setHintParam(OsiDoReducePrint, true, OsiHintTry);
		solver->osiSolver->initialSolve();
		cout << "Here is the initial objective value "  << solver->osiSolver->getObjValue()  << endl;
		
		CglKnapsackCover cover;
	    CglSimpleRounding round;  
		CglGomory gomory;
		CbcModel *model = new CbcModel( *solver->osiSolver);

		//model->setBestObjectiveValue(4000);
		model->setMaximumNodes(100000);
		//
		model->addCutGenerator(&gomory, 1, "Gomory");
		model->addCutGenerator(&cover, 1, "Cover");
		model->addCutGenerator(&round, 1, "Round");
		model->branchAndBound();	
		// now create a result object
		OSResult *osresult = new OSResult();
		// if we are throw an exception if the problem is nonlinear
		double *x = NULL;
		double *y = NULL;
		double *z = NULL;
		//int i = 0;
		std::string *rcost = NULL;
		// resultHeader infomration
		if(osresult->setServiceName("Solved with Coin Solver: " + solver->sSolverName) != true)
			throw ErrorClass("OSResult error: setServiceName");
		if(osresult->setInstanceName(  solver->osinstance->getInstanceName()) != true)
			throw ErrorClass("OSResult error: setInstanceName");
		if(osresult->setVariableNumber( solver->osinstance->getVariableNumber()) != true)
			throw ErrorClass("OSResult error: setVariableNumer");
		if(osresult->setObjectiveNumber( 1) != true)
			throw ErrorClass("OSResult error: setObjectiveNumber");
		if(osresult->setConstraintNumber( solver->osinstance->getConstraintNumber()) != true)
			throw ErrorClass("OSResult error: setConstraintNumber");
		if(osresult->setSolutionNumber(  1) != true)
			throw ErrorClass("OSResult error: setSolutionNumer");	
		int solIdx = 0;
		std::string description = "";
		osresult->setGeneralStatusType("success");
		std::cout << "PROVEN OPTIMAL " << model->isProvenOptimal() << std::endl;
		int i;
		if (model->isProvenOptimal() == 1){
			osresult->setSolutionStatus(solIdx, "optimal", description);
			/* Retrieve the solution */
			x = new double[solver->osinstance->getVariableNumber() ];
			y = new double[solver->osinstance->getConstraintNumber() ];
			z = new double[1];
			rcost = new std::string[ solver->osinstance->getVariableNumber()];
			//
			*(z + 0)  =  model->getObjValue();
			osresult->setObjectiveValuesDense(solIdx, z);
			for(i=0; i < solver->osinstance->getVariableNumber(); i++){
				*(x + i) = model->getColSolution()[i];
			}
			osresult->setPrimalVariableValuesDense(solIdx, x );
			//if( solver->sSolverName.find( "symphony") == std::string::npos){
			for(i=0; i <  solver->osinstance->getConstraintNumber(); i++){
				*(y + i) = model->getRowPrice()[ i];
			}
			osresult->setDualVariableValuesDense(solIdx, y);
			//
			// now put the reduced costs into the osrl
			int numberOfOtherVariableResult = 1;
			int otherIdx = 0;
			// first set the number of Other Variable Results
			osresult->setNumberOfOtherVariableResults(solIdx, numberOfOtherVariableResult);
			
			std::ostringstream outStr;
			int numberOfVar =  solver->osinstance->getVariableNumber();
			for(i=0; i < numberOfVar; i++){
				outStr << model->getReducedCost()[ i]; 
				rcost[ i] = outStr.str();
				outStr.str("");
			}
			osresult->setAnOtherVariableResultDense(solIdx, otherIdx, "reduced costs", "", "the variable reduced costs",  
				rcost);			
			// end of settiing reduced costs			
		}
		else{ 
			if(solver->osiSolver->isProvenPrimalInfeasible() == true) 
				osresult->setSolutionStatus(solIdx, "infeasible", description);
			else
				if(solver->osiSolver->isProvenDualInfeasible() == true) 
					osresult->setSolutionStatus(solIdx, "dualinfeasible", description);
				else
					osresult->setSolutionStatus(solIdx, "other", description);
		}
		OSrLWriter *osrlwriter = new OSrLWriter();
		std::cout <<  osrlwriter->writeOSrL( osresult) << std::endl;
		if(solver->osinstance->getVariableNumber() > 0){
			delete[] x;
			x = NULL;
		}
		if(solver->osinstance->getConstraintNumber()) delete[] y;
		y = NULL;
		delete[] z;	
		z = NULL;
		if(solver->osinstance->getVariableNumber() > 0){
			delete[] rcost;
			rcost = NULL;
		}
    	// do garbage collection
		delete osresult;
		osresult = NULL;
		delete osrlwriter;
		osrlwriter = NULL;
		delete solver;
		solver = NULL;
		delete osilreader;
		osilreader = NULL;
		delete fileUtil;
		fileUtil  = NULL;
		delete model;
		model = NULL;
		cout << "Done with garbage collection" << endl;
		return 0;
	}
	catch(const ErrorClass& eclass){
		delete fileUtil;
		std::cout << eclass.errormsg <<  std::endl;
		return 0;
	} 
}// end main
int run()
{
    int sockfd, new_fd;  // listen on sock_fd, new connection on new_fd
    struct addrinfo hints, *servinfo, *p;
    struct sockaddr_storage their_addr; // connector's address information
    socklen_t sin_size;
    struct sigaction sa;
    int yes=1;
    char s[INET6_ADDRSTRLEN];
    int rv,numbytes;
    char inputBuffer[400];
    CommandLine cl;
    FileUtil util;


    memset(&hints, 0, sizeof hints);
    hints.ai_family = AF_UNSPEC;
    hints.ai_socktype = SOCK_STREAM;
    hints.ai_flags = AI_PASSIVE; // use my IP

    if ((rv = getaddrinfo(NULL, PORT, &hints, &servinfo)) != 0) {
        fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(rv));
        return 1;
    }

    // loop through all the results and bind to the first we can
    for(p = servinfo; p != NULL; p = p->ai_next) {
        if ((sockfd = socket(p->ai_family, p->ai_socktype,
                p->ai_protocol)) == -1) {
            perror("server: socket");
            continue;
        }

        if (setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, &yes,
                sizeof(int)) == -1) {
            perror("setsockopt");
            exit(1);
        }

        if (bind(sockfd, p->ai_addr, p->ai_addrlen) == -1) {
            close(sockfd);
            perror("server: bind");
            continue;
        }

        break;
    }

    if (p == NULL)  {
        fprintf(stderr, "server: failed to bind\n");
        return 2;
    }

    freeaddrinfo(servinfo); // all done with this structure

    if (listen(sockfd, BACKLOG) == -1) {
        perror("listen");
        exit(1);
    }

    sa.sa_handler = sigchld_handler; // reap all dead processes
    sigemptyset(&sa.sa_mask);
    sa.sa_flags = SA_RESTART;
    if (sigaction(SIGCHLD, &sa, NULL) == -1) {
        perror("sigaction");
        exit(1);
    }

    printf("server: waiting for connections...\n");

    while(1) {  // main accept() loop
        sin_size = sizeof their_addr;
        new_fd = accept(sockfd, (struct sockaddr *)&their_addr, &sin_size);
        if (new_fd == -1) {
            perror("accept");
            continue;
        }
        //


        numbytes = recv(new_fd, inputBuffer, sizeof inputBuffer, 0);
        inputBuffer[numbytes] = '\0';
        std::string inpbf(inputBuffer);

        //printf("input received:%d  and %s \n",numbytes,inputBuffer);
        //printf("input is:%s \n",inputBuffer[0]);

        std::string inputdata=" ";

        //cout<<"input:"<<inpbf<<endl;

        string::const_iterator start, end;
        boost::match_results<std::string::const_iterator> what;
        boost::match_flag_type flags = boost::match_default;

        //get input from incoming request here
        regex expr_ref("(GET)(\\s+)(\\/)(query=)(.*?)(\\s+)");
        	start = inpbf.begin();
        	end = inpbf.end();
        	while (boost::regex_search(start, end, what, expr_ref, flags)) {
        		inputdata = what[5];
        		break;
        	}

       cout<<"input:"<<inputdata<<endl;

        //input fetch code ends

        inet_ntop(their_addr.ss_family,
            get_in_addr((struct sockaddr *)&their_addr),
            s, sizeof s);
        printf("server: got connection from %s\n", s);
        std::string op;
        std::string response;
        list<size_t> qresp;
        if(inputdata.length()>0){
        	qresp = cl.runQueryWeb(inputdata);
        	response = "data";
        }else{
        	response = "empty";
        }


        std::string html_inner_content;
        std::string html_end_content;

        std::string title = "this is title";
        std::string link = "file path is here";
        std::string description = "description should have come here";

        std::string css = "<style type=\"text/css\">ol,ul,li{border:0;margin:0;padding:0}h3,.med{font-size:medium;font-weight:400}body{color:#222}li.head,li.g,body,html,.std,.c h2,#mbEnd h2,h1{font-size:small;font-family:arial,sans-serif}li.g{margin-top:0;margin-bottom:20px}ol li{list-style:none}li{line-height:1.2}#res h3.r{display:block;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.vsc{display:inline-block;position:relative;width:100%}#ires h3,#res h3,#tads h3,#tadsb h3,#mbEnd h3{font-size:medium}.sl,.r{display:inline;font-weight:400;margin:0}.s{max-width:42em;color:#222}div{display:block}.kv,.kvs{display:block;margin-bottom:2px}.f,.f a:link,.m,.c h2,#mbEnd h2,#tads h2,#tadsb h2,#tadsto h2,.descbox{color:#666}.st,.ac{line-height:1.24}.a,cite,cite a:link,cite a:visited,.cite,.cite:link,#mbEnd cite b,#tads cite b,#tadsb cite b,#tadsto cite b,#ans > i,.bc a:link{color:#093;font-style:normal}a:link,.w,.q:active,.q:visited,.tbotu{color:#12C;cursor:pointer}</style>";


        vector<std::string> outputList;
        op="<html><head><title>Falcon Search Engine</title>" + css + "</head><body><h2>Falcon Search Engine - Team Mango</h2><form name=\"input\" action=\"http://localhost:8888\" method=\"post\" id=\"input\">Query: <input type=\"text\" id=\"queryId\" name=\"query\" value=\"query here\" /><input type=\"submit\" value=\"Submit\" /></form><ol>";


        BOOST_FOREACH(size_t t, qresp){

            html_inner_content="<li class=\"g\"><div class=\"vsc\"><h3 class=\"r\"><a href=\"#\">" + util.getStringValue(t) + "</a></h3><div class=\"s\"><div class=\"f kv\"><cite>" + cl.tutil.fileMap[util.getStringValue(t)] + "</cite></div><span class=\"st\">" + description + "</span></div></div></li>";
            op = op + html_inner_content;

        }

        op = op+ "</ol></body></html>";

        if (!fork()) { // this is the child process
            close(sockfd); // child doesn't need the listener
            if (send(new_fd,op.c_str() , op.length(), 0) == -1)
                perror("send");
            close(new_fd);
            exit(0);
        }
        close(new_fd);  // parent doesn't need this
    }
OSServiceMethods::OSServiceMethods(OSCommandLine *oscommandline): resultString("") 
{
#ifdef DEBUG_OSSERVICEMETHODS
    cout << "Inside the OSServiceMethods Constructor" << endl;
#endif

    FileUtil   *fileUtil   = NULL;
	OSiLReader *osilreader = NULL;
	OSoLReader *osolreader = NULL;
	OSiLWriter *osilwriter = NULL;
	OSoLWriter *osolwriter = NULL;
	OSmps2osil *mps2osil   = NULL;

#ifdef COIN_HAS_ASL
//    OSnl2os *nl2os = NULL;
    OSnl2osil *nl2osil = NULL;
#endif

#ifdef COIN_HAS_GAMSUTILS
    OSgams2os *gams2os = NULL;
#endif

    try
	{
	    fileUtil = new FileUtil();

		/** Prepare the OSInstance and OSOption objects if needed.
		 *  The objects are needed if
		 *  1. any output is based on the instance ((i.e, printModel, 
		 *     printRow or osilOutputFile is specified) OR
		 *  2. a solve/send command is based on input other than OSiL format
		 */
		if ( (oscommandline->printModel || oscommandline->printRowNumberAsString != "" || oscommandline->osilOutputFile != "") ||
			((oscommandline->serviceMethod[0] = 's') && (oscommandline->osilFile == "")))
		{
		/** Search for an instance in the following order
		 *  1. osil file
		 *  2. non-proprietary formats (only MPS for now)
		 *  3. proprietary formats (AMPL nl, GAMS dat, etc.)
		 */
			if (oscommandline->osilFile != "") 
			{
				osilreader = new OSiLReader();			
	            oscommandline->osil = fileUtil->getFileAsString(
                                  (oscommandline->osilFile).c_str());
				oscommandline->osinstance = osilreader->readOSiL(oscommandline->osil);
				if (oscommandline->osolFile != "") 
				{
		            oscommandline->osol = fileUtil->getFileAsString(
			                      (oscommandline->osolFile).c_str());
					osolreader = new OSoLReader();			
					oscommandline->osoption = osolreader->readOSoL(oscommandline->osol);
				}
			}
		    else if (oscommandline->mpsFile != "") 
			{
                mps2osil = new OSmps2osil(oscommandline->mpsFile);
                mps2osil->createOSInstance();
                oscommandline->osinstance = mps2osil->osinstance;
				if (oscommandline->osolFile != "") 
				{
		            oscommandline->osol = fileUtil->getFileAsString(
			                      (oscommandline->osolFile).c_str());
					osolreader = new OSoLReader();			
					oscommandline->osoption = osolreader->readOSoL(oscommandline->osol);
				}
			}
		    else if (oscommandline->nlFile != "")
			{
#ifdef COIN_HAS_ASL
//                nl2os = new OSnl2os(oscommandline);
//                nl2os->createOSObjects();
//                osinstance = nl2os->osinstance;
//                osoption   = nl2os->osoption;
                nl2osil = new OSnl2osil(oscommandline->nlFile);
                nl2osil->createOSInstance();
                oscommandline->osinstance = nl2osil->osinstance;
#else
                throw ErrorClass(
                    "nl file specified locally but ASL not present");
#endif
			}
		    else if (oscommandline->gamsControlFile != "")
			{
#ifdef COIN_HAS_GAMSUTILS
                gams2os = new OSgams2os(oscommandline);
                gams2os->createOSObjects();
                osinstance = gams2os->osinstance;
                osoption   = gams2os->osoption;
#else
                throw ErrorClass(
                    "a Gams Control specified locally but GAMSIP not present");
#endif
			}
			else
			{
				if (oscommandline->osolFile != "" && oscommandline->serviceLocation != "") 
				{
		            oscommandline->osol = fileUtil->getFileAsString(
                                  (oscommandline->osolFile).c_str());
					osolreader = new OSoLReader();			
					oscommandline->osoption = osolreader->readOSoL(oscommandline->osol);
					if (oscommandline->solverName != "")
						oscommandline->osoption->setSolverToInvoke(oscommandline->solverName);
				}
                if (oscommandline->osol.find( "<instanceLocation") == std::string::npos)
                    throw ErrorClass(
                        "Error: no optimization instance found");
			}

			// Make sure the solver name is recorded properly
			if (oscommandline->solverName != "") 
			{	
				if (oscommandline->osol == "" && oscommandline->osolFile != "") 
		            oscommandline->osol = fileUtil->getFileAsString(
                                  (oscommandline->osolFile).c_str());
				oscommandline->osoption->setSolverToInvoke(oscommandline->solverName);
			}	

			// convert OS objects to strings if necessary
			if (oscommandline->serviceLocation != "" && oscommandline->osil == "") 
			{	
				osilwriter= new OSiLWriter();
				oscommandline->osil = osilwriter->writeOSiL(oscommandline->osinstance);
			}	
			if (oscommandline->serviceLocation != "" && oscommandline->osoption != NULL) 
			{	
				osolwriter= new OSoLWriter();
				oscommandline->osol = osolwriter->writeOSoL(oscommandline->osoption);
			}	
		}

		// cleanup
	    if (fileUtil != NULL) delete fileUtil;
		fileUtil = NULL;
	    if (osilreader != NULL) delete osilreader;
		osilreader = NULL;
	    if (osolreader != NULL) delete osolreader;
		osolreader = NULL;
	    if (osilwriter != NULL) delete osilwriter;
		osilwriter = NULL;
	    if (osolwriter != NULL) delete osolwriter;
		osolwriter = NULL;
	    if (mps2osil != NULL) delete mps2osil;
		mps2osil = NULL;

#ifdef COIN_HAS_ASL
//	    if (nl2os != NULL) delete nl2os;
//	    nl2os = NULL;
	    if (nl2osil != NULL) delete nl2osil;
	    nl2osil = NULL;
#endif

#ifdef COIN_HAS_GAMSUTILS
	    if (gams2os != NULL) delete gams2os;
		gams2os = NULL;
#endif
	}
	catch(const ErrorClass& eclass)
	{
	    if (fileUtil != NULL) delete fileUtil;
		fileUtil = NULL;
	    if (osilreader != NULL) delete osilreader;
		osilreader = NULL;
	    if (osolreader != NULL) delete osolreader;
		osolreader = NULL;
	    if (osilwriter != NULL) delete osilwriter;
		osilwriter = NULL;
	    if (osolwriter != NULL) delete osolwriter;
		osolwriter = NULL;
	    if (mps2osil != NULL) delete mps2osil;
		mps2osil = NULL;

#ifdef COIN_HAS_ASL
	    if (nl2osil != NULL) delete nl2osil;
	    nl2osil = NULL;
#endif

#ifdef COIN_HAS_GAMSUTILS
	    if (gams2os != NULL) delete gams2os;
		gams2os = NULL;
#endif

		throw ErrorClass(eclass.errormsg);
	}
}//end nonstandard OSServiceMethods constructor
Exemple #16
0
Map DataManager::map(Task* task) {
    FileUtil util;
    Map result = util.readMapping(task, _projects, _tasks);
    return result;
}
Exemple #17
0
int main(int argc, char* argv[])
{
    // Select between GUI and console mode.
    bool console = false;
    bool help = false;
    for(int i=0; i<argc; i++)
    {
        csString s(argv[i]);
        if(s.CompareNoCase("--console") || s.CompareNoCase("-console") ||
           s.CompareNoCase("--switch") || s.CompareNoCase("-switch") ||
           s.CompareNoCase("--repair") || s.CompareNoCase("-repair"))
        {
            console = true;
        }
        else if(s.CompareNoCase("--help") || s.CompareNoCase("-help"))
        {
            help = true;
        }
    }

    if(help)
    {
        // Create new string array to make sure --help is there.
        const char** argvs = new const char*[argc+1];
        for(int i=0; i<argc; i++)
        {
            argvs[i] = argv[i];
        }
        argvs[argc] = "--help";

        // Set up CS
        psUpdater* updater = new psUpdater(argc+1, argvs);

        // Convert args to an array of csString.
        csStringArray args;
        for(int i=0; i<argc+1; i++)
        {
            args.Push(argvs[i]);
        }

        // Initialize updater engine.
        UpdaterEngine* engine = new UpdaterEngine(args, updater->GetObjectRegistry(), "pslaunch");

        printf("PlaneShift Updater Version %1.2f for %s.\n"
               "Launcher and updater for Planeshift\n\n"
               "pslaunch [--help] [--console] [--repair] [--switch]\n\n"
               "--help      Displays this help dialog\n"
               "--console   Run updater without the GUI\n"
               "--switch    Switch active updater mirror\n"
               "--repair    Check for any problems and prompt to repair them\n", 
               UPDATER_VERSION, engine->GetConfig()->GetCurrentConfig()->GetPlatform());

        // Terminate updater!
        delete argvs;
        delete engine;
        delete updater;
        engine = NULL;
        updater = NULL;
    }
    else if(console)
    {
        // Create new string array to make sure --console is there.
        const char** argvs = new const char*[argc+1];
        for(int i=0; i<argc; i++)
        {
            argvs[i] = argv[i];
        }
        argvs[argc] = "--console";

        // Set up CS
        psUpdater* updater = new psUpdater(argc+1, argvs);

        // Convert args to an array of csString.
        csStringArray args;
        for(int i=0; i<argc+1; i++)
        {
            args.Push(argvs[i]);
        }

        // Initialize updater engine.
        UpdaterEngine* engine = new UpdaterEngine(args, updater->GetObjectRegistry(), "pslaunch");

        printf("\nPlaneShift Updater Version %1.2f for %s.\n\n", UPDATER_VERSION, engine->GetConfig()->GetCurrentConfig()->GetPlatform());

        // Run the update process!
        updater->RunUpdate(engine);

        // Maybe this fixes a bug.
        fflush(stdout);

        if(!engine->GetConfig()->IsSelfUpdating())
        {
#if defined(WIN32) && defined(NDEBUG)
            printf("\nUpdater finished!\n");
#else
            printf("\nUpdater finished, press enter to exit.\n");
            getchar();
#endif
        }

        // Terminate updater!
        delete argvs;
        delete engine;
        delete updater;
        engine = NULL;
        updater = NULL;
    }
    else
    {
        bool exitApp = false;
        while(!exitApp)
        {
            // Set up CS
            iObjectRegistry* object_reg = csInitializer::CreateEnvironment (argc, argv);

            if(!object_reg)
            {
                printf("Object Reg failed to Init!\n");
                exit(1);
            }

            // Request needed plugins for updater.
            csInitializer::SetupConfigManager(object_reg, LAUNCHER_CONFIG_FILENAME);
            csInitializer::RequestPlugins(object_reg, CS_REQUEST_VFS, CS_REQUEST_END);

            // Convert args to an array of csString.
            csStringArray args;
            for(int i=0; i<argc; i++)
            {
                args.Push(argv[i]);
            }

            // Mount the VFS paths.
            csRef<iVFS> vfs = csQueryRegistry<iVFS>(object_reg);
            if (!vfs->Mount ("/planeshift/", "$^"))
            {
                printf("Failed to mount /planeshift!\n");
                return false;
            }

            // Set config path.
            csRef<iConfigManager> configManager = csQueryRegistry<iConfigManager> (object_reg);
            csString configPath = csGetPlatformConfigPath("PlaneShift");
            configPath.ReplaceAll("/.crystalspace/", "/.");
            configPath = configManager->GetStr("PlaneShift.UserConfigPath", configPath);

            // Check that the path exists, else attempt to create it.
            FileUtil* fileUtil = new FileUtil(vfs);
            csRef<FileStat> filestat = fileUtil->StatFile(configPath);
            if (!filestat.IsValid() && CS_MKDIR(configPath) < 0)
            {
                printf("Could not create required %s directory!\n", configPath.GetData());
                return false;
            }
            filestat.Invalidate();
            delete fileUtil;
            fileUtil = NULL;

            // Mount config path.
            if (!vfs->Mount("/planeshift/userdata", configPath + "$/"))
            {
                printf("Could not mount %s as /planeshift/userdata!\n", configPath.GetData());
                return false;
            }

            // Init thread communication structure.
            InfoShare *infoShare = new InfoShare();
            infoShare->SetPerformUpdate(false);
            infoShare->SetUpdateNeeded(false);

            // Initialize updater engine.
            csRef<UpdaterEngine> engine;
            engine.AttachNew(new UpdaterEngine(args, object_reg, "pslaunch", infoShare));

            // If we're self updating, continue self update.
            if(engine->GetConfig()->IsSelfUpdating())
            {
                exitApp = engine->SelfUpdate(engine->GetConfig()->IsSelfUpdating());
            }

            // Set to true by GUI if we have to launch the client.
            bool execPSClient = false;

            // If we don't have to exit the app, create updater thread and run the GUI.
            if(!exitApp)
            {
                // Start up updater.
                csRef<Thread> updaterThread;
                updaterThread.AttachNew(new Thread(engine));
                updaterThread->Start();

                // Request needed plugins for GUI.
                csInitializer::RequestPlugins(object_reg, CS_REQUEST_FONTSERVER, CS_REQUEST_IMAGELOADER,
                    CS_REQUEST_OPENGL3D, CS_REQUEST_END);

                // Start GUI.
                psLauncherGUI* gui = new psLauncherGUI(object_reg, infoShare, &execPSClient);
                gui->Run();

                // Free GUI.
                delete gui;
            }

            // Set to exit app.
            exitApp = true;

            // Clean up everything else.
            engine.Invalidate();
            delete infoShare;
            configManager.Invalidate();
            vfs.Invalidate();
            csInitializer::DestroyApplication(object_reg);

            if (execPSClient)
            {
              // Execute psclient process.

#ifdef CS_PLATFORM_WIN32

              // Info for CreateProcess.
              STARTUPINFO siStartupInfo;
              DWORD dwExitCode;
              PROCESS_INFORMATION piProcessInfo;
              memset(&siStartupInfo, 0, sizeof(siStartupInfo));
              memset(&piProcessInfo, 0, sizeof(piProcessInfo));
              siStartupInfo.cb = sizeof(siStartupInfo);

              csString commandLine = "psclient.exe";

              for(int i=1; i<argc; ++i)
              {
                  commandLine.AppendFmt(" %s", argv[i]);
              }

	      if(CreateProcess(NULL, (LPSTR)commandLine.GetData(), 0, 0, false,
                CREATE_DEFAULT_ERROR_MODE, 0, 0, &siStartupInfo, &piProcessInfo))
	      {
                  GetExitCodeProcess(piProcessInfo.hProcess, &dwExitCode);
                  while (dwExitCode == STILL_ACTIVE)
                  {
                      csSleep(1000);
                      GetExitCodeProcess(piProcessInfo.hProcess, &dwExitCode);
                  }
                  exitApp = dwExitCode ? 0 : !0;
                  CloseHandle(piProcessInfo.hProcess);
                  CloseHandle(piProcessInfo.hThread);
	      }
	      else
		  printf("Failed to launch psclient!\n");
#else
              if(fork() == 0)
              {
#ifdef CS_PLATFORM_MACOSX
                  char* nargv[argc+2];
                  char* name = "/usr/bin/open";
                  char* psc = "psclient.app";
                  nargv[0] = name;
                  nargv[1] = psc;
                  for(int i=2; i<argc+1; ++i)
                  {
                      nargv[i] = argv[i-1];
                  }
                  nargv[argc+1] = (char*)0;
                  execv("/usr/bin/open", nargv); 
#else
                  char* nargv[argc+1];
                  char* name = const_cast<char*>("./psclient");
                  nargv[0] = name;
                  for(int i=1; i<argc; ++i)
                  {
                      nargv[i] = argv[i];
                  }
                  nargv[argc] = (char*)0;
                  execv("./psclient", nargv);  
#endif
              }                
              else
              {
                  int status;
                  wait(&status);
                  exitApp = (status == 0);
              }                
#endif
            }
            else
            {
                exitApp = true;
            }
        }
    }

    return 0;
}