当前位置: 首页>>代码示例>>C++>>正文


C++ StringBuffer::length方法代码示例

本文整理汇总了C++中StringBuffer::length方法的典型用法代码示例。如果您正苦于以下问题:C++ StringBuffer::length方法的具体用法?C++ StringBuffer::length怎么用?C++ StringBuffer::length使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在StringBuffer的用法示例。


在下文中一共展示了StringBuffer::length方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C++代码示例。

示例1: loadValueFromURL

String AbstractContextI::loadValueFromURL(const String& urlstring) const throw (Exception)
{
	String result;
	StringBuffer buf;
	buf->append(urlstring);
	if (0 == buf->indexOf(L"http://"))
	{
		URL url = new URLI(urlstring);
		HttpURLConnection httpurlconnection;
		url->openConnection()->downcast(httpurlconnection);
		if (verboseOutput()) cout << "JNDI context : Get response from url : " << urlstring << endl;
		int rc = httpurlconnection->getResponseCode();
		UTF8StringBuffer cbuf;
#if defined (_WINDOWS_SOURCE)
		cbuf->append(getenv("TEMP"));
		cbuf->append("\\");
		cbuf->append(getenv("USERNAME"));
		cbuf->append(".");
#else
		cbuf->append(getenv("USER_HOME"));
		cbuf->append("/.");
#endif
		cbuf->append(urlstring->toMD5());
		cbuf->append(".properties");
		String cachefilepath = cbuf->toString()->toLowerCase();
		if (200 != rc) 
		{
			if (verboseOutput()) cout << "JNDI context : HTTP status = " << rc << endl;
			if (verboseOutput()) cout << "JNDI context : Trying to load from cached file : " << cachefilepath << endl;
			InputStream file = new FileInputStreamI(cachefilepath);
			UTF8String content;
			file->read(content, 0);
			file->close();
			result = content->toString();
		}
		else
		{
			String response = httpurlconnection->getResponseMessage();
			Writer file = new FileWriterI(cachefilepath);
			file->write(response);
			file->close();
			if (verboseOutput()) cout << "JNDI context : Caching to file : " << cachefilepath << endl;
			result = response;
		}
	}
	else if (0 == buf->indexOf(L"file://"))
	{
		result = loadValueFromFile(urlstring);
	}
	else
	{
		throw NamingException(WITHDETAILS(L"Unsupported URI format: " + urlstring));
	}
	StringBuffer b = result;
	while (-1 < b->indexOf(L"${"))
	{
		InitialContext initialcontext = InitialContext::newInstance();
		int bpos = 0;
		int epos = 0;
		while (bpos < b->length())
		{
			bpos = b->indexOf(L"${", bpos);
			if (-1 == bpos) break;
			epos = b->indexOf(L"}", bpos);
			String variablename = b->substring(bpos + 2, epos);
			StringAnything variablevalue ;
			initialcontext->lookup(L"/" + variablename, variablevalue);
			StringBuffer value = variablevalue->toString(); 
			if (-1 < value->indexOf(L"${" + variablename + L"}") )
				throw Exception(WITHDETAILS(L"Recursive reference found : ${" + variablename + L"}"));
			b->replace(bpos, epos + 1, value->toString());
			bpos = epos + 1;
		}
	}
	return b->toString();
}
开发者ID:weltermann17,项目名称:just-like-java,代码行数:76,代码来源:AbstractContext.cpp

示例2: _doReplicate

static void _doReplicate(CActivityBase *activity, IPartDescriptor &partDesc, ICopyFileProgress *iProgress)
{
    StringBuffer primaryName;
    getPartFilename(partDesc, 0, primaryName);;
    RemoteFilename rfn;
    IFileDescriptor &fileDesc = partDesc.queryOwner();
    unsigned copies = partDesc.numCopies();
    unsigned c=1;
    for (; c<copies; c++)
    {
        unsigned replicateCopy;
        unsigned clusterNum = partDesc.copyClusterNum(c, &replicateCopy);
        rfn.clear();
        partDesc.getFilename(c, rfn);
        StringBuffer dstName;
        rfn.getPath(dstName);
        assertex(dstName.length());

        if (replicateCopy>0 )  
        {
            try
            {
                queryThor().queryBackup().backup(dstName.str(), primaryName.str());
            }
            catch (IException *e)
            {
                Owned<IThorException> re = MakeActivityWarning(activity, e, "Failed to create replicate file '%s'", dstName.str());
                e->Release();
                activity->fireException(re);
            }
        }
        else // another primary
        {
            ActPrintLog(activity, "Copying to primary %s", dstName.str());
            StringBuffer tmpName(dstName.str());
            tmpName.append(".tmp");
            OwnedIFile tmpIFile = createIFile(tmpName.str());
            OwnedIFile srcFile = createIFile(primaryName.str());
            CFIPScope fipScope(tmpName.str());
            try
            {
                try
                {
                    ensureDirectoryForFile(dstName.str());
                    ::copyFile(tmpIFile, srcFile, 0x100000, iProgress);
                }
                catch (IException *e)
                {
                    IThorException *re = MakeActivityException(activity, e, "Failed to copy to tmp file '%s' from source file '%s'", tmpIFile->queryFilename(), srcFile->queryFilename());
                    e->Release();
                    throw re;
                }
                try
                {
                    OwnedIFile dstIFile = createIFile(dstName.str());
                    dstIFile->remove();
                    tmpIFile->rename(pathTail(dstName.str()));
                }
                catch (IException *e)
                {
                    IThorException *re = ThorWrapException(e, "Failed to rename '%s' to '%s'", tmpName.str(), dstName.str());
                    e->Release();
                    throw re;
                }
            }
            catch (IException *)
            {
                try { tmpIFile->remove(); }
                catch (IException *e) { ActPrintLog(&activity->queryContainer(), e, NULL); e->Release(); }
                throw;
            }
        }
    }
}
开发者ID:xyuan,项目名称:HPCC-Platform,代码行数:74,代码来源:thactivityutil.cpp

示例3: init_main

int init_main(int argc, char* argv[])
{
    InitModuleObjects();

    Owned<IProperties> inputs = createProperties(true);

    bool interactive = false;

    for (int i = 1; i < argc; i++)
    {
        if (stricmp(argv[i], "-?")==0 || stricmp(argv[i], "-h")==0 || stricmp(argv[i], "-help")==0
             || stricmp(argv[i], "/?")==0 || stricmp(argv[i], "/h")==0)
             usage();
        else if(stricmp(argv[i], "interactive") == 0)
            interactive = true;
        else if (strchr(argv[i],'='))
        {
            inputs->loadProp(argv[i]);
        }
        else
        {
            fprintf(stderr, "Unknown option: %s", argv[i]);
            return 0;
        }
    }

    int result = -1;

#ifdef _WIN32 
    if (!interactive)
        ::SetErrorMode(SEM_NOGPFAULTERRORBOX|SEM_FAILCRITICALERRORS);
#endif

    SET_ESP_SIGNAL_HANDLER(SIGPIPE, brokenpipe_handler);

    bool SEHMappingEnabled = false;

    CEspAbortHandler abortHandler;

    Owned<IFile> sentinelFile = createSentinelTarget();
    removeSentinelFile(sentinelFile);

    Owned<CEspConfig> config;
    Owned<CEspServer> server;
    try
    {
        const char* cfgfile = NULL;
        const char* procname = NULL;
        if(inputs.get())
        {
            if(inputs->hasProp("config"))
                cfgfile = inputs->queryProp("config");
            if(inputs->hasProp("process"))
                procname = inputs->queryProp("process");
        }
        if(!cfgfile || !*cfgfile)
            cfgfile = "esp.xml";

        Owned<IPropertyTree> envpt= createPTreeFromXMLFile(cfgfile, ipt_caseInsensitive);
        Owned<IPropertyTree> procpt = NULL;
        if (envpt)
        {
            envpt->addProp("@config", cfgfile);
            StringBuffer xpath;
            if (procname==NULL || strcmp(procname, ".")==0)
                xpath.appendf("Software/EspProcess[1]");
            else
                xpath.appendf("Software/EspProcess[@name=\"%s\"]", procname);

            DBGLOG("Using ESP configuration section [%s]", xpath.str());
            procpt.set(envpt->queryPropTree(xpath.str()));
            if (!procpt)
                throw MakeStringException(-1, "Config section [%s] not found", xpath.str());
        }
        else
            throw MakeStringException(-1, "Failed to load config file %s", cfgfile);

        StringBuffer logdir;
        if(procpt->hasProp("@name"))
        {
            StringBuffer espNameStr;
            procpt->getProp("@name", espNameStr);
            if (!getConfigurationDirectory(envpt->queryPropTree("Software/Directories"), "log", "esp", espNameStr.str(), logdir))
            {
                logdir.clear();
            }
        }

        const char* build_ver = BUILD_TAG;
        setBuildVersion(build_ver);

        const char* build_level = BUILD_LEVEL;
        setBuildLevel(build_level);

        if(logdir.length() == 0)
        {
            if(procpt->hasProp("@logDir"))
                procpt->getProp("@logDir", logdir);
        }
        if(logdir.length() == 0)
//.........这里部分代码省略.........
开发者ID:hszander,项目名称:HPCC-Platform,代码行数:101,代码来源:espp.cpp

示例4: substitute

    void GermanStemmer::substitute(StringBuffer& buffer) {
      substCount = 0;

      for ( size_t c = 0; c < buffer.length(); c++ ) {
        // Replace the second char of a pair of the equal characters with an asterisk
        if ( c > 0 && buffer.charAt( c ) == buffer.charAt ( c - 1 )  ) {
          buffer.setCharAt( c, _T('*') );
        }
        // Substitute Umlauts.
        else if ( buffer.charAt( c ) == _T('ä') ) {
          buffer.setCharAt( c, _T('a') );
        }
        else if ( buffer.charAt( c ) == _T('ö') ) {
          buffer.setCharAt( c, _T('o') );
        }
        else if ( buffer.charAt( c ) == _T('ü') ) {
          buffer.setCharAt( c, _T('u') );
        }
        // Fix bug so that 'ß' at the end of a word is replaced.
        else if ( buffer.charAt( c ) == _T('ß') ) {
            buffer.setCharAt( c, _T('s') );
            buffer.insert( c + 1, _T('s') );
            substCount++;
        }
        // Take care that at least one character is left left side from the current one
        if ( c < buffer.length() - 1 ) {
          // Masking several common character combinations with an token
          if ( ( c < buffer.length() - 2 ) && buffer.charAt( c ) == _T('s') &&
            buffer.charAt( c + 1 ) == _T('c') && buffer.charAt( c + 2 ) == _T('h') )
          {
            buffer.setCharAt( c, _T('$') );
            buffer.deleteChars( c + 1, c + 3 );
            substCount =+ 2;
          }
          else if ( buffer.charAt( c ) == _T('c') && buffer.charAt( c + 1 ) == _T('h') ) {
            buffer.setCharAt( c, _T('§') );
            buffer.deleteCharAt( c + 1 );
            substCount++;
          }
          else if ( buffer.charAt( c ) == _T('e') && buffer.charAt( c + 1 ) == _T('i') ) {
            buffer.setCharAt( c, _T('%') );
            buffer.deleteCharAt( c + 1 );
            substCount++;
          }
          else if ( buffer.charAt( c ) == _T('i') && buffer.charAt( c + 1 ) == _T('e') ) {
            buffer.setCharAt( c, _T('&') );
            buffer.deleteCharAt( c + 1 );
            substCount++;
          }
          else if ( buffer.charAt( c ) == _T('i') && buffer.charAt( c + 1 ) == _T('g') ) {
            buffer.setCharAt( c, _T('#') );
            buffer.deleteCharAt( c + 1 );
            substCount++;
          }
          else if ( buffer.charAt( c ) == _T('s') && buffer.charAt( c + 1 ) == _T('t') ) {
            buffer.setCharAt( c, _T('!') );
            buffer.deleteCharAt( c + 1 );
            substCount++;
          }
        }
      }
    }
开发者ID:Beirdo,项目名称:beirdobot,代码行数:62,代码来源:GermanStemmer.cpp

示例5: processMessage

    void processMessage(CMessageBuffer &mb)
    {
        ICoven &coven=queryCoven();
        SessionId id;
        int fn;
        mb.read(fn);
        switch (fn) {
        case MSR_REGISTER_PROCESS_SESSION: {
                acceptConnections.wait();
                acceptConnections.signal();
                Owned<INode> node(deserializeINode(mb));
                Owned<INode> servernode(deserializeINode(mb));  // hopefully me, but not if forwarded
                int role=0;
                if (mb.length()-mb.getPos()>=sizeof(role)) { // a capability block present
                    mb.read(role);
                    if (!manager.authorizeConnection(role,false)) {
                        SocketEndpoint sender = mb.getSender();
                        mb.clear();
                        coven.reply(mb);
                        MilliSleep(100+getRandom()%1000); // Causes client to 'work' for a short time.
                        Owned<INode> node = createINode(sender);
                        coven.disconnect(node);
                        break;
                    }
#ifdef _DEBUG
                    StringBuffer eps;
                    PROGLOG("Connection to %s authorized",mb.getSender().getUrlStr(eps).str());
#endif
                }
                
                IGroup *covengrp;
                id = manager.registerClientProcess(node.get(),covengrp,(DaliClientRole)role);
                mb.clear().append(id);
                if (covengrp->rank(servernode)==RANK_NULL) { // must have been redirected
                    covengrp->Release(); // no good, so just use one we know about (may use something more sophisticated later)
                    INode *na = servernode.get();
                    covengrp = createIGroup(1, &na);
                }
                covengrp->serialize(mb);
                covengrp->Release();
                coven.reply(mb);
            }
            break;
        case MSR_SECONDARY_REGISTER_PROCESS_SESSION: {
                mb.read(id);
                Owned<INode> node (deserializeINode(mb));
                int role;
                mb.read(role);
                manager.addProcessSession(id,node.get(),(DaliClientRole)role);
                mb.clear();
                coven.reply(mb);
            }
            break;
        case MSR_REGISTER_SESSION: {
                SecurityToken tok;
                SessionId parentid;
                mb.read(tok).read(parentid);
                SessionId id = manager.registerSession(tok,parentid);
                mb.clear().append(id);
                coven.reply(mb);
            }
            break;
        case MSR_SECONDARY_REGISTER_SESSION: {
                mb.read(id);
                manager.addSession(id);
                mb.clear();
                coven.reply(mb);
            }
            break;
        case MSR_LOOKUP_PROCESS_SESSION: {
                // looks up from node or from id
                Owned<INode> node (deserializeINode(mb));
                if (node->endpoint().isNull()&&(mb.length()-mb.getPos()>=sizeof(id))) {
                    mb.read(id);
                    INode *n = manager.getProcessSessionNode(id);
                    if (n)
                        node.setown(n);
                    node->serialize(mb.clear());
                }
                else {
                    id = manager.lookupProcessSession(node.get());
                    mb.clear().append(id);
                }
                coven.reply(mb);
            }
            break;
        case MSR_STOP_SESSION: {
                SessionId sessid;
                bool failed;
                mb.read(sessid).read(failed);
                manager.stopSession(sessid,failed);
                mb.clear();
                coven.reply(mb);
            }
            break;
        case MSR_LOOKUP_LDAP_PERMISSIONS: {
                StringAttr key;
                StringAttr obj;
                Owned<IUserDescriptor> udesc=createUserDescriptor();
                StringAttr username;
//.........这里部分代码省略.........
开发者ID:anirudh3LOQ,项目名称:HPCC-Platform,代码行数:101,代码来源:dasess.cpp

示例6: substitute

void GermanStemmer::substitute(StringBuffer& buffer) {
    substCount = 0;

    for ( size_t i = 0; i < buffer.length(); i++ ) {
#ifdef _UCS2
        TCHAR c = buffer.charAt(i);
#else
        unsigned char c = buffer.charAt(i);
#endif
        // Replace the second char of a pair of the equal characters with an asterisk
        if ( i > 0 && c == buffer.charAt ( i - 1 )  ) {
            buffer.setCharAt( i, _T('*') );
        }
        // Substitute Umlauts.
        else if ( c  == 0xe4 ) {
            buffer.setCharAt( i, _T('a') );
        }
        else if ( c == 0xf6 ) {
            buffer.setCharAt( i, _T('o') );
        }
        else if ( c == 0xfc ) {
            buffer.setCharAt( i, _T('u') );
        }
        // Fix bug so that 'ß' at the end of a word is replaced.
        else if ( c == 0xdf ) {
            buffer.setCharAt( i, _T('s') );
            buffer.insert( i + 1, _T('s') );
            substCount++;
        }
        // Take care that at least one character is left left side from the current one
        if ( i < buffer.length() - 1 ) {
            // Masking several common character combinations with an token
            if ( ( i < buffer.length() - 2 ) && c == _T('s') &&
                    buffer.charAt( i + 1 ) == _T('c') && buffer.charAt( i + 2 ) == _T('h') )
            {
                buffer.setCharAt( i, _T('$') );
                buffer.deleteChars( i + 1, i + 3 );
                substCount =+ 2;
            }
            else if ( c == _T('c') && buffer.charAt( i + 1 ) == _T('h') ) {
                buffer.setCharAt( i, 0xa7 ); // section sign in UTF-16
                buffer.deleteCharAt( i + 1 );
                substCount++;
            }
            else if ( c == _T('e') && buffer.charAt( i + 1 ) == _T('i') ) {
                buffer.setCharAt( i, _T('%') );
                buffer.deleteCharAt( i + 1 );
                substCount++;
            }
            else if ( c == _T('i') && buffer.charAt( i + 1 ) == _T('e') ) {
                buffer.setCharAt( i, _T('&') );
                buffer.deleteCharAt( i + 1 );
                substCount++;
            }
            else if ( c == _T('i') && buffer.charAt( i + 1 ) == _T('g') ) {
                buffer.setCharAt( i, _T('#') );
                buffer.deleteCharAt( i + 1 );
                substCount++;
            }
            else if ( c == _T('s') && buffer.charAt( i + 1 ) == _T('t') ) {
                buffer.setCharAt( i, _T('!') );
                buffer.deleteCharAt( i + 1 );
                substCount++;
            }
        }
    }
}
开发者ID:Chen-Zhihui,项目名称:WizQTClient,代码行数:67,代码来源:GermanStemmer.cpp

示例7: determineInstallFiles

//---------------------------------------------------------------------------
//  determineInstallFiles
//---------------------------------------------------------------------------
int CConfigGenEngine::determineInstallFiles(IPropertyTree& processNode, CInstallFiles& installFiles) const
{
    try
    {
        m_pCallback->printStatus(STATUS_NORMAL, NULL, NULL, NULL, 
            "Determining files to install for %s", processNode.queryProp("@name"));

        StringBuffer compListPath(CONFIGGEN_COMP_LIST);
        if (m_inDir.length())
            compListPath.clear().append(m_inDir).append(PATHSEPCHAR).append(CONFIGGEN_COMP_LIST);

        Owned<IPropertyTree> deployNode = createPTreeFromXMLFile(compListPath.str(), ipt_caseInsensitive);
        StringBuffer srcFilePath;
        srcFilePath.ensureCapacity(_MAX_PATH);
        const bool bFindStartable = &m_process == &processNode && m_startable == unknown;
        const bool bFindStoppable = &m_process == &processNode && m_stoppable == unknown;

        StringBuffer xpath;
        xpath.appendf("Component[@name=\"%s\"]",processNode.queryProp("@buildSet"));
        IPropertyTree* pComponent = deployNode->queryPropTree(xpath.str());

        if (!pComponent)
        {
            m_pCallback->printStatus(STATUS_NORMAL, NULL, NULL, NULL, 
                "Cannot find files to install for %s", processNode.queryProp("@buildSet"));
            return 0;
        }

        Owned<IPropertyTreeIterator> iter = pComponent->getElements("File");
        ForEach(*iter)
        {
            IPropertyTree* pFile = &iter->query();
            const char* name = pFile->queryProp("@name");

            if (!stricmp(name, "deploy_map.xml"))
                continue;

            if (bFindStartable && !strnicmp(name, "startup", sizeof("startup")-1))
                m_startable = yes;

            if (bFindStoppable && !strnicmp(name, "stop", sizeof("stop")-1))
                m_stoppable = yes;

            const char* method  = pFile->queryProp("@method");
            if (method && !stricmp(method, "schema"))
                continue;

            //if we are not deploying build files and method is copy then ignore this file
            if (!(m_deployFlags & DEFLAGS_BUILDFILES) && (!method || !stricmp(method, "copy")))
                continue;

            const char* srcPath = pFile->queryProp("@srcPath");
            const char* destPath= pFile->queryProp("@destPath");
            const char* destName= pFile->queryProp("@destName");
            bool bCacheable     = pFile->getPropBool("@cache", false);

            // Get source filespec
            if (srcPath && !strcmp(srcPath, "@temp"))
            {
                char tempfile[_MAX_PATH];
                getTempPath(tempfile, sizeof(tempfile), m_name);
                srcFilePath.clear().append(tempfile).append(name);
            }
            else
            {
                srcFilePath.clear().append(m_inDir);

        //adjust source paths
                if (srcPath && 0!=strcmp(srcPath, "."))
                {
                    if (!strncmp(srcPath, "..", 2) && (*(srcPath+2)=='/' || *(srcPath+2)=='\\'))
                    {
                        StringBuffer reldir(srcPath);
                        reldir.replace('/', '\\');

                        while (!strncmp(reldir.str(), "..\\", 3))
                        {
                            srcFilePath.setLength( srcFilePath.length() - 1 ); //remove last char PATHSEPCHAR
                            const char* tail = pathTail(srcFilePath.str());
                            srcFilePath.setLength( tail - srcFilePath.str() );
                            reldir.remove(0, 3);
                        }
                        srcFilePath.append(reldir).append(PATHSEPCHAR);
                    }
                    else
                        srcFilePath.append(srcPath).append(PATHSEPCHAR);
                }
                srcFilePath.append(name);
            }

            std::string sDestName;
            if (method && (!stricmp(method, "esp_service_module") || !stricmp(method, "esp_plugin")))
            {
                //if this is xsl transformation and we are not generating config files then ignore
                //
                if (!(m_deployFlags & DEFLAGS_CONFIGFILES) && !stricmp(method, "esp_service_module"))
                    continue;
//.........这里部分代码省略.........
开发者ID:EwokVillage,项目名称:HPCC-Platform,代码行数:101,代码来源:configgenengine.cpp

示例8: main

int main( int argc, char *argv[] )
{
    int res=0;
    if (argc < 3)
    {
        printf
            ("frunssh <nodelistfile> \"command\" [options] \n"
            "    options: -i:<identity-file> \n"
            "             -u:<user> \n"
            "             -n:<number_of_threads>\n"
            "             -t:<connect-timeout-secs>\n"
            "             -a:<connect-attempts>\n"
            "             -d:<working_directory>\n"
            "             -s                -- strict, must match known_hosts\n"
            "             -b                -- background\n"
            "             -pw:<password>    -- INSECURE: requires pssh (NB identity file preferred)\n"
            "             -pe:<password>    -- INSECURE: as -pw except encrypted password\n"
            "             -pl               -- use plink (on windows)\n"
            "             -v                -- verbose, lists commands run\n"
            "             -d                -- dry run (for testing, enables verbose)\n"
            );
        return 255;
    }


    InitModuleObjects();

#ifndef __64BIT__
    // Restrict stack sizes on 32-bit systems
    Thread::setDefaultStackSize(0x10000);   // NB under windows requires linker setting (/stack:)
#endif

    try  {
        StringBuffer logname;
        splitFilename(argv[0], NULL, NULL, &logname, NULL);

        Owned<IComponentLogFileCreator> lf = createComponentLogFileCreator("frunssh");
        lf->setCreateAliasFile(false);
        lf->setMsgFields(MSGFIELD_prefix);
        lf->beginLogging();

        Owned<IFRunSSH> runssh = createFRunSSH();
        runssh->init(argc,argv);
        runssh->exec();
        const StringArray & strArray = runssh->getReplyText();
        const UnsignedArray & unsArray = runssh->getReply();
        for(unsigned i = 0;i < unsArray.ordinality();i++) {
            StringBuffer buf = strArray.item(i);
            // strip newlines off end of string buf
            if (buf.length() && (buf.charAt(buf.length()-1)) == '\n') {
                buf.setLength(buf.length()-1);
                buf.clip();
            }
            if (buf.length())
                PROGLOG("%d: ssh(%d): %s",i+1,unsArray.item(i),buf.str());
        }
    }
    catch(IException *e)
    {
        EXCLOG(e,"frunssh");
        e->Release();
        res=255;
    }
    releaseAtoms();
    return res;
}
开发者ID:GordonSmith,项目名称:HPCC-Platform,代码行数:66,代码来源:frunssh.cpp

示例9: if

/**
 * Run the built process.
 * @return	The built process.
 * @throws SystemException	Thrown if there is an error during the build.
 */
Process *ProcessBuilder::run(void) {
#if defined(__unix) || defined(__APPLE__)
	int error = 0;
	int old_in = -1, old_out = -1, old_err = -1;

	Process *process = 0;

	// Prepare the streams
	if(in->fd() != io::in.fd()) {
		old_in = dup(0);
		if(old_in < 0)
			error = errno;
		else
			dup2(in->fd(), 0);
	}
	if(!errno && out->fd() != io::out.fd()) {
		old_out = dup(1);
		if(old_out < 0)
			error = errno;
		else
			dup2(out->fd(), 1);
	}
	if(!errno && err->fd() != io::err.fd()) {
		old_err = dup(2);
		if(old_err < 0)
			error = errno;
		else
			dup2(err->fd(), 2);
	}

	// Create the process
	if(!error) {
		int pid = fork();
		// error
		if(pid < 0)
			error = errno;
		// father
		else if(pid != 0)
			process = new Process(pid);
		// son
		else {

			// Build arguments
			char *tab[args.count() + 1];
			for(int i = 0; i < args.count(); i++)
				tab[i] = (char *)&args[i];
			tab[args.count()] = 0;

			// Launch the command
			execvp(tab[0], tab);
			exit(1);
		}
	}

	// Reset the streams
	if(old_in >= 0) {
		close(0);
		dup2(old_in, 0);
		close(old_in);
	}
	if(old_out >= 0) {
		close(1);
		dup2(old_out, 1);
		close(old_out);
	}
	if(old_err >= 0) {
		close(2);
		dup2(old_err, 2);
		close(old_err);
	}

#elif defined(__WIN32) || defined(__WIN64)
	// no  need to redirect output, if bInheritHandles is set to false when creating process
	// it uses standard input, output and error output

	int error = 0;
	Process *process;
	PROCESS_INFORMATION *pi = new PROCESS_INFORMATION;
	STARTUPINFO si = {sizeof(si)};

	if (!error) {
		// Build arguments
		StringBuffer tab;
		for(int i = 0; i < args.count() ; i++)
		{
					tab << args[i];
					tab << " ";
		}
		char tabtemp[tab.length() +1];
		strcpy(tabtemp,tab.toString().chars());
		cout << tabtemp << " error1 = "<< GetLastError() << io::endl;
		// Launch process
		if(CreateProcess(NULL,tabtemp,0,0,TRUE,0,0,0,&si,pi) == 0)
			error = GetLastError();
		cout << "error2 = " << GetLastError() << "error value = " << error << io::endl;
//.........这里部分代码省略.........
开发者ID:alexjordan,项目名称:otawa,代码行数:101,代码来源:system_ProcessBuilder.cpp

示例10: onRunEcl

bool CEclDirectEx::onRunEcl(IEspContext &context, IEspRunEclRequest & req, IEspRunEclResponse & resp)
{
    if (!context.validateFeatureAccess(ECLDIRECT_ACCESS, SecAccess_Full, false))
        throw MakeStringException(-1, "EclDirect access permission denied.");

    StringBuffer user;
    if (!context.getUserID(user).length())
        user.append(req.getUserName());

    Owned <IWorkUnitFactory> factory = getWorkUnitFactory(context.querySecManager(), context.queryUser());
    Owned <IWorkUnit> workunit;
    if (!user.length())
        workunit.setown(factory->createWorkUnit("ECL-Direct", ""));
    else
    {
        workunit.setown(factory->createWorkUnit("ECL-Direct", user.str()));
        workunit->setUser(user.str());
    }

    Owned<IWUQuery> query = workunit->updateQuery();
    query->setQueryText(req.getEclText());
    query.clear();

    const char* clustername = req.getCluster();
    if (!clustername || !*clustername || strieq(clustername, "default"))
        clustername = defaultCluster.str();

    if (!clustername || !*clustername)
        throw MakeStringException(-1, "No Cluster Specified");

    if (!isValidCluster(clustername))
        throw MakeStringException(-1, "Invalid TargetCluster %s Specified", clustername);

    workunit->setClusterName(clustername);
    if (req.getLimitResults())
        workunit->setResultLimit(100);

    const char* snapshot = req.getSnapshot();
    if (snapshot && *snapshot)
        workunit->setSnapshot(snapshot);

    // Execute it
    SCMStringBuffer wuid;
    
    workunit->getWuid(wuid);
    workunit->setAction(WUActionRun);
    workunit->setState(WUStateSubmitted);
    workunit.clear();

    submitWorkUnit(wuid.str(), context.querySecManager(), context.queryUser());

    if (waitForWorkUnitToComplete(wuid.str(), defaultWait))
    {
        Owned<IConstWorkUnit> cw = factory->openWorkUnit(wuid.str(), false);

        SCMStringBuffer resultXML;
        getFullWorkUnitResultsXML(context.queryUserId(), context.queryPassword(), cw.get(), resultXML);
        resp.setResults(resultXML.str());

        cw.clear();

        if (deleteWorkunits)
            deleteEclDirectWorkunit(factory, wuid.str());
    }
    else
    {
        // Don't delete these ones...
        DBGLOG("WorkUnit %s timed out", wuid.str());
        
        StringBuffer result;
        result.appendf("<Exception><Source>ESP</Source><Message>Timed out waiting for job to complete: %s</Message></Exception>", wuid.str());
        resp.setResults(result.str());
    }

    return true;
}
开发者ID:martinec,项目名称:HPCC-Platform,代码行数:76,代码来源:EclDirectService.cpp

示例11: onRunEclEx

bool CEclDirectEx::onRunEclEx(IEspContext &context, IEspRunEclExRequest & req, IEspRunEclExResponse & resp)
{
    if (!context.validateFeatureAccess(ECLDIRECT_ACCESS, SecAccess_Full, false))
        throw MakeStringException(-1, "EclDirect access permission denied.");

    const char* eclText = req.getEclText();
    if (!eclText || !*eclText)
    {
        resp.setResults("<Exception><Source>ESP</Source><Message>No Ecl Text provided</Message></Exception>");
        return true;
    }

    StringBuffer user;
    if (!context.getUserID(user).length())
        user.append(req.getUserName());

    Owned <IWorkUnitFactory> factory = getWorkUnitFactory(context.querySecManager(), context.queryUser());
    Owned <IWorkUnit> workunit;
    if (!user.length())
        workunit.setown(factory->createWorkUnit("ECL-Direct", ""));
    else
    {
        workunit.setown(factory->createWorkUnit("ECL-Direct", user.str()));
        workunit->setUser(user.str());
    }

    Owned<IWUQuery> query = workunit->updateQuery();
    query->setQueryText(eclText);
    query.clear();

    const char* cluster = req.getCluster();
    if (!cluster || !*cluster || !stricmp(cluster, "default"))
        cluster = defaultCluster.str();

    if (!cluster || !*cluster)
        throw MakeStringException(-1, "No Cluster Specified");

    if (!isValidCluster(cluster))
        throw MakeStringException(-1, "Invalid TargetCluster %s Specified", cluster);

    workunit->setClusterName(cluster);

    const char* snapshot = req.getSnapshot();
    if (snapshot && *snapshot)
        workunit->setSnapshot(snapshot);

    if (req.getResultLimit())
        workunit->setResultLimit(req.getResultLimit());

    // Execute it
    SCMStringBuffer wuid;
    workunit->getWuid(wuid);
    workunit->setAction(WUActionRun);
    workunit->setState(WUStateSubmitted);
    workunit.clear();

    resp.setWuid(wuid.str());

    submitWorkUnit(wuid.str(), context.querySecManager(), context.queryUser());

    if (!waitForWorkUnitToComplete(wuid.str(), (req.getWait_isNull()) ? defaultWait : req.getWait()))
    {
        StringBuffer result;
        result.appendf("<Exception><Source>ESP</Source><Message>Timed out waiting for job to complete: %s</Message></Exception>", wuid.str());
        resp.setResults(result.str());
        return true;
    }

    if (!deleteWorkunits && context.queryRequestParameters()->hasProp("redirect"))
    {
        StringBuffer url("/WsWorkunits/WUInfo?Wuid=");
        resp.setRedirectUrl(url.append(wuid).str());
        return true;
    }

    Owned<IConstWorkUnit> cw = factory->openWorkUnit(wuid.str(), false);
    EclDirectWUExceptions errors(*cw);
    resp.setErrors(errors);

    if (req.getIncludeResults())
    {
        StringBuffer results;
        CRunEclExFormat outputFormat = req.getFormat();
        Owned<IWuWebView> web = createWuWebView(wuid.str(), NULL, NULL, getCFD(), true);
        if (!web)
            results.appendf("<Exception><Source>ESP</Source><Message>Failed loading result workunit %s</Message></Exception>", wuid.str());
        else if (outputFormat == CRunEclExFormat_Table)
        {
            StringBuffer xsltfile(getCFD());
            web->applyResultsXSLT(xsltfile.append("xslt/wsecl3_result.xslt").str(), results);
        }
        else
        {
            unsigned xmlflags = 0;
            if (outputFormat != CRunEclExFormat_ExtendedXml)
                xmlflags |= WWV_OMIT_SCHEMAS;
            if (context.queryRequestParameters()->hasProp("display_xslt"))
                xmlflags |= WWV_USE_DISPLAY_XSLT;
            else
                xmlflags |= WWV_OMIT_XML_DECLARATION;
//.........这里部分代码省略.........
开发者ID:martinec,项目名称:HPCC-Platform,代码行数:101,代码来源:EclDirectService.cpp

示例12: onGetInstantQuery

int CFileSpraySoapBindingEx::onGetInstantQuery(IEspContext &context, CHttpRequest* request, CHttpResponse* response, const char *service, const char *method)
{
    bool permission = true;
    bool bDownloadFile = false;
    bool bProcess;
    StringBuffer sourceLogicalFile;
    StringBuffer methodbuf;
    StringBuffer submethod;
    StringBuffer xsltFileName(getCFD());
    xsltFileName.append("smc_xslt/");

    if (stricmp(method, "SprayFixedInput")==0)
    {
        if (!context.validateFeatureAccess(FILE_SPRAY_URL, SecAccess_Write, false))
            permission = false;

        bProcess = true;
        xsltFileName.append("fs_sprayForm.xslt");
        methodbuf.append("SprayFixed");
    }
    else if(stricmp(method, "SprayVariableInput")==0)
    {
        if (!context.validateFeatureAccess(FILE_SPRAY_URL, SecAccess_Write, false))
            permission = false;

        bProcess = true;
        xsltFileName.append("fs_sprayForm.xslt");
        methodbuf.append("SprayVariable");
        request->getParameter("submethod", submethod);
    }
    else if (stricmp(method, "DesprayInput")==0)
    {
        if (!context.validateFeatureAccess(FILE_DESPRAY_URL, SecAccess_Write, false))
            permission = false;

        request->getParameter("sourceLogicalName", sourceLogicalFile);
        xsltFileName.append("fs_desprayCopyForm.xslt");
        methodbuf.append("Despray");
        bProcess = true;
    }
    else if (stricmp(method, "CopyInput") == 0)
    {
        if (!context.validateFeatureAccess(FILE_SPRAY_URL, SecAccess_Write, false))
            permission = false;

        request->getParameter("sourceLogicalName", sourceLogicalFile);
        xsltFileName.append("fs_desprayCopyForm.xslt");
        methodbuf.append("Copy");
        bProcess = true;
    }
    else if (stricmp(method, "RenameInput") == 0)
    {
        if (!context.validateFeatureAccess(FILE_SPRAY_URL, SecAccess_Write, false))
            permission = false;

        request->getParameter("sourceLogicalName", sourceLogicalFile);
        xsltFileName.append("fs_renameForm.xslt");
        methodbuf.append("Rename");
        bProcess = true;
    }
    else if (stricmp(method, "DownloadFile") == 0)
    {
        if (!context.validateFeatureAccess(FILE_SPRAY_URL, SecAccess_Full, false))
            permission = false;

        downloadFile(context, request, response);
        bDownloadFile = true;
        bProcess = true;
    }
    else
        bProcess = false;

    if (bProcess)
    {
        if (bDownloadFile)
            return 0;

        StringBuffer xml;
        Owned<IProperties> params(createProperties());
        if (!permission)
        {
            params->setProp("@method", methodbuf.str());
            xml.append("<Environment><ErrorMessage>Permission denied.</ErrorMessage></Environment>");
        }
        else
        {
            if(submethod.length() > 0)
                params->setProp("@submethod", submethod.str());
            params->setProp("@method", methodbuf.str());

            if (*sourceLogicalFile.str())
            {
                params->setProp("@sourceLogicalName", sourceLogicalFile.str());

                Owned<IUserDescriptor> userdesc;
                StringBuffer username;
                context.getUserID(username);
                if(username.length() > 0)
                {
                    const char* passwd = context.queryPassword();
//.........这里部分代码省略.........
开发者ID:magg,项目名称:HPCC-Platform,代码行数:101,代码来源:ws_fsBinding.cpp

示例13: createPTreeForXslt

IPropertyTree* CFileSpraySoapBindingEx::createPTreeForXslt(const char* method, const char* dfuwuid)
{
    Owned<IEnvironmentFactory> factory = getEnvironmentFactory();
#if 0
    Owned<IConstEnvironment> m_constEnv = factory->openEnvironment();
#else
    Owned<IConstEnvironment> m_constEnv = factory->openEnvironmentByFile();
#endif
    Owned<IPropertyTree> pEnvRoot = &m_constEnv->getPTree();
    IPropertyTree* pEnvSoftware = pEnvRoot->queryPropTree("Software");

    Owned<IPropertyTree> pRoot = createPTreeFromXMLString("<Environment/>");
    IPropertyTree* pSoftware = pRoot->addPropTree("Software", createPTree("Software"));

    if (pEnvSoftware)
    {
        StringBuffer dfuwuidSourcePartIP, wuxml;
        if(dfuwuid && *dfuwuid)
        {
            Owned<IDFUWorkUnitFactory> dfuwu_factory = getDFUWorkUnitFactory();
            Owned<IConstDFUWorkUnit> dfuwu = dfuwu_factory->openWorkUnit(dfuwuid, false);
            if(dfuwu)
            {   
                dfuwu->toXML(wuxml);

                Owned<IPropertyTree> wu = createPTreeFromXMLString(wuxml.str());
                if (wu)
                {
                    const char* ip = wu->queryProp("Source/Part/@node");
                    if (ip && *ip)
                        dfuwuidSourcePartIP.append(ip);
                }
            }
        }

        Owned<IPropertyTreeIterator> it = pEnvSoftware->getElements("DropZone");
        ForEach(*it)
        {
            IPropertyTree* pDropZone = pSoftware->addPropTree("DropZone", &it->get());
            //get IP Address of the computer associated with this drop zone
            const char* pszComputer = it->query().queryProp("@computer");
            if (!strcmp(pszComputer, "."))
                pszComputer = "localhost";

            StringBuffer xpath;
            xpath.appendf("Hardware/Computer[@name='%s']/@netAddress", pszComputer);

            StringBuffer sNetAddr;
            const char* pszNetAddr = pEnvRoot->queryProp(xpath.str());
            if (strcmp(pszNetAddr, "."))
            {       
                sNetAddr.append(pszNetAddr);
            }
            else
            {
                StringBuffer ipStr;
                IpAddress ipaddr = queryHostIP();
                ipaddr.getIpText(ipStr);
                if (ipStr.length() > 0)
                {
#ifdef MACHINE_IP
                    sNetAddr.append(MACHINE_IP);
#else
                    sNetAddr.append(ipStr.str());
#endif
                }
            }
            pDropZone->addProp("@netAddress", sNetAddr.str());
            if ((dfuwuidSourcePartIP.length() > 0) && (sNetAddr.length() > 0))
            {
                IpAddress ip1(dfuwuidSourcePartIP.str()), ip2(sNetAddr.str());
                if (ip1.ipequals(ip2))              
                    pDropZone->addProp("@sourceNode", "1");
            }

            Owned<IConstMachineInfo> machine;
            if (strcmp(pszNetAddr, "."))
                machine.setown(m_constEnv->getMachineByAddress(sNetAddr.str()));
            else
            {
                machine.setown(m_constEnv->getMachineByAddress(pszNetAddr));
                if (!machine)
                    machine.setown(m_constEnv->getMachineByAddress(sNetAddr.str()));
            }

            if (machine)
            {
                //int os = machine->getOS();
                StringBuffer dir;
                pDropZone->getProp("@directory", dir);
                if (machine->getOS() == MachineOsLinux || machine->getOS() == MachineOsSolaris)
                {         
                    dir.replace('\\', '/');//replace all '\\' by '/'
                    pDropZone->setProp("@linux", "true");
                }
                else
                {       
                    dir.replace('/', '\\');
                    dir.replace('$', ':');
                }
//.........这里部分代码省略.........
开发者ID:magg,项目名称:HPCC-Platform,代码行数:101,代码来源:ws_fsBinding.cpp

示例14: ConfigurationException

void
SchemaTypeTuple::validate(
	const SchemaValidator *		sv,
	const Configuration *		cfg,
	const char *				scope,
	const char *				name,
	const char *				typeName,
	const char *				origTypeName,
	const StringVector &		typeArgs,
	int							indentLevel) const
											throw(ConfigurationException)
{
	StringBuffer				msg;
	StringBuffer				errSuffix;
	StringBuffer				fullyScopedName;
	const char **				list;
	const char *				elemValue;
	const char *				elemTypeName;
	int							i;
	int							listSize;
	int							typeArgsSize;
	int							elemNameIndex;
	int							typeIndex;
	int							rowNum;
	int							numElems;
	SchemaType *				elemTypeDef;
	StringVector				emptyArgs;
	bool						ok;
	const char *				sep;

	//--------
	// Check the length of the list matches the size of the tuple
	//--------
	typeArgsSize = typeArgs.length();
	assert(typeArgsSize != 0);
	assert(typeArgsSize % 2 == 0);
	numElems = typeArgsSize / 2;
	cfg->lookupList(scope, name, list, listSize);
	if (listSize != numElems) {
		cfg->mergeNames(scope, name, fullyScopedName);
		msg << cfg->fileName() << ": there should be " << numElems
			<< " entries in the '" << fullyScopedName << "' " << typeName
		    << "; entries denote";
		for (i = 0; i < numElems; i++) {
			msg << " '" << typeArgs[i*2+0] << "'";
			if (i < numElems-1) {
				msg << ",";
			}
		}
		throw ConfigurationException(msg.c_str());
	}
	//--------
	// Check each item is of the type specified in the tuple
	//--------
	for (i = 0; i < listSize; i++) {
		typeIndex     = (i * 2 + 0) % typeArgsSize;
		elemNameIndex = (i * 2 + 1) % typeArgsSize;
		rowNum = (i / numElems) + 1;
		elemValue = list[i];
		elemTypeName = typeArgs[typeIndex];
		elemTypeDef = findType(sv, elemTypeName);
		ok = callIsA(elemTypeDef, sv, cfg, elemValue, elemTypeName, emptyArgs,
					 indentLevel + 1, errSuffix);
		if (!ok) {
			if (errSuffix.length() == 0) {
				sep = "";
			} else {
				sep = "; ";
			}
			cfg->mergeNames(scope, name, fullyScopedName);
			msg << cfg->fileName() << ": bad " << elemTypeName << " value ('"
				<< elemValue << "') for element " << i+1 << " ('"
			    << typeArgs[elemNameIndex] << "') of the '" << fullyScopedName
				<< "' " << typeName << sep << errSuffix;
			throw ConfigurationException(msg.c_str());
		}
	}
}
开发者ID:2mia,项目名称:config4cpp,代码行数:78,代码来源:SchemaTypeTuple.cpp

示例15: onDFUXRefArrayAction

bool CWsDfuXRefEx::onDFUXRefArrayAction(IEspContext &context, IEspDFUXRefArrayActionRequest &req, IEspDFUXRefArrayActionResponse &resp)
{
    try
    {
        StringBuffer username;
        context.getUserID(username);
        DBGLOG("CWsDfuXRefEx::onDFUXRefArrayAction User=%s",username.str());
        Owned<IUserDescriptor> userdesc;
        if(username.length() > 0)
        {
            const char* passwd = context.queryPassword();
            userdesc.setown(createUserDescriptor());
            userdesc->set(username.str(), passwd);
        }

        if(*req.getAction() == 0 || *req.getType() == 0 || *req.getCluster() == 0)
        {
            ERRLOG("Invalid Parameters into CWsDfuXRefEx::onDFUXRefArrayAction");
            throw MakeStringExceptionDirect(ECLWATCH_INVALID_INPUT, "Action, cluster, or type not defined.");
        }
        
        Owned<IXRefNode> xRefNode = XRefNodeManager->getXRefNode(req.getCluster());
        if (xRefNode.get() == 0)
        {
            ERRLOG("Unable to resolve XRef cluster name %s",req.getCluster());
            throw MakeStringException(ECLWATCH_CANNOT_RESOLVE_CLUSTER_NAME, "Unable to resolve cluster name %s",req.getCluster());
        }

        
        Owned<IXRefFilesNode> _fileNode = getFileNodeInterface(*xRefNode.get(),req.getType());
        if (_fileNode.get() == 0)
        {
            ERRLOG("Unable to find a suitable IXRefFilesNode interface for %s",req.getType());
            throw MakeStringException(ECLWATCH_CANNOT_FIND_IXREFFILESNODE, "Unable to find a suitable IXRefFilesNode interface for %s",req.getType());
        }

        if (!context.validateFeatureAccess(FEATURE_URL, SecAccess_Full, false))
            throw MakeStringException(ECLWATCH_DFU_XREF_ACCESS_DENIED, "Failed to run Xref command. Permission denied.");
       
        StringBuffer returnStr,UserName;
        const char* ActionType = req.getAction();

        DBGLOG("Running Xref Command %s for user %s",ActionType,context.getUserID(UserName).str());

        for(unsigned i = 0; i < req.getXRefFiles().length();i++)
        {
            DBGLOG("CWsDfuXRefEx::onDFUXRefArrayAction %s file %s for User=%s", ActionType, req.getXRefFiles().item(i), username.str());

            StringBuffer errstr;
            if (strcmp("Delete" ,ActionType) == 0)
            {
                if (_fileNode->RemovePhysical(req.getXRefFiles().item(i),userdesc,req.getCluster(),errstr))
                    appendReplyMessage(returnStr,NULL,"Removed Physical part %s",req.getXRefFiles().item(i));
                else
                    appendReplyMessage(returnStr,NULL,"Error(s) removing physical part %s\n%s",req.getXRefFiles().item(i),errstr.str());
            }
            else if (strcmp("Attach" ,ActionType) == 0)
            {
                if(_fileNode->AttachPhysical(req.getXRefFiles().item(i),userdesc,req.getCluster(),errstr) )
                    appendReplyMessage(returnStr,NULL,"Reattached Physical part %s",req.getXRefFiles().item(i));
                else
                    appendReplyMessage(returnStr,NULL,"Error(s) attaching physical part %s\n%s",req.getXRefFiles().item(i),errstr.str());
            }
            if (strcmp("DeleteLogical" ,ActionType) == 0)
            {
                // Note we don't want to physically delete 'lost' files - this will end up with orphans on next time round but that is safer
                if (_fileNode->RemoveLogical(req.getXRefFiles().item(i),userdesc,req.getCluster(),errstr)) {
                    appendReplyMessage(returnStr,NULL,"Removed Logical File %s",req.getXRefFiles().item(i));
                }
                else
                    appendReplyMessage(returnStr,NULL,"Error(s) removing File %s\n%s",req.getXRefFiles().item(i),errstr.str());
            }
        }

        xRefNode->commit();
        resp.setDFUXRefArrayActionResult(returnStr.str());
    }
    catch(IException* e)
    {   
        FORWARDEXCEPTION(context, e,  ECLWATCH_INTERNAL_ERROR);
    }
    return true;
}
开发者ID:AlexLuya,项目名称:HPCC-Platform,代码行数:83,代码来源:ws_dfuXRefService.cpp


注:本文中的StringBuffer::length方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。