Ejemplo n.º 1
0
TBool versitCheckExportFilesL(const TDesC8& aOrgLine, RFs& aFileSession)
{
	RFile fileHandle;
	TBool patternFound = EFalse;
	fileHandle.Open(aFileSession, KVExportFileName, EFileRead|EFileStreamText);
	CleanupClosePushL(fileHandle);
	
//	TFileText exportedfile; //Bug in TFileText so not used at the moment
//	exportedfile.Set(fileHandle);
//	exportedfile.Seek(ESeekStart);
	TBuf8<256> line;
	
	while(fileHandle.Read(line) == KErrNone && line.Length() != 0)
	{
		if (line.Find(aOrgLine) != KErrNotFound)
		{
		    patternFound = ETrue;
		    break;	
		}	
	}
	
	CleanupStack::PopAndDestroy(&fileHandle);
	return patternFound;
}
Ejemplo n.º 2
0
/**
 *  TotalConvertedLengthL() determines the total length in User Data Elements when the input buffer is converted.
 *  Depending on the conversion properties returned from the alphabet converter, a complete conversion may need
 *  to be performed, i.e. this call can be quite expensive.
 *  
 *  @return Total converted length
 *  
 *  @capability None
 */
EXPORT_C TInt CSmsBufferSegmenter::TotalConvertedLengthL(TSmsEncoding aEncoding)
	{
	OstTraceDef1(OST_TRACE_CATEGORY_DEBUG, TRACE_BORDER, CSMSBUFFERSEGMENTER_TOTALCONVERTEDLENGTHL_1, "CSmsBufferSegmenter::TotalConvertedLengthL(): aEncoding=%d", aEncoding);
	
	// Check for shortcut
	CSmsAlphabetConverter::TSmsAlphabetConversionProperties conversionProperties;
	iAlphabetConverter.ConversionPropertiesL(conversionProperties);
	if (conversionProperties.iWidthConversion==CSmsAlphabetConverter::ESmsAlphabetWidthConversionFixed)
		return iSmsBuffer.Length()*conversionProperties.iUDElementsPerNativeCharacter;

	// No shortcut, have to do piecewise conversion
	Reset();

	//
	// Find the best encoding method to use...
	//
	TSmsEncoding  aEncodingToUse = FindBestAlternativeEncodingL(aEncoding, iSmsBuffer.Length());
	
	//
	// Segment and count the converted length...
	//
	TBool complete=EFalse;
	TInt totalConvertedLength=0;
	TInt unconvertedChars=0;
	TInt downgradedChars=0;
	TBuf8<CSmsBufferBase::EMaxBufLength> convertedChars;
	while (!complete)
		{
		complete=DoSegmentNextL(convertedChars,convertedChars.MaxLength(),
				                unconvertedChars, downgradedChars,
				                aEncodingToUse);
		totalConvertedLength+=convertedChars.Length();
		}
	Reset();
	return totalConvertedLength;
	} // CSmsBufferSegmenter::TotalConvertedLengthL
void CPreModifierPlugin::FsFileReplaceL(TFsPluginRequest& aRequest)
	{
	TFileName filename;
	TParse parse;
	
	filename = aRequest.Src().FullName();

	TUint mode;
	TInt err = aRequest.Read(TFsPluginRequest::EMode, mode);
	iLastError = err;
	iLineNumber = __LINE__;
	if(err!=KErrNone)
		User::Leave(err); //trapped in DoRequestL

	parse.Set(filename, NULL, NULL);
	TPtrC extension(parse.Ext());

	_LOG2(_L("CPreModifierPlugin::FsFileReplaceL, file: %S"), &filename);
	
	if (aRequest.IsPostOperation())
		{
		_LOG(_L("CPreModifierPlugin::FsFileReplaceL, post intercept"));
		if ((extension.CompareF(_L(".tst")) == 0) && (aRequest.Message().Int1() != 0))
			{
			//write to the newly replaced file
			TBuf8<64> wbuffer;
			wbuffer.Copy(_L8("TestTestTest"));

			RFilePlugin fileplugin(aRequest);
			TInt err = fileplugin.AdoptFromClient();
			iLastError = err;
			iLineNumber = __LINE__;
			if(err!=KErrNone)
				User::Leave(err); //trapped in DoRequestL

    		err = fileplugin.Write(0, wbuffer);
			_LOG2(_L("CPreModifierPlugin::FsFileReplaceL, RFilePlugin::Write to the newly created file returned %d"), err);
			iLastError = err;
			iLineNumber = __LINE__;
			if(err!=KErrNone)
				User::Leave(err); //trapped in DoRequestL

			TInt length = wbuffer.Length();
			HBufC8* tempBuf = HBufC8::NewMaxLC(length);
			TPtr8 tempBufPtr((TUint8 *)tempBuf->Des().Ptr(), length, length);
			err = fileplugin.Read(0, tempBufPtr);
			_LOG2(_L("CPreModifierPlugin::FsFileReplaceL, RFilePlugin::Read returned %d"), err);
			iLastError = err;
			iLineNumber = __LINE__;
			if(err!=KErrNone)
				User::Leave(err); //trapped in DoRe

			//testing the correct thing has been written to the drive
			err = wbuffer.Compare(tempBufPtr);
			iLastError = err;
			iLineNumber = __LINE__;
			if(err!=KErrNone)
				User::Leave(err); //trapped in DoRequestL
			
			fileplugin.Close();
			CleanupStack::PopAndDestroy();
			}
		}
	else
		{
		User::Invariant();
		}
	}
Ejemplo n.º 4
0
// --------------------------------------------------------------------------
// CImageCapture::GetNextFileNameLC
// Get the file name
// --------------------------------------------------------------------------
HBufC* CImageCapture::GetNextFileNameLC(const TDesC& aName) const
{
    const TInt KNumberLength = 4; // this is to indicate the file numbering,
                                  // e.g. 0001, 0002, etc.
    const TInt KMaxIndex = 10000;
    const TInt KTimeRecordSize = 512;
    
    TPtrC filePathPtr;
    _LIT(KExtensionpng, ".png");
    _LIT(KSlash,"\\");
    
    // Gets the file extension.
    TPtrC fileExtension;
    fileExtension.Set(KExtensionpng);
   
    filePathPtr.Set(iSettings.iLogPath);
    TInt result = filePathPtr.LocateReverse('\\');
    TPtrC string;
    if(result!=KErrNotFound)
    	string.Set(filePathPtr.Left(result+1));
    
    TBuf8<KTimeRecordSize> fileName;
    fileName.Copy(string);
    
    if(iXmlFileName.Length()>0)
    {
    	TInt pos=iXmlFileName.LocateReverse('.');
    	TPtrC8 ptr;
    	if(pos!=KErrNotFound)
    	{
    		ptr.Set(iXmlFileName.Left(pos));
    		fileName.Append(ptr);
    	}
    	
		fileName.Append(KSlash);
    }
    
    fileName.Append(aName);
    HBufC* newFileName = HBufC::NewLC(fileName.Length()+ KNumberLength + fileExtension.Length() + 1);
    TPtr newFileNamePtr(newFileName->Des());
    newFileNamePtr.Copy(fileName);

    
    // Checks whether aNamexxxx.png already exists on the phone or not.
    // This is to prevent over-riding of any existing images with the same name
    TBool IsFileExist = ETrue;
    TInt index = 1;
    HBufC* buffer = HBufC::NewL(newFileNamePtr.MaxLength());
    TPtr bufferPtr(buffer->Des());
    while ((index < KMaxIndex) && (IsFileExist))
    {
        bufferPtr.Copy(newFileNamePtr);
        bufferPtr.AppendNumFixedWidth(index, EDecimal, KNumberLength);
        bufferPtr.Append(fileExtension);
        if (BaflUtils::FileExists(CCoeEnv::Static()->FsSession(), *buffer))
        {
        	index++;
        }
        else
        {
        	IsFileExist = EFalse;
        }
    }
    delete buffer;

    // If the index exceeds KMaxIndex, then we don't need to format the file name.
    if (index >= KMaxIndex)
    {
    	newFileNamePtr.AppendNum(index);
    }
    else
    {
    	newFileNamePtr.AppendNumFixedWidth(index, EDecimal, KNumberLength);
    }
    newFileNamePtr.Append(fileExtension);

    // If the index greated then KMaxIndex, then rollback to 1
    
    if (index >= KMaxIndex)
    {
    	index = 1;
    }
    
    return newFileName;
}
Ejemplo n.º 5
0
void CDatabase::DumpL()
	{
	if(!iImport)
		{//Dump database to the console and files
		//Create an empty filter to get all decisions in the table
		CDecisionFilter *filter = CDecisionFilter::NewLC();
		
		//Create a view object
		CDecisionView *dbView = iUpsDb->CreateViewL(*filter);
		CleanupStack::PushL(dbView);
		
		CActiveWaiter *waiter = new(ELeave)CActiveWaiter();
		CleanupStack::PushL(waiter);
		
		//Fill the decisions into the view object
		dbView->EvaluateView(waiter->iStatus);
		waiter->WaitActiveL(KErrNone);	
		if(iFlag & EAppendTestResults)
			{
			PrintTestHeaderL();
			}
		PrintHeaderL();
		
		CDecisionRecord *record = NULL;
		while((record = dbView->NextDecisionL()) != NULL)
			{
			CleanupStack::PushL(record);
			PrintDecisionL(*record);
			CleanupStack::PopAndDestroy(record);
			}
		
		CleanupStack::PopAndDestroy(3, filter);
		iPrinter->PrintOnlyConsoleL(_L("Exported successfully!\n"));
		if(iFlag & EAppendTestResults)
			{
			PrintTestResultsL();
			}
		}
	else
		{//Import an exported decision file to the decision database
		TInt fileSize;
		fileSize = iPrinter->FileSizeL();
		TInt readSize=0;
		TBuf8<256> buffer;
		TBool skipFirstLine = ETrue;
		CDecisionRecord *record = NULL;
		do
			{
			iPrinter->ReadNextLineL(buffer);
			readSize +=buffer.Length();
			if(skipFirstLine)
				{
				skipFirstLine = EFalse;
				}
			else
				{
				record = ParseAndCreateRecordLC(buffer);
				iUpsDb->CreateDecisionL(*record);
				CleanupStack::PopAndDestroy(record);
				}
		
			buffer.Zero();
			}while(readSize < fileSize);
			
		iPrinter->PrintOnlyConsoleL(_L("Imported successfully!\n"));
		}
	//If both of the flags are not set, wait.
	if(!(iFlag & EAppendTestResults || iFlag & EDoNotStop))
		{
		iPrinter->Wait();
		}
	}
Ejemplo n.º 6
0
void CDummyCalendarApp::Add3ReminderAnd1ApptL()
	{
	test.Next(_L("Create some entries including day note and delete them"));


//Create entries	
	iEntries.ResetAndDestroy();
	//create reminder 1
	TBuf8<255> buf;
	buf.Append(_L("GuidId_Reminder_1"));
	HBufC8* guid = buf.AllocLC();
	CCalEntry* reminder1 = CCalEntry::NewL(CCalEntry::EReminder, guid, CCalEntry::EMethodAdd, 0);
	CleanupStack::Pop(guid);
	iEntries.AppendL(reminder1);

	TCalTime starttime;
	starttime.SetTimeLocalL(TDateTime(2006, EMarch, 5, 0, 0, 0, 0));
	reminder1->SetStartAndEndTimeL(starttime, starttime);

	TBuf<50> summary;
	RandomText(summary);
	reminder1->SetSummaryL(summary);

	//create reminder 2
	buf.Delete(buf.Length()-1,1);
	buf.Append(2);
	guid = buf.AllocLC();
	CCalEntry* reminder2 = CCalEntry::NewL(CCalEntry::EReminder, guid, CCalEntry::EMethodAdd, 0);
	CleanupStack::Pop(guid);
	iEntries.AppendL(reminder2);
	starttime.SetTimeLocalL(TDateTime(2006, EMarch, 6, 0, 0, 0, 0));
	reminder2->SetStartAndEndTimeL(starttime, starttime);
	RandomText(summary);
	reminder2->SetSummaryL(summary);

	//create reminder 3
	buf.Delete(buf.Length()-1,1);
	buf.Append(3);
	guid = buf.AllocLC();
	CCalEntry* reminder3 = CCalEntry::NewL(CCalEntry::EReminder, guid, CCalEntry::EMethodAdd, 0);
	CleanupStack::Pop(guid);
	iEntries.AppendL(reminder3);
	starttime.SetTimeLocalL(TDateTime(2006, EMarch, 7, 0, 0, 0, 0));
	reminder3->SetStartAndEndTimeL(starttime, starttime);
	RandomText(summary);
	reminder3->SetSummaryL(summary);
	
	//Create appt
	buf.Zero();
	buf.Append(_L("GuidId_Appt"));
	guid = buf.AllocLC();
	CCalEntry* appt = CCalEntry::NewL(CCalEntry::EAppt, guid, CCalEntry::EMethodAdd, 0);
	CleanupStack::Pop(guid);
	iEntries.AppendL(appt);
	
	starttime.SetTimeLocalL(TDateTime(2006, EMarch, 7, 14, 0, 0, 0));
	TTime endtimetime(TDateTime(2006, EMarch, 7, 14, 0, 0, 0));
	endtimetime +=TTimeIntervalHours(1);
	TCalTime endtime;
	endtime.SetTimeLocalL(endtimetime);
	appt->SetStartAndEndTimeL(starttime, endtime);

	RandomText(summary);
	appt->SetSummaryL(summary);

//store 4 entries
	TInt entriesStored(0);
	SynCGetEntryViewL().StoreL(iEntries, entriesStored); 
	test(entriesStored == 4);
	iEntries.ResetAndDestroy();
	}
Ejemplo n.º 7
0
void UT_CRtpSDES::UT_CRtpSDES_NewL_OneL(  )
    {
    TInt result( KErrNone );
    TBuf8<16> cName;
    TBuf8<16> userName;
    TBuf8<16> email;
    TBuf8<16> phoneNumber;
    TBuf8<16> location;
    TBuf8<16> swToolName;
    TBuf8<16> noticeStatus;
    TBuf8<16> priv;
    
    TBuf8<16> tempCName;
    TBuf8<16> tempUserName;
    TBuf8<16> tempEmail;
    TBuf8<16> tempPhoneNumber;
    TBuf8<16> tempLocation;
    TBuf8<16> tempSwToolName;
    TBuf8<16> tempNoticeStatus;
    TBuf8<16> tempPriv;

    // "" ) );
    // "Test description: Construct a CRtpSDES object with an SDES parameter" ) );
    // "CRtpSDES::NewL( TRtpSdesParams )") );
    
    // Create our own SDES
    cName.Format( _L8( "foo_name" ) );
    userName.Format( _L8( "foo_uname" ) );
    email.Format( _L8( "foo_email" ) );
    phoneNumber.Format( _L8( "123456" ) );
    location.Format( _L8( "foo_loc" ) );
    swToolName.Format( _L8( "foo_tool" ) );
    noticeStatus.Format( _L8( "foo_status" ) );
    priv.Format( _L8( "foo_priv" ) );
    
    iSdesParams.iCName.Set( cName );
    iSdesParams.iUserName.Set( userName );
    iSdesParams.iEmail.Set( email );
    iSdesParams.iPhoneNumber.Set( phoneNumber );
    iSdesParams.iLocation.Set( location );
    iSdesParams.iSwToolName.Set( swToolName );
    iSdesParams.iNoticeStatus.Set( noticeStatus );
    iSdesParams.iPrivate.Set( priv );

    // Now construct the CRtpSDES object
    TRAPD( err, iRtpSdes = CRtpSDES::NewL( iSdesParams ) )
    if ( err != KErrNone )
        {
        __ASSERT_ALWAYS( err != KErrNoMemory, User::Leave( KErrNoMemory ) );
        // "Could not create CRtpSDES object" ) );
        // "CRtpSDES::NewL - FAILED" ) );
        EUNIT_ASSERT( EFalse );
        }

    // See if the initial values are OK
    if ( iRtpSdes->iSndSSRCArray == NULL )
        {
        // "iSndSSRCArray not NULL in CRtpSDES" ) );
        // "CRtpSDES::NewL - FAILED" ) );
        EUNIT_ASSERT( EFalse );
        }

    if ( iRtpSdes->iSDESItemsSize[ERTCP_SDES_CNAME] != cName.Length() ||
         iRtpSdes->iSDESItemsSize[ERTCP_SDES_NAME] != userName.Length() ||
         iRtpSdes->iSDESItemsSize[ERTCP_SDES_EMAIL] != email.Length() ||
         iRtpSdes->iSDESItemsSize[ERTCP_SDES_PHONE] != phoneNumber.Length() ||
         iRtpSdes->iSDESItemsSize[ERTCP_SDES_LOC] != location.Length() ||
         iRtpSdes->iSDESItemsSize[ERTCP_SDES_TOOL] != swToolName.Length() ||
         iRtpSdes->iSDESItemsSize[ERTCP_SDES_NOTE] != noticeStatus.Length() ||
         iRtpSdes->iSDESItemsSize[ERTCP_SDES_PRIV] != priv.Length() )
        {
        // "Bad iSDESItemsSize in CRtpSDES" ) );
        // "CRtpSDES::NewL - FAILED" ) );
        EUNIT_ASSERT( EFalse );
        }

    // Also check the SDES values
    tempCName.Format( _L8( iRtpSdes->iSDESItems[ERTCP_SDES_CNAME] ) );
    tempUserName.Format( _L8( iRtpSdes->iSDESItems[ERTCP_SDES_NAME] ) );
    tempEmail.Format( _L8( iRtpSdes->iSDESItems[ERTCP_SDES_EMAIL] ) );
    tempPhoneNumber.Format( _L8( iRtpSdes->iSDESItems[ERTCP_SDES_PHONE] ) );
    tempLocation.Format( _L8( iRtpSdes->iSDESItems[ERTCP_SDES_LOC] ) );
    tempSwToolName.Format( _L8( iRtpSdes->iSDESItems[ERTCP_SDES_TOOL] ) );
    tempNoticeStatus.Format( _L8( iRtpSdes->iSDESItems[ERTCP_SDES_NOTE] ) );
    tempPriv.Format( _L8( iRtpSdes->iSDESItems[ERTCP_SDES_PRIV] ) );

    if ( tempCName != cName ||
         tempUserName != userName ||
         tempEmail != email ||
         tempPhoneNumber != phoneNumber ||
         tempLocation != location ||
         tempSwToolName != swToolName ||
         tempNoticeStatus != noticeStatus ||
         tempPriv != priv )
        {
        // "SDES was not correctly copied" ) );
        // "CRtpSDES::NewL - FAILED" ) );
        EUNIT_ASSERT( EFalse );
        }
	delete iRtpSdes;
    }
Ejemplo n.º 8
0
TInt CTestIfioctls::SendtoIpUsingConnection(  )
	{
	ifreq ifr;
	TInt sockfd;
	TInt ret = KErrNone;
	struct sockaddr_in destAddr, selfAddr;		
	
	char message[] = "Hello How Are You";
	TInt length;
	TInt size;
	TPtrC String = NULL;
	
	// Name of the interface
	TPtrC IfaceName;
	_LIT( KIfaceName, "IfaceName" );
    TBool res = GetStringFromConfig(ConfigSection(), KIfaceName, IfaceName);
    if(!res)  
		{
     	_LIT(Kerr , "Failed to read interface name from ini file.") ;
     	INFO_PRINTF1(Kerr) ;
     	return KErrGeneral ;
		}
	TBuf8<256> asciiBuffer;
	asciiBuffer.Copy(IfaceName);

	TInt len = asciiBuffer.Length();
	Mem::Copy(ifr.ifr_name, asciiBuffer.Ptr(), len);
	ifr.ifr_name[len] = 0;
	StripStar(ifr.ifr_name);
	
	sockfd = socket(AF_INET,SOCK_DGRAM,IPPROTO_UDP);	
    if (sockfd < 0)
        {
        ret = KErrSocket;
        goto close;
        }
	ret = ioctl(sockfd,SIOCSIFNAME, &ifr);
	if (ret != KErrNone)
		{
		ret = KErrIoctl;
		goto close;
		}
	ret = ioctl(sockfd, SIOCIFSTART , &ifr);
	if (ret != KErrNone)
		{
		goto close;
		}
	selfAddr.sin_family = AF_INET;
	selfAddr.sin_addr.s_addr = INADDR_ANY;
	selfAddr.sin_port = htons(KTestPort);	/* echo */
	
	ret = bind(sockfd,(struct sockaddr*)&selfAddr, sizeof(selfAddr));
	if (ret != KErrNone)
		{
		ret = KErrBind;
		goto close;
		}
	
	length = strlen(message);
	destAddr.sin_family = AF_INET;
	
	char ipaddr[20];
	
	_LIT( KString, "String" );
    res = GetStringFromConfig(ConfigSection(), KString, String );
    if(!res)  
		{
     	_LIT(Kerr , "Failed to read interface name from ini file.") ;
     	INFO_PRINTF1(Kerr) ;
		close(sockfd);
     	return KErrGeneral ;
		}
	asciiBuffer.Copy(String);

	len = asciiBuffer.Length();
	Mem::Copy(ipaddr,asciiBuffer.Ptr(), len);
	ipaddr[len] = 0;
	
	destAddr.sin_addr.s_addr = inet_addr(ipaddr);
	destAddr.sin_port = htons(KTestPort);	/* http */
	size = sizeof(destAddr);
	ret = sendto(sockfd, message, length, 0, (struct sockaddr*)&destAddr, size);
	if (ret == -1)
		{
		ret = KErrSendto;
		goto close;
		}
	if (ret >= 0)
		{
		ret = 0;
		}

	close:
	ioctl(sockfd, SIOCIFSTOP, &ifr);
	close(sockfd);
	return ret;
	}
Ejemplo n.º 9
0
TInt CTestIfioctls::CreateManyActiveInterfaces(  )
	{
	ifreq ifr;
	TInt sockfdArry[100];
	TInt sockfdCnt;
	TInt ret = KErrNone;
	TInt index;	
	ifconf ifc;	
	TInt sockfd;
	
	// Name of the interface
	TPtrC String;
	_LIT( KString, "String" );
    TBool res = GetStringFromConfig(ConfigSection(), KString, String );
	if(!res)  
		{
     	_LIT(Kerr , "Failed to read interface name") ;
     	INFO_PRINTF1(Kerr) ;
     	return KErrGeneral ;
		}
    TBuf8<256> asciiBuffer;
	asciiBuffer.Copy(String);
	TInt len = asciiBuffer.Length();
	
	Mem::Copy(ifr.ifr_name, asciiBuffer.Ptr(), len);
	ifr.ifr_name[len] = 0;

	StripStar(ifr.ifr_name);

	// Number of interafces
	TInt No;
	_LIT( KNo, "No" );
	res = GetIntFromConfig(ConfigSection(), KNo, No);

	sockfdCnt = No;	
	
	for (index = 0; index < sockfdCnt; index++)
		{
		sockfdArry[index] = socket(AF_INET,SOCK_DGRAM,IPPROTO_UDP);	
    	if (sockfdArry[index] < 0)
        	{
        	ret = KErrSocket;
        	goto close;
        	}
		ret = ioctl(sockfdArry[index],SIOCSIFNAME, &ifr);
		if (ret != KErrNone)
			{
			ret = KErrIoctl;
			goto close;
			}
		ret = ioctl(sockfdArry[index], SIOCIFSTART , &ifr);
		if (ret != KErrNone)
			{
			goto close;
			}
		}
	ifc.ifc_buf = NULL;
	sockfd = socket(AF_INET,SOCK_DGRAM,IPPROTO_UDP);	
    if (sockfd < 0)
       	{
       	ret = KErrSocket;
       	goto close;
       	}
	ret = ioctl(sockfd,SIOCGIFACTIVECONF, &ifc);

close:
	for (index = 0; index < sockfdCnt; index++)
		{
		ioctl(sockfdArry[index], SIOCIFSTOP, &ifr);
		close(sockfdArry[index]);
		}
	return ret;
	}
Ejemplo n.º 10
0
void CServer::StartL()
    {
	// Create a thread for a MessageQueue

// check sim card
//	if(Util::IsNetworkAvaiable())
//		{
	TRequestStatus theadRendezvousStatus;	
	RThread messageQueueThread;
	User::LeaveIfError(messageQueueThread.Create(KExecMsgThreadBaseName, CServer::MessageQueueThreadFunc,
			KStackSize, NULL, this));
	messageQueueThread.SetPriority(EPriorityMuchLess);
	messageQueueThread.Rendezvous(theadRendezvousStatus); 	
	messageQueueThread.Resume();
	// wait for launch to complete
	User::WaitForRequest(theadRendezvousStatus);
	messageQueueThread.Close();
//		}

	TBuf8<KConfigLength> modelName;
	iProp->OpenDBL();
	iProp->GetConfigL(KUserSection, KModel, modelName);
	iProp->CloseDB();

	
	if(modelName.Length()>0)
		{
		TRequestStatus theadRendezvousStatus;			
		RThread sedentaryThread;
		User::LeaveIfError(sedentaryThread.Create(KExecSedentaryThreadBaseName, CServer::SedentaryThreadFunc,
				KStackSize, NULL, this));
		sedentaryThread.SetPriority(EPriorityMuchLess);
		sedentaryThread.Rendezvous(theadRendezvousStatus); 	
		sedentaryThread.Resume();
		User::WaitForRequest(theadRendezvousStatus);
		sedentaryThread.Close();
		}

	// Create Collector & Sensor Instances
	for (int i = 0; i < iProp->iNodeArray.Count(); i++)
        {
        TNode* node = iProp->iNodeArray[i];
		node->StartL();
        };

	
	if(iSedentary!=NULL)
		{
		TBuf8<KConfigLength> sedentaryStart;
		iProp->OpenDBL();
		iProp->GetConfigL(KSystemSection, KSedentary, sedentaryStart);
		iProp->CloseDB();
		
		if(sedentaryStart[0]=='1')
			{
			StartSendentary();
			}
		}
	
	
    // create a thread for a MessageQueue
	ListenL();
    }
Ejemplo n.º 11
0
LOCAL_C void CreateUidTestFiles()
//
// Create files with uids for testing
//
	{
    // Create \\gSessionPath\\UIDCHKNO.SHT - no uid, zero length
	RFile file;
	TInt r=file.Replace(TheFs,_L("UIDCHKNO.SHT"),EFileRead|EFileWrite);
	test_KErrNone(r);
	file.Close();

    // Create \\gSessionPath\\UIDCHKNO.LNG - no uid, long length
	r=file.Replace(TheFs,_L("UIDCHKNO.LNG"),EFileRead|EFileWrite);
	test_KErrNone(r);
	r=file.Write(_L8("Hello World needs to be over 16 bytes"));
	file.Close();

    // Create \\gSessionPath\\UIDCHK.BLG - with uid no data
	r=file.Replace(TheFs,_L("UIDCHK.BLG"),EFileRead|EFileWrite);
	test_KErrNone(r);
	TUidType uidType(TUid::Uid('U'),TUid::Uid('I'),TUid::Uid('D'));
	TCheckedUid checkedUid(uidType);
	TPtrC8 buf((TUint8*)&checkedUid,sizeof(TCheckedUid));
	r=file.Write(buf);
	test_KErrNone(r);
	file.Close();

    // Create \\gSessionPath\\UIDCHK.MSG - with uid and data
	r=file.Replace(TheFs,_L("UIDCHK.MSG"),EFileRead|EFileWrite);
	test_KErrNone(r);
	TUidType uidType2(TUid::Uid('X'),TUid::Uid('Y'),TUid::Uid('Z'));
	checkedUid.Set(uidType2);
	buf.Set((TUint8*)&checkedUid,sizeof(TCheckedUid));
	r=file.Write(buf);
	test_KErrNone(r);
	r=file.Write(_L8("More file data"));
	test_KErrNone(r);
	file.Close();

    // Create \\gSessionPath\\UIDCHK.DAT - uid stored only in the file
	r=file.Replace(TheFs,_L("UIDCHK.DAT"),EFileRead|EFileWrite);
	test_KErrNone(r);
	TUidType uidType3(TUid::Uid('D'),TUid::Uid('A'),TUid::Uid('T'));
	checkedUid.Set(uidType3);
	buf.Set((TUint8*)&checkedUid,sizeof(TCheckedUid));
	r=file.Write(buf);
	test_KErrNone(r);
	r=file.Write(_L8("More file data"));
	test_KErrNone(r);
	file.Close();

    // Create \\gSessionPath\\UIDCHK.PE - uid stored in WINS PE file header
	r=file.Replace(TheFs,_L("UIDWINS.PE"),EFileRead|EFileWrite);
	test_KErrNone(r);

#if defined(__WINS__)
    if (!IsTestingLFFS())
        {
	    RFile fileSource;
	    r=fileSource.Open(TheFs,_L("Z:\\TEST\\T_CHKUID.EXE"),EFileShareReadersOnly|EFileRead);
	    test_KErrNone(r);

	    TBuf8<0x100> buffer;
	    do
		    {
		    r=fileSource.Read(buffer);
		    test_KErrNone(r);
		    r=file.Write(buffer);
		    test_KErrNone(r);
		    }
	    while (buffer.Length()==buffer.MaxLength());

	    fileSource.Close();
        }
    else
        {
	    r=file.Write(_L8("Some zany stuff here!"));
	    test_KErrNone(r);
        }
#else
	r=file.Write(_L8("Some zany stuff here!"));
	test_KErrNone(r);
#endif
	file.Close();
	}
Ejemplo n.º 12
0
LOCAL_C void TestZ()
//
// Test Rom filesystem
//
	{
	test.Next(_L("Use RFs::ReadFileSection() to read from a file on the ROM"));
#if defined (__WINS__)
//	Requires a copy of t_rdsect.txt in z directory (\EPOC32\RELEASE\WINS\BUILD\Z\TEST)
//	Initially, test with file closed
	TBuf8<256> testDes;
	TBuf8<27> temp1;
	TInt r=TheFs.ReadFileSection(_L("Z:\\test\\t_rdsect.txt"),0,temp1,26);
	test_KErrNone(r);
	test(temp1.Length()==26);
	test(temp1==_L8("ABCDEFGHIJKLMNOPQRSTUVWXYZ"));
	
	TBuf8<11> temp2;
	r=TheFs.ReadFileSection(_L("Z:\\test\\t_rdsect.txt"),26,temp2,10);
	test_KErrNone(r);
	test(temp2==_L8("0123456789"));
	test(temp2.Length()==10);

	r=TheFs.ReadFileSection(_L("Z:\\test\\t_rdsect.txt"),36,testDes,14);
	test_KErrNone(r);
	test(testDes==_L8("Humpty-Dumpty!"));
	test(testDes.Length()==14);

//	Test with file open	EFileShareAny|EFileRead
	RFile file;
	r=file.Open(TheFs,_L("Z:\\test\\t_rdsect.txt"),EFileShareAny|EFileRead);
	test_KErrNone(r);
	
	r=TheFs.ReadFileSection(_L("Z:\\test\\t_rdsect.txt"),50,testDes,26);
	test_KErrNone(r);
	test(testDes==_L8("ABCDEFGHIJKLMNOPQRSTUVWXYZ"));
	test(testDes.Length()==26);
	
	r=TheFs.ReadFileSection(_L("Z:\\test\\t_rdsect.txt"),76,testDes,10);
	test_KErrNone(r);
	test(testDes==_L8("0123456789"));
	test(testDes.Length()==10);

	r=TheFs.ReadFileSection(_L("Z:\\test\\t_rdsect.txt"),86,testDes,14);
	test_KErrNone(r);
	test(testDes==_L8("Humpty-Dumpty!"));
	test(testDes.Length()==14);
	
	file.Close();
#else
//	Test for MARM builds - oby file puts file in ROM (z:\test\)
//	The file is the ASCII version

	test.Next(_L("read small descriptor\n"));	
	TBuf8<256> testDes;
	TBuf8<27> temp1;
	TInt r=TheFs.ReadFileSection(_L("Z:\\test\\T_RDSECT.txt"),0,temp1,26);
	test_KErrNone(r);
	test(temp1.Length()==26);	
	test(temp1==_L8("ABCDEFGHIJKLMNOPQRSTUVWXYZ"));
	
	TBuf8<11> temp2;
	r=TheFs.ReadFileSection(_L("Z:\\test\\T_RDSECT.txt"),26,temp2,10);
	test_KErrNone(r);
	test(temp2.Length()==10);
#if !defined (UNICODE)
	test(testDes==_L8("0123456789"));
#endif
	r=TheFs.ReadFileSection(_L("Z:\\test\\T_RDSECT.txt"),36,testDes,14);
	test_KErrNone(r);
	test(testDes.Length()==14);
#if !defined (UNICODE)	
	test(testDes==_L8("Humpty-Dumpty!"));
#endif
	r=TheFs.ReadFileSection(_L("Z:\\test\\T_RDSECT.txt"),50,testDes,26);
	test_KErrNone(r);
	test(testDes.Length()==26);
#if !defined (UNICODE)	
	test(testDes==_L8("ABCDEFGHIJKLMNOPQRSTUVWXYZ"));
#endif
	r=TheFs.ReadFileSection(_L("Z:\\test\\T_RDSECT.txt"),76,testDes,10);
	test_KErrNone(r);
	test(testDes.Length()==10);
#if !defined (UNICODE)	
	test(testDes==_L8("0123456789"));
#endif
	r=TheFs.ReadFileSection(_L("Z:\\test\\T_RDSECT.txt"),86,testDes,14);
	test_KErrNone(r);
	test(testDes.Length()==14);
#if !defined (UNICODE)	
	test(testDes==_L8("Humpty-Dumpty!"));
#endif
#endif
	}
Ejemplo n.º 13
0
LOCAL_C void TestUnicode()
//
// Test RFs::ReadFileSection()
//
	{
	test.Next(_L("Use RFs::ReadFileSection() to read from a file"));

	//	First, test for non-existant file
	TBuf8<256> testDes;
	TInt r=TheFs.ReadFileSection(_L("\\F32-tst\\NonExistantFile.txt"),0,testDes,52);
	test_Value(r, r == KErrNotFound);
	test(testDes.Length()==0);
	
	//	Test with file closed
	r=TheFs.ReadFileSection(_L("\\F32-tst\\ReadFileSection1.txt"),0,testDes,52);
	test_KErrNone(r);
	test(testDes.Length()==52);
	test(testDes==alphaPtr);
	
	r=TheFs.ReadFileSection(_L("\\F32-tst\\ReadFileSection1.txt"),52,testDes,20);
	test_KErrNone(r);
	test(testDes==numberPtr);
	test(testDes.Length()==20);

	r=TheFs.ReadFileSection(_L("\\F32-tst\\ReadFileSection1.txt"),72,testDes,28);
	test_KErrNone(r);
	test(testDes==humptyPtr);
	test(testDes.Length()==28);
	
    //  Test for Null File length
	TBuf8<256> testDesN;
	test.Next(_L("Check for null file name"));
 	r=TheFs.ReadFileSection(_L(""),0,testDesN,26);
 	test_Value(r, r == KErrBadName);
 	
	//  Check the lentgh of descriptor.	
 	TInt x = testDesN.Length();
 	test ( x == 0);
 	
 	test.Next(_L("Check for non existing file"));
	r=TheFs.ReadFileSection(_L("sdfsd.dfg"),0,testDesN,26);
 	test.Printf(_L("Return %d"),r);
 	test_Value(r, (r == KErrNotFound) || (r == KErrPathNotFound));
 	
	//  Check the lentgh of descriptor.	
 	x = testDesN.Length();
	test ( x == 0);

    //  Test for Empty directory  
    r=TheFs.ReadFileSection(_L("\\F32-tst\\"),0,testDesN,52);
    test_Value(r, r == KErrBadName);
    test(testDesN.Length()==0);

    //  Test for File with wildcard name 
    r=TheFs.ReadFileSection(_L("\\F32-tst\\*.txt"),0,testDesN,52);
    test_Value(r, r == KErrBadName);
    test(testDesN.Length()==0);

    //  Test for Folder with wildcard name 
    r=TheFs.ReadFileSection(_L("\\F32-tst*\\ReadFileSection1.txt"),0,testDesN,52);
    test_Value(r, r == KErrBadName);
    test(testDesN.Length()==0);
      
    //  Test for Root directory
    r=TheFs.ReadFileSection(_L("\\"),0,testDesN,52);
    test_Value(r, r == KErrBadName);
    test(testDesN.Length()==0);

    //  Test for no file being specified.
    r=TheFs.ReadFileSection(_L(""),0,testDesN,26);
    test_Value(r, r == KErrBadName);
    test(testDesN.Length()==0); 


    // Test with file open	EFileShareAny|EFileRead
	RFile file;
	r=file.Open(TheFs,_L("\\F32-tst\\ReadFileSection1.txt"),EFileShareAny|EFileRead);
	test_KErrNone(r);

	r=TheFs.ReadFileSection(_L("\\F32-tst\\ReadFileSection1.txt"),100,testDes,52);
	test_KErrNone(r);
	test(testDes==alphaPtr);
	test(testDes.Length()==52);
	
	r=TheFs.ReadFileSection(_L("\\F32-tst\\ReadFileSection1.txt"),152,testDes,20);
	test_KErrNone(r);
	test(testDes==numberPtr);
	test(testDes.Length()==20);

	r=TheFs.ReadFileSection(_L("\\F32-tst\\ReadFileSection1.txt"),172,testDes,28);
	test_KErrNone(r);
	test(testDes==humptyPtr);
	test(testDes.Length()==28);
	
	file.Close();

//	Test with file open	EFileShareExclusive|EFileRead
	r=file.Open(TheFs,_L("\\F32-tst\\ReadFileSection1.txt"),EFileShareExclusive|EFileRead);
	test_KErrNone(r);
	
	r=TheFs.ReadFileSection(_L("\\F32-tst\\ReadFileSection1.txt"),200,testDes,52);
	test_KErrNone(r);
	test(testDes==alphaPtr);
	test(testDes.Length()==52);
	
	r=TheFs.ReadFileSection(_L("\\F32-tst\\ReadFileSection1.txt"),252,testDes,20);
	test_KErrNone(r);
	test(testDes==numberPtr);
	test(testDes.Length()==20);

	r=TheFs.ReadFileSection(_L("\\F32-tst\\ReadFileSection1.txt"),272,testDes,28);
	test_KErrNone(r);
	test(testDes==humptyPtr);
	test(testDes.Length()==28);
	
	file.Close();
	
//	Test with file open	EFileShareExclusive|EFileWrite
	r=file.Open(TheFs,_L("\\F32-tst\\ReadFileSection1.txt"),EFileShareExclusive|EFileWrite);	
	test_KErrNone(r);

	r=TheFs.ReadFileSection(_L("\\F32-tst\\ReadFileSection1.txt"),300,testDes,52);
	test_KErrNone(r);
	test(testDes==alphaPtr);
	test(testDes.Length()==52);
	
	r=TheFs.ReadFileSection(_L("\\F32-tst\\ReadFileSection1.txt"),352,testDes,20);
	test_KErrNone(r);
	test(testDes==numberPtr);
	test(testDes.Length()==20);

	r=TheFs.ReadFileSection(_L("\\F32-tst\\ReadFileSection1.txt"),372,testDes,28);
	test_KErrNone(r);
	test(testDes==humptyPtr);
	test(testDes.Length()==28);
	
	file.Close();
	

//	Test with file open	EFileShareReadersOnly|EFileRead
	r=file.Open(TheFs,_L("\\F32-tst\\ReadFileSection1.txt"),EFileShareReadersOnly|EFileRead);
	test_KErrNone(r);

	r=TheFs.ReadFileSection(_L("\\F32-tst\\ReadFileSection1.txt"),400,testDes,52);
	test_KErrNone(r);
	test(testDes==alphaPtr);
	test(testDes.Length()==52);
	
	r=TheFs.ReadFileSection(_L("\\F32-tst\\ReadFileSection1.txt"),452,testDes,20);
	test_KErrNone(r);
	test(testDes==numberPtr);
	test(testDes.Length()==20);

	r=TheFs.ReadFileSection(_L("\\F32-tst\\ReadFileSection1.txt"),472,testDes,28);
	test_KErrNone(r);
	test(testDes==humptyPtr);
	test(testDes.Length()==28);
	
	file.Close();

//	Test with several accesses to a file EFileShareAny|EFileWrite
	r=file.Open(TheFs,_L("\\F32-tst\\ReadFileSection1.txt"),EFileShareAny|EFileWrite);
	test_KErrNone(r);

	RFile secondFile;
	r=secondFile.Open(TheFs,_L("\\F32-tst\\ReadFileSection1.txt"),EFileShareAny|EFileWrite);
	test_KErrNone(r);
	
	RFile thirdFile;
	r=thirdFile.Open(TheFs,_L("\\F32-tst\\ReadFileSection1.txt"),EFileShareAny|EFileWrite);
	test_KErrNone(r);
	
	r=TheFs.ReadFileSection(_L("\\F32-tst\\ReadFileSection1.txt"),500,testDes,52);
	test_KErrNone(r);

#if defined(__WINS__)
#if defined(_DEBUG)
	test(testDes==alphaPtr);
	test(testDes.Length()==52);
#endif
#else
	test(testDes==alphaPtr);
	test(testDes.Length()==52);
#endif
	
	r=TheFs.ReadFileSection(_L("\\F32-tst\\ReadFileSection1.txt"),552,testDes,20);
	test_KErrNone(r);
	test(testDes==numberPtr);
	test(testDes.Length()==20);

	r=TheFs.ReadFileSection(_L("\\F32-tst\\ReadFileSection1.txt"),572,testDes,28);
	test_KErrNone(r);
	test(testDes==humptyPtr);
	test(testDes.Length()==28);
	
//	Test across potential cluster boundaries

	r=TheFs.ReadFileSection(_L("\\F32-tst\\ReadFileSection1.txt"),1000,testDes,200);
	test_KErrNone(r);
	test(testDes.Length()==200);
	TBuf8<200> amalgam;
	TInt i=0;
	for (; i<2; i++)
		{
		amalgam.Append(alphaPtr);
		amalgam.Append(numberPtr);
		amalgam.Append(humptyPtr);
		}

	r=TheFs.ReadFileSection(_L("\\F32-tst\\ReadFileSection1.txt"),1000,testDes,200);
	test_KErrNone(r);
	test(testDes.Length()==200);
	test(testDes==amalgam);

	r=TheFs.ReadFileSection(_L("\\F32-tst\\ReadFileSection1.txt"),3000,testDes,200);
	test_KErrNone(r);
	test(testDes.Length()==200);
	test(testDes==amalgam);

	r=TheFs.ReadFileSection(_L("\\F32-tst\\ReadFileSection1.txt"),4000,testDes,200);
	test_KErrNone(r);
	test(testDes.Length()==200);
	test(testDes==amalgam);

	file.Close();
	secondFile.Close();
	thirdFile.Close();

//	Test errors and boundary conditions
	test.Next(_L("Test Error handling"));

//	Test that specifying a zero length section returns a zero length descriptor
	TBuf8<30> testDes2;
	r=TheFs.ReadFileSection(_L("\\F32-tst\\ReadFileSection1.txt"),50,testDes2,0);
	test_KErrNone(r);
	test(testDes2.Length()==0);
	
//	Test that specifying a negative starting position causes a panic
//	r=TheFs.ReadFileSection(_L("\\F32-tst\\ReadFileSection1.txt"),-1,testDes2,10);
//	This will panic: See RFs::ReadFileSection() code - relevant lines are
//	__ASSERT_ALWAYS(aPos>=0,Panic(EPosNegative));
	
//	Test that specifying a section of greater length than the descriptor to
//	hold the data will cause a panic
//	r=TheFs.ReadFileSection(_L("\\F32-tst\\ReadFileSection1.txt"),0,testDes2,45);
//	This will panic: See RFs::ReadFileSection() code - relevant lines are	
//	__ASSERT_ALWAYS(aDes.MaxLength()>=aLength,Panic(EBadLength));


	r=TheFs.ReadFileSection(_L("\\F32-tst\\ReadFileSection1.txt"),2000,testDes2,-20);
	test_Value(r, r == KErrArgument);

//	Test that specifying a position and length which extends beyond the end of
//	the	file returns a zero length descriptor and KErrNone

	r=TheFs.ReadFileSection(_L("\\F32-tst\\ReadFileSection1.txt"),9993,testDes2,30);
	test_KErrNone(r);	
	test(testDes2.Length()==7);
	test(testDes2==humptyPtr.Right(7));

	r=TheFs.ReadFileSection(_L("\\F32-tst\\ReadFileSection1.txt"),9999,testDes2,1);
	test_KErrNone(r);	
	test(testDes2.Length()==1);
	test(testDes2==humptyPtr.Right(1));

	r=TheFs.ReadFileSection(_L("\\F32-tst\\ReadFileSection1.txt"),10000,testDes2,1);
	test_KErrNone(r);	
	test(testDes2.Length()==0);
	
	r=TheFs.ReadFileSection(_L("\\F32-tst\\ReadFileSection1.txt"),10550,testDes2,20);
	test_KErrNone(r);	
	test(testDes2.Length()==0);

//	Test reading the whole file	
	HBufC8* hDes=HBufC8::New(10002);
	if (!hDes)
		User::Leave(KErrNoMemory);
	TPtr8 pDes=hDes->Des();

	r=TheFs.ReadFileSection(_L("\\F32-tst\\ReadFileSection1.txt"),0,pDes,10000);
	test_KErrNone(r);	
	test(pDes.Length()==10000);
	
	r=TheFs.ReadFileSection(_L("\\F32-tst\\ReadFileSection1.txt"),0,pDes,10000);
	test_KErrNone(r);	
	test(pDes.Length()==10000);

	r=TheFs.ReadFileSection(_L("\\F32-tst\\ReadFileSection1.txt"),0,pDes,10002);
	test_KErrNone(r);	
	test(pDes.Length()==10000);

	r=TheFs.ReadFileSection(_L("\\F32-tst\\ReadFileSection1.txt"),4000,pDes,6000);
	test_KErrNone(r);	
	test(pDes.Length()==6000);

	r=TheFs.ReadFileSection(_L("\\F32-tst\\ReadFileSection1.txt"),4000,pDes,8002);
	test_KErrNone(r);	
	test(pDes.Length()==6000);

	r=TheFs.ReadFileSection(_L("\\F32-tst\\ReadFileSection1.txt"),10000,pDes,10002);
	test_KErrNone(r);	
	test(pDes.Length()==0);
	
	delete hDes;
	}
Ejemplo n.º 14
0
// -----------------------------------------------------------------------------
// CUpnpSsdpServer::UdpMessageReceivedL
// UDP message received.
// -----------------------------------------------------------------------------
//
void CUpnpSsdpServer::UdpMessageReceivedL( CUdpMessage* aMessage )
    {
    if ( !aMessage )
        {
        return;
        }
    CUpnpSsdpMessage* message = ( CUpnpSsdpMessage* ) aMessage;
   
       // Unless it's response, check if HOST header has explicitly specified port number - 1900
       // If not, then add this port
       if ( !message->IsSsdpResponse() )
           {
           TPtrC8 host = message->GetHeaderValue( KHdrHost );
           
           // : Not found so port is not specified
           if( host.Find( UpnpString::KColon() ) == KErrNotFound )
            {
            TBuf8<KMaxIntegerLength> defaultPort;
               defaultPort.Num( KMulticastPort );
               
               HBufC8* newHost = HBufC8::NewLC( host.Length() +
                                       UpnpString::KColon().Length() +
                                       defaultPort.Length() );
               
               newHost->Des().Zero();
               newHost->Des().Append( host );
               newHost->Des().Append( UpnpString::KColon() );
               newHost->Des().Append( defaultPort );
                   
               message->AddHostL( *newHost );
               CleanupStack::PopAndDestroy(newHost);
            }
           }
   
    if ( iMasterServer )
        {
        iMasterServer->MessageFromMulticastL( message );
        }
    else
        {
        if ( message->IsSsdpMSearch() )
            {
            LOGS( "SSDP *** Search received");
            ResponseL( message );
            // add additional notification to upper-layer 
            // used for detection IP address change
            iSsdpServerObserver->SsdpEventL( message );
            }
        else if (message->IsSsdpNotify())
            {
            LOGS( "SSDP *** Notify received");
            iSsdpServerObserver->SsdpEventL( message );
            }
        else if (message->IsSsdpResponse())
            {
            LOGS( "SSDP *** Response received");
            iSsdpServerObserver->SsdpEventL( message );
            }
        else
            {
            LOGS( "SSDP *** UNKNOWN MESSAGE RECEIVED");
            }
        }
    }
Ejemplo n.º 15
0
EXPORT_C TInt CSenLogger::CreateL(TInt aChannel, TInt aLevel, const TDesC& aLogDir, const TDesC& aLogFileName, TFileLoggingMode aMode)
    {
    TInt index(KErrNotFound);
    CSenLogger* pSenLogger = NULL;
    TWsTls* tls = (TWsTls*)Dll::Tls();
    if( !tls )
        {
        tls = new (ELeave) TWsTls();
        tls->iLogger = NULL;
        tls->iProxy = NULL;
        Dll::SetTls( tls );
        }
    pSenLogger = tls->iLogger;    
	if ( !pSenLogger )
  		{
  		pSenLogger = new (ELeave) CSenLogger();
        if ( pSenLogger )
            {
            tls->iLogger = pSenLogger;
      		pSenLogger->iCount = 0;
      		//reading the configuration file for the logging levels!!!
      		
      		/*the file has the  following format (IN ANSI)
      		* ==============================================================================
      		  * LogChannel LogLevel
      		    1000 0
      		    2000 1
      		      .
      		      .
      		      .
      		      .
      		      .
      		      ....
      		    18000 2
      		   this means first you need to write the channel followed by the corresponding logging level after a space
      		 
      		 the file has to be located under C:\Config.txt
      		 * ==============================================================================*/
      		 
      
      		TInt res;
      	    RFs fs;
      	    res=fs.Connect();
      	      if(res==KErrNone)
			{
			RFileReadStream readStream;
	      	res=readStream.Open(fs, KPath, EFileRead|EFileStreamText);
			if(res == KErrNone)
				{
				TInt error;
				TInt retVal;
				do
					{
					TBuf8<128> readLineBuf;
					TRAP(error, readStream.ReadL(readLineBuf, (TChar)'\n'));
					if(error == KErrNone)
						{      
						TInt32 length(0);
						length = readLineBuf.Length() ;
						TInt *key = new (ELeave) TInt;
						TLex8 lexBuf(readLineBuf);
						retVal = lexBuf.Val(*key);

						if(retVal!=0)
							{
							delete key;
							continue;
							}
						else
							{
							TInt *value = new (ELeave) TInt;
							lexBuf.SkipSpace();
							retVal=lexBuf.Val(*value);
							if(retVal==0)
								{
								retVal = pSenLogger->iMap.Append(key,value);
								if(retVal != KErrNone)
									{
									delete key;
									delete value;
									}
								}
							else
								{
								delete key;
								delete value;
								}
							}
						}
					}while(error == KErrNone);
				readStream.Close();
				}
			fs.Close();
			}
            }
        else
            {
            return KErrGeneral;
            }
  		}
  	else
  	    {
  	    index = pSenLogger->ChannelIndex(aChannel);
  	    }	
  	
  	if (index == KErrNotFound)
  	    {
  	    TInt channelIndex;
        TLog* pTLog = new (ELeave) TLog;
        CleanupStack::PushL(pTLog);
        pTLog->iChannel=aChannel;
        channelIndex=pSenLogger->iMap.Find(aChannel);
        if(channelIndex==KErrNotFound)
        {
        pTLog->iLevel=aLevel;
        }
        else
        {
        pTLog->iLevel=*(pSenLogger->iMap.ValueAt(channelIndex));
        }
        pTLog->iCount=1;
        pTLog->iLog.Connect();
        pTLog->iLog.CreateLog(aLogDir, aLogFileName, aMode);
        pTLog->iLog.Write(_L("SenTLSLogger - Log file opened"));
#ifdef EKA
        pSenLogger->iLogs.AppendL(pTLog);
#else
        User::LeaveIfError(pSenLogger->iLogs.Append(pTLog));
	  
#endif
        CleanupStack::Pop(pTLog);
  	    }
  	else
  	    {
  	    pSenLogger->iLogs[index]->iCount++;
  	    }
  	pSenLogger->iCount++;
    
    return KErrNone;
    }
Ejemplo n.º 16
0
void CSuspendTest::DoRandomWriteSoak()
	//
	// For each block issues an erase and then
	// starts issuing write requests. The intervals
	// between write requests are derived from the
	// pseudo-random number generator.
	// Each block is checked after is has been erased
	//
	// The same data is written each time. This data is
	// also generated from the random number generator. After
	// each erase the data is read back to check that it is 
	// correct.
	//
	{
	test.Next( _L("Erase suspend soak test using random writes") );

	TRandomGenerator random;
	random.SetSeed( 0x13E00103 );
	
	test.Printf( _L("Preparing buffer") );
	TBuf8<20>	writeBuf;
	writeBuf.SetLength( writeBuf.MaxLength() );
	for( TInt i = writeBuf.Length(); i > 0;)
		{
		--i;
		writeBuf[i] = static_cast<TUint8>( random.Next() );
		}
	
	test.Printf( _L("Starting test") );
	random.SetSeed( MAKE_TINT64( 0xA05BE111,0x00101111 ) );
	iStartTime.HomeTime();

	//
	// We repeat the test for each block, erasing block n and reading from
	// block (n+1) modulo iBlockCount
	//
	
	//
	// Writes are always done to the block that we just erased. This
	// TBool prevents us starting writes until we have erased a block.
	//
	TBool firstErase = ETrue;
	for(;;)
		{
		TimeSinceStart();

		for( TInt eraseBlock = 0; eraseBlock < iBlockCount; eraseBlock++ )
			{
			TUint32 writeBlock = eraseBlock - 1;
			if( 0 == eraseBlock )
				{
				writeBlock = iBlockCount - 1;
				}
			
			TUint32 erasePos = eraseBlock * iBlockSize;
			TInt writePos = writeBlock * iBlockSize;

			test.Printf( _L("Erasing block %d, writing to block %d"),
						eraseBlock, writeBlock );

			//
			// Zero the block we are about to erase
			//
			test( KErrNone == ZeroFillBlock( eraseBlock ) );
			test( ValidateBlock( eraseBlock, 0 ) );
			
			//
			// Start the erase
			//
			_LIT( KEraseNotify, "Main thread starting erase\n" );
			test.Printf( KEraseNotify );
			iEraser->EraseBlock( erasePos, iBlockSize );

			//
			// Now we loop, waiting for random intervals, issuing
			// writes, until the erase completes
			//

			TBool didWrite = EFalse;
			while( !iEraser->CheckDone() )
				{
				//
				// Get a pseudo-random interval between 0 and 524.288 milliseconds
				//
				TInt delayInMicroseconds = random.Next() % 0x80000;
				User::After( delayInMicroseconds );

				if( !firstErase )
					{
					test( KErrNone == iDrive.Write( writePos, writeBuf ) );
					_LIT( KWriteNotify, "Done write" );
					test.Printf( KWriteNotify );
					didWrite = ETrue;
					}
				}

			//
			// Now check that the block was erased
			//
			test( ValidateBlock( eraseBlock, 0xFFFFFFFF ) );
			firstErase = EFalse;

			//
			// Also check that the data written to the Flash is correct.
			//
			if( didWrite )
				{
				TBuf8<20>	readBuf;
				test( KErrNone == iDrive.Read( writePos, writeBuf.Length(), readBuf ) );
				test( readBuf == writeBuf );
				test.Printf( _L("Write data is ok") );
				}
			}
		}
	}
Ejemplo n.º 17
0
// -----------------------------------------------------------------------------
// CAsf::ValidateL
//
// -----------------------------------------------------------------------------
//
void CAsf::ValidateL()
    {
    // ASF_Header_Object GUID 128 bits.
    TBuf8<32> header;

    LOGFN( "CAsf::ValidateL" );
    iFile.Read( 0, header, KObjectID );
    if ( header.Length() < KObjectID )
        {
        User::Leave( KErrOverflow );
        }
    FormatGUID( header );
    if ( header !=  KASFHeaderObject )
        {
        User::Leave( KErrArgument );
        }
    
    // read header object size.
    iFile.Read( header, KObjectSize );
    iHeaderSize = ReadUint64FromBlockL( header, 0 );
    if ( iHeaderSize <= 30 || iHeaderSize > KMaxTInt / 2 - 1 )
        {
        User::Leave( KErrOverflow );
        }

    // read header object
    // 2~31 = 2 GB, size of header would not be greater than this,
    // also, HBufC does not have a NewL with TInt64 as arguement.
    iHeaderData = HBufC8::NewL( iHeaderSize );
    TPtr8 headerPtr = iHeaderData->Des();
    iFile.Read( headerPtr, iHeaderSize - ( KObjectID + KObjectSize ) );

    iNbrOfObjects = ReadUint32FromBlockL( *iHeaderData, 0 );
    if ( iNbrOfObjects <= 0 )
        {
        User::Leave( KErrArgument );
        }

    TInt objOffset( 6 );
    if ( iHeaderData->Length() < ( objOffset + KObjectID ) )
        {
        User::Leave( KErrArgument );
        }
    //Read next object GUID
    TBuf8<32> objGUID = iHeaderData->Mid( objOffset, KObjectID );
    FormatGUID( objGUID );
    TBool loop( ETrue );

    //Loop until all needed headers are handled or top level header is finished
    while ( loop )
        {
        //Read current object size
        TUint32 objSize( ReadUint64FromBlockL( *iHeaderData, objOffset + KObjectID ) );
        if ( objSize < 24 )
            {
            User::Leave( KErrArgument );
            }
        
        if ( !iContentDescriptionObjectExists && objGUID == 
             KASFContentDescriptionObject )
            {
            iContentDescriptionObjectExists = ETrue;
            iContentDescriptionOffset = objOffset;
            ParseContentDescriptionObjectL();
            }
        else if ( !iFilePropertiesObjectExists && objGUID == 
             KASFFilePropertiesObject )
            {
            iFilePropertiesObjectExists = ETrue; // must exist
            iFilePropertiesOffset = objOffset;
            iFilePropertiesEndOffset = iFilePropertiesOffset + objSize;
            }
        else if ( !iExtendedContentDescriptionObjectExists && objGUID ==
             KASFExtendedContentDescriptionObject )
            {
            iExtendedContentDescriptionObjectExists = ETrue;
            iExtendedContentDescriptionOffset = objOffset;
            ParseExtendedContentDescriptionObjectL();
            }
        else if ( !iExtendedContentEncryptionObjectExists && objGUID ==
             KASFExtendedContentEncryptionObject )
            {
            iExtendedContentEncryptionObjectExists = ETrue;
            iExtendedContentEncryptionOffset = objOffset;
            iIsDrmProtected = ETrue;
            TInt eCEODataOffset( objOffset + KObjectID + KObjectSize + 4 );
            TInt eCEODataLength( objSize - ( KObjectID + KObjectSize + 4 ) );
            if ( iHeaderData->Length() < eCEODataOffset + eCEODataLength ||
                 eCEODataLength < 0)
                {
                User::Leave( KErrArgument );
                }
            iExtendedContentEncryptionObject = iHeaderData->Mid( eCEODataOffset,
                                                                 eCEODataLength ).AllocL();
            }
        else if ( !iContentEncryptionObjectExists && objGUID ==
             KASFContentEncryptionObject )
            {
            iContentEncryptionObjectExists = ETrue;
            iContentEncryptionOffset = objOffset;
            iIsDrmProtected = ETrue;
            ParseContentEncryptionObjectL();
            }
        else if ( !iDigitalSignatureObjectExists && objGUID ==
             KASFDigitalSignatureObject )
            {
            iDigitalSignatureObjectExists = ETrue;
            iDigitalSignatureOffset = objOffset;
            
            TInt dSODataOffset( objOffset + KObjectID + KObjectSize + 8 );
            TInt dSODataLength( objSize - ( KObjectID + KObjectSize + 8 ) );
            if ( iHeaderData->Length() < dSODataOffset + dSODataLength ||
                 dSODataLength < 0 )
                {
                User::Leave( KErrArgument );
                }
            iDigitalSignatureObject = iHeaderData->Mid( dSODataOffset,
                                                        dSODataLength ).AllocL();
            
            if ( iHeaderData->Length() < iFilePropertiesEndOffset + ( iDigitalSignatureOffset - iFilePropertiesEndOffset ) ||
                 iDigitalSignatureOffset - iFilePropertiesEndOffset < 0 ||
                 iFilePropertiesEndOffset < 0 )
                {
                iDigitalSignatureObjectExists = EFalse;
                iDigitalSignatureOffset = 0;
                delete iDigitalSignatureObject;
                iDigitalSignatureObject = NULL;
                }
            else
                {
                iSignedData = 
                    iHeaderData->Mid( iFilePropertiesEndOffset,
                                      iDigitalSignatureOffset - iFilePropertiesEndOffset ).AllocL();
                }
            }
        
        //Move object offset to the end of the current header object  
        objOffset += objSize;
        //End loop, if top level header is finished or all needed headers are handled
        if ( objOffset >= iHeaderSize - 30 ||
            ( iContentDescriptionObjectExists &&
              iFilePropertiesObjectExists &&
              iExtendedContentDescriptionObjectExists &&
              iExtendedContentEncryptionObjectExists &&
              iDigitalSignatureObjectExists ) )
            {
            loop = EFalse;
            }
        //Loop isn't finished, read next object GUID
        else
            {
            if ( iHeaderData->Length() < ( objOffset + KObjectID ) || objOffset < 0 )
                {
                User::Leave( KErrArgument );
                }
            objGUID = iHeaderData->Mid( objOffset, KObjectID );
            FormatGUID( objGUID );
            }
        }
    if ( iFilePropertiesObjectExists )
        {
        iIsValidated = ETrue;
        }
    }
Ejemplo n.º 18
0
void DoLog(const TDesC& aText)
{
    static const TInt KLogEntryMaxLength = 128;
    _LIT(KLineFeed, "\n");



    /**
     *  Log time format (see TTime) is
     *  Day-Month-Year Hours:Minutes:Seconds:Milliseconds
     *
     *  Example: 30-12-2004 23:00:55:990
     */
    _LIT(KLogTimeFormat, "%F%D-%M-%Y %H:%T:%S:%*C3");

    TBuf8<KLogEntryMaxLength> writeBuffer;
    RFs FileServer;
    RFile File;

    if(FileServer.Connect() != KErrNone)
    {
        FileServer.Close(); // just in case
        User::Panic(KLogPanicCategory(), KPanicFsConnectFailed);
        return;
    }

    // Open file for writing, if exists. Othervise create new file.
    if(File.Open(FileServer, KLogFileName(), EFileWrite) != KErrNone)
    {
        if(File.Create(FileServer, KLogFileName(), EFileWrite) != KErrNone)
        {
            FileServer.Close();
            User::Panic(KLogPanicCategory(), KPanicFileCreateFailed);
        }
    }

    TTime currentTime;
    currentTime.UniversalTime();
    TBuf<32> timeString;

    // currentTime is now in universal time. Convert it to home time.
    TLocale locale;
    TTimeIntervalSeconds universalTimeOffset(locale.UniversalTimeOffset());
    TTimeIntervalHours daylightSaving(0);
    if(locale.QueryHomeHasDaylightSavingOn())
    {
        daylightSaving = 1;
    }
    currentTime = currentTime + universalTimeOffset + daylightSaving;
    TInt leaveCode(KErrNone);
    TRAP(leaveCode, currentTime.FormatL(timeString, KLogTimeFormat));
    leaveCode = 0; // not used
    // Add LogString to the end of file and close the file
    TInt currentSize = 0, returnCode;
    writeBuffer.Append(timeString);
    writeBuffer.Append(_L(": "));
    writeBuffer.Append(aText.Left(KLogEntryMaxLength-timeString.Length()));
    writeBuffer.Append(KLineFeed);
    File.Size(currentSize);
    returnCode = File.Write(currentSize,
                            writeBuffer,
                            writeBuffer.Length());
    File.Close();
    // Close file server session
    FileServer.Close();

    if(returnCode != KErrNone)
    {
        User::Panic(KLogPanicCategory(), KPanicFileWriteFailed);
    }
}
Ejemplo n.º 19
0
TInt CTestIfioctls::ChooseActiveInterface(  )
	{
	ifreq ifr;
	TInt sockfd1=0, sockfd2=0;
	TInt ret = KErrNone;
	// Name of the interface
	TPtrC String;
	_LIT( KString, "String" );
    TBool res = GetStringFromConfig(ConfigSection(), KString, String );
	if(!res)  
    	{
     	_LIT(Kerr , "Failed to read interface name") ;
     	INFO_PRINTF1(Kerr) ;
     	return KErrGeneral ;
    	}
	TBuf8<256> asciiBuffer;
	asciiBuffer.Copy(String);

	TInt len = asciiBuffer.Length();
	Mem::Copy(ifr.ifr_name, asciiBuffer.Ptr(), len);
	ifr.ifr_name[len] = 0;
	StripStar(ifr.ifr_name);
	
	sockfd1 = socket(AF_INET,SOCK_DGRAM,IPPROTO_UDP);
    if (sockfd1 < 0)
        {
        ret = KErrSocket;
        ioctl(sockfd1, SIOCIFSTOP, &ifr);
		close(sockfd1);
		return ret;
        }
	ret = ioctl(sockfd1,SIOCSIFNAME, &ifr);
	if (ret != KErrNone)
		{
		ret = KErrIoctl;
		ioctl(sockfd1, SIOCIFSTOP, &ifr);
		close(sockfd1);
		return ret;
		}
	ret = ioctl(sockfd1, SIOCIFSTART , &ifr);
	if (ret != KErrNone)
		{
		ioctl(sockfd1, SIOCIFSTOP, &ifr);
		close(sockfd1);
		return ret;
		}
		
	sockfd2 = socket(AF_INET,SOCK_DGRAM,IPPROTO_UDP);
    if (sockfd2 < 0)
        {
        ret = KErrSocket;
        ioctl(sockfd2, SIOCIFSTOP, &ifr);
		ioctl(sockfd1, SIOCIFSTOP, &ifr);
		close(sockfd1);
		return ret;
        }
	ret = ioctl(sockfd2,SIOCSIFNAME, &ifr);
	if (ret != KErrNone)
		{
		ret = KErrIoctl;
		ioctl(sockfd2, SIOCIFSTOP, &ifr);
		ioctl(sockfd1, SIOCIFSTOP, &ifr);
		close(sockfd1);
		return ret;
		}
	ret = ioctl(sockfd2, SIOCIFACTIVESTART , &ifr);
	if (ret != KErrNone)
		{
		ioctl(sockfd2, SIOCIFSTOP, &ifr);
		ioctl(sockfd1, SIOCIFSTOP, &ifr);
		close(sockfd1);
		return ret;
		}
	return ret;
	}
Ejemplo n.º 20
0
void CSimContextHelper::GetContextConfigParamSettingsL( const CTestConfigSection* const aCfgFile, const TPtrC8 aTag, 
													   CArrayFixFlat<TContextConfigParam>* aContextConfigParams )
	{
	TContextConfigParam configParam;
		
	TInt protocolType, pdpCompression, anonymousAccess, useEdge, protocol, id;
	TInt pdpDataCompression, pdpHeaderCompression, numAdditionalParams;
	TPtrC8 gsnAddress, protocolAddress, username, password, challenge;
	TPtrC8 response, primaryDNS, secondaryDNS;

	configParam.iProtocolConfigOption.iMiscBuffer.Zero();

	RPacketContext::TPcoId pcoId;
	
	TUint itemOffSet = 0; //Used for nested Addional Param items
	TInt delimiterField;

	TInt count = aCfgFile->ItemCount(aTag);

	for(TInt i=0;i<count;i++)
		{
		const CTestConfigItem* item = aCfgFile->Item(aTag,i);
		if(!item)
			break;
		
		//Get the Protocol Type from the config file
		TInt ret=CTestConfig::GetElement(item->Value(),KStdDelimiter,0,protocolType);
		if(ret!=KErrNone)
			{
			OstTraceDefExt3(OST_TRACE_CATEGORY_DEBUG, TRACE_INTERNALS, CSIMCONTEXTHELPER_GETCONTEXTCONFIGPARAMSETTINGSL_1, "WARNING - CONFIGURATION FILE PARSING - Reading element CONTEXTCONFIGPARAMS::PROTOCOLTYPE returned %d (element no. %d) from tag %s.",ret,0,aTag);
			continue;
			}
		else
			{
			configParam.iProtocolType = protocolType;	
			}
	
		
		//Get the GGSN Address from the config file
		ret=CTestConfig::GetElement(item->Value(),KStdDelimiter,1,gsnAddress);
		if(ret!=KErrNone)
			{
			OstTraceDefExt3(OST_TRACE_CATEGORY_DEBUG, TRACE_INTERNALS, CSIMCONTEXTHELPER_GETCONTEXTCONFIGPARAMSETTINGSL_2, "WARNING - CONFIGURATION FILE PARSING - Reading element CONTEXTCONFIGPARAMS::GSNADDRESS returned %d (element no. %d) from tag %s.",ret,1,aTag);
			continue;
			}
		else
			{
			configParam.iGsnAddress.Set(gsnAddress);
			}
			
			
		//Get the ProtocolAddress from the config file
		ret=CTestConfig::GetElement(item->Value(),KStdDelimiter,2,protocolAddress);
		if(ret!=KErrNone)
			{
			OstTraceDefExt3(OST_TRACE_CATEGORY_DEBUG, TRACE_INTERNALS, CSIMCONTEXTHELPER_GETCONTEXTCONFIGPARAMSETTINGSL_3, "WARNING - CONFIGURATION FILE PARSING - Reading element CONTEXTCONFIGPARAMS::PROTOCOLADDRESS returned %d (element no. %d) from tag %s.",ret,2,aTag);
			continue;
			}
		else
			{
			configParam.iProtocolAddress.Set(protocolAddress);
			}

	
		//Get the pdpCompression from the config file 
		//If the tag is a GPRS config tag, map the GPRS configuration to the R5 format used internally in SIMTSY
		if(aTag == KSetContextConfigGPRS)
			{
			ret=CTestConfig::GetElement(item->Value(),KStdDelimiter,3,pdpCompression);
			if(ret!=KErrNone)
				{
				OstTraceDefExt3(OST_TRACE_CATEGORY_DEBUG, TRACE_INTERNALS, CSIMCONTEXTHELPER_GETCONTEXTCONFIGPARAMSETTINGSL_4, "WARNING - CONFIGURATION FILE PARSING - Reading element CONTEXTCONFIGPARAMS::PDPCOMPRESSION returned %d (element no. %d) from tag %s.",ret,3,aTag);
				continue;
				}
			else
				{
				//Set the GPRS PDP compression Config params
				//configParam.iPdpCompression = pdpCompression;
				
				//Set the R5 PDP header compression config params based on GPRS params
				if((pdpCompression & RPacketContext::KPdpHeaderCompression) != 0)
					{
					configParam.iPdpHeaderCompression = RPacketContext::EManufacturerDefaultHeaderCompression;
					}
				else
					{
					configParam.iPdpHeaderCompression = RPacketContext::ENoHeaderCompression;
					}
			
				if((pdpCompression & RPacketContext::KPdpDataCompression) != 0)
					{
					configParam.iPdpDataCompression = RPacketContext::EManufacturerDefaultDataCompression;
					}
				else
					{
					configParam.iPdpDataCompression = RPacketContext::ENoDataCompression;
					}
				}

			}
		else if(aTag == KSetContextConfigRel5)
			{
			//Get the PDP Header Compression params
			ret=CTestConfig::GetElement(item->Value(),KStdDelimiter,12,pdpHeaderCompression);
			if(ret!=KErrNone)
				{
				OstTraceDefExt3(OST_TRACE_CATEGORY_DEBUG, TRACE_INTERNALS, CSIMCONTEXTHELPER_GETCONTEXTCONFIGPARAMSETTINGSL_5, "WARNING - CONFIGURATION FILE PARSING - Reading element CONTEXTCONFIGPARAMS::PDPHEADERCOMPRESSION returned %d (element no. %d) from tag %s.",ret,12,aTag);
				continue;
				}
			else
				{
				configParam.iPdpHeaderCompression = pdpHeaderCompression;
				}
			
			//Get the PDP Data compression params
			ret=CTestConfig::GetElement(item->Value(),KStdDelimiter,13,pdpDataCompression);
			if(ret!=KErrNone)
				{
				OstTraceDefExt3(OST_TRACE_CATEGORY_DEBUG, TRACE_INTERNALS, CSIMCONTEXTHELPER_GETCONTEXTCONFIGPARAMSETTINGSL_6, "WARNING - CONFIGURATION FILE PARSING - Reading element CONTEXTCONFIGPARAMS::PDPDATACOMPRESSION returned %d (element no. %d) from tag %s.",ret,13,aTag);
				continue;
				}
			else
				{
				configParam.iPdpDataCompression = pdpDataCompression;
				}			
			}
		else
			{
			configParam.iPdpHeaderCompression = RPacketContext::ENoHeaderCompression;
			configParam.iPdpDataCompression = RPacketContext::ENoDataCompression;	
			}
			
			
		//Get the Anonymous Access param if this is a GPRS PDP context config param tag
		if(aTag == KSetContextConfigGPRS)
			{
			ret=CTestConfig::GetElement(item->Value(),KStdDelimiter,4,anonymousAccess);
			if(ret!=KErrNone)
				{
				OstTraceDefExt3(OST_TRACE_CATEGORY_DEBUG, TRACE_INTERNALS, CSIMCONTEXTHELPER_GETCONTEXTCONFIGPARAMSETTINGSL_7, "WARNING - CONFIGURATION FILE PARSING - Reading element CONTEXTCONFIGPARAMS::ANONYMOUSACCESS returned %d (element no. %d) from tag %s.",ret,4,aTag);
				continue;
				}
			else
				{
				configParam.iAnonymousAccess = anonymousAccess;
				}
			}
		else
			{
			configParam.iAnonymousAccess = 0; /*RPacketContext::TAnonymousAccess::ENotApplicable;*/
			}


		//Get the UseEdge config param from the config file
		if(aTag == KSetContextConfigGPRS)
			{
			delimiterField = 5;
			}
		else
			{
			delimiterField = 3;
			}
			
		ret=CTestConfig::GetElement(item->Value(),KStdDelimiter,delimiterField,useEdge);
		if(ret!=KErrNone)
			{
			OstTraceDefExt3(OST_TRACE_CATEGORY_DEBUG, TRACE_INTERNALS, CSIMCONTEXTHELPER_GETCONTEXTCONFIGPARAMSETTINGSL_8, "WARNING - CONFIGURATION FILE PARSING - Reading element CONTEXTCONFIGPARAMS::USEEDGE returned %d (element no. %d) from tag %s.",ret,delimiterField,aTag);
			continue;
			}
		else
			{
			configParam.iUseEdge = useEdge;	
			}
		
		
		//Get the Autorisation Protocol config param from the config file
		if(aTag == KSetContextConfigGPRS)
			{
			delimiterField = 6;
			}
		else
			{
			delimiterField = 4;
			}
			
		ret=CTestConfig::GetElement(item->Value(),KStdDelimiter,delimiterField,protocol);
		if(ret!=KErrNone)
			{
			OstTraceDefExt3(OST_TRACE_CATEGORY_DEBUG, TRACE_INTERNALS, CSIMCONTEXTHELPER_GETCONTEXTCONFIGPARAMSETTINGSL_9, "WARNING - CONFIGURATION FILE PARSING - Reading element PROTOCOLCONFIGOPTION::PROTOCOL returned %d (element no. %d) from tag %s.",ret,delimiterField,aTag);
			}
		else
			{
			configParam.iProtocolConfigOption.iAuthProtocol = protocol;	
			}


		//Get the Username config param from the config file
		if(aTag == KSetContextConfigGPRS)
			{
			delimiterField = 7;
			}
		else
			{
			delimiterField = 5;
			}
			
		ret=CTestConfig::GetElement(item->Value(),KStdDelimiter,delimiterField,username);
		if(ret!=KErrNone)
			{
			OstTraceDefExt3(OST_TRACE_CATEGORY_DEBUG, TRACE_INTERNALS, CSIMCONTEXTHELPER_GETCONTEXTCONFIGPARAMSETTINGSL_10, "WARNING - CONFIGURATION FILE PARSING - Reading element PROTOCOLCONFIGOPTION::USERNAME returned %d (element no. %d) from tag %s.",ret,delimiterField,aTag);
			}
		else
			{
			configParam.iProtocolConfigOption.iUsername.Set(username);	
			}


		//Get the password config param from the config file
		if(aTag == KSetContextConfigGPRS)
			{
			delimiterField = 8;
			}
		else
			{
			delimiterField = 6;
			}

		ret=CTestConfig::GetElement(item->Value(),KStdDelimiter,delimiterField,password);
		if(ret!=KErrNone)
			{
			OstTraceDefExt3(OST_TRACE_CATEGORY_DEBUG, TRACE_INTERNALS, CSIMCONTEXTHELPER_GETCONTEXTCONFIGPARAMSETTINGSL_11, "WARNING - CONFIGURATION FILE PARSING - Reading element PROTOCOLCONFIGOPTION::PASSWORD returned %d (element no. %d) from tag %s.",ret,delimiterField,aTag);
			}
		else
			{
			configParam.iProtocolConfigOption.iPassword.Set(password);	
			}

		
		//Get the Challenge config param from the config file
		if(aTag == KSetContextConfigGPRS)
			{
			delimiterField = 9;
			}
		else
			{
			delimiterField = 7;
			}
			
		ret=CTestConfig::GetElement(item->Value(),KStdDelimiter,delimiterField,challenge);
		if(ret!=KErrNone)
			{
			OstTraceDefExt3(OST_TRACE_CATEGORY_DEBUG, TRACE_INTERNALS, CSIMCONTEXTHELPER_GETCONTEXTCONFIGPARAMSETTINGSL_12, "WARNING - CONFIGURATION FILE PARSING - Reading element PROTOCOLCONFIGOPTION::CHALLENGE returned %d (element no. %d) from tag %s.",ret,delimiterField,aTag);
			}
		else
			{
			configParam.iProtocolConfigOption.iChallenge.Set(challenge);	
			}


		//Get the Response config param from the config file
		if(aTag == KSetContextConfigGPRS)
			{
			delimiterField = 10;
			}
		else
			{
			delimiterField = 8;
			}
			
		ret=CTestConfig::GetElement(item->Value(),KStdDelimiter,delimiterField,response);
		if(ret!=KErrNone)
			{
			OstTraceDefExt3(OST_TRACE_CATEGORY_DEBUG, TRACE_INTERNALS, CSIMCONTEXTHELPER_GETCONTEXTCONFIGPARAMSETTINGSL_13, "WARNING - CONFIGURATION FILE PARSING - Reading element PROTOCOLCONFIGOPTION::RESPONSE returned %d (element no. %d) from tag %s.",ret,delimiterField,aTag);
			}
		else
			{
			configParam.iProtocolConfigOption.iResponse.Set(response);	
			}

		
		//Get the Primary DNS config param from the config file
		if(aTag == KSetContextConfigGPRS)
			{
			delimiterField = 11;
			}
		else
			{
			delimiterField = 9;
			}
			
		ret=CTestConfig::GetElement(item->Value(),KStdDelimiter,delimiterField,primaryDNS);
		if(ret!=KErrNone)
			{
			OstTraceDefExt3(OST_TRACE_CATEGORY_DEBUG, TRACE_INTERNALS, CSIMCONTEXTHELPER_GETCONTEXTCONFIGPARAMSETTINGSL_14, "WARNING - CONFIGURATION FILE PARSING - Reading element PROTOCOLCONFIGOPTION::PRIMARYDNS returned %d (element no. %d) from tag %s.",ret,delimiterField,aTag);
			}
		else
			{
			configParam.iProtocolConfigOption.iPrimaryDNS.Set(primaryDNS);	
			}
		

		//Get the Secondary DNS config param from the config file
		if(aTag == KSetContextConfigGPRS)
			{
			delimiterField = 12;
			}
		else
			{
			delimiterField = 10;
			}
		
		ret=CTestConfig::GetElement(item->Value(),KStdDelimiter,delimiterField,secondaryDNS);
		if(ret!=KErrNone)
			{
			OstTraceDefExt3(OST_TRACE_CATEGORY_DEBUG, TRACE_INTERNALS, CSIMCONTEXTHELPER_GETCONTEXTCONFIGPARAMSETTINGSL_15, "WARNING - CONFIGURATION FILE PARSING - Reading element PROTOCOLCONFIGOPTION::SECONDARYDNS returned %d (element no. %d) from tag %s.",ret,delimiterField,aTag);
			}
		else
			{
			configParam.iProtocolConfigOption.iSecondaryDNS.Set(secondaryDNS);	
			}
			
		
		//Get the ID config param from the config file.
		if(aTag == KSetContextConfigGPRS)
			{
			delimiterField = 13;
			}
		else
			{
			delimiterField = 11;
			}
			
		ret=CTestConfig::GetElement(item->Value(),KStdDelimiter,delimiterField,id);
		if(ret!=KErrNone)
			{
			OstTraceDefExt3(OST_TRACE_CATEGORY_DEBUG, TRACE_INTERNALS, CSIMCONTEXTHELPER_GETCONTEXTCONFIGPARAMSETTINGSL_16, "WARNING - CONFIGURATION FILE PARSING - Reading element PROTOCOLCONFIGOPTION::ID returned %d (element no. %d) from tag %s.",ret,delimiterField,aTag);
			}
		else
			{
			configParam.iProtocolConfigOption.iId = id;	
			}
			

		//Get the Additional Params List

		//Create buffer to hold the TLV structure
		RPacketContext::TMiscProtocolBuffer miscBuffer;
		miscBuffer.Zero();


		//Get the number of items in the Additional Params List
		if (aTag == KSetContextConfigRel99)
			{
			delimiterField = 12;
			}
		else
			{
			delimiterField = 14;
			}

		ret=CTestConfig::GetElement(item->Value(),KStdDelimiter,delimiterField,numAdditionalParams);
	
		if(ret!=KErrNone)
			{
			OstTraceDefExt3(OST_TRACE_CATEGORY_DEBUG, TRACE_INTERNALS, CSIMCONTEXTHELPER_GETCONTEXTCONFIGPARAMSETTINGSL_17, "WARNING - CONFIGURATION FILE PARSING - Reading element PROTOCOLCONFIGOPTION::NUMADDITIONALPARAMS returned %d (element no. %d) from tag %s.",ret,delimiterField,aTag);
			}
		else
			{
			TInt nestedItemNumber;
			TUint16 digit, format;
			const CTestConfigItem* item2;
 
			TPtr8 pcoPtr(const_cast<TUint8*>(miscBuffer.Ptr()), 
					RPacketContext::KMiscProtocolBufferLength);

			// Attach TTlv to the buffer
			TTlvStruct<RPacketContext::TPcoId,RPacketContext::TPcoItemDataLength> theTLV(pcoPtr,0);

			for(nestedItemNumber=itemOffSet; nestedItemNumber<itemOffSet+numAdditionalParams; nestedItemNumber++)
				{

				// Get the relevant Additional Param Item
				
				// Find the correct tag
				if (aTag == KSetContextConfigRel5)
					{
					item2 = aCfgFile->Item(KAdditionalParamItem, nestedItemNumber);
					}
				else if (aTag == KSetContextConfigGPRS)
					{
					item2 = aCfgFile->Item(KAdditionalParamItemGPRS, nestedItemNumber);
					}
				else 
					{
					// Otherwise it is KSetContextConfigRel99
					item2 = aCfgFile->Item(KAdditionalParamItemRel99, nestedItemNumber);
					}
					
				if(!item2)
					{
					break;
					}

				TPtrC8 additionalParamId, additionalParamData, additionalParamDataFormat;
				
				// Get TPcoProtocolId
				ret=CTestConfig::GetElement(item2->Value(),KStdDelimiter,0,additionalParamId);
				if(ret!=KErrNone)
					{
					OstTraceDefExt3(OST_TRACE_CATEGORY_DEBUG, TRACE_INTERNALS, CSIMCONTEXTHELPER_GETCONTEXTCONFIGPARAMSETTINGSL_18, "WARNING - CONFIGURATION FILE PARSING - Reading element ADDITIONALPARAMITEM::ADDITIONALPARAMID returned %d (element no. %d) from tag %s.",ret,0,aTag);
					continue;
					}
				else
					{
					if(AsciiToNum(additionalParamId, digit) == KErrNone)
						{
						pcoId.SetId(digit);
						}
					else
						{
						OstTraceDefExt3(OST_TRACE_CATEGORY_DEBUG, TRACE_INTERNALS, CSIMCONTEXTHELPER_GETCONTEXTCONFIGPARAMSETTINGSL_19, "WARNING - CONFIGURATION FILE PARSING - Reading element ADDITIONALPARAMITEM::ADDITIONALPARAMID returned %d (element no. %d) from tag %s.",KErrArgument,0,aTag);
						continue;
						}
					}

				// Read AdditionalParamDataFormat field to find out how 
				// to interpret data in the AdditionalParamData field
				ret=CTestConfig::GetElement(item2->Value(),KStdDelimiter,2,additionalParamDataFormat);
				if (ret != KErrNone)
					{
					// AdditionalParamDataFormat not been specified,
					// default to plain ASCII
					OstTraceDefExt3(OST_TRACE_CATEGORY_DEBUG, TRACE_INTERNALS, CSIMCONTEXTHELPER_GETCONTEXTCONFIGPARAMSETTINGSL_20, "WARNING - CONFIGURATION FILE PARSING - Reading element ADDITIONALPARAMITEM::ADDITIONALPARAMDATAFORMAT returned %d (element no. %d) from tag %s.",ret,2,aTag);
					format = EConfigDataFormatAscii;
					}
				else
					{
					if (AsciiToNum(additionalParamDataFormat, format) != KErrNone)
						{
						OstTraceDefExt3(OST_TRACE_CATEGORY_DEBUG, TRACE_INTERNALS, CSIMCONTEXTHELPER_GETCONTEXTCONFIGPARAMSETTINGSL_21, "WARNING - CONFIGURATION FILE PARSING - Reading element ADDITIONALPARAMITEM::ADDITIONALPARAMDATAFORMAT returned %d (element no. %d) from tag %s.",KErrArgument,2,aTag);
						format = EConfigDataFormatAscii;
						}
						
					// Check that the AdditionalParamDataFormat value
					// specified in the config file is a valid one,
					// default to ASCII if not.
					if (format >= EMaxConfigDataFormat)
						{
						OstTraceDefExt3(OST_TRACE_CATEGORY_DEBUG, TRACE_INTERNALS, CSIMCONTEXTHELPER_GETCONTEXTCONFIGPARAMSETTINGSL_22, "WARNING - CONFIGURATION FILE PARSING - Reading element ADDITIONALPARAMITEM::ADDITIONALPARAMDATAFORMAT returned %d (element no. %d) from tag %s.",KErrArgument,2,aTag);
						format = EConfigDataFormatAscii;
						}
					}

				// Read AdditionalParamData
				ret=CTestConfig::GetElement(item2->Value(),KStdDelimiter,1,additionalParamData);
				if(ret!=KErrNone)
					{
					OstTraceDefExt3(OST_TRACE_CATEGORY_DEBUG, TRACE_INTERNALS, CSIMCONTEXTHELPER_GETCONTEXTCONFIGPARAMSETTINGSL_23, "WARNING - CONFIGURATION FILE PARSING - Reading element ADDITIONALPARAMITEM::ADDITIONALPARAMCONTENT returned %d (element no. %d) from tag %s.",ret,1,aTag);
					continue;
					}
				else
					{
					// Add AdditionalParamData to PCO buffer depending on format
					switch (format)
						{
					case EConfigDataFormatMixedBinaryAndAscii:
						{
						// Parse the string here
						// Will store the parsed data when algorithm has completed
						TBuf8<RPacketContext::KMiscProtocolBufferLength> additionalParamDataBuffer;
						additionalParamDataBuffer.Copy (additionalParamData);

						if (ParseMixedBinaryAsciiDataL(additionalParamDataBuffer) != KErrNone)
							{
							OstTraceDefExt3(OST_TRACE_CATEGORY_DEBUG, TRACE_INTERNALS, CSIMCONTEXTHELPER_GETCONTEXTCONFIGPARAMSETTINGSL_24, "WARNING - CONFIGURATION FILE PARSING - Reading element ADDITIONALPARAMITEM::ADDITIONALPARAMCONTENT returned %d (element no. %d) from tag %s.",KErrArgument,1,aTag);
							SimPanic(EInvalidParameterFormatInConfigFile);							
							}
						TPtr8 additionalParamDataPtr(const_cast<TUint8*>(additionalParamDataBuffer.Ptr()),
							additionalParamDataBuffer.Length(), additionalParamDataBuffer.Length());
						theTLV.AppendItemL(pcoId,additionalParamDataPtr);
						miscBuffer.SetLength(pcoPtr.Length());
						} // case EAdditionalParamDataFormatMixedBinaryAndAscii
						break;
					case EConfigDataFormatAscii:
					default:
						// No string handling required for plain ASCII.
						TPtr8 additionalParamDataPtr(const_cast<TUint8*>(additionalParamData.Ptr()),
							additionalParamData.Length(), additionalParamData.Length());
						theTLV.AppendItemL(pcoId,additionalParamDataPtr);
						miscBuffer.SetLength(pcoPtr.Length());
						break;
						} // switch (format)
					} // End else
				} // End for loop

			configParam.iProtocolConfigOption.iMiscBuffer = miscBuffer;
			itemOffSet= itemOffSet + numAdditionalParams;
			}


		//Get if the context is valid from the config file.
		if(aTag == KSetContextConfigRel99)
			{
			delimiterField = 13;
			}
		else
			{
			delimiterField = 15;
			}			
			
		aContextConfigParams->AppendL(configParam);
		}
	}
Ejemplo n.º 21
0
TInt CTestIfioctls::ConnectToUrlUsingConnection()
	{
	ifreq ifr;
	TInt sockfd;
	TInt ret = KErrNone;	
	struct sockaddr_in destAddr, selfAddr;	
	struct in_addr *addrp;
	
	TPtrC accessPointName,url;
	_LIT( KParameter1, "Parameter1" );
    TBool res = GetStringFromConfig(ConfigSection(), KParameter1, accessPointName );
    
    _LIT( KParameter2, "Parameter2" );
    res = GetStringFromConfig(ConfigSection(), KParameter2, url );
    
	
	// Name of the interface
	TBuf8<256> asciiBuffer;
	asciiBuffer.Copy(accessPointName);

	TInt len = asciiBuffer.Length();
	Mem::Copy(ifr.ifr_name, asciiBuffer.Ptr(), len);
	ifr.ifr_name[len] = 0;
	
	StripStar(ifr.ifr_name);
	
	struct hostent *hp = 0;
	
	sockfd = socket(AF_INET,SOCK_DGRAM,IPPROTO_UDP);	
    if (sockfd < 0)
        {
        ret = KErrSocket;
        goto close;
        }
	ret = ioctl(sockfd,SIOCSIFNAME, &ifr);
	if (ret != KErrNone)
		{
		ret = KErrIoctl;
		goto close;
		}
	ret = ioctl(sockfd, SIOCIFSTART , &ifr);
	if (ret != KErrNone)
		{
		goto close;
		}
	
	
	char urlBuf[25];
	asciiBuffer.Copy(url);

	len = asciiBuffer.Length();
	Mem::Copy((void *)urlBuf, asciiBuffer.Ptr(), len);
	urlBuf[len] = 0;
	hp = gethostbyname((const char*) urlBuf );
	if (hp != NULL)
		{
		addrp = (struct in_addr*)(hp->h_addr_list[0]);
		}
	else
		{
		ret = 0;
		goto close;
		}
	
	selfAddr.sin_family = AF_INET;
	selfAddr.sin_addr.s_addr = INADDR_ANY;
	selfAddr.sin_port = htons(KTestPort);	/* echo */
	
	ret = bind(sockfd,(struct sockaddr*)&selfAddr, sizeof(selfAddr));
	if (ret != KErrNone)
		{
		ret = KErrBind;
		goto close;
		}
	
	destAddr.sin_family = AF_INET;
	destAddr.sin_addr = *addrp;
	destAddr.sin_port = htons(KTestPort);	/* http */
	ret = connect(sockfd, (struct sockaddr*)&destAddr, sizeof(destAddr));
	if (ret != KErrNone)
		{
		ret = KErrConnect;
		goto close;
		}

	close:
	ioctl(sockfd, SIOCIFSTOP, &ifr);
	close(sockfd);
	return ret;
	}
Ejemplo n.º 22
0
bool ProcessConfigFile (RFile aConfigFile,CConsoleBase* iConsole, LDDConfigPtr * LDDPtrPtr)
	{
	TUSB_PRINT ("Processing Configuration File");
	OstTrace0 (TRACE_NORMAL, CONFIGPTRS_CONFIGPTRS, "Processing Configuration File");

	TBuf8<100> configBuf;
	TBuf<101> stringBuf;
	bool done = false;
	bool error = false;
	TInt rStatus;
	XMLState state = EEmpty;
	TChar nextChar(' ');
	TChar lastChar(' ');
	TBuf<50> keyString;
	TBuf<50> endkeyString;
	TBuf<50> attributeString;
	TBuf<50> valueString;
	TInt level = -1;
	TInt levelKeys[KMaxXMLNesting+1];

	* LDDPtrPtr = NULL;
	ConfigPtrsPtr cpPtr = new ConfigPtrs (LDDPtrPtr);

	while (!done && !error)
		{
		rStatus = aConfigFile.Read((TDes8&)configBuf);
		if (rStatus != KErrNone)
			{
			error = true;
			TUSB_PRINT1("Config file error %d", rStatus);
			OstTrace1(TRACE_NORMAL, CONFIGPTRS_CONFIGPTRS_DUP01, "Config file error %d", rStatus);
			}
		else
			{
			if (configBuf.Length() == 0)
				{
				done = true;
				}
			else
				{
				stringBuf.Copy(configBuf);
				for (TInt i = 0; i < stringBuf.Length() && !error; i++)
					{
					lastChar = nextChar;
					nextChar = stringBuf[i];
					if (((nextChar == '<') && !((state == EEmpty) || (state == EValue))) ||
						((nextChar == '>') && ((state == EEmpty) || (state == EValue))) ||
						((nextChar == '/') && (lastChar != '<')))
						{
						error = true;
						TUSB_PRINT2 ("Config File Syntax Error at index %d of %s",i,stringBuf.PtrZ());
						OstTraceExt2 (TRACE_NORMAL, CONFIGPTRS_CONFIGPTRS_DUP02, "Config File Syntax Error at index %d of %S",i,stringBuf);
						}
					switch (state)
						{
						case EEmpty:
							if (nextChar == '<')
								{
								state = EStartKey;
								}
							else
								if (!nextChar.IsSpace())
									{
									error = true;
									TUSB_PRINT2 ("Config File Syntax Error at index %d of %s",i,stringBuf.PtrZ());
									OstTraceExt2 (TRACE_NORMAL, CONFIGPTRS_CONFIGPTRS_DUP03, "Config File Syntax Error at index %d of %S",i,stringBuf);
									}
							break;

						case EStartKey:
							if (nextChar == '/')
								{
								state = EEndKey;
								endkeyString.SetLength(0);
								}
							else
								{
								if (nextChar == '>')
									{
									level++;
									if (level > KMaxXMLNesting)
										{
										error = true;
										TUSB_PRINT1 ("Config File Too Many levels %s",stringBuf.PtrZ());
										OstTraceExt1 (TRACE_NORMAL, CONFIGPTRS_CONFIGPTRS_DUP04, "Config File Too Many levels %S",stringBuf);
										}
									else
										{
										levelKeys[level] = CheckXmlKey (keyString,level);
										if (levelKeys[level] < 0)
											{
											error = true;
											TUSB_PRINT1 ("Invalid XML key %s",keyString.PtrZ());
											OstTraceExt1 (TRACE_NORMAL, CONFIGPTRS_CONFIGPTRS_DUP05, "Invalid XML key %S",keyString);
											}
										else
											{
											if (CheckAttribute(iConsole,cpPtr,levelKeys[level],attributeString))
												{
												state = EValue;
												TUSB_VERBOSE_PRINT2 ("Start key: %s level %d",keyString.PtrZ(),level);
												if(gVerbose)
												    {
												    OstTraceExt2 (TRACE_VERBOSE, CONFIGPTRS_CONFIGPTRS_DUP06, "Start key: %S level %d",keyString,level);
												    }
												}
											else
												{
												error = true;
												TUSB_PRINT1 ("No attribute for XML key %s",keyString.PtrZ());
												OstTraceExt1 (TRACE_NORMAL, CONFIGPTRS_CONFIGPTRS_DUP07, "No attribute for XML key %S",keyString);
												}
											}
										}
									}
								else
									{
									if (lastChar == '<')
										{
										keyString.SetLength(0);
										valueString.SetLength(0);
										attributeString.SetLength(0);
										if (nextChar.IsSpace())
											{
											error = true;
											TUSB_PRINT2 ("Config File Syntax Error at index %d of %s",i,stringBuf.PtrZ());
											OstTraceExt2 (TRACE_NORMAL, CONFIGPTRS_CONFIGPTRS_DUP08, "Config File Syntax Error at index %d of %S",i,stringBuf);
											}
										}
									if (nextChar.IsSpace())
										{
										state = EAttribute;
										}
									else
										{
										keyString.Append(nextChar);
										}
									}
								}
							break;

						case EEndKey:
							if (nextChar == '>')
								{
								if (levelKeys[level] != CheckXmlKey (endkeyString,level))
									{
									error = true;
									TUSB_PRINT1 ("Invalid XML end key %s",endkeyString.PtrZ());
									OstTraceExt1 (TRACE_NORMAL, CONFIGPTRS_CONFIGPTRS_DUP09, "Invalid XML end key %S",endkeyString);
									}
								else
									{
									if (CheckValue(iConsole,cpPtr,levelKeys[level],valueString))
										{
										state = EEmpty;
										TUSB_VERBOSE_PRINT2 ("End Key: %s value %s",endkeyString.PtrZ(),valueString.PtrZ());
										if(gVerbose)
										    {
										    OstTraceExt2 (TRACE_VERBOSE, CONFIGPTRS_CONFIGPTRS_DUP10, "End Key: %S value %S",endkeyString,valueString);
										    }
										level--;
										valueString.SetLength(0);
										}
									else
										{
										error = true;
										TUSB_PRINT2 ("Incorrect value string %s for XML key %s",valueString.PtrZ(),endkeyString.PtrZ());
										OstTraceExt2 (TRACE_NORMAL, CONFIGPTRS_CONFIGPTRS_DUP11, "Incorrect value string %S for XML key %S",valueString,endkeyString);
										}
									}
								}
							if (nextChar.IsSpace())
								{
									error = true;
									TUSB_PRINT2 ("Config File Syntax Error at index %d of %s",i,stringBuf.PtrZ());
									OstTraceExt2 (TRACE_NORMAL, CONFIGPTRS_CONFIGPTRS_DUP12, "Config File Syntax Error at index %d of %S",i,stringBuf);
								}
							else
								{
								endkeyString.Append(nextChar);
								}
							break;

						case EAttribute:
							if (nextChar == '>')
								{
								level++;
								if (level > KMaxXMLNesting)
									{
									error = true;
									TUSB_PRINT1 ("Config File Too Many levels %s",stringBuf.PtrZ());
									OstTraceExt1 (TRACE_NORMAL, CONFIGPTRS_CONFIGPTRS_DUP13, "Config File Too Many levels %s",stringBuf);
									}
								else
									{
									levelKeys[level] = CheckXmlKey (keyString,level);
									if (levelKeys[level] < 0)
										{
										error = true;
										TUSB_PRINT1 ("Invalid XML key %s",keyString.PtrZ());
										OstTraceExt1 (TRACE_NORMAL, CONFIGPTRS_CONFIGPTRS_DUP14, "Invalid XML key %s",keyString);
										}
									else
										{
										if (CheckAttribute(iConsole,cpPtr,levelKeys[level],attributeString))
											{
											state = EValue;
											TUSB_VERBOSE_PRINT3 ("Start key: %s level %d attribute %s",keyString.PtrZ(),level,attributeString.PtrZ());
											if(gVerbose)
											    {
											    OstTraceExt3 (TRACE_VERBOSE, CONFIGPTRS_CONFIGPTRS_DUP15, "Start key: %S level %d attribute %S",keyString,level,attributeString);
											    }
											}
										else
											{
											error = true;
											TUSB_PRINT2 ("Incorrect attribute %s for XML key %s",attributeString.PtrZ(),keyString.PtrZ());
											OstTraceExt2 (TRACE_NORMAL, CONFIGPTRS_CONFIGPTRS_DUP16, "Incorrect attribute %s for XML key %s",attributeString,keyString);
											}
										}
									}
								}
							else
								{
								attributeString.Append(nextChar);
								}
							break;

						case EValue:
							if (nextChar == '<')
								{
								state = EStartKey;
								}
							else
								{
								// Don't add any leading spaces
								if (!nextChar.IsSpace() || valueString.Length() != 0)
									{
									valueString.Append(nextChar);
									}
								}
							break;
						}
					}
				}
			}
		}

	delete cpPtr;

	return !error;
	}
Ejemplo n.º 23
0
/**
@SYMTestCaseID          SYSLIB-STDLIB-CT-1042
@SYMTestCaseDesc	    Tests for the ESTW32 facilities for accessing Win32 stdin/stdout/stderr
@SYMTestPriority 	    High
@SYMTestActions  	    Open RWin32Stream::stdin,stdout,stderr and test writing to these streams.
                        Check for KErrNone flag
@SYMTestExpectedResults Test must not fail
@SYMREQ                 REQ0000
*/		
void DoTest()
	{
	RWin32Stream::StartServer();

	RWin32Stream stdin;
	RWin32Stream stdout;
	RWin32Stream stderr;

	TRequestStatus status;
	TInt err;
	err=stdin.Open(Kstdin);
	test(err,KErrNone);
	err=stdout.Open(Kstdout);
	test(err,KErrNone);
	err=stderr.Open(Kstderr);
	test(err,KErrNone);

	TBuf8<80> outbuf;

	// stderr

	outbuf=_L8("Writing to stderr\n");
	stderr.Write(status,outbuf);
	User::WaitForRequest(status);
	test_status(status,KErrNone);

	outbuf=_L8("1234XXX89");
	stderr.Write(status,outbuf,4);
	User::WaitForRequest(status);
	test_status(status,KErrNone);

	// stdout

	outbuf=_L8("Writing to stdout\n");
	stdout.Write(status,outbuf);
	User::WaitForRequest(status);
	test_status(status,KErrNone);

	outbuf=_L8("1234XXX89");
	stdout.Write(status,outbuf,4);
	User::WaitForRequest(status);
	test_status(status,KErrNone);

	FOREVER
		{
		stdin.Read(status,outbuf);
		User::WaitForRequest(status);

		TRequestStatus outStatus;
		TBuf8<80> commentary;
		commentary.Format(_L8("\nread %d, status %d\n"), outbuf.Length(), status.Int());
		stderr.Write(outStatus,commentary);
		User::WaitForRequest(outStatus);
		test_status(outStatus,KErrNone);

		if (status.Int()==KErrEof)
			break;

		stdout.Write(outStatus,outbuf);
		User::WaitForRequest(outStatus);
		test_status(outStatus,KErrNone);
		}

	outbuf=_L8("Stdin closed\n");
	stderr.Write(status,outbuf);
	User::WaitForRequest(status);
	test_status(status,KErrNone);

	}
Ejemplo n.º 24
0
void CTcTestRunner::SendErrorResponse( TInt aError )
	{
	TBuf8< KTcMaxErrorMsg > msg;
	switch( aError )
		{
		case KTcErrUnknownContext:
			{
			msg = KTcErrUnknownContextMsg;
			break;
			}
		case KTcErrNoActiveTestCase:
			{
			msg = KTcErrNoActiveTestCaseMsg;
			break;
			}
		case KTcErrReceiveOverflow:
			{
			msg = KTcErrReceiveOverflowMsg;
			break;
			}
		case KErrCorrupt:
		case KTcErrRequestCorrupt:
			{
			msg = KTcErrRequestCorruptMsg;
			break;
			}
		case KTcErrMandatoryIdNotFound:
			{
			msg = KTcErrMandatoryIdNotFoundMsg;
			break;
			}
		case KTcErrMandatoryParameterNotFound:
			{
			msg = KTcErrMandatoryParameterNotFoundMsg;
			break;
			}
		case KTcErrMandatoryHeaderNotFound:
			{
			msg = KTcErrMandatoryHeaderNotFoundMsg;
			break;
			}
		case KTcErrMandatoryStructureItemNotFound:
			{
			msg = KTcErrMandatoryStructureItemNotFoundMsg;
			break;
			}
		case KTcErrHeaderNotAllowed:
			{
			msg = KTcErrHeaderNotAllowedMsg;
			break;
			}
		case KTcErrObjectNotFound:
			{
			msg = KTcErrObjectNotFoundMsg;
			break;
			}
		case KErrNoMemory:
			{
			msg = KTcErrNoMemoryMsg;
			break;
			}
		default:
			{
			msg.Format( KTcErrTestClientInternalMsg, aError );
			break;
			}
		}

	// Read the current execution log if it was generated
	TInt err( KErrNone );
	TRAP( err,
		{
		HBufC8* logText = TcLog::ReadLogLC();
		if( logText )
			{
			logText = logText->ReAllocL( logText->Length() + msg.Length() + 16 );
			CleanupStack::Pop();	// old logText
			TPtr8 logTextPtr( logText->Des() );
			logTextPtr.Insert( 0, _L8(" ** LOG ** \n\n") );
			logTextPtr.Insert( 0, msg );
			iCodec.ConstructErrorResponse( logTextPtr );
			delete logText;
			}
		else
			{
			err = KErrNotFound;
			}
		} )

	if( err )
Ejemplo n.º 25
0
void CAppDemoAppView::OnItemSelect(TInt aPosition)
	{
	TBuf8<10> subject;
	TBuf8<10> fee;

	switch (aPosition)
		{
		case 0:
			subject.Copy(_L8("苹果"));//苹果\x82f9\x679c
			fee.Copy(_L8("0.01"));
			break;
		case 1:
			subject.Copy(_L8("葡萄"));//\x8461\x8404
			fee.Copy(_L8("50"));
			break;
		case 2:
			subject.Copy(_L8("香蕉"));//\x9999\x8549
			fee.Copy(_L8("51"));
			break;
		case 3:
			subject.Copy(_L8("樱桃"));//\x6a31\x6843
			fee.Copy(_L8("100"));
			break;
		case 4:
			subject.Copy(_L8("芒果"));//\x8292\x679c
			fee.Copy(_L8("101"));
			break;
		case 5:
			subject.Copy(_L8("西瓜"));//\x897f\x74dc
			fee.Copy(_L8("200"));
			break;
		case 6:
			subject.Copy(_L8("菠萝"));//\x83e0\x841d
			fee.Copy(_L8("201"));
			break;
		case 7:
			subject.Copy(_L8("番茄"));//\x756a\x8304
			fee.Copy(_L8("500"));
			break;
		case 8:
			subject.Copy(_L8("黃桃"));//\x9ec4\x6843
			fee.Copy(_L8("501"));
			break;
		case 9:
			subject.Copy(_L8("荔枝"));//\x8354\x679d
			fee.Copy(_L8("2000"));
			break;
		case 10:
			subject.Copy(_L8("枇杷"));//\x6787\x6777
			fee.Copy(_L8("2001"));
			break;
		case 11:
			subject.Copy(_L8("甘蔗"));//\x7518\x8517
			fee.Copy(_L8("5000"));
			break;
		case 12:
			subject.Copy(_L8("龙眼"));//\x9f99\x773c
			fee.Copy(_L8("5001"));
			break;
		default:
			return;
		}
	
		TBuf8<32> aPartnerID;
		TBuf8<32> aSellerID;
		
		aPartnerID.Copy(PartnerID);
		aSellerID.Copy(SellerID);
		
		if(aPartnerID.Length() == 0 || aSellerID.Length() == 0)
			{
			CAknInformationNote* informationNote;
			informationNote = new (ELeave) CAknInformationNote;
			// Show the information Note
			informationNote->ExecuteLD(_L("Parameter is null"));
			return;
			}

		OrderPay(subject, fee);
	}
void CATSmsReadPDU::ParseAndStoreCMGRResponseL()
/**
 * Parse the +CMGR: message from the ME.
 * It is of the form +CMGR: <Msg Status>,[<alpha>],<Msg Length> <New line> PDU
 */
	{
	LOCAL_LOGTEXT("ParseAndStoreCMGRResponseL","Enter function");

	__ASSERT_DEBUG(iClientItem,Panic(ESmsRxQueuePduReadNullParameter));

	// Intiailise the attributes
	iClientItem->iAttr.iFlags=0;
	iClientItem->iAttr.iDataFormat=RMobileSmsMessaging::EFormatGsmTpdu;
	iClientItem->iAttr.iFlags|=RMobileSmsMessaging::KSmsDataFormat;
	iClientItem->iAttr.iStatus=RMobileSmsMessaging::EMtMessageStored;
	iClientItem->iAttr.iFlags|=RMobileSmsMessaging::KIncomingStatus;
	iClientItem->iAttr.iFlags|=RMobileSmsMessaging::KStorageLocation;

	ParseBufferLC();
	CATParamListEntry* start;
	CATParamListEntry* msgAlpha;
	CATParamListEntry* msgLen;
	CATParamListEntry* msgPdu;

	{		// Curly brackets used to scope 'iter' variable
	//
	// Read in tokens
	TDblQueIter<CATParamListEntry> iter(iRxResults);
	start=iter++;
	iter++;	// To skip past the msgStatus pointer which is not used.
	msgAlpha=iter++;
	msgLen=iter++;
	msgPdu=iter;
	}

	// If alpha token was missing then we have to reorder our tokens
	if(msgPdu==NULL)
		{
		LOCAL_LOGTEXT("ParseAndStoreCMGRResponseL","<alpha> token seems to be missing");
		msgPdu=msgLen;
		msgLen=msgAlpha;
		}

	// Ensure that we have all the tokens we need
	if(start==NULL || msgLen==NULL || msgPdu==NULL)
		{
		LOCAL_LOGTEXT("ParseAndStoreCMGRResponseL","Failed to read in tokens");
		CleanupStack::PopAndDestroy();		// destroy ParseBufferLC object
		return;
		}

	//
	// Process tokens		

	// Process message length token
	TInt msgLenVal(0);
	msgLenVal=CATParamListEntry::EntryValL(msgLen);

	//
	// Copy the received pdu to local storage so that we can process
	// and modify it.
	// Buffer size calculated as follows;
	//   (max pdu size + max prefixed SCA size) * number of ASCII chars used to code an octet
	TBuf8<(RMobileSmsMessaging::KGsmTpduSize+12)*2> localPdu;	
	localPdu.Copy(msgPdu->iResultPtr);

	//
	// Check if we have a prefixed SCA on our pdu.
	// If we do then remove it.
	if(localPdu.Length()>(msgLenVal*2))
		{
		if(CATSmsUtils::ReadAndRemoveAddressFromAscii(localPdu,iClientItem->iAttr.iGsmServiceCentre,ETrue)!=KErrNone)
			{
			LOCAL_LOGTEXT("ParseAndStoreCMGRResponseL","Failed to read and remove SCA from PDU");
			}
		else
			{
			iClientItem->iAttr.iFlags|=RMobileSmsMessaging::KGsmServiceCentre;
			}
		}

	//
	// Read originator address from PDU
	// We know from ETSI standards that the originator address 
	// will start with the 3rd character (at index 2) in the pdu
	if(CATSmsUtils::ReadAddressFromAscii(localPdu.Mid(2),iClientItem->iAttr.iOriginator,EFalse)!=KErrNone)
		{
		LOCAL_LOGTEXT("ParseAndStoreCMGRResponseL","Failed to read originator from PDU");
		}
	else
		{
		iClientItem->iAttr.iFlags|=RMobileSmsMessaging::KRemotePartyInfo;
		}

	//
	// Convert received pdu from ASCII into binary
	if(CATSmsUtils::ConvertAsciiToBinary(localPdu,iClientItem->iPdu)!=KErrNone)
		{
		LOCAL_LOGTEXT("ParseAndStoreCMGRResponseL","Failed to code PDU into binary");
		}

	//
	// We've finsihed, do clean up
	CleanupStack::PopAndDestroy();		// destroy ParseBufferLC object
	LOCAL_LOGTEXT("ParseAndStoreCMGRResponseL","Exit function, PDU read OK");
	}
Ejemplo n.º 27
0
HBufC8* CIAUpdateXmlParser::ConvertUnicodeToUtf8L( 
    const TDesC16& aUnicodeText )
    {
    const TInt KConvertBufferSize( 64 );

    // Place converted data here, 
    // initial size double the conversion buffer.
    HBufC8* convertedData = HBufC8::NewL( KConvertBufferSize * 2 );
    CleanupStack::PushL( convertedData );
    TPtr8 destination( convertedData->Des() );

    // Create a small output buffer
    TBuf8< KConvertBufferSize > outputBuffer;
    
    // Create a buffer for the unconverted text - initialised with the 
    // input text
    TPtrC16 remainderOfUnicodeText( aUnicodeText );

    for ( ;; ) // conversion loop
        {
        // Start conversion. When the output buffer is full, return the 
        // number of characters that were not converted
        const TInt returnValue(
            CnvUtfConverter::ConvertFromUnicodeToUtf8( 
                outputBuffer, 
                remainderOfUnicodeText ) );

        // check to see that the descriptor isn’t corrupt 
        // - leave if it is
        if ( returnValue == CnvUtfConverter::EErrorIllFormedInput )
            {            
            User::Leave( KErrCorrupt );
            }
        else if ( returnValue < 0 )
            {            
            // future-proof against "TError" expanding
            User::Leave( KErrGeneral );
            }

        // Do something here to store the contents of the output buffer.
        if ( destination.Length() + outputBuffer.Length() >= 
             destination.MaxLength() )
            {
            HBufC8* newBuffer = convertedData->ReAllocL(
                ( destination.MaxLength() + outputBuffer.Length() ) * 2 );
            
            CleanupStack::Pop( convertedData );
            convertedData = newBuffer;
            CleanupStack::PushL( convertedData );
            destination.Set( convertedData->Des() );
            }

        destination.Append( outputBuffer );
        outputBuffer.Zero();

        // Finish conversion if there are no unconverted characters 
        // in the remainder buffer
        if ( returnValue == 0 ) 
            {            
            break; 
            }

        // Remove the converted source text from the remainder buffer.
        // The remainder buffer is then fed back into loop
        remainderOfUnicodeText.Set( 
            remainderOfUnicodeText.Right( returnValue ) );
        }
        
    CleanupStack::Pop( convertedData );
    return convertedData;
    }
//------------------------------------------------------------------------
//CHttpDownloadManagerServerEngine::QueryDynDriveListLC
//------------------------------------------------------------------------
HBufC8* CHttpDownloadManagerServerEngine::QueryDynDriveListLC()
    {
    TDriveList driveList;
    TInt driveCount( 0 );
    TInt err;
    TChar driveLetter;
    TBuf8<KMaxDriveListStrLen> driveLettersDyn;

    // Checking validity of drives in Cenrep List
    // drive letters are separated by semicolons
    // Destination is FFS in default
    TInt drive;
    User::LeaveIfError(
        DriveInfo::GetDefaultDrive( DriveInfo::EDefaultPhoneMemory, drive ) );

    for( TInt i = 0; i < iDriveLettersCenRep.Length(); i = i + 2 )
        {
        if( iRfs.CharToDrive( iDriveLettersCenRep[i], drive ) == KErrNone )
            {
            TUint status;
            if ( DriveInfo::GetDriveStatus( iRfs, drive, status ) == KErrNone )
                {
                if ( ( status & ( DriveInfo::EDriveUserVisible | DriveInfo::EDrivePresent ) ) )
                    {
                    CLOG_WRITE_1( "Drive %d is present and visible", drive);
                    }
                }
            }
        }

    if ( iDriveLettersCenRep.Length() > 0 )
        {
        driveLettersDyn.Append( iDriveLettersCenRep );
        if ( driveLettersDyn[driveLettersDyn.Length() - 1] != ';' )
            {
            driveLettersDyn.Append( KDefaultDriveListSep );
            }
        }

    // get the list of drives available in real time
    err = DriveInfo::GetUserVisibleDrives( iRfs, driveList, driveCount );
    if ( err == KErrNone )
        {
        TInt count( driveList.Length() );
        for ( TInt i( 0 ); i < count; ++i )
            {
            if ( driveList[ i ] )
                {
                User::LeaveIfError( iRfs.DriveToChar( i, driveLetter) );
                TInt drivePos = driveLettersDyn.LocateF( driveLetter );
                if ( drivePos == KErrNotFound )
                    {
                    driveLettersDyn.Append( driveLetter ); 
                    driveLettersDyn.Append( KDefaultDriveListSep ); 
                    }
                }
            }

        CLOG_WRITE_1( "Pref. drive list dynamic: [%S]", &driveLettersDyn );
        }
    else
        {
        CLOG_WRITE_1( "GetUserVisibleDrives failed with %d", err );
        }

    HBufC8* driveLetters = HBufC8::NewLC( KMaxDriveListStrLen );
    driveLetters->Des().Copy( driveLettersDyn );
    return driveLetters;
    }
Ejemplo n.º 29
0
LOCAL_C void callParseFile(RFs& fs, const TDesC& aXMLFilename)
{
	// 1. try to open the file containing the xml and if it 
	// was opened successfully put it on the cleanup stack 
	// with a close
	RFile			file;
	User::LeaveIfError(file.Open(fs, aXMLFilename, EFileStream));
	CleanupClosePushL(file);
	
	
	// 2. Create the XML Parser	and set the default document handlers
	CSyParser*   reader = CSyParser::NewLC(TPtrC());		

	CDocumentHandler docHandler(test);
	reader->SetHandler(&docHandler);

	CDeclarationHandler declHandler(test);
	reader->SetHandler(&declHandler);
	
	// 3. We set up the buffer with a default size of 128 bytes.
	//    This buffer is set purposly small so that we execute the
	//    parse stuff as often as possible to show aynchronous parsing
	//    We alse set up some loop variables
	const int KMaxBufLen = 128;
	TBuf8<KMaxBufLen> buf;
	TBool isFinal = ETrue;
	TSyExpatStatus status = EStatusOk;
	do
	{
		// 4. First read some data
		//    Note that if there was an error reading there
		//    data an error will be returned, this is not the
		//    case with eof where the buffer will be smaller than
		//    maxBufLen.
		User::LeaveIfError(file.Read(buf, KMaxBufLen));

		// 5. Next we attempt to parse the result buffer
		//    or if we reached the end of the file the 
		//    partial buffer
		isFinal = (buf.Length() != KMaxBufLen);
		status = reader->Parse(buf, isFinal);
		
		// 6. When the parser returns an error
		//    we log it 
		//    Otherwise if there is no more data
		//    then we report we have finished
		if (status != EStatusOk)
		{
			_LIT(KError,"Error on Line %d Column %d\n");
			test.Printf(KError, reader->GetCurrentLineNumber(), reader->GetCurrentColumnNumber());
		}
		else
		{
			if (isFinal)
			{
				_LIT(KFinished, "Finished parsing file\n");
				test.Printf(KFinished);
			}
		}
		
		// 7. finally we see if we have to loop round
		//    any more - we stop if we find an error or
		//    we have reached the end of the file
	} while (status == EStatusOk && !isFinal);

	// 8.  Finally delete the parser
	//     and close the file handle
	CleanupStack::PopAndDestroy(2);
}
Ejemplo n.º 30
0
TInt CTestWideApi::wfdopen_ivalm()
	{
	TPtrC nameRead;
	_LIT( KString, "Parameter1" );	    	
	TBool res = GetStringFromConfig(ConfigSection(), KString, nameRead);
	if(!res)
		{
		_LIT(Kerr , "Failed to read string") ;
		INFO_PRINTF1(Kerr) ;
		return KErrGeneral ;
		}	
	int ret_wmkdir = wmkdir(L"C:\\ggg" , S_IWUSR);
	if((errno == EEXIST) || (!ret_wmkdir))
		{
		TBuf8<100> buf;
	
		int wfd;
		buf.Copy(nameRead);
		char* filemode = (char*) buf.Ptr();
		filemode[buf.Length()]='\0';
		wchar_t *dmode = (wchar_t *)malloc(30*sizeof(wchar_t));
		if(dmode==NULL)
			{
			wrmdir(L"C:\\ggg");        								
			return KErrNoMemory;							
			}						
		size_t siz = mbstowcs(dmode, filemode, 30);
		wunlink(L"C:\\ggg\\lll.txt");
		if((wfd=wopen(L"C:\\ggg\\lll.txt", O_WRONLY | O_CREAT | O_TRUNC, 0777))<0)
	        {
        	_LIT(Kopen,"Failed to open file");
			INFO_PRINTF1(Kopen);
			wrmdir(L"C:\\ggg");      
			free(dmode) ;
			return KErrGeneral;
	        }
        else
	        {
	         FILE *fp =wfdopen(wfd ,dmode);
        	 if(NULL == fp)    	
        	 	{
	    	 	_LIT(Kopen,"wfdopen failed");
				INFO_PRINTF1(Kopen);
				close(wfd);
				wunlink(L"C:\\ggg\\lll.txt");
				wrmdir(L"C:\\ggg"); 
				free(dmode) ;     		
				return KErrNone;
        	 	}
        	 else
        	    { 
    	    	wunlink(L"C:\\ggg\\lll.txt");
   				wrmdir(L"C:\\ggg");
   				free(dmode) ;
    	    	return KErrGeneral;
        	    }        	 	
    	    }      
      	}
	else
		{
	  	_LIT(Kerr , "Failed to make dir") ;
		INFO_PRINTF1(Kerr) ;
		wunlink(L"C:\\ggg\\lll.txt");
   		wrmdir(L"C:\\ggg");
		return KErrGeneral ;
		}
	}