void CAppfwkAmaStarterTestStepCancel::TestCase1L()
	{
	// Launch the appropriate AMAStarter(s) via CAmaStart::StartL()
	
	TRequestStatus myRequestStatus;

	CAmaStart* amaStart = CAmaStart::NewL();
	CleanupStack::PushL(amaStart);
	
	amaStart->Start(TUid::Uid(0x10000017), myRequestStatus);
	TEST(myRequestStatus == KRequestPending);
	User::After(100000); // Wait for a tenth of a second to give the starter a chance to start something - if the cancel is issued without waiting, nothing is started.
	amaStart->CancelStart();	
	User::WaitForRequest(myRequestStatus);
	TEST(myRequestStatus == KErrCancel);
	INFO_PRINTF3(_L("CAmaStart->Start(TUid::Uid(0x10000017), &myRequestStatus) finished with request status '%d' (expected '%d')"), myRequestStatus.Int(), KErrCancel);
	
	//Check that the last item in the DSC didn't run
	RFs fs;
	User::LeaveIfError(fs.Connect());
	CleanupClosePushL(fs);
	RFileReadStream rs;
	TInt ret = rs.Open(fs, KLogFileName, EFileShareExclusive|EFileRead);
	if (KErrNone != ret)
		{
		ERR_PRINTF2(_L("Could not open log file. Leave code: '%d'"), ret);
		User::LeaveIfError(ret);
		}
	rs.PushL();
	const TInt KMaxCommandLength = 256;
	TBuf<KMaxCommandLength> commandLine;
	rs.ReadL(commandLine,1);
	TEST(commandLine.Compare(_L("9")) != 0);
	INFO_PRINTF2(_L("Checking log result: Expected not '9', Actual '%s'"), &commandLine);
	CleanupStack::PopAndDestroy(); //rs
	
	ret = fs.Delete(KLogFileName);
	if (KErrNone != ret)
		{
		ERR_PRINTF2(_L("Could not delete log file. Leave code: '%d'"), ret);
		User::LeaveIfError(ret);
		}

	// clean-up
	CleanupStack::PopAndDestroy(2,amaStart); // fs, amaStart
	}
void CJavaDebugAgentSettings::LoadL(const TDesC& aPrefsFile)
{
    RFs fs;
    User::LeaveIfError(fs.Connect());
    CleanupClosePushL(fs);

    RFileReadStream in;
    in.PushL();
    User::LeaveIfError(in.Open(fs, aPrefsFile, EFileRead));
    TRAPD(err, LoadL(&in));
    in.Close();
    in.Pop();

    if (err != KErrNone) {
        err = fs.Delete(aPrefsFile);
    }
    CleanupStack::PopAndDestroy(&fs);
}
/**
 Start a test application synchronously using Wait-for-Signal with timeout
 more than the time required for the application to start and which starts after the no. of retries given.
*/
void CSsTestStepAppTimeout::DoTestWaitForSignalWithMoreTimeOutAndWithRetriesL()
	{	
	INFO_PRINTF1(_L("Performing Wait-for-Signal test with timeout and retries"));

	// Write the retry number to a file to be read, updated 
	// and eventually deleted by the test-app.
	RFs fs;	
	CleanupClosePushL( fs );
	
	RFileWriteStream writeStream;
	CleanupClosePushL( writeStream );

	User::LeaveIfError(fs.Connect());
	User::LeaveIfError(writeStream.Replace(fs, KFileForFAndF, EFileWrite));

	const TInt KSsTestRequiredDelay = 0;
	const TInt KSsTestFailCount = 1;
	const TInt KSsTestRetryCount = 0;
	writeStream.WriteInt8L(KSsTestRetryCount);
	writeStream.WriteInt8L(KSsTestFailCount);
	writeStream.WriteInt8L(KSsTestRequiredDelay);
	writeStream.CommitL();
	writeStream.Close();
	
	const TInt KRetries = KSsTestFailCount + 1;
	TInt completionCode = DoTestAndStopperL(KRetries, KWaitTimeForTestAppForFAndF * 3, KTestAppForFAndF);
	TEST(completionCode == 0);
	
	INFO_PRINTF2( _L("Anticipated completion code 0. Supplied completion code %d"),completionCode);
	RFileReadStream readStream;
	CleanupClosePushL(readStream);

	User::LeaveIfError(readStream.Open(fs, KFileForFAndF, EFileRead));
	TInt retryCount = readStream.ReadInt8L();
	readStream.Close();	
	fs.Delete(KFileForFAndF);

	CleanupStack::PopAndDestroy(3, &fs);

	TEST(1 == FindAndKill(KTestAppForFAndF));
	TEST(retryCount == 1);

	INFO_PRINTF3( _L("ssmtestappsucessfulafterretry.exe is started after %d retries. anticipated retries value %d"),retryCount, 1);
	}
// ----------------------------------------------------------------------------
// CAudioStreamEngine::LoadAudioFileL()
//
// loads the audio data from a file into the buffer
// ----------------------------------------------------------------------------
void CAudioStreamEngine::LoadAudioFileL()
    {
    RFileReadStream audiofile;

    // open file
    TFileName fileName;
    fileName.Copy(iAudioFilePath);
    fileName.Append(iAudioFile);

    TInt err = audiofile.Open(iFs, fileName, EFileRead|EFileStream);
    iStreamBuffer->Des().FillZ(iFrameCount * iFrameSize);  // Empty the stream buffer
    if (err==KErrNone) 
        {
        // file opened ok, proceed reading
        if (iUseAMR)
            {
            // Read the AMR header (the first 6 bytes). We don't need to save/use the header,
            // since while playback we already know it's an AMR-NB encoded stream.
            TBuf8<KAMRHeaderLength> temp;
            audiofile.ReadL(temp, KAMRHeaderLength);
            }

        TUint idx=0;
        while (idx < iFrameCount)
            {
            TRAPD(fstatus, audiofile.ReadL(GetFrame(idx), iFrameSize));
            if (fstatus!=KErrNone)
                break;
            idx++;
            }
        iStreamStart=0;
        iStreamEnd=idx-1;
        ShowMessage(_L("CAudioStreamEngine::LoadAudioFileL() Loading complete!"), ETrue);
        iBufferOK = ETrue;  
        }   
    else 
        {
        // failed to open file
        ShowMessage(_L("CAudioStreamEngine::LoadAudioFileL() Error loading audio sample!"), ETrue); 
        iBufferOK = EFalse;
        }
    audiofile.Close();
    }
EXPORT_C TInt TEFparser::ReadFileLC(RFs& aFs, 
										const TDesC& aScriptFilepath,
										TPtrC& aScriptFileContents )
	{
	
	RFile scriptFile;
	TInt err = scriptFile.Open(aFs, aScriptFilepath, EFileStream | EFileRead | EFileShareAny);
	if (err != KErrNone)
		{	
		return KErrNotFound;
		}
	// gets size of ini file
	TInt size;
	scriptFile.Size(size);
	scriptFile.Close();
			
	// reads ini into iTestInput
	HBufC* scriptFileH16 = HBufC::NewLC(size);
	HBufC8* scriptFileH = HBufC8::NewLC(size);
	
	//RBuf scriptFileR;
	TPtr8 pInput = scriptFileH->Des(); 
	TPtr pInput16 = scriptFileH16->Des(); 
	
	pInput.SetLength(size); 
	
	RFileReadStream stream;
	User::LeaveIfError(stream.Open(aFs, aScriptFilepath, EFileStream | EFileRead | EFileShareReadersOnly));
	CleanupClosePushL(stream);
	stream.ReadL(pInput,size);
	
//	stream.ReadL(pInput, size);
	
	pInput16.Copy(pInput);
	//scriptFileR.Assign(scriptFileH16);
	
	aScriptFileContents.Set(*scriptFileH16);
	
	CleanupStack::PopAndDestroy(2); // stream, testInput
	
	return KErrNone;
	}
Exemple #6
0
/** Import contacts from the vCard file specified by aFileName */
void CAgentTest::ImportContactsL(const TDesC& aFileName)
	{
	RFileReadStream vcard;
	User::LeaveIfError(vcard.Open(iTest.Fs(), aFileName, EFileRead));
	CleanupClosePushL(vcard);

	TBool success=EFalse;
	CArrayPtr<CContactItem>* contactItems=iDb->ImportContactsL(TUid::Uid(KUidVCardConvDefaultImpl), vcard, success, CContactDatabase::ETTFormat);
	CleanupStack::PopAndDestroy(&vcard);
	       
	CleanupStack::PushL(TCleanupItem(CleanUpResetAndDestroy,contactItems));
	iIdArray->Reset();
	TContactItemId contactId;
 	for(TInt loop = 0;loop < contactItems->Count();++loop)
		{
		contactId = (*contactItems)[loop]->Id();
		iIdArray->AddL(contactId);		
		}
	CleanupStack::PopAndDestroy(contactItems);	
	}
HBufC8* CValidateTest::ReadFileLC(const TDesC& aFilename)
	{
	RFile file;
	User::LeaveIfError(file.Open(iFs, aFilename, EFileRead));
	CleanupClosePushL(file);
	TInt size;
	file.Size(size);
	CleanupStack::PopAndDestroy(1);//fileClose

	HBufC8* res = HBufC8::NewLC(size);
	TPtr8 p(res->Des());
	p.SetLength(size);

	RFileReadStream stream;
	User::LeaveIfError(stream.Open(iFs, aFilename, EFileStream));
	CleanupClosePushL(stream);
	stream.ReadL(p, size);
	CleanupStack::PopAndDestroy();//streamClose...bleurgh
	return res;
	}
// -----------------------------------------------------------------------------
// CDRMHelperServer::RestoreL().
// This function restore internal list from data file
// -----------------------------------------------------------------------------
//
void CDRMHelperServer::RestoreL()
    {
#ifdef _DRM_TESTING
    WriteL(_L8("RestoreL"));
#endif

    TInt err = 0;
    RFileReadStream file;

    RFile test;
    err = test.Open( iFs , DataFileL(iFs).FullName() , EFileRead );
    if ( !err )
        {
        CleanupClosePushL(test);
        TInt size = 0;
        err = test.Size(size);
        User::LeaveIfError(err);
        CleanupStack::PopAndDestroy(&test); //test
        if (size == 0)
            {
            StoreL();
            }
        }
    else if ( err == KErrNotFound )
        {
        StoreL();
        }
    else
        {
        User::Leave(err);
        }

    User::LeaveIfError(file.Open( iFs , DataFileL(iFs).FullName() , EFileRead ));
    file.PushL();
    InternalizeL(file);
    CleanupStack::PopAndDestroy(&file); //file

#ifdef _DRM_TESTING
    WriteL(_L8("RestoreL->End"));
#endif
    }
//////////////////////////////////////////////////////////////////////////////////
//	Test fix for INC023303: CX509Certificate externalize - internalize don't work 
//////////////////////////////////////////////////////////////////////////////////
void CSyntaxTest::TestInternalizeExternalizeL(CX509Certificate* aCert)
	{
	RFileWriteStream newwriter;
	newwriter.PushL();
	User::LeaveIfError(newwriter.Replace(iFs,_L("x509stream"),EFileStream));
	
	aCert->ExternalizeL(newwriter);
	newwriter.CommitL();
	CleanupStack::PopAndDestroy(1);//newwriter
	
	RFileReadStream newreader;
	newreader.PushL();
	newreader.Open(iFs,_L("x509stream"),EFileStream);
	CX509Certificate* readCert=CX509Certificate::NewLC(newreader); //Use the stream to create new cert

	if (!readCert->IsEqualL(*aCert))
		User::Leave(KErrGeneral);

//	iFs.Delete(_L("x509stream"));
	CleanupStack::PopAndDestroy(2);	//	readCert, newreader
	}
void TTcSettings::Load()
	{
	// Connect to file server
	RFs fs;
	if( fs.Connect() )
		{
		return;
		}

	// Open the settings file for reading, it might not exist yet
	RFileReadStream in;
	if( !in.Open( fs, KTcSettingsFile, EFileRead ) )
		{
		// Load actual data, ignore errors (the file might be of a previous
		// version and/or some items might be missing).
		TRAP_IGNORE( doLoadL( in ) )
		}

	in.Close();
	fs.Close();
	}
/**
 @fn void ReadIniFileL()
 Open the ini file and read the contents. Intended for manually testing the 
 write code.
 */
LOCAL_C void ReadIniFileL()
	{
	RFs fileSession;
	User::LeaveIfError(fileSession.Connect());
	CleanupClosePushL(fileSession);
	
	RFileReadStream fileReadStream;
	User::LeaveIfError(fileReadStream.Open(fileSession, IniFileName, EFileRead));
	CleanupClosePushL(fileReadStream);

    TInt32 value1 = 0;
    TInt8 value2 = 0;

	//read the KEComUid and KSsaUid
	value1 = fileReadStream.ReadInt32L();
	value1 = fileReadStream.ReadInt32L();
	value2 = fileReadStream.ReadInt8L();

	// close: fileSession, fileReadStream
	CleanupStack::PopAndDestroy(2);
	}
/**
@SYMTestCaseID          PDS-STORE-CT-4042
@SYMTestCaseDesc	    Tests for attaching write stream and read stream to an encrypted stream.
@SYMTestPriority 	    High
@SYMTestActions  	    Encrypt data and write to a store.Read the encrypted data for decrypting and compare the result.
@SYMTestExpectedResults Test must not fail
@SYMDEF                 DEF135804
*/
LOCAL_C void testEncryptionDataAttachL()
	{
	test.Next(_L(" @SYMTestCaseID:PDS-STORE-CT-4042 "));
	CPBEncryptElement* elementKey = CPBEncryptElement::NewLC(KTestPassword);
	TParsePtrC parse(KFileLocationSpec);
	
	RFileWriteStream writeStream;
	writeStream.PushL();
	User::LeaveIfError(writeStream.Replace(TheFs, parse.NameAndExt(), EFileWrite));
	
	REncryptStream encryptStream;
	TRAPD(ret, encryptStream.AttachL(writeStream, *elementKey));
	test(ret == KErrNone);
	encryptStream.PushL();
	
	encryptStream << KTestDes;
	encryptStream.CommitL();
	writeStream.CommitL();
	
	CleanupStack::PopAndDestroy(2); // encryptStream, writeStream
	
	const CPBEncryptionData& encryptData = elementKey->EncryptionData();
	
	CPBEncryptElement* newElementKey = CPBEncryptElement::NewLC(encryptData, KTestPassword);
	
	RFileReadStream readStream;
	readStream.PushL();
	User::LeaveIfError(readStream.Open(TheFs, parse.NameAndExt(), EFileWrite));
	
	
	RDecryptStream decryptStream;
	decryptStream.AttachL(readStream, *newElementKey);
	decryptStream.PushL();
	
	decryptStream >> TheBuf;
	
	test(KTestDes == TheBuf);
	
	CleanupStack::PopAndDestroy(4, elementKey);
	}
void CJournalFile::ReadL()
	{
	RFileReadStream journalStream;
	User::LeaveIfError(journalStream.Open(iFs, iJournalFileName, EFileRead | EFileShareAny));
	CleanupClosePushL(journalStream);
	
	// we need to check that any filenames read from the journal are on the
	// same drive as the journal itself
	TDriveUnit journalDrive(iJournalFileName);
	
	TInt err = KErrNone;
	while(err == KErrNone)
		{
		// read the next journal entry
		TRAP(err, ReadEntryL(journalStream, journalDrive));
		if(err != KErrNone && err != KErrEof)
			{
			DEBUG_PRINTF2(_L("CJournalFile::ReadL() - CJournalFile::ReadEntryL() has left with error %d Leaving with this error!"), err);							
			User::Leave(err);
			}
		}
	CleanupStack::PopAndDestroy(&journalStream);
	}
TCalLocalUid CDstIntUtils::ImportVCalL(RFs& aFs, CCalSession& aSession, CCalEntryView& aEntryView, const TDesC& aFileName)
	{
	RFileReadStream readStream;
	User::LeaveIfError(readStream.Open(aFs, aFileName, EFileRead));
	CleanupClosePushL(readStream);

	// Create ptr array for new entries
	RPointerArray<CCalEntry> entryArray;
	CleanupStack::PushL(TCleanupItem(ResetAndDestroyArrayOfEntries, &entryArray));

	CCalDataExchange* dataExchange = CCalDataExchange::NewL(aSession);
	CleanupStack::PushL(dataExchange);
	dataExchange->ImportL(KUidVCalendar, readStream, entryArray);

	TInt elements = entryArray.Count();
	TCalLocalUid id = 0;

	if(elements > 0)
		{
		CCalEntry* entry = entryArray[0];
		// add the first entry only
		while (entryArray.Count() > 1)
			{
			delete entryArray[1];
			entryArray.Remove(1);
			}
		TInt success = 0;
		aEntryView.StoreL(entryArray, success);
		id = entryArray[0]->LocalUidL();
		}

	CleanupStack::PopAndDestroy(dataExchange);
	CleanupStack::PopAndDestroy();	// ResetAndDestroyArrayOfEntries(entryArray)
	CleanupStack::PopAndDestroy();	// readStream.Close()

	return id;
	}
// ---------------------------------------------------------------------------
// 
// ---------------------------------------------------------------------------
//    
void CNcdProviderUtils::ReadDatabaseVersionsL( 
    const TDesC& aRootPath,
    TUint32& aGeneralVersion, 
    TUint32& aPurchaseHistoryVersion )
    {
    DLTRACEIN((""));        
    
    RBuf path;
    AppendPathsLC( 
        path, 
        aRootPath, 
        NcdProviderDefines::KNcdDatabaseVersionFile );
    
    
    RFileReadStream stream;
    CleanupClosePushL( stream );
    User::LeaveIfError( stream.Open( FileSession(), 
        path, EFileRead ) );
    aGeneralVersion = stream.ReadUint32L();
    aPurchaseHistoryVersion = stream.ReadUint32L();
    CleanupStack::PopAndDestroy( 2, &path ); // stream, path
    DLTRACEOUT(("Versions, general: %d, purchase history: %d",
        aGeneralVersion, aPurchaseHistoryVersion ));
    }
void CTestImpExvCardSuiteStepBase::OpenVCFAndImportItemL(TBuf<80> aPath, RFs aFsSession, TInt aIndex)
	{
	User::LeaveIfError(aFsSession.Connect());
	CleanupClosePushL(aFsSession);
	RFileReadStream readVCFStream;
	
	// Format buf to hold relevant vcf file
	TBuf<100> buf;
	buf.Zero();
#ifdef __WINS__	
    buf.Append(_L("c:"));
#else
    TFileName processFileName = RProcess().FileName();
    TParsePtrC parse(processFileName);
    buf.Append(parse.Drive());
#endif 
	buf.Append(aPath);
	buf.AppendNum(aIndex);
	buf.Append(_L(".vcf"));
	
	// Open vcf file
	User::LeaveIfError(readVCFStream.Open(aFsSession, buf, EFileRead));
	
	TBuf<MAX_TEXT_MESSAGE> message;
	message.Format(KOpenVCFFile, &buf);
	INFO_PRINTF1(message);
	
	CleanupClosePushL(readVCFStream);
	
	// Imports the vCard
	ImportCardL(readVCFStream);
	
	CleanupStack::PopAndDestroy(); // pop readVCFStream
	aFsSession.Close();
	CleanupStack::PopAndDestroy(); // pop aFsSession
	}
// -----------------------------------------------------------------------------
// CSisxUIStartupFile::ReadPrivateStartupItemsL
// Read startup items from private file.
// (other items were commented in a header).
// -----------------------------------------------------------------------------
//
void CSisxUIStartupFile::ReadPrivateStartupItemsL( RArray<TStartupTaskParam>& aStartupItems )
    {
    RFileReadStream reader;
    reader.PushL();
    
    User::LeaveIfError( reader.Open( iFileSession, *iPrivateFile, EFileRead ) );
    
    // Read the number of entries
    TInt count = reader.ReadInt32L();

     // Read file names from the file
    while ( count-- )
        {
        TStartupTaskParam item;

        HBufC* fileName = HBufC::NewLC( reader, KMaxFileName );
        item.iFileName.Copy( *fileName );        
        CleanupStack::PopAndDestroy( fileName);       

        aStartupItems.Append( item );
        }

    CleanupStack::PopAndDestroy(); // reader
    }
TBool CSupLoginServiceProvider::ReadDataFromFileL()
{
	__LOGSTR_TOFILE("CSupLoginServiceProvider::ReadDataFromFileL() begins");

	// If current operation should be cancelled
	if (iCancelStatus)
		return EFalse;

	TBool retValue = ETrue;

	RFs fsSession;
	RFileReadStream readStream; // Read stream from file

	// Install read file session
	User::LeaveIfError(fsSession.Connect());
	CleanupClosePushL(fsSession);

	TInt err = readStream.Open(fsSession, iSettingsFile, EFileStream | EFileRead | EFileShareExclusive);
	CleanupClosePushL(readStream);

	// If file does not exist - return EFalse
	if (err != KErrNone)
	{
		retValue = EFalse;

		__LOGSTR_TOFILE("CSupLoginServiceProvider::ReadDataFromFileL() failed to open");
	}

	if (retValue)
	{
		TInt valueMaxLen = 0;
		HBufC8* tempValue = NULL;	

		// iMemberID
		valueMaxLen = readStream.ReadInt32L();

		__LOGSTR_TOFILE("CSupLoginServiceProvider::ReadDataFromFileL() reading member id");

		tempValue = HBufC8::NewL(readStream, valueMaxLen);
		if (tempValue)
		{
			if (iMemberID)
			{
				delete iMemberID;
				iMemberID = NULL;
			}

			iMemberID = tempValue->Des().AllocL();

			delete tempValue;
			tempValue = NULL;
		}

		// iUsername
		valueMaxLen = readStream.ReadInt32L();

		__LOGSTR_TOFILE("CSupLoginServiceProvider::ReadDataFromFileL() reading username");

		tempValue = HBufC8::NewL(readStream, valueMaxLen);
		if (tempValue)
		{
			if (iUsername)
			{
				delete iUsername;
				iUsername = NULL;
			}

			iUsername = tempValue->Des().AllocL();

			delete tempValue;
			tempValue = NULL;
		}

		// iPassword
		valueMaxLen = readStream.ReadInt32L();

		__LOGSTR_TOFILE("CSupLoginServiceProvider::ReadDataFromFileL() reading password");

		tempValue = HBufC8::NewL(readStream, valueMaxLen);
		if (tempValue)
		{
			if (iPassword)
			{
				delete iPassword;
				iPassword = NULL;
			}

			iPassword = tempValue->Des().AllocL();

			delete tempValue;
			tempValue = NULL;
		}
	}

	// Free resource handlers
	CleanupStack::PopAndDestroy(&readStream);
	CleanupStack::PopAndDestroy(&fsSession);	

	__LOGSTR_TOFILE("CSupLoginServiceProvider::ReadDataFromFileL() ends");

	return retValue;
}
// ----------------------------------------------------------------------------
// WidgetPreferences::PreferenceL
// Get preference for a key
//
//
// ----------------------------------------------------------------------------
TInt WidgetPreferences::preferenceL( const TDesC& akey, HBufC*& avalue)
{

    TInt rSuccess = KErrNotFound;
    TInt size = 0;

    if ( !m_basepath || (m_basepath->Length() <= 0) )
        return rSuccess;


    if ( akey.Length() <= KMaxKeyValueSize ) {

        HBufC* k = HBufC::NewLC( akey.Length() + KMaxIntLength + 1 );
        k->Des().Format( KKeyFormat, m_widgetid, &akey );

        PrefElement* pref = m_preferences->Find( *k );

        if ( !pref ) {
            CleanupStack::PopAndDestroy( k );
            return rSuccess;
        }

        size = pref->valueSize();

        if ( size > KMaxKeyValueSize ) {
            // return contents from temp file whose name is stored
            // in the m_value member of m_preferences
            RFs fs;

            if ( fs.Connect() == KErrNone ) {
                CleanupClosePushL( fs );
                HBufC* filePath = HBufC::NewLC( pref->value().Length() );
                TPtr fName( filePath->Des() );
                fName.Append( pref->value() );

                RFileReadStream readStream;

                if ( readStream.Open( fs, *filePath, EFileRead ) == KErrNone ) {
                    CleanupClosePushL( readStream );
                    TInt len( readStream.ReadInt32L() );
                    if ( len > 0 ) {
                        HBufC* v = HBufC::NewLC( len );
                        TPtr ptrvalue = v->Des();
                        readStream.ReadL( ptrvalue, len );
                        avalue = v; // ownership xfered
                        CleanupStack::Pop( v );
                        rSuccess = KErrNone;
                    }
                    CleanupStack::PopAndDestroy();//readStream
                }

                CleanupStack::PopAndDestroy( 2 ); //filePath,fs
            }
        }
        else if ( size >= 0 ) {
            avalue = pref->value().AllocL();
            rSuccess = KErrNone;
        }

        CleanupStack::PopAndDestroy( k );
    }

    return rSuccess;

}
// ---------------------------------------------------------------------------
// CLbtCleanupHandler::ReadCleanupDataFromFileL
// ---------------------------------------------------------------------------
//
void CLbtCleanupHandler::ReadCleanupDataFromFileL()
	{
	FUNC_ENTER("CLbtCleanupHandler::ReadCleanupDataFromFileL");
	
	// First reset the cleanup data 
	iCleanupItems.ResetAndDestroy();
	
	// Open handle to file system
	RFs fs;
	User::LeaveIfError(fs.Connect());
	
	CleanupClosePushL(fs);
	
	// Obtain the file path
    TFileName file;
    
    // Gets the path in which the file can be created
    fs.SessionPath(file);

    // Create the file Directory ie the private directory of the process
    fs.MkDirAll(file);
    
    // Append the name of the file
    file.Append(KLbtAppCleanupFileName);
    
    // Open read stream
    RFileReadStream readStream;
    
    TInt error = readStream.Open( fs, file, EFileRead );
    if( error != KErrNone )
    	{
    	// File may not exists
    	ERROR("Opening of cleanup file failed with : %d", error);
    	readStream.Close();
    	CleanupStack::PopAndDestroy(); //fs
    	return;
    	}
    CleanupClosePushL( readStream );
    
    // Get the count in the cleanup array
    TInt count = readStream.ReadInt16L();    
    for(TInt i=0; i<count; ++i)
    	{
    	RArray<TLbtTriggerId> triggers;
    	CleanupClosePushL(triggers);
    	
    	// Read the trigger ids
    	TInt triggerCount = readStream.ReadInt16L();
    	for(TInt j=0;j<triggerCount;++j)
    		{
    		triggers.Append( readStream.ReadUint32L() );
    		}
    	
    	// Read the universal time
    	TInt year = readStream.ReadInt32L();
    	TMonth month = static_cast<TMonth>( readStream.ReadInt32L() );
    	TInt day = readStream.ReadInt32L();
    	
    	TDateTime dateTime( year,
    						month,
    						day,
    						0,
    						0,
    						0,
    						0 );
    	TTime time( dateTime );
    	
    	CLbtCleanupItem* cleanupItem = new (ELeave) CLbtCleanupItem();
    	cleanupItem->AddCleanupItem( triggers, time );
    	
    	CleanupStack::Pop(); // triggers
    	triggers.Close();
    	
    	// Append cleanup item to the cleaup items array
    	iCleanupItems.Append( cleanupItem );
    	}

    CleanupStack::PopAndDestroy(2); // fs and readStream
	}
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;
    }
void CGsaStateTranToDiffStatesTest::DoStateRequestTransitionToDiffStatesL()
	{
	INFO_PRINTF1(_L("DoStateRequestTransitionToDiffStates test started...."));
	
	RFs fs;
	TInt err = fs.Connect();
	TEST(err == KErrNone);
	User::LeaveIfError(err);
	CleanupClosePushL(fs);
		
	if (iProcessName == KTestProcTranFromNormal)
		{
		RFileReadStream fileReadStream1;
		err = fileReadStream1.Open(fs, KGsaTestStateTranFromNormalResult, EFileRead);
		INFO_PRINTF2(_L("Error in opening file: %d"), err);
		TEST(err == KErrNone);
		User::LeaveIfError(err);
		CleanupClosePushL(fileReadStream1);

		//System state before starting the test.
		CurrentSystemStateForStateTranTestL(fileReadStream1, ESsmNormal);

		//Scenario 1 - Request for state change from Normal to invalid state results in KErrNotSupported
		INFO_PRINTF1(_L("Request for state change from Normal to invalid state"));
		TInt stateTranResult = fileReadStream1.ReadInt32L();
		TEST(stateTranResult == KErrNotSupported);
		INFO_PRINTF2(_L("Actual : %d Expected : -5"), stateTranResult);
		CurrentSystemStateForStateTranTestL(fileReadStream1, ESsmNormal);
		
		//Scenario 2 - Request for state change from Normal to fail state with invalid substate results in KErrNotSupported
		INFO_PRINTF1(_L("Request for state change from Normal to fail state with invalid substate"));
		stateTranResult = fileReadStream1.ReadInt32L();
		TEST(stateTranResult == KErrNotSupported);
		INFO_PRINTF2(_L("Actual : %d Expected : -5"), stateTranResult);
		CurrentSystemStateForStateTranTestL(fileReadStream1, ESsmNormal);

		//Scenario 3 - Request for two state changes(1. fail state 2. shutdown state) one after the other without waiting 
		// for the first one to complete. Cancels both transition request. 		
		INFO_PRINTF1(_L("Request for two state changes(1. fail state 2. shutdown state)"));
		INFO_PRINTF1(_L("one after the other without waiting for the first one to complete."));
		INFO_PRINTF1(_L("Cancel the fail state transition request."));
		stateTranResult = fileReadStream1.ReadInt32L();
		TEST(stateTranResult == KErrCancel);
		INFO_PRINTF2(_L("First request to the fail state will be completed with %d Expected -3"), stateTranResult);
		CurrentSystemStateForStateTranTestL(fileReadStream1, ESsmNormal);

		stateTranResult = fileReadStream1.ReadInt32L();
		TEST(stateTranResult == KErrCancel);
		INFO_PRINTF2(_L("Second request to transit to the shutdown state will be completed with %d Expected -3"), stateTranResult);
		CurrentSystemStateForStateTranTestL(fileReadStream1, ESsmNormal);

		INFO_PRINTF2(_L("Test process exits with %d Expected -3"), stateTranResult);

		CleanupStack::PopAndDestroy();
		// Delete the result file
		//err = fs.Delete(KGsaTestStateTranFromNormalResult);

		RFileReadStream fileReadStream2;
		err = fileReadStream2.Open(fs, KGsaTestStateTranToShutdownResult, EFileRead);
		TEST(err == KErrNone);
		User::LeaveIfError(err);
		CleanupClosePushL(fileReadStream2);

		//System state before starting the test.
		CurrentSystemStateForStateTranTestL(fileReadStream2, ESsmNormal);

		//Scenario 1 - Request for state transition to shutdown state - invalid substate
		// request to transit to the shutdown state will be completed with KErrNotSupported
		INFO_PRINTF1(_L("Request for state transition to shutdown state - invalid substate"));
		stateTranResult = fileReadStream2.ReadInt32L();
		TEST(stateTranResult == KErrNotSupported);
		INFO_PRINTF2(_L("Actual : %d Expected : -5"), stateTranResult);
		CurrentSystemStateForStateTranTestL(fileReadStream2, ESsmNormal);
		
		INFO_PRINTF2(_L("Test process exits with %d Expected -5"), stateTranResult);

		CleanupStack::PopAndDestroy();
		// Delete the result file
		//err = fs.Delete(KGsaTestStateTranToShutdownResult);

		RFileReadStream fileReadStream3;
		err = fileReadStream3.Open(fs, KGsaTestStateTranFromShutdownResult, EFileRead);
		TEST(err == KErrNone);
		User::LeaveIfError(err);
		CleanupClosePushL(fileReadStream3);

		//System state before starting the test.
		CurrentSystemStateForStateTranTestL(fileReadStream3, ESsmNormal);

		//Scenario 1 - Request for state change from Normal to shutdown state to critical substate
		// Cancel the request immediately
		INFO_PRINTF1(_L("Request for state change from Normal to shutdown critical substate and Cancel the request"));
		stateTranResult = fileReadStream3.ReadInt32L();
		TEST(stateTranResult == KErrCancel);
		INFO_PRINTF2(_L("Actual : %d Expected : -3"), stateTranResult);
		CurrentSystemStateForStateTranTestL(fileReadStream3, ESsmNormal);

		//Scenario 2 - Request for state change from Normal to shutdown state to any substate
		// Cancel the request immediately, so that we can proceed with the next test scenario.

		INFO_PRINTF1(_L("Request for state change from Normal to shutdown any substate and Cancel the request"));
		stateTranResult = fileReadStream3.ReadInt32L();
		TEST(stateTranResult == KErrCancel);
		INFO_PRINTF2(_L("Actual : %d Expected : -3"), stateTranResult);
		CurrentSystemStateForStateTranTestL(fileReadStream3, ESsmNormal);

		INFO_PRINTF2(_L("Test process exits with %d Expected -3"), stateTranResult);

		CleanupStack::PopAndDestroy();
		// Delete the result file
		//err = fs.Delete(KGsaTestStateTranFromShutdownResult);
		}
	else if(iProcessName == KTestProcTranFromStartup)
		{
		RFileReadStream fileReadStream;
		err = fileReadStream.Open(fs, KGsaTestStateTranFromStartupResult, EFileRead);
		TEST(err == KErrNone);
		User::LeaveIfError(err);
		CleanupClosePushL(fileReadStream);

		//System state before starting the test.
		CurrentSystemStateForStateTranTestL(fileReadStream, ESsmStartup);

		//Scenario 1 - Request for state change from Startup to invalid state
		INFO_PRINTF1(_L("Request for state change from Startup to invalid state"));
		TInt stateTranResult = fileReadStream.ReadInt32L();
		TEST(stateTranResult == KErrNotSupported);
		INFO_PRINTF2(_L("Actual : %d Expected : -5"), stateTranResult);
		CurrentSystemStateForStateTranTestL(fileReadStream, ESsmStartup);
		
		INFO_PRINTF2(_L("Test process exits with %d Expected -5"), stateTranResult);
		
		CleanupStack::PopAndDestroy();
		// Delete the result file
		//err = fs.Delete(KGsaTestStateTranFromStartupResult);
		}
	else
		{
		TEST(err == KErrArgument);
		return;
		}

	CleanupStack::PopAndDestroy();
	INFO_PRINTF1(_L("case completed\n"));
	}