bool DIR_LIB_SOURCE::makePartName( STRING* aPartName, const char* aEntry,
                        const STRING& aCategory )
{
    const char* cp = strrstr( aEntry, SWEET_EXT );

    // if base name is not empty, contains SWEET_EXT, && cp is not NULL
    if( cp > aEntry )
    {
        const char* limit = cp + strlen( cp );

        // If versioning, then must find a trailing "revN.." type of string.
        if( useVersioning )
        {
            const char* rev = endsWithRev( cp + SWEET_EXTZ, limit, '.' );
            if( rev )
            {
                if( aCategory.size() )
                    *aPartName = aCategory + "/";
                else
                    aPartName->clear();

                aPartName->append( aEntry, cp - aEntry );
                aPartName->append( "/" );
                aPartName->append( rev );
                return true;
            }
        }

        // If using versioning, then all valid partnames must have a rev string,
        // so we don't even bother to try and load any other partfile down here.
        else
        {
            // if file extension is exactly SWEET_EXT, and no rev
            if( cp==limit-5 )
            {
                if( aCategory.size() )
                    *aPartName = aCategory + "/";
                else
                    aPartName->clear();

                aPartName->append( aEntry, cp - aEntry );
                return true;
            }
        }
    }

    return false;
}
Exemple #2
0
void compareText(const FMINDEX& f, const STRING& text, const STRING *keyTbl, size_t keySize)
{
	for (size_t i = 0; i < keySize; i++) {
		const STRING& key = keyTbl[i];
		Set a = searchPos1(f, key);
		Set b = searchPos2(text, key);
		CYBOZU_TEST_EQUAL(a.size(), b.size());
		if (a.size() == b.size()) {
			size_t pos = 0;
			for (Set::const_iterator ia = a.begin(), ib = b.begin(); pos < a.size(); ++ia, ++ib, ++pos) {
				CYBOZU_TEST_EQUAL(*ia, *ib);
			}
		}
	}
	// recover string
	STRING org;
	f.getPrevString(org, 0, f.wm.size() - 1);
	CYBOZU_TEST_EQUAL(org.size(), text.size());
	CYBOZU_TEST_ASSERT(org == text);
}
void DIR_LIB_SOURCE::GetCategoricalPartNames( STRINGS* aResults, const STRING& aCategory )
    throw( IO_ERROR )
{
    PN_ITER end = aCategory.size() ?
                        partnames.lower_bound( aCategory + char( '/' + 1 ) ) :
                        partnames.end();

    PN_ITER it  = aCategory.size() ?
                        partnames.upper_bound( aCategory + "/" ) :
                        partnames.begin();

    aResults->clear();

    if( useVersioning )
    {
        STRING  partName;

        while( it != end )
        {
            const char* rev = endsWithRev( *it );

            // all cached partnames have a rev string in useVersioning mode
            assert( rev );

            // partName is substring which omits the rev AND the rev separator
            partName.assign( *it, 0, rev - it->c_str() - 1 );

            aResults->push_back( partName );

            // skip over all other versions of the same partName.
            it = partnames.lower_bound( partName + char( '/' + 1 ) );
        }

    }

    else
    {
        while( it != end )
            aResults->push_back( *it++ );
    }
}
// see struct BY_REV
bool BY_REV::operator() ( const STRING& s1, const STRING& s2 ) const
{
    // avoid instantiating new STRINGs, and thank goodness that c_str() is const.

    const char* rev1 = endsWithRev( s1 );
    const char* rev2 = endsWithRev( s2 );

    int rootLen1 =  rev1 ? rev1 - s1.c_str() : s1.size();
    int rootLen2 =  rev2 ? rev2 - s2.c_str() : s2.size();

    int r = memcmp( s1.c_str(), s2.c_str(), min( rootLen1, rootLen2 ) );

    if( r )
    {
        return r < 0;
    }

    if( rootLen1 != rootLen2 )
    {
        return rootLen1 < rootLen2;
    }

    // root strings match at this point, compare the revision number numerically,
    // and chose the higher numbered version as "less", according to std::set lingo.

    if( bool(rev1) != bool(rev2) )
    {
        return bool(rev1) < bool(rev2);
    }

    if( rev1 && rev2 )
    {
        int rnum1 = atoi( rev1+3 );
        int rnum2 = atoi( rev2+3 );

        // higher numbered revs are "less" so that they bubble to top.
        return rnum1 > rnum2;
    }

    return false;   // strings are equal, and they don't have a rev
}
static inline int okBase( const STRING& aField )
{
    int offset = int( aField.find_first_of( ":/" ) );
    if( offset != -1 )
        return offset;

    // cannot be empty
    if( !aField.size() )
        return 0;

    return offset;  // ie. -1
}
VOID CStringFilter::ReplaceToSign_Normal(const STRING& strIn, STRING& strOut)
{
	static STRING strSign		= "?";
	static BYTE byANSIBegin		= 0X20;
	static BYTE byANSIEnd		= 0X80;
	strOut = strIn;

	STRING::size_type allsize = m_vIncluce.size();
	//包含替换
	for(STRING::size_type i = 0; i < m_vIncluce.size(); ++i)
	{
		STRING::size_type pos = strIn.find(m_vIncluce[i]);

		while(STRING::npos != pos)
		{
			STRING strReplace = "";
			STRING::size_type len = m_vIncluce[i].size();
			//如果包含替换的是1个字节的ANSI字节,替换前,
			//需要确认前一个字节一定不是双字节字符集的前一个字节
			BOOL bSkip = FALSE;
			if(1 == len && pos > 0)
			{
				BYTE byChar = strIn[pos-1];
#if 0
				char dbgmsg[256];
				_snprintf(dbgmsg, 255, "strIn[pos-1]:0x%X(0x%X)\n", strIn[pos-1],byChar);
				::OutputDebugString(dbgmsg);
#endif
				//不是标准ANSI英文字符
				if(!(byChar >= byANSIBegin && byChar <= byANSIEnd || byChar == '\r' || byChar == '\n' || byChar == '\t'))
				{
					bSkip = TRUE;
				}
			}

			if(!bSkip)
			{
				for(STRING::size_type k = 0; k < len; ++k, strReplace += strSign);
				strOut.replace(pos, len, strReplace);
			}

			pos = strIn.find(m_vIncluce[i], pos+len);
		}
	}

	//完全匹配替换
	if(IsFullCmp(strIn))
	{
		STRING::size_type len = strIn.size();
		strOut.clear();
		for(STRING::size_type i = 0; i < len; ++i, strOut += strSign);
	}
}
VOID CStringFilter::ReplaceToSign_New(const STRING& strIn, STRING& strOut)
{
	static STRING strSign = "~$%^&(){}`-_+=?,.<>";
	strOut = strIn;

	STRING::size_type allsize = m_vIncluce.size();
	//包含替换
	for(STRING::size_type i = 0; i < m_vIncluce.size(); ++i)
	{
		STRING::size_type pos = strIn.find(m_vIncluce[i]);
		
		while(STRING::npos != pos)
		{
			STRING strReplace = "";
			STRING::size_type len = m_vIncluce[i].size();
			for(STRING::size_type k = 0; k < len; ++k)
			{
				STRING::size_type ri = rand()%int(strSign.size());
				strReplace += strSign.at(ri);
			}
			strOut.replace(pos, len, strReplace);
			pos = strIn.find(m_vIncluce[i], pos+len);
		}
	}

	//完全匹配替换
	if(IsFullCmp(strIn))
	{
		STRING::size_type len = strIn.size();
		strOut.clear();
		for(STRING::size_type i = 0; i < len; ++i)
		{
			STRING::size_type ri = rand()%int(strSign.size());
			strOut += strSign.at(ri);
		}
	}
}
static int okRevision( const STRING& aField )
{
    char  rev[32];  // C string for speed

    if( aField.size() >= 4 )
    {
        strcpy( rev, "x/" );
        strcat( rev, aField.c_str() );

        if( EndsWithRev( rev, rev + strlen(rev) ) == rev+2 )
            return -1;    // success
    }

    return 0; // first character position "is in error", is best we can do.
}
Exemple #9
0
STRING Unquote(const STRING& str)
{
    if (str[0] != L'"')
        return str;

    STRING Ret;
    size_t i = 1;
    while (i < str.size())
    {
        if (str[i] == L'"' || str[i] == UNICODE_NULL)
            break;

        UnescapeChar(str, i, Ret);
    }
    return Ret;
}
Exemple #10
0
STRING Escape(const STRING& str)
{
    STRING Ret;
    for (size_t i = 0; i < str.size(); ++i)
    {
        switch (str[i])
        {
            case L'"': case L'\\':
                Ret += L'\\';
                Ret += str[i];
                break;
            default:
                Ret += str[i];
        }
    }
    return Ret;
}
    /*!
     * Add quotes around the string if it contains any whitespace.
     */
    void AddQuotes(const T *whitespace)
    {
        if (_quoted.find_first_of(whitespace) != STRING::npos)
        {
            _quoted.insert(0, 1, '"');
            _quoted.append(1, '"');

            // If the last character (prior to adding the quotes) was a backslash,
            // it needs to be escaped now because it precedes a quote.
            //
            size_t quote = _quoted.size() - 1;
            if (_quoted[quote-1] == '\\')
            {
                size_t notSlash = _quoted.find_last_not_of('\\', quote-2);
                size_t numSlashes = quote - notSlash - 1;
                _quoted.insert(quote, numSlashes, '\\');
            }
        }
    }
Exemple #12
0
static void fgets(STRING & s, FILE * f)
{
    s.resize(0);
    char c;
    while (fgetc(c, f))
    {
        if (c == '\n' || c == '\r')
        {
            if (c == '\r' && (!fgetc(c, f) || c != '\n'))
                RuntimeError("fgets: malformed text file, CR without LF");
            break;
        }
        s.push_back(c);
        // strip Unicode BOM
        // We strip it from any string, not just at the start.
        // This allows to UNIX-'cat' multiple UTF-8 files with BOMs.
        // Since the BOM is otherwise invalid within a file, this is well-defined and upwards compatible.
        if (s.size() == 3 && BeginsWithUnicodeBOM(s.c_str()))
            s.clear();
    }
}
/// <summary>
/// Executes the specific request.
/// </summary>
/// <returns>
/// MgHttpResponse
/// This contains the response (including MgHttpResult and StatusCode) from the server.
/// </returns>
void MgHttpWfsDescribeFeatureType::Execute(MgHttpResponse& hResponse)
{
    Ptr<MgHttpResult> hResult = hResponse.GetResult();

    MG_HTTP_HANDLER_TRY()

    // We have to wrap the request parameters, since the outside
    // world is case-sensitive (with respect to names,) but
    // we need our parameters NOT to be so.
    Ptr<MgHttpRequestParam> origReqParams = m_hRequest->GetRequestParam();
    MgHttpRequestParameters Parms(origReqParams);
    MgHttpResponseStream Out;

    MgOgcServer::SetLoader(GetDocument);

    MgUserInformation::SetCurrentUserInfo(m_userInfo);

    // Instance a server-lette
    MgOgcWfsServer Wfs(Parms,Out);

    // Determine required feature types
    CPSZ pszFeatureTypes = Wfs.RequestParameter(MgHttpResourceStrings::reqWfsTypeName.c_str());
    STRING sFeatureTypes = pszFeatureTypes? pszFeatureTypes : _("");
    Ptr<MgStringCollection> featureTypeList;
    if(sFeatureTypes.empty())
    {
        featureTypeList = NULL;
    }
    else
    {
        featureTypeList = MgStringCollection::ParseCollection(sFeatureTypes, L",");
    }

    Ptr<MgResourceService> pResourceService = (MgResourceService*)(CreateService(MgServiceType::ResourceService));
    Ptr<MgFeatureService> pFeatureService = (MgFeatureService*)(CreateService(MgServiceType::FeatureService));

    // Retrieve feature definitions
    auto_ptr<MgWfsFeatureDefinitions> pFeatureTypes;
    if(NULL == featureTypeList)
    {
        pFeatureTypes.reset(new MgWfsFeatureDefinitions(pResourceService,pFeatureService));
    }
    else
    {
        pFeatureTypes.reset(new MgWfsFeatureDefinitions(pResourceService,pFeatureService,featureTypeList));
    }
    Wfs.SetFeatureDefinitions(pFeatureTypes.get());

    // In order to validate request we have to invoke the ProcessRequest
    if(!Wfs.ProcessRequest(this))
    {
        // Obtain the response byte reader
        Ptr<MgByteReader> errorResponse = Out.Stream().GetReader();

        // Set the result
        hResult->SetResultObject(errorResponse, errorResponse->GetMimeType());
        return;
    }

    // Determine required output format
    // This part must behind the Wfs.ProcessRequest, where parameters have been validated.
    CPSZ pszOutputFormat = Wfs.RequestParameter(MgHttpResourceStrings::reqWfsOutputFormat.c_str());
    STRING sOutputFormat = pszOutputFormat? pszOutputFormat : _("");
    if(sOutputFormat.empty())
    {
        sOutputFormat = Wfs.GetDefaultDescribeFeatureTypeOutputFormat(STRING(Wfs.RequestParameter(MgHttpResourceStrings::reqWfsVersion.c_str())));
    }

    if(pFeatureTypes->InSameNamespace()) 
    {
        STRING sPrefix = L"";
        STRING sUrl = L"";
        STRING sResource = L""; // TODO: look for this in arg, since POST may put it there to save us trouble.
        STRING sSchemaHash = L"";
        Ptr<MgResourceIdentifier> idResource;
        Ptr<MgStringCollection> pFeatureClasses = new MgStringCollection();

        while(pFeatureTypes->ReadNext())
        {
            STRING sClassFullName = pFeatureTypes->GetClassFullName();
            
            if(!sFeatureTypes.empty() && STRING::npos == sFeatureTypes.find(sClassFullName))
            {
                continue;
            }

            STRING::size_type iPos = sClassFullName.find(_(":")); //NOXLATE
            if(iPos != STRING::npos)
            {
                if(sPrefix.empty())
                {
                    sPrefix = sClassFullName.substr(0,iPos);
                }

                STRING sClass = sClassFullName.substr(iPos+1);

                sUrl = pFeatureTypes->GetNamespaceUrl();

                if(NULL == idResource)
                {
                    if(pFeatureTypes->PrefixToFeatureSource(sPrefix, sResource, sSchemaHash)) {
                        idResource = new MgResourceIdentifier(sResource);
                    }
                    else
                    {
                        // Badly formed feature type?  Throw an exception.
                        GenerateTypeNameException(hResult,sFeatureTypes);
                        return;
                    }
                }

                pFeatureClasses->Add(((sSchemaHash.size()==0) ? sClass : sSchemaHash + _(":") + sClass)); //NOXLATE
            }
            else {
                // Badly formed feature type?  Throw an exception.
                GenerateTypeNameException(hResult,sFeatureTypes);
                return;
            }
        }

        if(pFeatureClasses->GetCount() == 0)
        {
            // Badly formed feature type?  Throw an exception.
            GenerateTypeNameException(hResult,sFeatureTypes);
            return;
        }

        Ptr<MgByteReader> response  = pFeatureService->DescribeWfsFeatureType(idResource, pFeatureClasses, sPrefix, sUrl);

        // Set the result
        hResult->SetResultObject(response, sOutputFormat);
    }
    else {
        // There's more than one feature, so we need to enumerate
        // them and have each get imported.
        //
        if(!pFeatureTypes->SubsetFeatureList(sFeatureTypes.c_str()))
            GenerateTypeNameException(hResult,sFeatureTypes);
        else {

#ifdef _WFS_LOGGING
            MyLog.Write(_("WFS::DescribeFeatureType\r\n"));
#endif
            // Execute the request
            //Wfs.ProcessRequest(this);

            // Slurp the results.
            Ptr<MgByteReader> capabilities = Out.Stream().GetReader();

            // Set the result
            hResult->SetResultObject(capabilities, capabilities->GetMimeType());
        }
    }

    MG_HTTP_HANDLER_CATCH_AND_THROW_EX(L"MgHttpWfsDescribeFeatureType.Execute")
}
VOID CStringFilter::ReplaceToSign(const STRING& strIn, STRING& strOut)
{
	const CHAR		KeyStart		= '#';
	const CHAR		ContentsEnd		= '}';

	std::vector<PICE>	vSrcPice;	//来源字串分割成多段
	
	STRING strSrc = strIn;

	PICE			  pc;
	STRING::size_type sB = 0;
	STRING::size_type sC = 0;
	STRING::size_type sE = strSrc.find_first_of(KeyStart);
	STRING::size_type sLen = strSrc.size();

#if	0
	::OutputDebugString("ReplaceToSign Begin=======================\n");
	char dbgmsg[256];
	_snprintf(dbgmsg, 255, "strSrc:%s", strSrc.c_str());
	::OutputDebugString(dbgmsg);
	::OutputDebugString("\n------------------------------------------");
#endif

	do
	{	
		if(sE == STRING::npos)
		{
			//push last replace str
			pc.bReplace = TRUE;
			pc.pice = strSrc.substr(sC);
			vSrcPice.push_back(pc);
			break;
		}

		//get op
		STRING strOp = strSrc.substr(sE+1, 1);

		if(strOp == "{")	//ok, check magic #{} string.
		{
			//item element is valid. ex: #{_INFOID123}
			STRING strItemElement = strSrc.substr(sE+2, 7);
			//info message is valid. ex: #{_INFOMSGxxxxxx}
			STRING strInfoMsg = strSrc.substr(sE+2, 8);

			if(strItemElement == "_INFOID")
			{
				//get itemId
				//todo_yangjun	需要仔细检查剩下的字符是否还是一个完整的INFOID信息
				STRING::size_type sIDEnd = strSrc.find(ContentsEnd, sE+2+7);
				if(sE+2+7 >= sLen)	// fix dead loop if str is "xxx#{_INFOID" [9/25/2006]
				{
					//skip invalid #{
					sE += 2;
					goto LengthOver2;
				}
				STRING strId = strSrc.substr(sE+2+7, sIDEnd-sE-2-7);
				INT itemId = atoi(strId.c_str());

				if(g_pTransferItemSystem->IsElementExist(itemId))
				{//ok, valid item element found.

					//0. push normal replace str
					pc.bReplace = TRUE;
					pc.pice = strSrc.substr(sC, sE-sC);
					vSrcPice.push_back(pc);
					//1. push no replace str
					pc.bReplace = FALSE;
					pc.pice = strSrc.substr(sE, sIDEnd-sE+1);
					vSrcPice.push_back(pc);
				}

				//step to new point.
				sE = sIDEnd + 1;
				sC = sE;
			}
			else if(strInfoMsg == "_INFOMSG")
			{
				//get info message
				INT nContentsLen = atoi(strSrc.substr(sE+2+8,3).c_str());
				STRING::size_type sIDEnd = sE+2+8+3+nContentsLen;
				if(sE+2+8 >= sLen)
				{
					//skip invalid #{
					sE += 2;
					goto LengthOver2;
				}
				
				//ok, valid info message found.
				//0. push normal replace str
				pc.bReplace = TRUE;
				pc.pice = strSrc.substr(sC, sE-sC);
				vSrcPice.push_back(pc);
				//1. push no replace str
				pc.bReplace = FALSE;
				pc.pice = strSrc.substr(sE, sIDEnd-sE+1);
				vSrcPice.push_back(pc);

				//step to new point.
				sE = sIDEnd + 1;
				sC = sE;
			}
			else
			{
				//all other things
				sE += 2;
			}
		}
		else
		{
			//single #
			sE += 1;
		}
LengthOver2:
		if(sE >= sLen) 
		{
			if(sC != sE)
			{
				//push last replace str
				pc.bReplace = TRUE;
				pc.pice = strSrc.substr(sC);
				vSrcPice.push_back(pc);
			}
			break;
		}

		//save new begin point
		sB = sE;

		//find next KeyStart
		sE = strSrc.find(KeyStart, sB);

	}while(TRUE);

	//替换字串中的非法字符
	for(INT i = 0; i < (INT)vSrcPice.size(); ++i)
	{

#if	0
		_snprintf(dbgmsg, 255, "vSrcPice[%d]:%s\n", i, vSrcPice[i].pice.c_str());
		::OutputDebugString(dbgmsg);
#endif

		if(TRUE == vSrcPice[i].bReplace)
		{
			STRING strOld = vSrcPice[i].pice;
			ReplaceToSign_Normal(strOld, vSrcPice[i].pice);
		}
	}

	//生成结果字串
	strOut.clear();
	for(INT i = 0; i < (INT)vSrcPice.size(); ++i)
	{
		strOut += vSrcPice[i].pice;
	}

#if	0
	::OutputDebugString("ReplaceToSign End=========================\n");
#endif

}
STRING LPID::Format( const STRING& aLogicalLib, const STRING& aPartName, const STRING& aRevision )
    throw( PARSE_ERROR )
{
    STRING  ret;
    int     offset;

    if( aLogicalLib.size() )
    {
        offset = okLogical( aLogicalLib );
        if( offset != -1 )
        {
            THROW_PARSE_ERROR(
                    _( "Illegal character found in logical lib name" ),
                    wxString::FromUTF8( aLogicalLib.c_str() ),
                    aLogicalLib.c_str(),
                    0,
                    offset
                    );
        }
        ret += aLogicalLib;
        ret += ':';
    }

    {
        STRING  category;
        STRING  base;

        int separation = int( aPartName.find_first_of( "/" ) );

        if( separation != -1 )
        {
            category = aPartName.substr( 0, separation );
            base     = aPartName.substr( separation+1 );
        }
        else
        {
            // leave category empty
            base = aPartName;
        }

        if( (offset = okCategory( category )) != -1 )
        {
            THROW_PARSE_ERROR(
                    _( "Illegal character found in category" ),
                    wxString::FromUTF8( aRevision.c_str() ),
                    aRevision.c_str(),
                    0,
                    offset
                    );
        }

        if( (offset = okBase( base )) != -1 )
        {
            THROW_PARSE_ERROR(
                    _( "Illegal character found in base name" ),
                    wxString::FromUTF8( aRevision.c_str() ),
                    aRevision.c_str(),
                    0,
                    offset + separation + 1
                    );
        }

        if( category.size() )
        {
            ret += category;
            ret += '/';
        }

        ret += base;
    }

    if( aRevision.size() )
    {
        offset = okRevision( aRevision );
        if( offset != -1 )
        {
            THROW_PARSE_ERROR(
                    _( "Illegal character found in revision" ),
                    wxString::FromUTF8( aRevision.c_str() ),
                    aRevision.c_str(),
                    0,
                    offset
                    );
        }

        ret += '/';
        ret += aRevision;
    }

    return ret;
}
int LPID::Parse( const STRING& aLPID )
{
    clear();

    const char* rev = EndsWithRev( aLPID );
    size_t      revNdx;
    size_t      partNdx;
    size_t      baseNdx;
    int         offset;

    //=====<revision>=========================================
    if( rev )
    {
        revNdx = rev - aLPID.c_str();

        // no need to check revision, EndsWithRev did that.
        revision = aLPID.substr( revNdx );
        --revNdx;  // back up to omit the '/' which preceeds the rev
    }
    else
        revNdx = aLPID.size();

    //=====<logical>==========================================
    if( ( partNdx = aLPID.find( ':' ) ) != aLPID.npos )
    {
        offset = SetLogicalLib( aLPID.substr( 0, partNdx ) );
        if( offset > -1 )
        {
            return offset;
        }
        ++partNdx;  // skip ':'
    }
    else
        partNdx = 0;

    //=====<rawName && category>==============================
    // "length limited" search:
    const char* base = (const char*) memchr( aLPID.c_str() + partNdx, '/', revNdx - partNdx );

    if( base )
    {
        baseNdx  = base - aLPID.c_str();
        offset  = SetCategory( aLPID.substr( partNdx, baseNdx - partNdx ) );
        if( offset > -1 )
        {
            return offset + partNdx;
        }
        ++baseNdx;   // skip '/'
    }
    else
    {
        baseNdx = partNdx;
    }

    //=====<baseName>==========================================
    offset = SetBaseName( aLPID.substr( baseNdx, revNdx - baseNdx ) );
    if( offset > -1 )
    {
        return offset + baseNdx;
    }

    return -1;
}
MgSpatialContextData* MgServerGetSpatialContexts::GetSpatialContextData(
    FdoISpatialContextReader* spatialReader, MgSpatialContextInfo* spatialContextInfo)
{
    Ptr<MgSpatialContextData> spatialData = new MgSpatialContextData();

    // Name must exist
    FdoString* name = spatialReader->GetName();
    CHECKNULL((FdoString*)name, L"MgServerGetSpatialContexts.GetSpatialContexts");
    spatialData->SetName(STRING(name));

    STRING coordSysName = L"";
    FdoString* csName = spatialReader->GetCoordinateSystem();

    Ptr<MgCoordinateSystemFactory> csFactory;
    // WKT for co-ordinate system
    FdoString* csWkt = NULL;
    STRING srsWkt = L"";

    bool haveValidCoordSys = false;
    if(NULL != csName && *csName != '\0')
    {
        coordSysName = STRING(csName);
    }
    else
    {
        csWkt = spatialReader->GetCoordinateSystemWkt();
        if (csWkt != NULL && *csWkt != '\0')
        {
            srsWkt = csWkt;
            try
            {
                csFactory = new MgCoordinateSystemFactory();
                coordSysName = csFactory->ConvertWktToCoordinateSystemCode(srsWkt);
                haveValidCoordSys = (coordSysName.size() != 0);
            }
            catch (MgException* e)
            {
                SAFE_RELEASE(e);
            }
            catch(...)
            {
            }
        }
    }

    bool spatialContextDefined = !coordSysName.empty();
    bool coordSysOverridden = false;

    // look for coordinate system override
    if (NULL != spatialContextInfo)
    {
        // Perform substitution of missing coordinate system with
        // the spatial context mapping defined in feature source document
        MgSpatialContextInfo::const_iterator iter = spatialContextInfo->find(name);

        if (spatialContextInfo->end() != iter)
        {
            csName = (iter->second).c_str();
            coordSysOverridden = true;
        }
    }

    if (csName != NULL && *csName != '\0')
    {
        spatialData->SetCoordinateSystem(STRING(csName));
    }

    // Desc for spatial context
    STRING desc = L"";

    // This flag is obsolete and will be deprecated.
    bool isActive = spatialReader->IsActive();

    if (coordSysOverridden)
    {
        srsWkt = csName;
        desc = MgServerFeatureUtil::GetMessage(L"MgCoordinateSystemOverridden");
    }
    else if (spatialContextDefined && !coordSysOverridden)
    {
        // avoid looking one more time after CS in case we have a valid one...
        if (!haveValidCoordSys)
        {
            csWkt = spatialReader->GetCoordinateSystemWkt();
            if(NULL != csWkt && *csWkt != '\0')
                srsWkt = csWkt;

            if (srsWkt.empty())
            {
                try
                {
                    if (csFactory == NULL)
                        csFactory = new MgCoordinateSystemFactory();

                    // Check if the spatial context coordinate system data represents an EPSG
                    // code. If this is the case the WKT data for the EPSG code has to be
                    // retrieved.
                    if (IsEpsgCodeRepresentation(csName))
                    {
                        // This is an EPSG code
                        FdoString* p = NULL;
                        if ((csName[0] == L'E') || (csName[0] == L'e'))
                            p = csName+5;
                        else
                            p = csName;

                        INT32 epsgCode = (INT32)wcstol(p, NULL, 10);

                        // Convert the EPSG numerical code to WKT
                        srsWkt = csFactory->ConvertEpsgCodeToWkt(epsgCode);
                    }
                    else
                    {
                        srsWkt = csFactory->ConvertCoordinateSystemCodeToWkt(STRING(csName));
                    }
                }
                catch (MgException* e)
                {
                    SAFE_RELEASE(e);
                }
                catch(...)
                {
                    // Just use the empty WKT.
                }
            }
        }
        FdoString* fdoDesc = spatialReader->GetDescription();
        if(NULL != fdoDesc)
            desc = STRING(fdoDesc);
    }

    // retrieve other values from spatialReader
    FdoSpatialContextExtentType extentType = spatialReader->GetExtentType();
    FdoPtr<FdoByteArray> byteArray = spatialReader->GetExtent();
    double xyTol = spatialReader->GetXYTolerance();
    double zTol = spatialReader->GetZTolerance();

    spatialData->SetCoordinateSystemWkt(srsWkt);
    spatialData->SetDescription(desc);
    spatialData->SetExtentType((INT32)extentType);

    if (byteArray.p != NULL)
    {
        INT32 size = (INT32)byteArray->GetCount();
        BYTE_ARRAY_IN bytes = (BYTE_ARRAY_IN)byteArray->GetData();
        Ptr<MgByte> extent = new MgByte(bytes, size);
        spatialData->SetExtent(extent);
    }

    // XY Tolerance
    spatialData->SetXYTolerance(xyTol);

    // Z Tolerance
    spatialData->SetZTolerance(zTol);

    // This flag is obsolete and will be deprecated.
    spatialData->SetActiveStatus(isActive);

    return spatialData.Detach();
}
void DIR_LIB_SOURCE::cacheOneDir( const STRING& aCategory ) throw( IO_ERROR )
{
    STRING      curDir = sourceURI;

    if( aCategory.size() )
        curDir += "/" + aCategory;

    DIR_WRAP    dir = opendir( curDir.c_str() );

    if( !dir )
    {
        STRING  msg = strerror( errno );
        msg += "; scanning directory " + curDir;
        THROW_IO_ERROR( msg );
    }

    struct stat     fs;
    STRING          partName;
    STRING          fileName;
    dirent*         entry;

    while( (entry = readdir( *dir )) != NULL )
    {
        if( !strcmp( ".", entry->d_name ) || !strcmp( "..", entry->d_name ) )
            continue;

        fileName = curDir + "/" + entry->d_name;

        if( !stat( fileName.c_str(), &fs ) )
        {
            // is this a valid part name?
            if( S_ISREG( fs.st_mode ) && makePartName( &partName, entry->d_name, aCategory ) )
            {
                std::pair<NAME_CACHE::iterator, bool> pair = partnames.insert( partName );

                if( !pair.second )
                {
                    STRING  msg = partName;
                    msg += " has already been encountered";
                    THROW_IO_ERROR( msg );
                }
            }

            // is this an acceptable category name?
            else if( S_ISDIR( fs.st_mode ) && !aCategory.size() && isCategoryName( entry->d_name ) )
            {
                // only one level of recursion is used, controlled by the
                // emptiness of aCategory.
                categories.insert( entry->d_name );

                // somebody needs to test Windows (mingw), make sure it can
                // handle opendir() recursively
                cacheOneDir( entry->d_name );
            }
            else
            {
                //D( printf( "ignoring %s\n", entry->d_name );)
            }
        }
    }
}
void DIR_LIB_SOURCE::ReadPart( STRING* aResult, const STRING& aPartName, const STRING& aRev )
    throw( IO_ERROR )
{
    STRING      partName = aPartName;
    const char* hasRev   = endsWithRev( partName );

    if( useVersioning )
    {
        if( aRev.size() )
        {
            // a supplied rev replaces any in aPartName
            if( hasRev )
                partName.resize( hasRev - partName.c_str() - 1 );

            partName += '/';
            partName + aRev;

            // find this exact revision

            PN_ITER it = partnames.find( partName );

            if( it == partnames.end() )    // part not found
            {
                partName += " not found.";
                THROW_IO_ERROR( partName );
            }

            readString( aResult, makeFileName( partName ) );
        }

        else
        {
            // There's no rev on partName string.  Find the most recent rev, i.e. highest,
            // which will be first because of the BY_REV compare method, which treats
            // higher numbered revs as first.

            STRING search = partName + '/';

            // There's no rev on partName string.  Find the most recent rev, i.e. highest,
            // which will be first because of the BY_REV compare method, which treats
            // higher numbered revs as first.
            PN_ITER it = partnames.upper_bound( search );

            // verify that this one that is greater than partName is a match and not
            // some unrelated name that is larger.
            if( it == partnames.end() ||
                it->compare( 0, search.size(), search ) != 0 )
            {
                partName += " is not present without a revision.";
                THROW_IO_ERROR( partName );
            }

            readString( aResult, makeFileName( *it ) );
        }
    }

    else    // !useVersioning
    {
#if 1
        if( hasRev || aRev.size() )
        {
            STRING msg = "this type 'dir' LIB_SOURCE not using 'useVersioning' option, cannot ask for a revision";
            THROW_IO_ERROR( msg );
        }
#else
        // no revisions allowed, strip it
        if( hasRev )
            partName.resize( hasRev - partName.c_str() - 1 );
#endif

        // find the part name without any revision

        PN_ITER it = partnames.find( partName );

        if( it == partnames.end() )    // part not found
        {
            partName += " not found.";
            THROW_IO_ERROR( partName );
        }

        readString( aResult, makeFileName( partName ) );
    }
}
Exemple #20
0
int main(int argc, char** argv)
{
#if defined(_WIN32) && defined(_DEBUG)
#if !defined(USING_VLD)
    _CrtSetDbgFlag(_CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF);

    #ifdef _DEBUG
    // to debug memory leaks, set a breakpoint here and set iBlock
    // to the block allocation you want to break on
    long iBlock = -1;
    _CrtSetBreakAlloc(iBlock);
    #endif
#endif
#endif

    ACE_DEBUG((LM_INFO, ACE_TEXT("Initialize Platform.ini\n")));
    //Benchmark this
#ifdef WIN32
    //Muffle errors due to broken FDO RDBMS provider dlls, they aren't the ones exercised
    //under test anyway
    SetErrorMode(SEM_FAILCRITICALERRORS);
    long lStart = GetTickCount();
#endif
    MgdPlatform::Initialize(L"Platform.ini");
#ifdef WIN32
    ACE_DEBUG((LM_INFO, ACE_TEXT("Platform Initialization time in %dms\n"), (GetTickCount()-lStart)));
#endif
    Ptr<MgCoordinateSystemFactory> csFactory = new MgCoordinateSystemFactory();
    Ptr<MgCoordinateSystemCatalog> csCatalog = csFactory->GetCatalog();
    STRING dictDir = csCatalog->GetDictionaryDir();

    ACE_DEBUG((LM_INFO, ACE_TEXT("MENTOR_DICTIONARY_PATH is: %s\n"), dictDir.c_str()));

    CppUnit::TextUi::TestRunner runner;

    // Add all of the tests
    //NOTE: Leave trace log off, otherwise one of the tests here will fail
#if TEST_LOG_MANAGER == 1
    runner.addTest(CppUnit::TestFactoryRegistry::getRegistry("TestLogManager").makeTest());
#endif
#if TEST_RESOURCE_SERVICE == 1
    runner.addTest(CppUnit::TestFactoryRegistry::getRegistry("TestResourceService").makeTest());
#endif
#if TEST_RENDERING_SERVICE == 1
    runner.addTest(CppUnit::TestFactoryRegistry::getRegistry("TestRenderingService").makeTest());
#endif
#if TEST_FEATURE_SERVICE == 1
    runner.addTest(CppUnit::TestFactoryRegistry::getRegistry("TestFeatureService").makeTest());
#endif
#if TEST_MAPPING_SERVICE == 1
    runner.addTest(CppUnit::TestFactoryRegistry::getRegistry("TestMappingService").makeTest());
#endif
#if TEST_PROFILING_SERVICE == 1
	runner.addTest(CppUnit::TestFactoryRegistry::getRegistry("TestProfilingService").makeTest());
#endif
#if TEST_TILE_SERVICE == 1
    //This causes access violations in Visual Leak Detector when run in debug mode. Only uncommment
    //to verify functionality, but don't use VLD for memory leak detection. Seek an alternate tool/library
    //in this case.
    runner.addTest(CppUnit::TestFactoryRegistry::getRegistry("TestTileService").makeTest());
#endif

    STRING fileName = L"UnitTestResults.xml";
    if (fileName.size() > 0)
    {
        ofstream outfile(MG_WCHAR_TO_CHAR(fileName.c_str()));

        if (outfile.is_open())
        {
            runner.setOutputter(new CppUnit::XmlOutputter(&runner.result(), outfile, "ISO-8859-1"));
            runner.run();
            outfile.close();
        }
    }
    else
    {
        runner.setOutputter(new CppUnit::TextOutputter(&runner.result(), std::cout));
        runner.run();
    }

    int nResult = runner.result().testFailuresTotal();

    MgdPlatform::Terminate();

    return nResult;
}
Exemple #21
-1
/**
 * string replace function
 * @param string str need op string
 * @param string old_str need replace old string
 * @param string new_str need replace to new string
 */
STRING CCUtil::StrReplace( STRING str, STRING search_str, STRING replace_str )
{
    STRING::size_type pos = 0 ;
    while( ( pos = str.find( search_str, pos ) ) != STRING::npos )
    {
        str.replace( pos, search_str.size(), replace_str ) ;
        pos++ ;
    }
    return str ;
}