Example #1
0
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);
	}
}
Example #2
0
int main(int argumentCount, const CHAR** arguments)
{
    CommandLine commandLine(argumentCount, arguments);
    
    do
    {
        STRING simulationType;
        cout << "Entrez le type de simulation (1 ou 2 ou q pour quitter) : ";
        getline(cin, simulationType);

        UINT quitLetterPosition = simulationType.find("q");
        if ( quitLetterPosition != string::npos )
            return 0;

        UINT automaticLetterPosition = simulationType.find("a");

        BOOL promptPosition = automaticLetterPosition == string::npos;
        BOOL promptVelocity = automaticLetterPosition == string::npos;

        Vector initialPosition = Tp1Constants::INITIAL_POSITION;
        Vector initialVelocity = Tp1Constants::INITIAL_VELOCITY;

        if ( promptPosition )
            promptInitialPosition(initialPosition);
        if ( promptVelocity )
            promptInitialVelocity(initialVelocity);

        cout << endl << "Fermer la fenetre pour recommencer une simulation ou terminer le programme" << endl << endl;

        UINT type1Position = simulationType.find("1");
        if ( type1Position != string::npos ) // Simulation 1 
            ApplicationManager::get()->startApplication(new Tp1Simulation1(&commandLine, 
                                                                           initialPosition, 
                                                                           initialVelocity));
        else                                 // Simulation 2
            ApplicationManager::get()->startApplication(new Tp1Simulation2(&commandLine, 
                                                                           initialPosition, 
                                                                           initialVelocity));

        // Les resultat sont afficher dans la simulation directement

        ApplicationManager::destroy();

    } while( TRUE );

    return 0;
}
Example #3
0
CKT::CVersion::CVersion(STRING version)
{
	int iPoint = version.find('.');
	STRING sTemp = version.substr(0, iPoint);
	m_byMajor = (BYTE)toInt(sTemp.c_str());

	sTemp = version.substr(iPoint + 1, version.length() - iPoint);
	m_byMinor = (BYTE)toInt(sTemp.c_str());
}
Example #4
0
//////////////////////////////////////////////////////////////////////////
//CStringFilter
//////////////////////////////////////////////////////////////////////////
BOOL CStringFilter::IsInclude(const STRING& strIn)
{
	STRING::size_type allsize = m_vIncluce.size();
	for(STRING::size_type i = 0; i < m_vIncluce.size(); ++i)
	{
		if(STRING::npos != strIn.find(m_vIncluce[i]))	return TRUE;	//包含
	}
	return FALSE;
}
Example #5
0
void MgWmsLayerDefinitions::GenerateDefinitions(MgUtilDictionary& Dictionary)
{
    MgXmlSynchronizeOnElement ResourceDocument(*m_xmlParser,_("ResourceDocument"));
    if(!ResourceDocument.AtBegin())
        return; // Something is wrong.  We leave.

    while(!ResourceDocument.AtEnd()) {
        STRING sValue; // basic_string
        if(GetElementContents(_("ResourceId"),sValue)) {
            // Okay, the ResourceId is too decorated for our purposes;
            // the outside world doesn't need to know (and clutter up
            // URL command lines with) this syntactic "punctuation" so
            // we just get rid of it.
            // Remove the Library prefix, if present.
            if(sValue.find(_("Library://")) == 0)
                sValue = sValue.substr(10);
            // Remove the LayerDefinition suffix, if present.
            STRING::size_type iEnd = sValue.find(_(".LayerDefinition"));
            if(iEnd != STRING::npos)
                sValue.resize(iEnd);
            // There, that's our Layer Name.
            Dictionary.AddDefinition(_("Layer.Name"),sValue);

            // Until we have "Friendly Name" support, the
            // friendly name will simply be the layer name sans
            // path.
            iEnd = sValue.find_last_of('/');
            if(iEnd != STRING::npos)
                sValue = sValue.substr(iEnd+1); // one past the slash.

            // That's our Layer Title,
            // Note that subsequently-found metadata may override this
            // definition with a real title... one that the user actually
            // wants.  This just provides a default in case no such
            // friendly name exists.... that keeps the list of layer names
            // from being a list of empty strings.
            Dictionary.AddDefinition(_("Layer.Title"),sValue);
        }
        else if(!GetMetadataDefinitions(Dictionary)) {
          SkipElement(NULL);
        }
    }

}
Example #6
0
/*
 * Remove the path from a file name, perserving folders.
 * preserveFrom should carry a trailing \.
 */
STRING removePath(const STRING str, const STRING preserveFrom)
{
	const int pos = str.find(preserveFrom);
	if (pos != str.npos)
	{
		return str.substr(pos + preserveFrom.length());
	}
	// Return the path unaltered, since it didn't contain the
	// default folder and any other folders should be subfolders
	// (although a different default folder may be present).
	return str;
}
Example #7
0
Set searchPos2(const STRING& text, const STRING& key)
{
	Set ret;
	size_t pos = 0;
	for (;;) {
		size_t q = text.find(key, pos);
		if (q == std::string::npos) break;
		ret.insert((int)q);
		pos = q + 1;
	}
	return ret;
}
Example #8
0
// Resolve a file name
STRING resolvePakFile(const STRING path)
{
	if(path.find("Saved\\",0) ==0){ return path;}
	const STRING file = g_pakTempPath + path;
	resolve = resolveNonPakFile;
	if (!CFile::fileExists(file))
	{
		// Extract the file from the pak file or this executable.
		// (Assume the zip is open!)
		ZIPExtract(const_cast<char *>(path.c_str()), const_cast<char *>(file.c_str()));
	}
	resolve = resolvePakFile;
	return file;
}
Example #9
0
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);
		}
	}
}
Example #10
0
// The return value indicate the main loop to break the loop or not
BOOL promptData(Vector4d& initialLinearVelocity, Vector4d& initialAngularVelocity)
{
    STRING simulationStart;
    
    if (!gFirstRun)
    {
        cout << "Pesez la toucher [Enter] pour continuer la simulation ou q pour quitter : ";
        getline(cin, simulationStart);
    }
    gFirstRun = false;

    UINT quitLetterPosition = simulationStart.find("q");
    if ( quitLetterPosition != string::npos )
        return TRUE;

    promptLinearVelocity(initialLinearVelocity);
    promptAngularVelocity(initialAngularVelocity);

    return FALSE;
}
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;
}
/// <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")
}
Example #13
0
c_RestResponse_HttpData* c_RestResponse::PrepareHttpData(c_RestRequest* RestRequest)
{
  
try
{


    
  char tempHeader[4096];
  
  //string sResponseHeader;
  Ptr<MgByteReader> outputReader;

  Ptr<c_RestResult> result = GetResult();
  STATUS status = result->GetStatusCode();
  STRING statusMessage = result->GetHttpStatusMessage();
  if (status != 200)
  {
    
    if (statusMessage == MapAgentStrings::FailedAuth1 ||
      statusMessage == MapAgentStrings::FailedAuth2
      )
    {
      RequestAuth(RestRequest);
    }
    else
    {
      //TODO: Use a resource for the HTML error message
      char content[4096];

      STRING shortError = result->GetErrorMessage();
      STRING longError = result->GetDetailedErrorMessage();

      sprintf(content,"\r\n"
        "<html>\n<head>\n"
        "<title>%s</title>\n"
        "<meta http-equiv=\"Content-type\" content=\"text/html; charset=utf-8\">\n"
        "</head>\n"
        "<body>\n<h2>%s</h2>\n%s\n</body>\n</html>\n",
        MG_WCHAR_TO_CHAR(statusMessage),
        MG_WCHAR_TO_CHAR(shortError),
        MG_WCHAR_TO_CHAR(longError));

      DWORD  content_length = strlen(content);

      /*
      sprintf(tempHeader, MapAgentStrings::StatusHeader, status, MG_WCHAR_TO_CHAR(statusMessage));
      sResponseHeader.append(tempHeader);

      sprintf(tempHeader, MapAgentStrings::ContentLengthHeader, (int)content_length);
      sResponseHeader.append(tempHeader);

      sprintf(tempHeader, MapAgentStrings::ContentTypeHeader, MapAgentStrings::TextHtml, "");
      sResponseHeader.append(tempHeader);
      */
      
      m_HttpData.SetStatusAndReason(status,MG_WCHAR_TO_CHAR(statusMessage));      
      m_HttpData.AddHeader(MapAgentStrings::ContentTypeKey,MapAgentStrings::TextHtml);
      sprintf(tempHeader, "%d", (int)content_length);
      m_HttpData.AddHeader(MapAgentStrings::ContentLengthKey,tempHeader);
      
      
      m_HttpData.SetContent(content);
  
    }
  }
  else
  {

    // Status was ok.  Send the real result back.
    STRING result_contentType = result->GetResultContentType();
    STRING response_contentType = GetContentType();
    std::string stringval_utf8;

    //sprintf(tempHeader, MapAgentStrings::StatusOkHeader);
    //sResponseHeader.append(tempHeader);
    
    m_HttpData.SetStatusAndReason(200,"OK");
    

    if (response_contentType.length() > 0)
    {
      // If we are returning text, state that it is utf-8.
      
      STRING mime = response_contentType;
      if( response_contentType == RestMimeType::JsonP )
      {
        mime = L"text/plain";
      }
      else
      { 
        if( response_contentType == RestMimeType::Json )
        {
          mime = L"text/plain";
        }
      } 
      
      string charSet = "";
      if (mime.find(L"text") != mime.npos)  //NOXLATE
      {
        charSet = MapAgentStrings::Utf8Text;
      }
      //sprintf(tempHeader, MapAgentStrings::ContentTypeHeader, MG_WCHAR_TO_CHAR(response_contentType), charSet.c_str());
      //sResponseHeader.append(tempHeader);
      sprintf(tempHeader, "%s%s", MG_WCHAR_TO_CHAR(mime), charSet.c_str());
      m_HttpData.AddHeader(MapAgentStrings::ContentTypeKey,tempHeader);
    }
    else
    {
      //sprintf(tempHeader, MapAgentStrings::ContentTypeHeader, MapAgentStrings::TextPlain, MapAgentStrings::Utf8Text);
      //sResponseHeader.append(tempHeader);
      sprintf(tempHeader, "%s%s", MapAgentStrings::TextPlain, MapAgentStrings::Utf8Text);
      m_HttpData.AddHeader(MapAgentStrings::ContentTypeKey,tempHeader);
    }
    



    Ptr<MgDisposable> resultObj = result->GetResultObject();
    MgDisposable* pResultObj = (MgDisposable*)resultObj;

    // Test type of response needed
    Ptr<c_RestDataReader> restreader = NULL;

    MgProxyFeatureReader* proxyfreader = dynamic_cast<MgProxyFeatureReader*>(pResultObj);
    if( proxyfreader )
    {
      restreader = new c_RestDataReader_MgFeatureReader(proxyfreader);
      
    }
    else
    {
      restreader = SAFE_ADDREF(dynamic_cast<c_RestDataReader*>(pResultObj));
    }
    
    
    if( RestRequest->m_CfgRepresentation && RestRequest->m_CfgRepresentation->GetType() == c_CfgRepresentation::e_Template)
    {
      if( response_contentType == RestMimeType::Html  )
      {      
        c_FeatureReaderToHtml::ToHtml(restreader,RestRequest,RestRequest->GetOriginalFullUri(),RestRequest->GetBaseUri(),stringval_utf8,result->m_FeatureReader_StartIndex,result->m_FeatureReader_Count);            
        
      }
      else
      {
        if( response_contentType == RestMimeType::Kml  )
        {
            c_FeatureReaderToHtml::ToKml(restreader.p,RestRequest,RestRequest->GetOriginalFullUri(),RestRequest->GetBaseUri(),stringval_utf8,result->m_FeatureReader_StartIndex,result->m_FeatureReader_Count);            
        }
        else
        {
          if( response_contentType == RestMimeType::Kmz  )
          {
              outputReader = c_FeatureReaderToHtml::ToKmz(restreader.p,RestRequest,RestRequest->GetOriginalFullUri(),RestRequest->GetBaseUri(),result->m_FeatureReader_StartIndex,result->m_FeatureReader_Count);
          }
          else
          {
            c_FeatureReaderToHtml::ToTemplate(false,restreader,RestRequest,RestRequest->GetOriginalFullUri(),RestRequest->GetBaseUri(),stringval_utf8,result->m_FeatureReader_StartIndex,result->m_FeatureReader_Count);              
            
          }
        }
      }
    }
    
    if( RestRequest->m_CfgRepresentation && RestRequest->m_CfgRepresentation->GetType() == c_CfgRepresentation::e_FeaturesXML)
    {
      if( restreader.p )
      {
        c_FeatureReaderToXML::ToXml(restreader.p,stringval_utf8,result->m_FeatureReader_StartIndex,result->m_FeatureReader_Count);
      }
    }
    if( RestRequest->m_CfgRepresentation && RestRequest->m_CfgRepresentation->GetType() == c_CfgRepresentation::e_Sitemap)
    {
      if( restreader.p )
      {
        c_FeatureReaderToXML::ToSitemapXml(restreader.p,RestRequest,RestRequest->GetBaseUri(),stringval_utf8,result->m_FeatureReader_StartIndex,result->m_FeatureReader_Count);
      }
    }
    if( RestRequest->m_CfgRepresentation && RestRequest->m_CfgRepresentation->GetType() == c_CfgRepresentation::e_FeaturesJSON)
    {
      if( restreader.p )
      {
        c_FeatureReaderToGeoJson::ToGeoJson(restreader.p,stringval_utf8,result->m_FeatureReader_StartIndex,result->m_FeatureReader_Count);
      }
    }
    if( RestRequest->m_CfgRepresentation && RestRequest->m_CfgRepresentation->GetType() == c_CfgRepresentation::e_Custom)
    {
      if( restreader.p )
      {
        //std::stringstream strs;
        c_CfgRepresentation_Custom *customrep =  (c_CfgRepresentation_Custom *)RestRequest->m_CfgRepresentation;
        
        Ptr<c_StreamResponse_FReader2Custom> streamout = new c_StreamResponse_FReader2Custom(restreader.p,customrep);
        m_HttpData.SetContent(streamout);
        
        return &m_HttpData;  // need to go out here - bellow is closing featuer reader - setting hhtp header for content length etc..
         
        ///(*(customrep->m_CustomRenderer->m_FuncContent2Stream))(restreader.p,&strs);
        
        //stringval_utf8 = strs.str();
        //c_FeatureReaderToGeoJson::ToGeoJson(restreader.p,stringval_utf8,result->m_FeatureReader_StartIndex,result->m_FeatureReader_Count);
      }
    }
    if( restreader.p )
    {
      restreader->Close();
    }
    
    if (NULL != dynamic_cast<c_RestPrimitiveValue*>(pResultObj))
    { 
      stringval_utf8 = ((c_RestPrimitiveValue*)pResultObj)->ToStringUTF8();;

    }
    else if (NULL != dynamic_cast<MgByteReader*>(pResultObj))
    {
      outputReader = (MgByteReader*) SAFE_ADDREF(pResultObj);

    }
    else if (NULL != dynamic_cast<MgStringCollection*>(pResultObj))
    {
      outputReader = ((MgStringCollection*)pResultObj)->ToXml();

    }
    else if (NULL != dynamic_cast<MgSqlDataReader*>(pResultObj))
    {
      outputReader = ((MgSqlDataReader*)pResultObj)->ToXml();

    }
    else if (NULL != dynamic_cast<MgDataReader*>(pResultObj))
    {
      outputReader = ((MgDataReader*)pResultObj)->ToXml();

    }    
    

    if (stringval_utf8.length() > 0)
    {

      if( response_contentType == RestMimeType::JsonP || 
        ( response_contentType == RestMimeType::Json && (GetJsonpCallbackName().length()>0))
        )
      {
        //utf8 = response->GetJsonpCallbackName() + "( \"" + utf8 + "\" )"; ...
        std::string jsonp;
        CreateJsonpCallbackString(GetJsonpCallbackName(),stringval_utf8,jsonp);
        stringval_utf8 = jsonp;
      }

      sprintf(tempHeader, "%d", stringval_utf8.length());
      m_HttpData.AddHeader(MapAgentStrings::ContentLengthKey,tempHeader);
      

      m_HttpData.SetContent(stringval_utf8);
      
    }
    else if (outputReader != NULL)
    {
      if( response_contentType == RestMimeType::Json || response_contentType == RestMimeType::JsonP )
      {
        MgXmlJsonConvert convert;
        convert.ToJson(outputReader);

        if( response_contentType == RestMimeType::JsonP )
        {
          string json;
          // set read back to text from Jason so it can be converted to string with function 'ToStringUtf8'
          outputReader->GetByteSource()->SetMimeType(RestMimeType::Text);
          outputReader->ToStringUtf8(json);

          string jsonp;
          CreateJsonpCallbackString(GetJsonpCallbackName(),json,jsonp);

          Ptr<MgByteSource> byteSource = new MgByteSource(
            (unsigned char*)jsonp.c_str(), (INT32)jsonp.length());
          byteSource->SetMimeType(RestMimeType::JsonP);
          outputReader.Attach(byteSource->GetReader());   
        }
      }

      INT64 outLen = outputReader->GetLength();
      sprintf(tempHeader, "%d", (INT32)outLen);
      
      m_HttpData.AddHeader(MapAgentStrings::ContentLengthKey,tempHeader);
      
     
      m_HttpData.SetContent(outputReader);

      // Tell IIS to keep the connection open 
      //DWORD dwState = HSE_STATUS_SUCCESS_AND_KEEP_CONN;
      //m_pECB->ServerSupportFunction(m_pECB->ConnID, HSE_REQ_DONE_WITH_SESSION, &dwState, NULL, 0);
    }
    else
    {
      
      sprintf(tempHeader, "%d", 0);

      m_HttpData.AddHeader(MapAgentStrings::ContentLengthKey,tempHeader);
      

      // Tell IIS to keep the connection open 
      //DWORD dwState = HSE_STATUS_SUCCESS_AND_KEEP_CONN;
      //m_pECB->ServerSupportFunction(m_pECB->ConnID, HSE_REQ_DONE_WITH_SESSION, &dwState, NULL, 0);
    }
  }
  
  return &m_HttpData;
}                                                                         
catch (MgException* exc)                                                    
{       
  SendError(exc);
  exc->Release();                                                                
}                                                                        
catch (exception& e)                                                     
{                                                                         
  Ptr<MgException> mgException = MgSystemException::Create(e, L"c_RestResponse::PrepareHttpData", __LINE__, __WFILE__); 
  SendError(mgException);
}                                                                         
catch (...)                                                               
{                                                                         
  Ptr<MgException> mgException = new MgUnclassifiedException(L"c_RestResponse::PrepareHttpData", __LINE__, __WFILE__, NULL, L"", NULL); 
  SendError(mgException);
}  

}//end of c_RestResponse::PrepareHttpData
Example #14
0
// 字符串相关
INT	KLU_ConvertStringToVector(LPCTSTR strStrintgSource, std::vector< STRING >& vRet, LPCTSTR szKey, BOOL bOneOfKey, BOOL bIgnoreEmpty)
{
	vRet.clear();

	//------------------------------------------------------------
	//合法性
	if(!strStrintgSource || strStrintgSource[0] == '\0') return 0;
	
	STRING strSrc = strStrintgSource;

	//------------------------------------------------------------
	//查找第一个分割点
	STRING::size_type nLeft = 0;
	STRING::size_type nRight;
	if(bOneOfKey)
	{
		nRight = strSrc.find_first_of(szKey);
	}
	else
	{
		nRight = strSrc.find(szKey);
	}

	if(nRight == std::string::npos)
	{
		nRight = strSrc.length();
	}
	while(TRUE)
	{
		STRING strItem = strSrc.substr(nLeft, nRight-nLeft);
		if(strItem.length() > 0 || !bIgnoreEmpty)
		{
			vRet.push_back(strItem);
		}

		if(nRight == strSrc.length())
		{
			break;
		}

		nLeft = nRight + (bOneOfKey ? 1 : _tcslen(szKey));
		
		if(bOneOfKey)
		{
			STRING strTemp = strSrc.substr(nLeft);
			nRight = strTemp.find_first_of(szKey);
			if(nRight != STRING::npos) nRight += nLeft;
		}
		else
		{
			nRight = strSrc.find(szKey, nLeft);
		}

		if(nRight == std::string::npos)
		{
			nRight = strSrc.length();
		}
	}

	return (INT)vRet.size();
}
Example #15
0
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

}
Example #16
0
BOOL DoParseFile(LPVOID pvContents, DWORD dwSize)
{
    ITEMVECTOR  Items;

    LPWSTR pch, pchSep, pchStart = (LPWSTR)pvContents;

    pchStart[dwSize / sizeof(WCHAR)] = UNICODE_NULL;

    // check header
    const DWORD cbHeader = lstrlenW(g_pszFileHeader) * sizeof(WCHAR);
    if (memcmp(pchStart, g_pszFileHeader, cbHeader) != 0)
        return FALSE;

    pchStart += cbHeader / sizeof(WCHAR);

    // find the key
    WCHAR szKey[MAX_STRING];
    wsprintfW(szKey, L"[HKEY_LOCAL_MACHINE\\%s]", g_pszKey);
    pch = wcsstr(pchStart, szKey);
    if (pch == NULL)
        return FALSE;

    pchStart = pch + lstrlenW(szKey);

    for (;;)
    {
        pchStart = SkipSpace(pchStart);
        if (*pchStart == UNICODE_NULL || *pchStart == L'[')
            break;

        pch = wcschr(pchStart, L'\n');
        if (pch)
            *pch = UNICODE_NULL;

        pchSep = SkipQuoted(pchStart);
        if (*pchSep == L'=')
        {
            *pchSep = UNICODE_NULL;

            STRING key = pchStart;
            trim(key);
            key = Unquote(key);

            STRING value = pchSep + 1;
            trim(value);
            value = Unquote(value);

            BYTE CharSet1 = DEFAULT_CHARSET, CharSet2 = DEFAULT_CHARSET;

            size_t pos;
            pos = key.find(L',');
            if (pos != STRING::npos)
            {
                CharSet1 = (BYTE)_wtoi(&key[pos + 1]);
                key.resize(pos);
                trim(key);
            }
            pos = value.find(L',');
            if (pos != STRING::npos)
            {
                CharSet2 = (BYTE)_wtoi(&value[pos + 1]);
                value.resize(pos);
                trim(value);
            }

            ITEM Item(key, value, CharSet1, CharSet2);
            Items.push_back(Item);
        }

        if (pch == NULL)
            break;

        pchStart = pch + 1;
    }

    g_Items = Items;
    g_bModified = TRUE;

    LV_AddItems(g_hListView);
    return TRUE;
}
Example #17
0
void CgiResponseHandler::SendResponse(MgHttpResponse* response)
{
    MG_TRY()

    Ptr<MgHttpResult> result = response->GetResult();
    STATUS status = result->GetStatusCode();
    if (status != 200)
    {
        STRING statusMessage = result->GetHttpStatusMessage();
        if (statusMessage == MapAgentStrings::FailedAuth1 ||
            statusMessage == MapAgentStrings::FailedAuth2)
        {
            RequestAuth();
        }
        else
        {
            //TODO: Use a resource for the HTML error message
            STRING shortError = result->GetErrorMessage();
            STRING longError = result->GetDetailedErrorMessage();
            printf(MapAgentStrings::StatusHeader, status, MG_WCHAR_TO_CHAR(statusMessage));
            printf(MapAgentStrings::ContentTypeHeader, MapAgentStrings::TextHtml, "");
            printf("\r\n"
                "<html>\n<head>\n"
                "<title>%s</title>\n"
                "<meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\">\n"
                "</head>\n"
                "<body>\n<h2>%s</h2>\n%s\n</body>\n</html>\n",
                MG_WCHAR_TO_CHAR(statusMessage),
                MG_WCHAR_TO_CHAR(shortError),
                MG_WCHAR_TO_CHAR(longError));

            DumpMessage(MG_WCHAR_TO_CHAR(longError));
        }
    }
    else
    {
        DumpMessage(MapAgentStrings::StatusOkHeader);

        // Status was ok.  Send the real result back.
        STRING contentType = result->GetResultContentType();
        STRING stringVal;

        printf(MapAgentStrings::StatusOkHeader);
        if (contentType.length() > 0)
        {
            // If we are returning text, state that it is utf-8.
            string charSet = "";
            if (contentType.find(L"text") != contentType.npos)  //NOXLATE
            {
                charSet = MapAgentStrings::Utf8Text;
            }
            printf(MapAgentStrings::ContentTypeHeader, MG_WCHAR_TO_CHAR(contentType), charSet.c_str());
        }
        else
        {
            printf(MapAgentStrings::ContentTypeHeader, MapAgentStrings::TextPlain, MapAgentStrings::Utf8Text);
        }

        Ptr<MgByteReader> outputReader;
        Ptr<MgDisposable> resultObj = result->GetResultObject();
        MgDisposable* pResultObj = (MgDisposable*)resultObj;

        if (NULL != dynamic_cast<MgByteReader*>(pResultObj))
        {
            outputReader = (MgByteReader*) SAFE_ADDREF(pResultObj);
        }
        else if (NULL != dynamic_cast<MgStringCollection*>(pResultObj))
        {
            outputReader = ((MgStringCollection*)pResultObj)->ToXml();
        }
        else if (NULL != dynamic_cast<MgSpatialContextReader*>(pResultObj))
        {
            outputReader = ((MgSpatialContextReader*)pResultObj)->ToXml();
        }
        else if (NULL != dynamic_cast<MgLongTransactionReader*>(pResultObj))
        {
            outputReader = ((MgLongTransactionReader*)pResultObj)->ToXml();
        }
        else if (NULL != dynamic_cast<MgHttpPrimitiveValue*>(pResultObj))
        {
            stringVal = ((MgHttpPrimitiveValue*)pResultObj)->ToString();
        }

        if (stringVal.length() > 0)
        {
            string utf8 = MG_WCHAR_TO_CHAR(stringVal);
            printf(MapAgentStrings::ContentLengthHeader, utf8.length());
            printf("\r\n%s",utf8.c_str());
        }
        else if (outputReader != NULL)
        {
            Ptr<MgHttpHeader> respHeader = response->GetHeader();
            //Check for chunking hint
            if (respHeader->GetHeaderValue(MgHttpResourceStrings::hrhnTransfer_Encoding) == MgHttpResourceStrings::hrhnChunked)
            {
                CgiReaderStreamer crs(outputReader);
                crs.StreamResult();
            }
            else
            {
                INT64 outLen = outputReader->GetLength();
                printf(MapAgentStrings::ContentLengthHeader,(INT32)outLen);
                printf("\r\n");
                unsigned char buf[4096];
                int nBytes = outputReader->Read(buf,4096);
                while (nBytes > 0)
                {
                    fwrite(buf, 1, nBytes, stdout);
                    nBytes = outputReader->Read(buf,4096);
                }
            }
        }
        else
        {
            printf(MapAgentStrings::ContentLengthHeader, 0);
            printf("\r\n");
        }
    }

    MG_CATCH_AND_THROW(L"CgiResponseHandler.SendResponse");
}
Example #18
0
bool MgWmsLayerDefinitions::GetMetadataDefinitions(MgUtilDictionary& Dictionary)
{
//    STRING sDebug = m_xmlParser->Current().Contents();
    // We're looking for a <ResourceDocumentHeader ...>
    MgXmlSynchronizeOnElement ElementResourceDocumentHeader(*m_xmlParser,_("ResourceDocumentHeader"));
    if(!ElementResourceDocumentHeader.AtBegin())
        return false;

    // And inside that, there's a <Metadata ...>
    MgXmlSynchronizeOnElement ElementMetadata(*m_xmlParser,_("Metadata"));
    if(!ElementMetadata.AtBegin())
        return false;

    // And inside *that*, we hope there's a <Simple...>
    MgXmlSynchronizeOnElement ElementSimple(*m_xmlParser,_("Simple"));
    if(!ElementSimple.AtBegin())
        return false;

    // And once we're here, we hope to find a grunch of <Property...> elements
    while(!ElementSimple.AtEnd()) {
        MgXmlSynchronizeOnElement ElementProperty(*m_xmlParser,_("Property"));
        if(ElementProperty.AtBegin()) {
            // Each of which consist of <Name> and <Value> pairs...
            STRING sName;
            STRING sValue;
            if(GetElementContents(_("Name"),sName) && GetElementContents(_("Value"),sValue)) {
                STRING sDefinitionName =  _("Layer.");
                // Present the names slightly differently than internal representation.
                // System-defined metadata is published with an underscore prefix.  We
                // publish this without the underscore: "_Bounds" -> "Layer.Bounds".
                // User-defined metadata will not have the underscore, and we present
                // this for consumption as "Layer.user.Whatever" -- just to make sure
                // that the user and system namespaces remain distinct.
                if(sName[0] == '_')
                    sDefinitionName += sName.substr(1);
                else
                    sDefinitionName += _("user.") + sName;

                //----------------------------------------------------------------------
                // If it starts and ends with escaped angled brackets, let's assume it's
                // "corrupted" XML that simply needs unescaping.
                //
                // TODO: This is not meant to be a long-term solution; it just overcomes
                // a current schema restriction on metadata consisting of mixed content.
                STRING::size_type iLt =sValue.find(_("&lt;"));
                STRING::size_type iGt = sValue.rfind(_("&gt;"));
                STRING::size_type iLen = sValue.length();
                if(sValue.find(_("&lt;")) == 0 && sValue.rfind(_("&gt;")) == sValue.length() - 4) {
                  STRING::size_type iPos;
                  while((iPos = sValue.find(_("&lt;")))  != STRING::npos)
                    sValue = sValue.substr(0,iPos) + _("<") + sValue.substr(iPos+4);
                  while((iPos = sValue.find(_("&gt;")))  != STRING::npos)
                    sValue = sValue.substr(0,iPos) + _(">") + sValue.substr(iPos+4);
                  while((iPos = sValue.find(_("\x201d")))  != STRING::npos)
                    sValue = sValue.substr(0,iPos) + _("\"") + sValue.substr(iPos+1);
                }
                //----------------------------------------------------------------------

                Dictionary.AddDefinition(sDefinitionName,sValue);
            }
        }
    }

    return true;
}
Example #19
0
	//--------------------------------------------------------------------------
	D3D11Texture::D3D11Texture(const STRING& filename, eTextureType type, uint32 usage, bool bSRGB)
		: Texture(type, 0, 0, 0, ePF_Unknown, usage, true)
		, m_pTexture2D(nullptr)
		, m_pTexture3D(nullptr)
		, m_pRTV(nullptr)
		, m_pSRV(nullptr)
		, m_pDSV(nullptr)
		, m_pTexStaging(nullptr)
	{
		////////////////////////////////////////////////////////////////
		////////////// Load texture
		HRESULT hr = S_OK;
		D3DX11_IMAGE_LOAD_INFO loadInfo;
		loadInfo.MipLevels = 0;
		loadInfo.BindFlags = 0;
		loadInfo.Format = DXGI_FORMAT_FROM_FILE;
		ID3D11Resource** pTex = nullptr;

		switch (GetTextureType())
		{
		case eTextureType_2D:
			{
				pTex = (ID3D11Resource**)&m_pTexture2D;

				if (usage & eTextureUsage_ReadWrite)
				{
					loadInfo.Usage = D3D11_USAGE_STAGING;
					loadInfo.CpuAccessFlags = D3D11_CPU_ACCESS_WRITE | D3D11_CPU_ACCESS_READ;
				}
			}
			break;

		case eTextureType_CubeMap:
			{
				loadInfo.MiscFlags = D3D11_RESOURCE_MISC_TEXTURECUBE;
				pTex = (ID3D11Resource**)&m_pTexture2D;
			}
			break;

		case eTextureType_3D:
			{
				pTex = (ID3D11Resource**)&m_pTexture3D;
			}
			break;

		default: _AST(0);
		}

		if (filename.find(".dds") != STRING::npos)
		{
			if (usage & eTextureUsage_ReadWrite)
			{
				V(DirectX::CreateDDSTextureFromFileEx(g_pRenderSys->GetDevice(), EngineToUnicode(filename).c_str(),
					4096, D3D11_USAGE_STAGING, 0, D3D11_CPU_ACCESS_READ, 0, bSRGB, pTex, nullptr));
			} 
			else
			{
				V(DirectX::CreateDDSTextureFromFileEx(g_pRenderSys->GetDevice(), EngineToUnicode(filename).c_str(),
					4096, D3D11_USAGE_DEFAULT, D3D11_BIND_SHADER_RESOURCE, 0, 0, bSRGB, pTex, &m_pSRV));
			}
		} 
		else
		{
			V(D3DX11CreateTextureFromFileA(g_pRenderSys->GetDevice(), filename.c_str(), &loadInfo, nullptr, pTex, nullptr));

			if (!(usage & eTextureUsage_ReadWrite))
			{
				CreateSRV();
			}
		}

		// Store texture dimension and format
		switch (GetTextureType())
		{
		case eTextureType_2D:
		case eTextureType_CubeMap:
			{
				D3D11_TEXTURE2D_DESC desc;
				m_pTexture2D->GetDesc(&desc);

				m_width = desc.Width;
				m_height = desc.Height;

				m_texFormat = ConvertFromDXFormat(desc.Format);
			}
			break;

		case eTextureType_3D:
			{
				D3D11_TEXTURE3D_DESC desc;
				m_pTexture3D->GetDesc(&desc);

				m_width = desc.Width;
				m_height = desc.Height;

				m_texFormat = ConvertFromDXFormat(desc.Format);
			}
			break;

		default: _AST(0);
		}
	}
Example #20
-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 ;
}