Ejemplo n.º 1
0
LOCAL_D void MoveBookmarksTest()
	{
	RBkFolder root;
	root = gDatabase.OpenRootL();
	CleanupClosePushL(root);
	gTestWrapper->TEST(root.Count() == 0);

	RBkFolder folder1 = gDatabase.CreateFolderL(KTxtFolder2_1);
	CleanupClosePushL(folder1);
	RBkFolder folder2 = gDatabase.CreateFolderL(KTxtFolder2_2);
	CleanupClosePushL(folder2);

	RBkBookmark bookmark = gDatabase.CreateBookmarkL(&folder1);
	CleanupClosePushL(bookmark);
	Bookmark::TItemId id1 = bookmark.Id();
	CleanupStack::PopAndDestroy(&bookmark);

	bookmark = gDatabase.CreateBookmarkL(&folder1);
	CleanupClosePushL(bookmark);
	Bookmark::TItemId id2 = bookmark.Id();
	CleanupStack::PopAndDestroy(&bookmark);

	bookmark = gDatabase.CreateBookmarkL(&folder2);
	CleanupClosePushL(bookmark);
	Bookmark::TItemId id3 = bookmark.Id();
	CleanupStack::PopAndDestroy(&bookmark);

	bookmark = gDatabase.CreateBookmarkL(&folder2);
	CleanupClosePushL(bookmark);
	Bookmark::TItemId id4 = bookmark.Id();
	CleanupStack::PopAndDestroy(&bookmark);

	gTestWrapper->TEST(folder1.Count() == 2);
	gTestWrapper->TEST(folder2.Count() == 2);

	RBkNode item = folder1.OpenItemL(0);
	CleanupClosePushL(item);
	folder2.AppendL(item);
	CleanupStack::PopAndDestroy(&item);

	gTestWrapper->TEST(folder1.Count() == 1);
	gTestWrapper->TEST(folder2.Count() == 3);

	folder2.Move(0,2);

	item = folder2.OpenItemL(0);
	CleanupClosePushL(item);
	folder1.InsertL(item, 0);
	CleanupStack::PopAndDestroy(&item);

	gTestWrapper->TEST(folder1.Count() == 2);
	gTestWrapper->TEST(folder2.Count() == 2);

	item = folder1.OpenItemL(0);
	CleanupClosePushL(item);
	gTestWrapper->TEST(item.Id() == id4);
	CleanupStack::PopAndDestroy(&item);

	item = folder1.OpenItemL(1);
	CleanupClosePushL(item);
	gTestWrapper->TEST(item.Id() == id2);
	CleanupStack::PopAndDestroy(&item);

	item = folder2.OpenItemL(0);
	CleanupClosePushL(item);
	gTestWrapper->TEST(item.Id() == id1);
	CleanupStack::PopAndDestroy(&item);

	item = folder2.OpenItemL(1);
	CleanupClosePushL(item);
	gTestWrapper->TEST(item.Id() == id3);
	CleanupStack::PopAndDestroy(&item);

	CleanupStack::PopAndDestroy(2); //folders
	CleanupStack::PopAndDestroy(&root);
	}
Ejemplo n.º 2
0
// -----------------------------------------------------------------------------
// CBSBrandHandler::ReadStreamL()
// -----------------------------------------------------------------------------
//
MBSElement* CBSBrandHandler::ReadStreamL( const TDesC8& aId, RFileReadStream& aStream,
										  TBool aAllowEmptyId /* = EFalse */ )
	{
	TRACE( T_LIT( "CBSBrandHandler::ReadStreamL BEGIN"));
	TBSElementType type = (TBSElementType)aStream.ReadInt16L();
	MBSElement* returnValue = NULL;
	
	TInt idSize = aStream.ReadInt16L();
	
	HBufC8* elementId = HBufC8::NewLC( idSize );
	TPtr8 elementIdPtr = elementId->Des();

	if( idSize == 0 && aAllowEmptyId )
		{
		// we don't read empty ID
		}
	else
		{
		aStream.ReadL( elementIdPtr, idSize );
        elementIdPtr.SetLength( idSize );// Set length
		}
	

	TBool match = EFalse;
	if( aAllowEmptyId || ( 0 == elementIdPtr.Compare( aId ) ) )
		{
		match = ETrue;
		}
		
    TPtrC8 idPtrC( *elementId );// idPtrC creation moved here so it will be updated correctly.
	if( elementId->Length() == 0 )
		{
		CleanupStack::PopAndDestroy( elementId );
		elementId = NULL;
		idPtrC.Set( KNullDesC8 );
		}

	switch( type )
		{
		case EBSInt:
			{
			TInt intData = aStream.ReadInt16L();
			TRACE( T_LIT( "CBSBrandHandler::ReadStreamL type INT"));
			if( match )
				{
                // Codescanner warning: neglected to put variable on cleanup stack (id:35)
                // This method cannot leave after this line
				returnValue = BSElementFactory::CreateBSElementL( idPtrC, // CSI: 35 # See above
																  EBSInt,
																  intData ); 
				}
			break;
			}		
		case EBSText:
		case EBSFile: // flow through
			{
			TInt textSize = aStream.ReadInt16L();
			HBufC* textData = HBufC::NewLC( textSize );

			TPtr textPtr = textData->Des();
			aStream.ReadL( textPtr, textSize );

			TRACE( T_LIT( "CBSBrandHandler::ReadStreamL type TEXT/ FILE"));
			if( match )
				{
                // Codescanner warning: neglected to put variable on cleanup stack (id:35)
                // This method cannot leave after this line
				returnValue = BSElementFactory::CreateBSElementL( idPtrC, // CSI: 35 # See above
																  type,
																  *textData ); 
				}

			CleanupStack::PopAndDestroy( textData );
			break;
			}
		case EBSList:
			{
			RBSObjOwningPtrArray<MBSElement> listData;
			CleanupClosePushL( listData );
			TInt count = aStream.ReadInt16L();
			
			for( TInt i = 0; i < count; i++ )
				{
				MBSElement* subElement = ReadStreamL( KNullDesC8, aStream, ETrue );
				CleanupDeletePushL( subElement );
				listData.AppendL( subElement );
				CleanupStack::Pop(); // subElement
				}
				
			if( match )
				{
                // Codescanner warning: neglected to put variable on cleanup stack (id:35)
                // This method cannot leave after this line
				returnValue = BSElementFactory::CreateBSElementL( idPtrC, // CSI: 35 # See above
																  EBSList,
																  listData ); 
				}
			CleanupStack::Pop(); // listData
			break;
			}
		case EBSBuffer:
			{
			TInt bufferSize = aStream.ReadInt16L();
			HBufC8* buffeData = HBufC8::NewLC( bufferSize );

			TPtr8 bufferPtr = buffeData->Des();
			aStream.ReadL( bufferPtr, bufferSize );

			if( match )
				{
                // Codescanner warning: neglected to put variable on cleanup stack (id:35)
                // This method cannot leave after this line				
				returnValue = BSElementFactory::CreateBSElementL( idPtrC, // CSI: 35 # See above
																  EBSBuffer,
																  *buffeData ); 
				}

			CleanupStack::PopAndDestroy( buffeData );
			break;
			}
		case EBSBitmap:
			{
			TInt length = aStream.ReadInt16L();
			HBufC8* fileId = HBufC8::NewLC( length );
			
			TPtr8 fileIdPtr = fileId->Des();
			aStream.ReadL( fileIdPtr, length );
			
			TInt bitmapId = aStream.ReadInt16L();
			TInt maskId = aStream.ReadInt16L();
			TInt skinId = aStream.ReadInt16L();
			TInt skinMaskId = aStream.ReadInt16L();

			TRACE( T_LIT( "CBSBrandHandler::ReadStreamL type BITMAP .. bitmap ID is [%d]"), bitmapId);
			if( match )
				{
				CBSBitmap* bitmap = CBSBitmap::NewLC( bitmapId,
													  maskId,
													  skinId,
													  skinMaskId,
													  fileIdPtr );

                // Codescanner warning: neglected to put variable on cleanup stack (id:35)
                // This method cannot leave after this line
				returnValue = BSElementFactory::CreateBSElementL( idPtrC, // CSI: 35 # See above
																  EBSBitmap,
																  bitmap ); 
				CleanupStack::Pop( bitmap ); 
				}
		    CleanupStack::PopAndDestroy( fileId ); 

			break;
			}
		default:
			{
			TRACE( T_LIT( "CBSBrandHandler::ReadStreamL type DEFAULT : corrupt"));
			User::Leave( KErrCorrupt );
			break;
			}
		}

	if( elementId )
		{
		CleanupStack::PopAndDestroy( elementId );
		}

	TRACE( T_LIT( "CBSBrandHandler::ReadStreamL END"));
	return returnValue;
	}
Ejemplo n.º 3
0
/**
 * Write the file to the hard drive.
 * 
 * @param aFileName 
 * @param aBodyPartArray
 */ 
void CMultipartTestContainer::WriteFileL( const TDesC& aFileName,
                                           RPointerArray<CBodyPart>& aBodyPartArray )
    {
    RFs fs;
    fs.Connect();
    CleanupClosePushL(fs);
    RFile output;
    TInt err = output.Open(fs, aFileName, EFileWrite);
    if (err == KErrNotFound)
    	{
			User::LeaveIfError(output.Create(fs, aFileName, EFileWrite));
			}		
    
    // output file
    TInt size = aBodyPartArray.Count();
    TInt i;
		_LIT8(KEol, "\r\n");
    for (i = 0; i < size; i++)
        {

        CBodyPart* bodyPart = aBodyPartArray[i];

        if( bodyPart->Url().Ptr() )
            {
            output.Write(_L8("***************Ur"));
            output.Write(KEol);
			RBuf8 narrow;
			err = narrow.Create(bodyPart->Url().Length()*2);
			if (err != KErrNone)
				{
				INFO_PRINTF1(_L("Error printing Url to output file; continueing..."));
				}						
			narrow.Copy(bodyPart->Url());
            output.Write(narrow.Left(narrow.Length()));
            output.Write(KEol);
            }
        if( bodyPart->ContentID().Ptr() )
            {
            output.Write(_L8("***************ContentID"));
            output.Write(KEol);
            output.Write(bodyPart->ContentID() );
            output.Write(KEol);
            }
        if( bodyPart->Charset().Ptr() )
            {
            output.Write(_L8("***************Charset"));
            output.Write(KEol);
            output.Write( bodyPart->Charset() );
            output.Write(KEol);
            }
        if( bodyPart->ContentType().Ptr() )
            {
            output.Write(_L8("***************ContentType"));
            output.Write(KEol);
            output.Write( bodyPart->ContentType() );
            output.Write(KEol);
            }
        if( bodyPart->Headers().Ptr() )
            {
            output.Write(_L8("***************Headers"));
            output.Write(KEol);
            output.Write(bodyPart->Headers() );
            output.Write(KEol);
            }
        if( bodyPart->Body().Ptr() )
            {
            output.Write(_L8("***************Body"));
            output.Write(KEol);
            output.Write(bodyPart->Body() );
            output.Write(KEol);
            }
        output.Write(_L8("=========================================part ends"));
        output.Write(KEol);

        } // end of loop
    
    output.Close();
    CleanupStack::PopAndDestroy(1, &fs);
    fs.Close();
		}
Ejemplo n.º 4
0
enum TVerdict CTestStepLoopback::doTestStepL()
	{
	SetTestStepResult(EFail);
	
//	const TUid KPktTxKey = {0x104045dd};
//	const TUid KPktRxKey = {0x104045de};
//	const TUid KMeUid = {0x101F529F};
//	TSecurityPolicy readPolicy(ECapability_None);
//	TSecurityPolicy writePolicy(ECapability_None);
//	TInt result = RProperty::Define(KMeUid, KPktTxKey .iUid, RProperty::EInt, readPolicy, writePolicy);
//	result = RProperty::Define(KMeUid, KPktRxKey .iUid, RProperty::EInt, readPolicy, writePolicy);
	
	
	RSocketServ ss;
	CleanupClosePushL(ss);
	Logger().WriteFormat(_L("Start: creating + starting connection"));
	User::LeaveIfError(ss.Connect());
	RConnection conn;
	CleanupClosePushL(conn);
	User::LeaveIfError(conn.Open(ss));
	User::LeaveIfError(conn.Start());

	TInt srvPort;
	if(!GetIntFromConfig(_L("TcpLoop"), _L("Port"), srvPort))
		{
		srvPort = 5002;
		}
	Logger().WriteFormat(_L("Start: creating server socket listening on %d"), srvPort);
	RSocket srv;
	CleanupClosePushL(srv);
	User::LeaveIfError(srv.Open(ss, KAfInet, KSockStream, KProtocolInetTcp, conn));
	TInetAddr srvAddr(KAfInet);
	srvAddr.SetPort(srvPort);
	User::LeaveIfError(srv.Bind(srvAddr));
	User::LeaveIfError(srv.Listen(5));
	RSocket acc;
	CleanupClosePushL(acc);
	User::LeaveIfError(acc.Open(ss));
	TRequestStatus accStat;
	srv.Accept(acc, accStat);
	
	Logger().WriteFormat(_L("Start: connecting client socket"));
	RSocket cli;
	CleanupClosePushL(cli);
	User::LeaveIfError(cli.Open(ss, KAfInet, KSockStream, KProtocolInetTcp, conn));
	srvAddr.SetAddress(0xC0A80707);
	TRequestStatus cliStat;
	cli.Connect(srvAddr, cliStat);
	User::WaitForRequest(cliStat, accStat);
	User::WaitForRequest(cliStat, accStat);
	User::LeaveIfError(cliStat.Int());
	User::LeaveIfError(accStat.Int());

	//_LIT8(KTest, "jackdaws love my big sphinx of quartz");
	
	TInt xferSize = 0;
	if(!GetIntFromConfig(_L("TcpLoop"), _L("xferSize"), xferSize))
		{
		xferSize = 1 * 1000 * 1000;
		}
	TInt fc = User::FastCounter();
	TInt txSize = 0;
	TInt txCnt = 0;
	TRequestStatus txStat(KErrNone);
	TBuf8<4096> txBuf;
	txBuf.SetMax();
	TInt rxSize = 0;
	TInt rxCnt = -1;
	TRequestStatus rxStat(KErrNone);
	TBuf8<4096> rxBuf;
	
	Logger().WriteFormat(_L("Transferring %d bytes"), xferSize);
	while(rxSize < xferSize)
		{
		fc = User::FastCounter();
		if(txStat.Int() != KRequestPending)
			{
			RDebug::Printf("tx status:%d, ", txStat.Int());
			cli.Send(txBuf, 0, txStat);
			++txCnt;
			txSize += txBuf.Length();
			RDebug::Printf("tx #%d, %d, +%d\n", txCnt, fc, txBuf.Length());
			}
		if(rxStat.Int() != KRequestPending)
			{
			RDebug::Printf("rx status:%d, ", rxStat.Int());
			++rxCnt;
			rxSize += rxBuf.Length();
			RDebug::Printf("rx #%d, %d, +%d\n", rxCnt, fc, rxBuf.Length());
			TSockXfrLength dummy;
			acc.RecvOneOrMore(rxBuf, 0, rxStat, dummy);
			}
		User::WaitForRequest(rxStat, txStat);
		}
	
	Logger().WriteFormat(_L("Transferred; %d writes, %d reads"), txCnt, rxCnt);
	
//	RProperty::Get(KUidSystemCategory, KPktTxKey .iUid, txCnt);
//	RProperty::Define(KUidSystemCategory, KPktRxKey .iUid, rxCnt);
//	Logger().WriteFormat(_L("Packet counts; %d sends, %d processes"), txCnt, rxCnt);
	
	
	CleanupStack::PopAndDestroy(5, &ss);
	
	SetTestStepResult(EPass);
	return TestStepResult();
	};
Ejemplo n.º 5
0
// ---------------------------------------------------------------------------
// CCmFmUpnpMngr::BrowseResponseL
// ---------------------------------------------------------------------------
//
void CCmFmUpnpMngr::BrowseResponseL( TInt aStatus,
                                     TInt /*aTotalCount*/,
                                     const TDesC8& aResultArray )
{
    LOG(_L("[FILL MNGR]\t CCmFmUpnpMngr::BrowseResponseL()"));

    RPointerArray<CUpnpObject> tempArray;
    CleanupClosePushL( tempArray );
    TInt err( aStatus );
    TRACE(Print(_L("[FILL MNGR]\t BrowseResponse err = %d"), err ));
    if( !err )
    {
        TRAP( err, iParser->ParseResultDataL(
                  tempArray, aResultArray ) );
    }

    /** Browse finished */
    iBrowseFinished.HomeTime();
    TTimeIntervalMicroSeconds usecsFrom =
        iBrowseFinished.MicroSecondsFrom( iBrowseStarted );
    TRACE(Print(_L("[FILL MNGR]\t Browse took = %ld microseconds"),
                usecsFrom.Int64() ));

    if( !err )
    {
        if ( tempArray.Count() )
        {
            if( iItem )
            {
                delete iItem;
                iItem = NULL;
            }
            iItem = CUpnpItem::NewL();
            // first object is an item, safe to downcast
            CUpnpItem* item = static_cast<CUpnpItem*>( tempArray[0] );
            iItem->CopyL( *tempArray[0] );

            const CUpnpElement& res = UPnPItemUtility::ResourceFromItemL( *item );
            if( iSelectOptimalImageSize )
            {
                RUPnPElementsArray array;
                UPnPItemUtility::GetResElements( *tempArray[0], array );
                const CUpnpElement& res = ParseImageResolutions( array );
            }

            if(iURI)
            {
                delete iURI;
                iURI = NULL;
            }
            iURI = res.Value().AllocL();
            iObserver->URICheckResult( EUriChecked, item, &res );
        }
        else
        {
            LOG(_L("[FILL MNGR]\t tempArray.Count() = 0"));
            iObserver->URICheckResult( ENoUriAvailable );
        }
    }
    else
    {
        LOG(_L("[FILL MNGR]\t err != 0"));
        iObserver->URICheckResult( ENoUriAvailable );
    }

    tempArray.ResetAndDestroy();
    CleanupStack::PopAndDestroy( &tempArray );
}
enum TVerdict TE_RConnectionTest501::doTestStepL(void)
{
    SetTestStepResult(EFail);
    TInt err;

    RSocketServ socketServer;
    RConnection startConn;
    RConnection monitorConn;

    err = OpenSocketServer(socketServer);
    TESTEL(KErrNone == err, err);
    CleanupClosePushL(socketServer);

    err = OpenConnection(startConn, socketServer);
    TESTEL(KErrNone == err, err);
    CleanupClosePushL(startConn);

    err = OpenConnection(monitorConn, socketServer);
    TESTEL(KErrNone == err, err);
    CleanupClosePushL(monitorConn);

    // start up connection (destined to fail startup)
    TRequestStatus startStatus;
    StartConnectionAsynchronous(startConn, startStatus);

    // wait for completion of selection, after which we can attach to the connection
    TNifProgressBuf progressBuf;
    TRequestStatus progressStatus;
    ProgressNotification(startConn, progressStatus, progressBuf, KFinishedSelection);
    User::WaitForRequest(progressStatus);

    // Attach to the connection from another RConnection
    //
    // It can take a finite time from KFinishedSelection progress to the point where the
    // connection actually appears in the enumeration list, so take this into account by looping
    // waiting for the connection to enumerate.  We are only interested in obtaining the connection
    // info so that we can attach to the starting connection - we are not testing connection
    // enumeration here.

    TInt i = 0;
    TUint count;
    do
    {
        err = EnumerateConnections(startConn, count);
        TESTEL(KErrNone == err, err);
        if (count == 0)
        {
            User::After(50000);
        }
    }
    while (count == 0 && ++i <= 5);
    TESTEL(1 == count, count);

    TPckgBuf<TConnectionInfo> info;
    err = GetConnectionInfo(startConn, 1, info);
    TESTEL(KErrNone == err, err);

    err = AttachMonitor(monitorConn, info);
    TESTEL(KErrNone == err, err);

    ProgressNotification(monitorConn, progressStatus, progressBuf, KLinkLayerClosed);

    // wait for the startup to fail
    User::WaitForRequest(startStatus);
    TESTEL(KErrIfAuthenticationFailure == startStatus.Int(), startStatus.Int());

    // Wait for KLinkLayerClosed or any progress which has an error associated.  Actually,
    // we are more interested in waiting for a progress with an error than KLinkLayerClosed.
    // Use a timer to prevent waiting forever and fail with an error if the progress never arrives.
    RTimer timer;
    err = timer.CreateLocal();
    TESTEL(KErrNone == err, err);
    CleanupClosePushL(timer);

    TRequestStatus timerStatus;
    const TUint KMaxProgressWait = 5;
    timer.After(timerStatus, KMaxProgressWait * 1000000);

    User::WaitForRequest(progressStatus, timerStatus);
    if (progressStatus.Int() == KRequestPending)
    {
        // failure - timer fired
        CancelProgressNotification(monitorConn);
        User::WaitForRequest(progressStatus);
    }

    if (timerStatus.Int() == KRequestPending)
    {
        // success - progress arrived
        timer.Cancel();
        User::WaitForRequest(timerStatus);
    }
    // check that we correctly received a progress with an associated error on the RConnection
    // that attached to the underlying connection.
    TESTEL(KErrNone == progressStatus.Int(), progressStatus.Int());
    TESTEL(KErrIfAuthenticationFailure == progressBuf().iError, progressBuf().iError);
    SetTestStepResult(EPass);

    // ************************************************************************************
    // NOTE:
    // The following pause is apparently necessary to prevent WinTunnel from intermittently
    // entering an endless cpu loop and hanging the emulator.  The cause needs to be
    // investigated and fixed and then this pause can be removed.
    // ************************************************************************************
    User::After(1000000);

    CleanupStack::PopAndDestroy(&timer);
    CloseConnection(monitorConn);
    CleanupStack::Pop(&monitorConn);
    CloseConnection(startConn);
    CleanupStack::Pop(&startConn);
    CloseSocketServer(socketServer);
    CleanupStack::Pop(&socketServer);	// just sanity check our pops

    return TestStepResult();
}
TVerdict CAppFwkStartSafeTestStepAppStartRvError::doTestStepL()
	{
	TInt threadHandles_Before;
	TInt processHandles_Before;
	TInt threadHandles_After;
	TInt processHandles_After;
		
	RThread().HandleCount(processHandles_Before, threadHandles_Before);
	
	CStartSafe *startSafe = CStartSafe::NewL();	
	CleanupStack::PushL( startSafe );
	
	CStartupProperties *prop = CStartupProperties::NewL();
	CleanupStack::PushL( prop );
	
	RProcess proc;
	CleanupClosePushL( proc );
	
	prop->SetFileParamsL( KTestAppRvError, KNullDesC );
	prop->SetStartupType( EStartApp );
	prop->SetStartMethod( EWaitForStart );
	prop->SetNoOfRetries( KStartSafeAppStartRvErrorRetries );
	prop->SetTimeout( KStartSafeAppStartErrorNominalTimeout ); 

	TInt tried = 0;
	
	INFO_PRINTF1( _L("Start the Test Application") );
	TRAPD( err, startSafe->StartL(*prop, proc, tried) );

	// Ensure that the process-name of the test-app is not extant.
	TPtrC procNamePtr = proc.FileName().Right( KTestAppRvError().Length() );
	TInt nameComparison = procNamePtr.Compare( KTestAppRvError() );
		
	if ( (0 == nameComparison) )
		{
		ERR_PRINTF2( _L("Application whose process-name is\"%S\" was found, but should not have been"), &procNamePtr );
		
		// Dispose of the erroneously extant test-app.
		proc.Kill( KErrNone );
		SetTestStepResult( EFail );
		
		ERR_PRINTF1( _L("Test failed") );
		}
	else if( (KStartSafeAppStartRvErrorRetries +1) != tried )
		{
		ERR_PRINTF1( _L("Process-name (correctly) not found, but...") );
		ERR_PRINTF3( _L("Total tries = %d  should have been %d"), tried, (KStartSafeAppStartRvErrorRetries +1) );	
		
		SetTestStepResult( EFail );
		}
	else
		{
		INFO_PRINTF1( _L("Process was (correctly) not found") );
		INFO_PRINTF2( _L("Error code %d"), err );
		
		// The 'erroneous' rendezvous code
		TESTE( KErrGeneral, err );		
		}	


	CleanupStack::PopAndDestroy( 3, startSafe ); 
	
	RThread().HandleCount(processHandles_After, threadHandles_After);
	TEST(processHandles_After == processHandles_Before);
	TEST(threadHandles_After == threadHandles_Before);
	
	return TestStepResult();	
	}
Ejemplo n.º 8
0
/**
   Create a UDP socket. Perform a zero-length SendTo, then attempt to receive the zero-length datagram.

   @return EPass on success, EFail on failure
*/
TVerdict CEsockTest9_6::easyTestStepL()
	{
	Logger().WriteFormat(_L("TE_ESock: test 9.6"));
	
	TInt cleanupCount = 0;		// Number of items we've put on Cleanup Stack - remember to increment this after every Push operation.
	
	RSocket sendSocket;

	CleanupClosePushL( sendSocket );
	++cleanupCount;

	TSockAddr sendSocketAddress;
	Logger().WriteFormat(_L("Creating Send Socket"));
	if( !CreateUdpSocket( sendSocket, sendSocketAddress ) )
		{
		CleanupStack::PopAndDestroy( cleanupCount );
		return EFail;
		}


	RSocket recvSocket;

	CleanupClosePushL( recvSocket );
	++cleanupCount;

	TSockAddr recvSocketAddress;
	Logger().WriteFormat(_L("Creating Receive Socket"));
	if( !CreateUdpSocket( recvSocket, recvSocketAddress ) )
		{
		CleanupStack::PopAndDestroy( cleanupCount );
		return EFail;
		}



	HBufC8 *udpWriteBuffer = HBufC8::NewLC( 0 ); // Empty buffer for zero-length write
	++cleanupCount;

	HBufC8 *udpReadBuffer  = HBufC8::NewMaxLC( 32 ); // Non-Empty buffer for reads - 32 is an unimportant magic number
	++cleanupCount;

	TPtrC8  ptrWritebuf( udpWriteBuffer->Des() );
	TPtr8   ptrReadbuf( udpReadBuffer->Des() );
	TSockAddr toAddress( recvSocketAddress );

	TBool isOk = PerformSend( sendSocket, ptrWritebuf, toAddress );
	if( isOk )
		{
		TSockAddr fromAddress;
		isOk = PerformRecv( recvSocket, ptrReadbuf, fromAddress );
		if( isOk )
			{
			Logger().WriteFormat(_L("Receieved %d bytes"), udpReadBuffer->Length());
			if( udpReadBuffer->Length() != 0 )
				{
				isOk = EFalse;
				}
			}
		}
	
	CleanupStack::PopAndDestroy( cleanupCount );

	return isOk ? EPass : EFail;
	}
void CAccPolAudioUnitBase::CopyL ( const CAccPolAudioUnitBase& aAudioUnitBaseObject )
    {
    API_TRACE_( "[AccFW: ACCPOLAUDIODEVICETOPOLOGY] CAccPolAudioUnitBase::operator() - Enter" );
    // Copy base	
    CAccPolObjectBase::operator=( ( CAccPolObjectBase& )aAudioUnitBaseObject );

    //Copy Unit id
    iUnitId = aAudioUnitBaseObject.UnitId();
    RArray<TInt> sourceIds;
    CleanupClosePushL( sourceIds );
    
    //Copy source Ids
    aAudioUnitBaseObject.GetSourceIds( sourceIds );

    for( TInt i = 0; i < sourceIds.Count(); i++ )
        {
        iSourceId.AppendL( sourceIds.operator[]( i ) );
        }

    //Copy previous unit id
    iPreUnitId = aAudioUnitBaseObject.PreviousUnitId();

    //Copy audio controls.
    RPointerArray<CAccPolAudioControlBase> audioControls;
    CleanupClosePushL( audioControls );
    
    aAudioUnitBaseObject.GetAudioControlsL( audioControls );
    
    for( TInt j = 0; j < audioControls.Count(); j++ )
        {
        TUint8 objectType;
        objectType = audioControls.operator[]( j )->ObjectType();

        switch( objectType )
            {
            case EAccPolAudioVolumeControlObject:
                {
                CAccPolVolumeControl *volumeControl =
                    CAccPolVolumeControl::NewL();
                CleanupStack::PushL( volumeControl );
                *volumeControl
                    = *( CAccPolVolumeControl* )audioControls.operator[]( j );
                iAudioControls.AppendL( volumeControl );
                CleanupStack::Pop();
                }
                break;

            case EAccPolAudioMuteControlObject:
                {
                CAccPolMuteControl *muteControl = CAccPolMuteControl::NewL();
                CleanupStack::PushL( muteControl );
                *muteControl
                    = *( CAccPolMuteControl* )audioControls.operator[]( j );
                iAudioControls.AppendL( muteControl );
                CleanupStack::Pop();
                }
                break;

            case EAccPolAudioInputControlObject:
                {
                CAccPolInputControl *inputControl = CAccPolInputControl::NewL();
                CleanupStack::PushL( inputControl );
                *inputControl
                    = *( CAccPolInputControl* )audioControls.operator[]( j );
                iAudioControls.AppendL( inputControl );
                CleanupStack::Pop();
                }
                break;

            default:
                {
                User::Leave( KErrNotSupported );
                }
                break;
            }
        }

    CleanupStack::PopAndDestroy (); //audioControls...dont use ResetAndDestroy on this!
    CleanupStack::PopAndDestroy (); //sourceIds
        
    
    API_TRACE_( "[AccFW: ACCPOLAUDIODEVICETOPOLOGY] CAccPolAudioUnitBase::operator() - Return" );
    }
Ejemplo n.º 10
0
// -----------------------------------------------------------------------------
// CheckFileL()
// check if it is target file
// -----------------------------------------------------------------------------
//
void CDcfRepSrv::CheckFileL(const TDesC& aFile , TInt& aType)
{
#ifdef _DRM_TESTING
    WriteL(_L8("CheckFileL"));
#endif

    RFile f;
    TInt pos = 0;
    TBuf8<256> buf;

    switch(iState)
    {
    case EStateFullScan:
    case EStateScan:
    {
        User::LeaveIfError(f.Open(iFs,aFile,EFileRead|EFileShareReadersOrWriters));
        CleanupClosePushL(f);
        User::LeaveIfError(f.Seek(ESeekStart,pos));
        User::LeaveIfError(f.Read(0,buf));
        CleanupStack::PopAndDestroy(&f);
        if (COma1Dcf::IsValidDcf(buf))
        {
            aType = EOma1Dcf;
        }
#ifdef __DRM_OMA2
        else if (COma2Dcf::IsValidDcf(buf))
        {
            aType = EOma2Dcf;
        }
#endif
        else
        {
            aType = ENoDcf;
        }

    }
    break;
    case EStateSetTtid:
    {
        TParse p;
        User::LeaveIfError(p.Set(aFile,NULL,NULL));
        if ( !p.Ext().Compare( KOma2DcfExtension ) ||
                !p.Ext().Compare( KOma2DcfExtensionAudio ) ||
                !p.Ext().Compare( KOma2DcfExtensionVideo ) )
        {
            User::LeaveIfError(f.Open(iFs,aFile,EFileRead|EFileShareReadersOrWriters));
            CleanupClosePushL(f);
            User::LeaveIfError(f.Seek(ESeekStart,pos));
            User::LeaveIfError(f.Read(0,buf));
            CleanupStack::PopAndDestroy(&f);
            if (COma1Dcf::IsValidDcf(buf))
            {
                aType = EOma1Dcf;
            }
#ifdef __DRM_OMA2
            else if (COma2Dcf::IsValidDcf(buf))
            {
                aType = EOma2Dcf;
            }
#endif
            else
            {
                aType = ENoDcf;
            }
        }
    }
    break;
    default:
        ;
    }
}
Ejemplo n.º 11
0
// -----------------------------------------------------------------------------
// StoreFile()
// save file info into database
// -----------------------------------------------------------------------------
//
void CDcfRepSrv::StoreFileL(const TDesC& aFile , TInt aType)
{
#ifdef _DRM_TESTING
    WriteL(_L8("StoreFileL"));
#endif

    RFile f;
    User::LeaveIfError(f.Open(iFs,aFile,EFileRead|EFileShareReadersOrWriters));
    CleanupClosePushL(f);
    TInt i = 0;
    TInt setTtid = -1;
    HBufC16* cid = NULL;
    HBufC16* ttid = NULL;
    HBufC16* group = NULL;

    if (aType == EOma1Dcf)
    {
        COma1Dcf* d = COma1Dcf::NewL(f);
        CleanupStack::PushL(d);
        User::LeaveIfError( From8To16( *(d->iContentID) , cid ) );
        CleanupStack::PopAndDestroy(d);
        CleanupStack::PushL(cid);
        ttid = HBufC::NewMaxLC(16);
        *ttid = KNullDesC16;
        UpdateDatabaseL(aFile , KStartPosition , *cid , KNullDesC() , *ttid);
        if (iCidList)
        {
            for (i = 0; i<iCidList->Count(); i++)
            {
                HBufC* temp = NULL;
                User::LeaveIfError( From8To16(*((*iCidList)[i]) , temp ) );
                CleanupStack::PushL(temp);
                if (!temp->Compare(*cid))
                {
                    delete (*iCidList)[i];
                    iCidList->Remove(i);
                    CleanupStack::PopAndDestroy(temp);
                    break;
                }
                CleanupStack::PopAndDestroy(temp); //temp
            }
            if (iCidList->Count()<=0)
            {
                CompleteScanning(KErrNone);
            }
        }
        CleanupStack::PopAndDestroy(2); //cid,ttid
    }
    else if (aType == EOma2Dcf)
    {
        COma2Dcf* d = COma2Dcf::NewL(f);
        CleanupStack::PushL(d);

        // Set group ID and content ID for this entry
        if (d->iGroupId)
        {
            User::LeaveIfError( From8To16( *(d->iGroupId) , group ) );

            // replace the content ID for this entry with a placeholder to prevent
            // that the file is listed wrongly under the group ID
            cid = KGroupIdReplacement().AllocL();
        }
        else
        {
            User::LeaveIfError( From8To16( *(d->iContentID) , cid ) );
            group = HBufC::NewMaxL(16);
            *group = KNullDesC16;
        }
        CleanupStack::PushL(cid);
        CleanupStack::PushL(group);

        if (iState == EStateSetTtid)
        {
            for (i = 0; iPairList && i<iPairList->Count() && !ttid; i++)
            {
                HBufC* temp = NULL;
                User::LeaveIfError( From8To16(*((*iPairList)[i]->iCid) , temp ) );
                CleanupStack::PushL(temp);
                if (!temp->Compare(*cid))
                {
                    User::LeaveIfError( From8To16(*((*iPairList)[i]->iTtid) , ttid ) );

                    // EFileWrite is needed for this case
                    // So we cannot do it here. we must close the file
                    setTtid = i;
                }
                CleanupStack::PopAndDestroy(temp); //temp
            }
        }
        if (!ttid)
        {
            if (d->iTransactionTracking)
            {
                User::LeaveIfError( From8To16( *(d->iTransactionTracking) , ttid ) );
            }
            else
            {
                ttid = HBufC::NewMaxL(16);
                *ttid = KNullDesC16;
            }
        }
        CleanupStack::PushL(ttid);

        UpdateDatabaseL(aFile , KStartPosition , *cid , *group , *ttid);
        if (iCidList)
        {
            for (i = 0; i<iCidList->Count(); i++)
            {
                HBufC* temp = NULL;
                User::LeaveIfError( From8To16(*((*iCidList)[i]) , temp ) );
                CleanupStack::PushL(temp);
                if (!temp->Compare(*cid))
                {
                    delete (*iCidList)[i];
                    iCidList->Remove(i);
                    CleanupStack::PopAndDestroy(temp);
                    break;
                }
                CleanupStack::PopAndDestroy(temp); //temp
            }
            if (iCidList->Count()<=0)
            {
                CompleteScanning(KErrNone);
            }
        }
        CleanupStack::PopAndDestroy(4); // group,ttid,cid,d
    }

    CleanupStack::PopAndDestroy(&f); // f

    if (setTtid>=0)
    {
        ResetTtidL( aFile , *((*iPairList)[setTtid]->iTtid));
    }
}
Ejemplo n.º 12
0
/** Perform CX3pStep3 test step.
This test verifies that the Test Protocol Module correctly handles 
X3P cancellation.
Cancellation occurs after gateway receives location request.

@return TVerdict test result code
*/
TVerdict CX3pStep3::doTestStepL()
	{
	INFO_PRINTF1(_L("\t********************************************************************"));
	INFO_PRINTF1(_L("\tX3P with cancel sent after loc request received"));
	INFO_PRINTF1(_L("\t********************************************************************"));
	INFO_PRINTF1(_L("- START -"));

	// Initiate X3P
	INFO_PRINTF1(_L("\tLBS -> TransmitLocation"));
	TLbsAsistanceDataGroup dataRequestMask = (TUint) EAssistanceDataReferenceTime;
	TLbsNetSessionId sessionId(TUid::Uid(KDummyUid), KX3pSessionId);
	iModule->RequestTransmitLocation(sessionId, KX3pDestination(), KX3pPriority);

	// Check network receives X3P request
	if (EFail == CheckNetworkCallbackL(
				CNetworkObserver::ERegisterLcsMoLr) ||
		KX3pDestination() != iNetworkObserver->X3pDestination())
		{
		SetTestStepResult(EFail);
		return TestStepResult();
		}
	INFO_PRINTF1(_L("\t                                            RegisterLcsMoLr -> NET"));
	
	// Generate network Measurement Control
	INFO_PRINTF1(_L("\t                          ProcessMeasurementControlLocation <- NET"));
	TPositionInfo refLoc;
	RLbsAssistanceDataBuilderSet assistData;
	CleanupClosePushL(assistData);
	assistData.OpenL();
	SetDummyAssistanceData(assistData, dataRequestMask);
	TLbsNetPosRequestQuality quality;
	iNetworkObserver->ProcessMeasurementControlLocationL(refLoc, assistData, quality);
	CleanupStack::PopAndDestroy(&assistData);

	// Check gateway receives Assistance data
	if (EFail == CheckGatewayCallbackL(
				CGatewayObserver::EProcessAssistanceData))
		{
		SetTestStepResult(EFail);
		return TestStepResult();
		}
	INFO_PRINTF1(_L("\tLBS <- ProcessAssistanceData"));

	// Check gateway receives Network Based location
	if (EFail == CheckGatewayCallbackL(
				CGatewayObserver::EProcessLocationUpdate))
		{
		SetTestStepResult(EFail);
		return TestStepResult();
		}
	INFO_PRINTF1(_L("\tLBS <- ProcessLocationUpdate"));

	// Check gateway receives Location Request
	if (EFail == CheckGatewayCallbackL(
				CGatewayObserver::EProcessLocationRequest))
		{
		SetTestStepResult(EFail);
		return TestStepResult();
		}
	INFO_PRINTF1(_L("\tLBS <- ProcessLocationRequest"));

	// Cancel X3P
	INFO_PRINTF1(_L("\tLBS -> CancelTransmitLocation (REASON)"));	
	iModule->CancelTransmitLocation(iGatewayObserver->SessionIdValue(), KErrGeneral);

	// Check network receives cancel response
	if (EFail == CheckNetworkCallbackL(CNetworkObserver::EMeasurementControlFailure) ||
		KErrCancel != iNetworkObserver->MeasurementFailure())
		{
		SetTestStepResult(EFail);
		return TestStepResult();
		}
	INFO_PRINTF1(_L("\t                         MeasurementControlFailure (CANCEL) -> NET"));
	
	// Check network session completed
	if (EFail == CheckNetworkCallbackL(
				CNetworkObserver::EReleaseLcsMoLr) ||
		KErrGeneral != iNetworkObserver->SessionCloseReason())
		{
		SetTestStepResult(EFail);
		return TestStepResult();
		}
	INFO_PRINTF1(_L("\t                                    ReleaseLcsMoLr (REASON) -> NET"));
	
	// Check gateway session completed
	if (EFail == CheckGatewayCallbackL(CGatewayObserver::EProcessSessionComplete) ||
		sessionId != iGatewayObserver->SessionIdValue() ||
		KErrGeneral != iGatewayObserver->SessionCloseReason())
		{
		SetTestStepResult(EFail);
		return TestStepResult();
		}
	INFO_PRINTF1(_L("\tLBS <- ProcessSessionComplete"));

	// Check if more observer activity takes place
	if (iGatewayObserver->IsMoreObserverActivity() ||
		iNetworkObserver->IsMoreObserverActivity())
		{
		SetTestStepResult(EFail);
		return TestStepResult();
		}
								
	INFO_PRINTF1(_L("- END -"));
	SetTestStepResult(EPass);
	return TestStepResult();
	}
Ejemplo n.º 13
0
LOCAL_D void GeneralTestsL()
	{
	CBookmarkDb* db = CBookmarkDb::NewL(Bookmark::EVisibilityManager, NULL);
	CleanupStack::PushL(db);
	CBookmark& bookmark = db->CreateBookmarkL(db->RootL());

	gTestWrapper->Next(_L("[CBookmarkBase tests] id"));
	gTestWrapper->TEST(bookmark.Id() != KItemId);
	bookmark.SetId(KItemId);
	gTestWrapper->TEST(bookmark.Id() == KItemId);

	gTestWrapper->Next(_L("[CBookmarkBase tests] reference counting"));
	gTestWrapper->TEST(bookmark.RefCount() == 0);
	bookmark.IncRefCount();
	gTestWrapper->TEST(bookmark.RefCount() == 1);
	bookmark.DecRefCount();
	gTestWrapper->TEST(bookmark.RefCount() == 0);
	bookmark.IncRefCount();
	bookmark.IncRefCount();
	bookmark.IncRefCount();
	gTestWrapper->TEST(bookmark.RefCount() == 3);
	bookmark.DecRefCount();
	bookmark.DecRefCount();
	bookmark.DecRefCount();
	gTestWrapper->TEST(bookmark.RefCount() == 0);
	
	gTestWrapper->Next(_L("[CBookmarkBase tests] parent"));
	CBookmarkFolder& folder = db->CreateFolderL(KTxtNewFolder, db->RootL());
	gTestWrapper->TEST(bookmark.Parent()->Id() == db->RootL().Id());
	bookmark.SetParentL(folder);
	gTestWrapper->TEST(bookmark.Parent()->Id() == folder.Id());
	bookmark.SetParentL(db->RootL());
	gTestWrapper->TEST(bookmark.Parent()->Id() == db->RootL().Id());

	gTestWrapper->Next(_L("[CBookmarkBase tests] title"));
	bookmark.SetTitleL(KTxtItem1);
	gTestWrapper->TEST(bookmark.Title().Compare(KTxtItem1) == 0);

	gTestWrapper->Next(_L("[CBookmarkBase tests] public and writable"));
	gTestWrapper->TEST(bookmark.IsPublic());
	
	TInt err = KErrNone;
	gTestWrapper->TEST(bookmark.IsPublic());
	
	gTestWrapper->TEST(bookmark.IsWritable());
	bookmark.SetWritableL(EFalse);
	gTestWrapper->TEST(!bookmark.IsWritable());
	// test that write operations work as application is WriteDeviceData
	TRAP(err, bookmark.SetTitleL(KTxtItem1));
	gTestWrapper->TEST(err == KErrNone);
	TRAP(err, bookmark.SetPublicL(ETrue));
	gTestWrapper->TEST(err == KErrNone);
	bookmark.SetWritableL(ETrue);
	
	gTestWrapper->Next(_L("[CBookmarkBase tests] handle"));
	gTestWrapper->TEST(bookmark.RefCount() == 0);
	RBkFolder root = db->RootL().OpenFolder();
	CleanupClosePushL(root);
	RBkNode handle = root.OpenItemL(0);
	CleanupClosePushL(handle);
	
	gTestWrapper->TEST(bookmark.RefCount() == 1);
	gTestWrapper->TEST(handle.Type() == bookmark.Type());
	gTestWrapper->TEST(handle.Title() == bookmark.Title());
	
	CleanupStack::PopAndDestroy(&handle);
	CleanupStack::PopAndDestroy(&root);

	CleanupStack::PopAndDestroy(db);
	}
Ejemplo n.º 14
0
LOCAL_C void CreateManyFoldersL()
	{
	gTestWrapper->Next(_L("[Folders tests] creating levels of folders"));
	// Create a sub-root folder
	RBkFolder subroot;
	subroot = gDatabase.CreateFolderL(KTxtSubRootName);
	CleanupClosePushL(subroot);

	// Create three folders in the sub-root
	RBkFolder folderL2;
	folderL2 = gDatabase.CreateFolderL(KTxtFolder2_1, &subroot);
	folderL2.Close();

	folderL2 = gDatabase.CreateFolderL(KTxtFolder2_2, &subroot);
	CleanupClosePushL(folderL2);
	// Create a folder in folder 2.2
	RBkFolder folderL3;
	folderL3 = gDatabase.CreateFolderL(KTxtFolder2_2_1, &folderL2);
	folderL3.Close();
	CleanupStack::PopAndDestroy(&folderL2);

	folderL2 = gDatabase.CreateFolderL(KTxtFolder2_3, &subroot);
	folderL2.Close();

	CleanupStack::PopAndDestroy(&subroot);

	// Check that there are three folders in the sub-root
	RBkFolder folder = gDatabase.OpenFolderL(KTxtSubRootName);
	gTestWrapper->TEST(folder.Count() == 3);
	folder.Close();

	// Check that there is a folder in the folder 2.2
	folder = gDatabase.OpenFolderL(KTxtFolder2_2);
	gTestWrapper->TEST(folder.Count() == 1);
	Bookmark::TItemId id = folder.Id();
	folder.Close();

	// Delete folder 2.2. The default action is dump any children to the root folder
	gDatabase.DeleteItemL(id);

	// Check that folder 2.2 can not be found
	TRAPD(error, folder = gDatabase.OpenFolderL(KTxtFolder2_2));
	gTestWrapper->TEST(error == KErrNotFound);

	// There should now be 2 folders in the sub-root
	folder = gDatabase.OpenFolderL(KTxtSubRootName);
	gTestWrapper->TEST(folder.Count() == 2);
	folder.Close();

	// The folder 2.2.1 should now be in the root
	// Check it exists and check that it's parent is the root
	folder = gDatabase.OpenFolderL(KTxtFolder2_2_1);
	CleanupClosePushL(folder);
	subroot = folder.OpenParentL();
	CleanupClosePushL(subroot);
	gTestWrapper->TEST(subroot.Title().Compare(Bookmark::KTxtRootTitle) == 0);
	CleanupStack::PopAndDestroy(2);

	// Get the sub-root and delete it with all it's children
	subroot = gDatabase.OpenFolderL(KTxtSubRootName);
	id = subroot.Id();
	subroot.Close();
	gDatabase.DeleteItemL(id, ETrue);

	// There should now be only one item in the root
	// delete it
	folder = gDatabase.OpenRootL();
	gTestWrapper->TEST(folder.Count() == 1);
	folder.Close();
	folder = gDatabase.OpenFolderL(KTxtFolder2_2_1);
	id = folder.Id();
	folder.Close();
	gDatabase.DeleteItemL(id, ETrue);
	}
TVerdict CCreateMethodStep::doTestStepPreambleL()
	{
	ConstructL();
	
	CTlsCryptoAttributes* atts = Provider()->Attributes();
	
	// read the "server" random
	HBufC8* random = ServerRandomL();
	atts->iMasterSecretInput.iServerRandom.Copy(*random);
	delete random;
	
	// and the client random
	random = ClientRandomL();
	atts->iMasterSecretInput.iClientRandom.Copy(*random);
	delete random;
	
	// we only support null compression...
	atts->iCompressionMethod = ENullCompression;
	
	// read the cipher suite for the test
	atts->iCurrentCipherSuite = CipherSuiteL();
	
	// read the protocol version
	TTLSProtocolVersion version = ProtocolVersionL();
	atts->iNegotiatedProtocol = version;
	atts->iProposedProtocol = version;
	
	// set the session ID and "server" name (localhost)
	atts->iSessionNameAndID.iSessionId = SessionId();
	atts->iSessionNameAndID.iServerName.iAddress = KLocalHost; 
	atts->iSessionNameAndID.iServerName.iPort = 443;
	atts->idomainName.Copy(DomainNameL());
	
	// try and read DH params, this section may not exist
	RInteger gen;
	CleanupClosePushL(gen);
	
	RInteger prime;
	CleanupClosePushL(prime);
	
	TRAPD(err, ReadDHParamsL());
	if (err == KErrNone)
		{
		atts->iPublicKeyParams->iKeyType = EDHE;
		
		// The params are:
		// 1 - Prime
		// 2 - Generator
		// 3 - generator ^ random mod prime
		
		atts->iPublicKeyParams->iValue1 = Prime().BufferLC();
		CleanupStack::Pop(atts->iPublicKeyParams->iValue1);
		
		atts->iPublicKeyParams->iValue2 = Generator().BufferLC();
		CleanupStack::Pop(atts->iPublicKeyParams->iValue2);
		
		atts->iPublicKeyParams->iValue3 = KeyPair()->PublicKey().X().BufferLC();
		CleanupStack::Pop(atts->iPublicKeyParams->iValue3);
		}
		
	CleanupStack::PopAndDestroy(2, &gen); // prime
	
	// No client auth, no dialogs
	atts->iClientAuthenticate = EFalse;
	atts->iDialogNonAttendedMode = ETrue;
	
	return EPass;
	}
Ejemplo n.º 16
0
CPolicyPatchInfoList* CPolicyImporter::BuildPolicyPatchInfoListL()
    {
    LOG_("-> CPolicyImporter::BuildPolicyPatchInfoListL()");
    CPolicyPatchInfoList* patchInfoList = new (ELeave) CPolicyPatchInfoList(2);
    CleanupStack::PushL(patchInfoList);
    HBufC8* subjectName;
    // First, append the CA certs to patch list...
    for (TInt i = 0; i < iCurrCaCertList->Count(); i++)
        {

        CPolicyPatchInfo* patchInfo = new (ELeave) CPolicyPatchInfo();
        CleanupStack::PushL(patchInfo);

        TParse fileNameParser;
        fileNameParser.Set(iCurrCaCertList->At(i), NULL, NULL);

        patchInfo->iCertFileName.Copy(fileNameParser.NameAndExt());
        subjectName = CertSubjectNameL(iCurrCaCertList->At(i));
        CleanupStack::PushL(subjectName);
        if ( iCurrOtherCaCertList->Count()>1 && iCurrCaCertList->Count()==1 ) //if other than basic CA certificate exists
            {
            // Set original intermediate CA untrusted. . 
            HBufC8* certData = iFileUtil.LoadFileDataL(iCurrCaCertList->At(0));
            CleanupStack::PushL(certData);
            CX509Certificate* tempCert = CX509Certificate::NewLC(*certData);
            RArray<TUid> appArray;
            CleanupClosePushL(appArray);
            const TPtrC8* serialNumber = tempCert->DataElementEncoding(
                  CX509Certificate::ESerialNumber);
            const TPtrC8* issuername = tempCert->DataElementEncoding(
                  CX509Certificate::EIssuerName);

            iPkiService.SetApplicabilityL(
                       *issuername,
                       *serialNumber,
                       appArray);

            CleanupStack::PopAndDestroy(3); // appArray, tempcert
            
              //get CA from chain
            TFileName rootCAFile=GetCAFromFileListL(*subjectName, iCurrOtherCaCertList);
            CleanupStack::PopAndDestroy(subjectName);
            subjectName=NULL;
            subjectName = CertSubjectNameL(rootCAFile);
            CleanupStack::PushL(subjectName);
            
            //Set highest CA as trusted
            certData = iFileUtil.LoadFileDataL(rootCAFile);
            CleanupStack::PushL(certData);
            tempCert = CX509Certificate::NewLC(*certData);
            CleanupClosePushL(appArray);
            appArray.AppendL(TUid::Uid(KUidVpnManager));
            serialNumber = tempCert->DataElementEncoding(
                  CX509Certificate::ESerialNumber);
            issuername = tempCert->DataElementEncoding(
                  CX509Certificate::EIssuerName);

            iPkiService.SetApplicabilityL(
                       *issuername,
                       *serialNumber,
                       appArray);
 
            CleanupStack::PopAndDestroy(3); // appArray, tempcert, certData
            }
        patchInfo->SetCertSubjectNameL(*subjectName);

        patchInfoList->AppendL(patchInfo);
        CleanupStack::PopAndDestroy(subjectName);
        subjectName=NULL;
        CleanupStack::Pop(patchInfo); // patcInfo (now owned by the list)
        }

    // ... then, append also the user certificates.
    for (TInt i = 0; i < iCurrUserCertList->Count(); i++)
        {
        TInt keySize = 0;
        HBufC8* subjectName = CertInfoL(iCurrUserCertList->At(i), keySize);
        CleanupStack::PushL(subjectName);

        CPolicyPatchInfo* patchInfo = new (ELeave) CPolicyPatchInfo();
        CleanupStack::PushL(patchInfo);

        TParse fileNameParser;
        fileNameParser.Set(iCurrUserCertList->At(i), NULL, NULL);

        patchInfo->iCertFileName.Copy(fileNameParser.NameAndExt());
        patchInfo->SetCertSubjectNameL(*subjectName);
        patchInfo->SetUserCertKeyLen(keySize);

        patchInfoList->AppendL(patchInfo);

        CleanupStack::Pop(); // patchInfo (now owned by the list)
        CleanupStack::PopAndDestroy(); // subjectName
        }

    CleanupStack::Pop(); // patchInfoList, ownership transferred

    LOG_("<- CPolicyImporter::BuildPolicyPatchInfoListL()");
    return patchInfoList;
    }
Ejemplo n.º 17
0
// ---------------------------------------------------------------------------
// CNATFWStunSettings::ReadSettingsL
// ---------------------------------------------------------------------------
//  
void CNATFWStunSettings::ReadSettingsL( TUint32 aDomainKey,
    const CNATFWCenRepHandler& aRepHandler )
    {
    __NATSETTINGS( "CNATFWStunSettings::ReadSettingsL" )
     
    RArray<TUint32> serverKeys;
    CleanupClosePushL( serverKeys );
    
    TBool sharedSecretNotEnabled;
    TBool sharedSecretEnabled;
    
    // read sharedsecret enabled
    if ( KErrNone != aRepHandler.Read( KUNSAFProtocolsDomainSharedSecretNotSupported |
        aDomainKey, sharedSecretNotEnabled ) )
        {
        sharedSecretEnabled = KNATFWDefaultUseSharedSecret;
        }
    else
        {
        sharedSecretEnabled = !sharedSecretNotEnabled;
        }
        
    // read server settings
    TInt err = aRepHandler.FindServerKeys(
        KUNSAFProtocolsSTUNServerTableMask | aDomainKey, serverKeys );
        
    TInt serverCount = serverKeys.Count();
    
    if ( KErrNone == err && serverCount > 0 )
        {
        for( TInt i( 0 ); i < serverCount; i++ )
            {
            CNATFWServerSettings* serverSettings = CNATFWServerSettings::NewLC(
                KNullDesC8,
                KNATFWDefaultSTUNServerPort,
                KNullDesC8,
                KNullDesC8,
                sharedSecretEnabled );

            TUint32 key = serverKeys[i] | aDomainKey;
            serverSettings->ReadSettingsL( key, aRepHandler );
            iServerArray->AppendL( serverSettings );
            CleanupStack::Pop( serverSettings );
            }
        }
    else
        {
        if ( KErrNotFound == err )
            {
             __NATSETTINGS( "Server settings not found" )
            }
        else
            {
            User::Leave( err );
            }
        }
    CleanupStack::PopAndDestroy( &serverKeys );
    
    // read LatestConnectedStunServerAddress and possible port
    TInt port = 0;
    HBufC8* tempBufPointer = NULL;
    
    tempBufPointer = aRepHandler.ReadL(
        KUNSAFProtocolsLatestConnectedSTUNServerAddressMask | aDomainKey );
    if ( tempBufPointer ) 
        {
        CleanupStack::PushL( tempBufPointer );
        HBufC8* addr = TNATFWSettingsParser::ParseAddressLC(
            *tempBufPointer, port );
        SetLatestConnectedServerAddrL( *addr );
        SetLatestConnectedServerPort( port );
        CleanupStack::PopAndDestroy( addr );
        CleanupStack::PopAndDestroy( tempBufPointer );
        }
    else
        {
        SetLatestConnectedServerAddrL( KNullDesC8 );
        SetLatestConnectedServerPort( port );
        }
    
    // Read LatestConnectedStunServerPort, replaces previous data if found
    if ( KErrNone == aRepHandler.Read( KUNSAFProtocolsLatestConnectedSTUNServerPortMask |
        aDomainKey, port ) )
        {
        SetLatestConnectedServerPort( port );
        }
    
    // read retransmission timeout
    if ( KErrNone != aRepHandler.Read( KUNSAFProtocolsStunRetransmissionTimeoutMask |
        aDomainKey, iRto ) )
        {
        iRto = KNATFWDefaultRtoValue;
        }
    }
LOCAL_C TInt MainL()
{
    RProcess delayer;
    delayer.Create(_L("tsysmon_app_delayshutdown.exe"),KNullDesC);
    delayer.Resume();
    delayer.Close();

    TInt runCount = 0;
    CCommandLineArguments* args = CCommandLineArguments::NewLC();
    runCount = CSysMonTestHelper::ReadRunCountL(args->Arg(0));

    CSysMonTestHelper::IncrementRunCountL(args->Arg(0));
    CleanupStack::PopAndDestroy(args);

    TBool keepRunning = EFalse;

    switch (runCount)
    {
    case 0:
    {
        RProcess::Rendezvous(KErrNone);
        CSysMonTestHelper* helper = CSysMonTestHelper::NewLC();

        RSysMonSession sysmon;
        sysmon.OpenL();
        CleanupClosePushL(sysmon);

        TBuf<255> args;
        TBuf<255> testId;
        helper->GetTestId(testId);
        RDebug::Print(testId);
        args.Append(testId);
        args.Append(_L(" "));
        args.Append(_L("5000"));

        CStartupProperties* props = CStartupProperties::NewLC(KFilenameDeregTimeout, args);
        props->SetMonitored(ETrue);
        props->SetStartupType(EStartProcess);
        props->SetStartMethod(EWaitForStart);
        props->SetNoOfRetries(0);
        props->SetTimeout(0);
        props->SetRecoveryParams(ERestartOS, 0);

        CStartupProperties* props2 = CStartupProperties::NewLC(_L("tsysmon_app_donothing.exe"), KNullDesC);
        props2->SetMonitored(ETrue);
        props2->SetStartupType(EStartProcess);
        props2->SetStartMethod(EWaitForStart);
        props2->SetNoOfRetries(1);
        props2->SetTimeout(0);
        props2->SetRecoveryParams(EIgnoreOnFailure, 0);

        RProcess slave1;
        slave1.Create(KFilenameDeregTimeout, args);
        CleanupClosePushL(slave1);
        slave1.Resume();

        RProcess slave2;
        slave2.Create(_L("tsysmon_app_donothing.exe"), KNullDesC);
        CleanupClosePushL(slave2);
        slave2.Resume();

        // Register with SysMon
        TInt err = 0;
        TRAP(err, sysmon.MonitorL(*props, slave1));
        TRAP(err, sysmon.MonitorL(*props2, slave2));
        slave1.Terminate(KErrNone);
        slave2.Terminate(KErrNone);

        CleanupStack::PopAndDestroy(5, helper);
        break;
    }
    default: //Run normally
    {
        RProcess::Rendezvous(KErrNone);
        keepRunning = ETrue;
        break;
    }
    }

    CSysMonTestHelper::IncrementRunCountL(args->Arg(0));
    CleanupStack::PopAndDestroy(args);

    while (keepRunning)
    {
        User::After(5000000); // 5 seconds
    }
    return 0;
}
Ejemplo n.º 19
0
void T_CGlxCache::T_CGlxCache_UpdateMediaLL(  )
    {
    // Create helper class
    T_CacheTestHelpers cacheTestHelper(iCGlxCache);

    // Create cache observer class
    CGlxCacheObserverTest* cacheObserver = CGlxCacheObserverTest::NewL();
    CleanupStack::PushL(cacheObserver);

    CGlxCacheManager* cacheManager = CGlxCacheManager::InstanceL();
    CleanupClosePushL(*cacheManager);

    cacheManager->AddObserverL(cacheObserver);

    // New media without id
    CMPXMedia* newMedia3 = CMPXMedia::NewL();
    CleanupStack::PushL(newMedia3);

    EUNIT_PRINT(_L("Add new media without id"));
    iCGlxCache->UpdateMediaL(*newMedia3);

    EUNIT_PRINT(_L("Check new media not added"));
    EUNIT_ASSERT_DESC(cacheTestHelper.ItemPool().Count() == 2, "Cache doesn't contain two items");

    // New media without attributes
    newMedia3->SetTObjectValueL<TMPXItemId>(KMPXMediaGeneralId, TMPXItemId(KMediaId3));

    EUNIT_PRINT(_L("Add new media without attributes"));
    iCGlxCache->UpdateMediaL(*newMedia3);

    EUNIT_PRINT(_L("Check new media added without attributes"));
    EUNIT_ASSERT_DESC(cacheTestHelper.ItemPool().Count() == 3, "Cache doesn't contain three items");
    EUNIT_ASSERT_DESC(cacheTestHelper.ItemPool()[2]->Count() == 0, "Item contains attributes");

    TInt cachedNewMedia3Index = cacheTestHelper.ItemPool().FindInOrder(TGlxMediaId(KMediaId3), T_CacheTestHelpers::MediaItemOrderByKey);
    EUNIT_ASSERT_DESC(cachedNewMedia3Index != KErrNotFound, "New media not added to cache");

    EUNIT_PRINT(_L("Check observer not notified of new media attributes"));
    EUNIT_ASSERT_DESC(!cacheObserver->AttributesAvailableNotified(), "Observer notified of new media attributes");

    CleanupStack::PopAndDestroy(newMedia3);

    // New media with attributes
    CMPXMedia* newMedia4 = CMPXMedia::NewL();
    CleanupStack::PushL(newMedia4);

    newMedia4->SetTObjectValueL<TMPXItemId>(KMPXMediaGeneralId, TMPXItemId(KMediaId4));
    newMedia4->SetTObjectValueL<TSize>(KGlxMediaGeneralDimensions, TSize(640, 480));

    EUNIT_PRINT(_L("Add new media with attributes"));
    cacheObserver->ResetCalls();
    iCGlxCache->UpdateMediaL(*newMedia4);

    EUNIT_PRINT(_L("Check new media added with attributes"));
    EUNIT_ASSERT_DESC(cacheTestHelper.ItemPool().Count() == 4, "Cache doesn't contain four items");
    EUNIT_ASSERT_DESC(cacheTestHelper.ItemPool()[3]->Count() == 1, "Item doesn't contain attributes");

    EUNIT_PRINT(_L("Check observer notified of new media attributes"));
    EUNIT_ASSERT_DESC(cacheObserver->AttributesAvailableNotified(), "Observer not notified of new media attributes");
    EUNIT_ASSERT_DESC(cacheObserver->IdSpaceId().Value() == KIdSpaceId, "Observer not notified of correct new media IdSpaceId");
    EUNIT_ASSERT_DESC(cacheObserver->MediaId().Value() == KMediaId4, "Observer not notified of correct new media Id");

    EUNIT_ASSERT_DESC(TMPXAttribute::Match(cacheObserver->Attributes()[0], KGlxMediaGeneralDimensions), "Observer not notified of correct new media attribute");
    EUNIT_ASSERT_DESC(cacheObserver->Attributes().Count() == 1, "Observer not notified of correct new media attribute count");

    EUNIT_ASSERT_DESC(cacheObserver->Media() == cacheTestHelper.ItemPool()[3], "Observer not notified of correct new media pointer");

    CleanupStack::PopAndDestroy(newMedia4);

    // Create media user class
    CGlxMediaUserTest* mediaUser = CGlxMediaUserTest::NewL();
    CleanupStack::PushL(mediaUser);

    cacheTestHelper.ItemPool()[0]->ReserveUsersL(1);
    cacheTestHelper.ItemPool()[0]->AddUser(*mediaUser, KErrNotFound);

    // Update media with existing attributes
    CMPXMedia* Media1 = CMPXMedia::NewL();
    CleanupStack::PushL(Media1);
    Media1->SetTObjectValueL<TMPXItemId>(KMPXMediaGeneralId, TMPXItemId(KMediaId1));
    Media1->SetTObjectValueL<TBool>(KMPXMediaDrmProtected, ETrue);

    EUNIT_PRINT(_L("Update media with existing attributes"));
    cacheObserver->ResetCalls();
    iCGlxCache->UpdateMediaL(*Media1);

    EUNIT_PRINT(_L("Check media updated with existing attributes"));
    EUNIT_ASSERT_DESC(cacheTestHelper.ItemPool().Count() == 4, "Cache doesn't contain four items");
    EUNIT_ASSERT_DESC(cacheTestHelper.ItemPool()[0]->Count() == 1, "Item doesn't contain 1 attribute");

    EUNIT_PRINT(_L("Check user not notified of media new attributes"));
    EUNIT_ASSERT_DESC(!mediaUser->AttributesAvailableNotified(), "User notified of updated media new attributes");
    EUNIT_ASSERT_DESC(!cacheObserver->AttributesAvailableNotified(), "Observer notified of updated media new attributes");

    // Update media with new attributes
    Media1->SetTObjectValueL<TSize>(KGlxMediaGeneralDimensions, TSize(1024, 768));

    EUNIT_PRINT(_L("Update media with new attributes"));
    cacheObserver->ResetCalls();
    mediaUser->ResetCalls();
    iCGlxCache->UpdateMediaL(*Media1);

    EUNIT_PRINT(_L("Check media updated with new attributes"));
    EUNIT_ASSERT_DESC(cacheTestHelper.ItemPool().Count() == 4, "Cache doesn't contain four items");
    EUNIT_ASSERT_DESC(cacheTestHelper.ItemPool()[0]->Count() == 2, "Item doesn't contain 2 attributes");

    EUNIT_PRINT(_L("Check user notified of updated media new attributes"));
    EUNIT_ASSERT_DESC(mediaUser->AttributesAvailableNotified(), "User not notified of updated media new attributes");
    EUNIT_ASSERT_DESC(mediaUser->IdSpaceId().Value() == KIdSpaceId, "User not notified of correct updated media IdSpaceId");
    EUNIT_ASSERT_DESC(mediaUser->MediaId().Value() == KMediaId1, "User not notified of correct updated media Id");

    EUNIT_ASSERT_DESC(TMPXAttribute::Match(mediaUser->Attributes()[0], KGlxMediaGeneralDimensions), "Observer not notified of correct updated media attribute");
    EUNIT_ASSERT_DESC(mediaUser->Attributes().Count() == 1, "Observer not notified of correct updated media attribute count");

    EUNIT_PRINT(_L("Check observer notified of updated media new attributes"));
    EUNIT_ASSERT_DESC(cacheObserver->AttributesAvailableNotified(), "Observer not notified of updated media new attributes");
    EUNIT_ASSERT_DESC(cacheObserver->IdSpaceId().Value() == KIdSpaceId, "Observer not notified of correct updated media IdSpaceId");
    EUNIT_ASSERT_DESC(cacheObserver->MediaId().Value() == KMediaId1, "Observer not notified of correct updated media Id");

    EUNIT_ASSERT_DESC(TMPXAttribute::Match(cacheObserver->Attributes()[0], KGlxMediaGeneralDimensions), "Observer not notified of correct updated media attribute");
    EUNIT_ASSERT_DESC(cacheObserver->Attributes().Count() == 1, "Observer not notified of correct updated media attribute count");

    EUNIT_ASSERT_DESC(cacheObserver->Media() == cacheTestHelper.ItemPool()[0], "Observer not notified of correct updated media pointer");

    cacheTestHelper.ItemPool()[0]->RemoveUser(*mediaUser);
    cacheManager->RemoveObserver(cacheObserver);

    CleanupStack::PopAndDestroy(Media1);
    CleanupStack::PopAndDestroy(mediaUser);
    CleanupStack::PopAndDestroy(cacheManager);
    CleanupStack::PopAndDestroy(cacheObserver);
    }
// ================= MEMBER FUNCTIONS =======================
//
// ----------------------------------------------------------
// CFlashLite21LauncherAppUi::ConstructL()
//
// ----------------------------------------------------------
//
void CFlashLite21LauncherAppUi::ConstructL()
    {
    BaseConstructL();
	
	//timer
    iWaitTimer = CPeriodic::NewL( KWaitCallBackPriority );

	TThreadId id;
	RApaLsSession ls;
	User::LeaveIfError(ls.Connect());
	TApaAppInfo appinfo;
	TInt KError = ls.GetAppInfo(appinfo, KUidFlash21);
	CleanupClosePushL(ls);

	if(KError == KErrNone)
	{
		//Search for open player
		TFileName fnAppPath = appinfo.iFullName;
		TApaTaskList taskList( CEikonEnv::Static()->WsSession() );
		TApaTask task = taskList.FindApp( KUidFlash21 );
		
		if(task.Exists()) //If player is already running
		{
			TInt err = task.SwitchOpenFile( KLitSwfFileToLaunch );
			if(err == KErrNone)
			{
				//everything is fine
			} else 
			{
				//any error
			}
			task.BringToForeground();
		}
		else 
		{
			if(KError == KErrNone) //the player is not running so we launch it
			{
				
				TInt result = ls.StartDocument(fnAppPath,id);
				
				
				if (result!=KErrNone)
				{
					//any error
				} 
				else
				{
					if ( iWaitTimer->IsActive())
        			{
				        iWaitTimer->Cancel();
			        }
			        TCallBack callback( WaitTimerCallbackL, this );
			        iWaitTimer->Start( ( TTimeIntervalMicroSeconds32 ) KMaxWaitTime,
			                              ( TTimeIntervalMicroSeconds32 ) KMaxWaitTime, 
			                               callback );
				}
				CleanupStack::PopAndDestroy(); // Destroy cmd
			}
		}

	} 
	else 
	{
		//FlashPlayer not installed
	}
	
    /*iAppContainer = new (ELeave) CFlashLite21LauncherContainer;
    iAppContainer->SetMopParent( this );
    iAppContainer->ConstructL( ClientRect() );
    AddToStackL( iAppContainer );*/
    }
Ejemplo n.º 21
0
/**
 * @return - TVerdict code
 * Override of base class pure virtual
 * Our implementation only gets called if the base class doTestStepPreambleL() did
 * not leave. That being the case, the current test result value will be EPass.
 */
TVerdict CT_LbsClientStep_ModStat::doTestStepL()
	{
	// Generic test step used to test the LBS Client Notify position update API.
	INFO_PRINTF1(_L("&gt;&gt;CT_LbsClientStep_ModStat::doTestStepL()"));

	if (TestStepResult() == EPass)
		{
		TInt err = KErrNone;
			
		// Connect to self locate server.
		User::LeaveIfError(iServer.Connect());
		CleanupClosePushL(iServer);
		
		// Carryout unique test actions.
		TInt testCaseId;
		if (GetIntFromConfig(ConfigSection(), KTestCaseId, testCaseId))
			{
			switch (testCaseId)
				{
				// Test case LBS-ModStatus-0001 to 0004
				case 01:
				case 02:
				case 03:				
				case 04:
					{
					TPositionModuleId testmodId;
					
					T_LbsUtils utils;
					testmodId = utils.GetAGpsModuleIdL(iServer);
					
					// Get the module device status.
					TPositionModuleStatus& modStatus = iParent.iSharedData->iCurrentModuleStatus;					
					err = iServer.GetModuleStatus(modStatus, testmodId);
					if(KErrNone != err)
						{
						INFO_PRINTF2(_L("Failed with err %d"), err);
						SetTestStepResult(EFail);	
						}
					}
					break;
					
				// Test case LBS-ModStatus-0005
				case 05:
					{
					TPositionModuleId badmodId;
					T_LbsUtils utils;
					badmodId = utils.GetBadModuleId();
					
					// Get the module device status.
					TPositionModuleStatus moduleStatus;
					
					err = iServer.GetModuleStatus(moduleStatus, badmodId);
					if(KErrNotFound != err)
						{
						INFO_PRINTF2(_L("Failed with err %d. Should have been KErrNotFound(-1)"), err);
						SetTestStepResult(EFail);	
						}
					}
					break;					
										
				// LBS-Mod-Status-Event-0002
				case 22:
					{
					TPositionModuleStatus& testmodStatus = iParent.iSharedData->iCurrentModuleStatus;
												
					// Get device status events for any module:										
					if(!DoRequestAndVerifyModStatusEventsL(TPositionModuleStatusEvent::EEventDeviceStatus, testmodStatus))
						{
						SetTestStepResult(EFail);
						}
					}
					break;
					
				// LBS-Mod-Status-Event-0003
				case 23:
					{
					TPositionModuleStatus& testmodStatus = iParent.iSharedData->iCurrentModuleStatus;
					
					// Get device status events	for (test) agps module		
					if(!DoRequestAndVerifyAGPSModStatusEventsL(TPositionModuleStatusEvent::EEventDeviceStatus, testmodStatus))
						{
						SetTestStepResult(EFail);
						}
					
					// Get device status events again				
					if(!DoRequestAndVerifyModStatusEventsL(TPositionModuleStatusEvent::EEventDeviceStatus, testmodStatus))
						{
						SetTestStepResult(EFail);
						}
					}
					break;
				
				// LBS-Mod-Status-Event-0004
				case 24:
					{
					TPositionModuleStatus& testmodStatus = iParent.iSharedData->iCurrentModuleStatus;
						
					// Get device status events				
					if(!DoRequestAndVerifyAGPSModStatusEventsL(TPositionModuleStatusEvent::EEventDeviceStatus, testmodStatus))
						{
						SetTestStepResult(EFail);
						}
					}
					break;
				
				// LBS-Mod-Status-Event-0005
				case 25:
					{
					TPositionModuleStatus& testmodStatus = iParent.iSharedData->iCurrentModuleStatus;
					// Get device status events				
					if(!DoRequestAndVerifyAGPSModStatusEventsL(TPositionModuleStatusEvent::EEventDataQualityStatus, testmodStatus))
						{
						SetTestStepResult(EFail);
						}					
					}
					break;
										
				// LBS-Mod-Status-Event-0009
				case 29:
					{
					TPositionModuleStatus& testmodStatus = iParent.iSharedData->iCurrentModuleStatus;
					
					//In feature when system events support, change TPositionModuleStatusEvent::EEventAll 
					// Get device status events				
					if(!DoRequestAndVerifyAGPSModStatusEventsL(((TPositionModuleStatusEvent::EEventDeviceStatus)|(TPositionModuleStatusEvent::EEventDataQualityStatus)), testmodStatus))
						{
						SetTestStepResult(EFail);
						}					
					}
					break;
															
				// LBS-Mod-Status-Event-0010
				case 30:
					{
					TPositionModuleId modId;
					TInt err;
						
					// use bad module id
					T_LbsUtils utils;
					modId = utils.GetBadModuleId();
								
					err = DoRequestModStatusEventsWithError(TPositionModuleStatusEvent::EEventDataQualityStatus, modId);								
					if(KErrNotFound != err)
						{
						SetTestStepResult(EFail);
						}
					}
					break;
															
				// LBS-Mod-Status-Event-0011
				case 31:
					{
					TPositionModuleId modId;
					TInt err;
						
					// use agps module id
					T_LbsUtils utils;
					modId = utils.GetAGpsModuleIdL(iServer);
								
					err = DoRequestModStatusEventsWithError(0, modId);								
					if(KErrArgument != err)
						{
						SetTestStepResult(EFail);
						}
					}
					break;

				// LBS-Mod-Status-Event-0012
				case 32:
					{
					TPositionModuleId modId;
					TRequestStatus request;					
					TPositionModuleStatusEvent statusEvent;
						
					// use agps module id
					T_LbsUtils utils;
					modId = utils.GetAGpsModuleIdL(iServer);
					
					statusEvent.SetRequestedEvents(TPositionModuleStatusEvent::EEventDeviceStatus);
										
					iServer.NotifyModuleStatusEvent(statusEvent, request, modId);
					
					TInt err = iServer.CancelRequest(EPositionServerNotifyModuleStatusEvent);
					if(KErrNone == err)
						{
						User::WaitForRequest(request);
						if(KErrCancel != request.Int())
							{
							INFO_PRINTF2(_L("Failed: KErrCancel not returned, Got %d"), request.Int());
							SetTestStepResult(EFail);
							}
						}
					else
						{
						INFO_PRINTF2(_L("Failed: CancelRequest returned error %d"), err);
						SetTestStepResult(EFail);
						}
					}
					break;
				
				// LBS-Mod-Status-Event-0013
				case 33:
					{
					TInt err = iServer.CancelRequest(EPositionServerNotifyModuleStatusEvent);
					if(KErrNotFound != err)
						{
						INFO_PRINTF2(_L("Failed: CancelRequest returned error %d, expecting KErrNotFound"), err);
						SetTestStepResult(EFail);						
						}
					}
					break;

				// LBS-Mod-Status-Event-0014
				case 34:
					{
					// close server since we don't want to be connected for this test
					iServer.Close();
					
					TInt err = iServer.CancelRequest(EPositionServerNotifyModuleStatusEvent);
					
					// if we get here, something went wrong, so panic
					SetTestStepResult(EFail);
					
					User::Panic(KLbsClientStep_ModStatus, KErrGeneral);
					}
					break;
					
				// LBS-Mod-Status-Event-0015
				case 35:
					{
					TPositionModuleId modId;
					TRequestStatus request;					
					TPositionModuleStatusEvent statusEvent;
						
					// use agps module id
					T_LbsUtils utils;
					modId = utils.GetAGpsModuleIdL(iServer);
					
					// set requested events mask
					statusEvent.SetRequestedEvents(TPositionModuleStatusEvent::EEventDeviceStatus);
					
					// ask to be notified of requested events					
					iServer.NotifyModuleStatusEvent(statusEvent, request, modId);
					
					// ask to be notified of requested events a second time (panics)					
					iServer.NotifyModuleStatusEvent(statusEvent, request, modId);
					
					// if we get here, something went wrong, so panic
					SetTestStepResult(EFail);
					
					User::Panic(KLbsClientStep_ModStatus, KErrGeneral);
					}
					break;
				case 101:
					{
					// This test requires net sim to be open.
					OpenNetSim();
					
					// Select the network module.
					T_LbsUtils utils;
					TPositionModuleId modId;
					modId = utils.GetNetworkModuleIdL(iServer);
					User::LeaveIfError(iPositioner.Open(iServer, modId));
					CleanupClosePushL(iPositioner);
					
					// Initialise the position info variable.
					TPositionInfo* posInfo = new(ELeave) TPositionInfo();
					CleanupStack::PushL(posInfo);
						
					// set requested events mask so we get notified on EEventDeviceStatus (any status change)
					TPositionModuleStatusEvent statusEvent;
					statusEvent.SetRequestedEvents(TPositionModuleStatusEvent::EEventDeviceStatus);
					CT_LbsAsyncWaiter* waiter = CT_LbsAsyncWaiter::NewL();
					iServer.NotifyModuleStatusEvent(statusEvent, waiter->iStatus, modId);
					
					// Verify that the module status is ready before we make any requests.
					DoVerifyModStatus(TPositionModuleStatus::EDeviceReady,modId);

					// Request a position update, we should then see a state change to EDeviceActive
					TRequestStatus status;		
					INFO_PRINTF1(_L("Performing NotifyPositionUpdate()"));
					iPositioner.NotifyPositionUpdate(*posInfo,status);
					// Use the waiter object so that we can get the device status change.
					waiter->StartAndWait();
					waiter->Result();
					
					// Check that the change that happened was the correct thing.
					TPositionModuleStatusEvent::TModuleEvent eventsExpected = TPositionModuleStatusEvent::EEventDeviceStatus;
					TPositionModuleStatusEvent::TModuleEvent eventsOccurred = statusEvent.OccurredEvents();
					
					if(eventsOccurred!=eventsExpected)
						{
						INFO_PRINTF1(_L("No Module Status Event have Occured"));
						SetTestStepResult(EFail);
						}
					
					
					// Verify the device is now active
					DoVerifyModStatus(TPositionModuleStatus::EDeviceActive,modId);	
					
					INFO_PRINTF1(_L("Position Received"));
					User::WaitForRequest(status);

					//Verify that the position is EDeviceReady again
					DoVerifyModStatus(TPositionModuleStatus::EDeviceReady,modId);
				
					// Tidy up everything
					CloseNetSim();					
					delete waiter;
					CleanupStack::PopAndDestroy(posInfo);	
					CleanupStack::PopAndDestroy(&iPositioner);	
					}
					break;					
				default:
					{
					User::Panic(KLbsClientStep_ModStatus, KErrUnknown);
					}					
				}
				

			}
			
		// All done, clean up.
		CleanupStack::PopAndDestroy(&iServer);		
		}

	INFO_PRINTF1(_L("&lt;&lt;CT_LbsClientStep_ModStat::doTestStepL()"));

	return TestStepResult();
	}
TInt CMdSSqLiteConnection::ExecuteL( const TDesC& aCommand,
                                     const RRowData& aVariables,
                                     RMdsStatement* aStatement )
    {
    TInt err = KErrNone;

    if ( aVariables.Size() == 0 )
        {
        // no variables
        err = iMdeSqlDb.Exec( aCommand );

		if ( err < KErrNone )
        	{
            _LIT( KMdSExec, "Exec (no variables)" );
            TraceAndLeaveL( KMdSExec, err );
            }
		}
    else if ( aStatement )
    	{
        if ( aStatement->iPrepared == EFalse )
            {
            err = aStatement->iStatement.Prepare( iMdeSqlDb, aCommand );

        	if ( err < KErrNone )
                {
                _LIT( KMdSPrepare, "Prepare" );
                TraceAndLeaveL( KMdSPrepare, err );
                }
            aStatement->iPrepared = ETrue;
            }
        else
            {
            err = aStatement->iStatement.Reset();
         	if ( err < KErrNone )
                {
                _LIT( KMdSResume, "Resume" );
                TraceAndLeaveL( KMdSResume, err );
                }
            }
           
        DoBindL( aStatement->iStatement, aVariables );
        err = aStatement->iStatement.Exec();

        if ( err < KErrNone )
            {
            aStatement->iStatement.Reset();
            aStatement->iPrepared = EFalse;
			_LIT( KMdSExec, "Exec" );
            TraceAndLeaveL( KMdSExec, err );
            }
    	}
    else
        {
        RSqlStatement mdeSqlDbStmt;
        CleanupClosePushL( mdeSqlDbStmt );
        err = mdeSqlDbStmt.Prepare( iMdeSqlDb, aCommand );

        if ( err < KErrNone )
            {
            _LIT( KMdsPrepare, "Prepare (no statement)" );
            TraceAndLeaveL( KMdsPrepare, err );
            }

        DoBindL( mdeSqlDbStmt, aVariables );
        
        err = mdeSqlDbStmt.Exec();

        if ( err < KErrNone )
            {
            _LIT( KMdsExec, "Exec (no statement)" );
            TraceAndLeaveL( KMdsExec, err );
            }

        CleanupStack::PopAndDestroy( &mdeSqlDbStmt );
        }
    return err;
    }
Ejemplo n.º 23
0
void CHttpTestCase2::DoRunL()
	{
	// Literals used in the function
	_LIT8(KWapTestUrl,			"http://WapTestIP/perl/dumpform.pl");

	// Replace the host name in the URL
	HBufC8* newUrl8 = TSrvAddrVal::ReplaceHostNameL(KWapTestUrl(), iIniSettingsFile);
	CleanupStack::PushL(newUrl8);
	TPtr8 newUrlPtr8 = newUrl8->Des();

	TUriParser8 testURI;
	testURI.Parse(newUrlPtr8);

	//open a Session
	RHTTPSession mySession;
	mySession.OpenL();
	CleanupClosePushL(mySession);
	iEngine->Utils().LogIt(_L("Session Created (TC2)"));
	iEngine->Utils().LogIt(_L("Session (Default) parameters: RHTTPProxy aProxy = RHTTPProxy(), MHTTPSessionCallback* aCallback = NULL"));

	// Get the mySession'string pool handle;
	iMyStrP = mySession.StringPool();

	//get strings used in this test
	RStringF textPlain = iMyStrP.StringF(HTTP::ETextPlain, RHTTPSession::GetTable());
	RStringF textHtml = iMyStrP.StringF(HTTP::ETextHtml, RHTTPSession::GetTable());
	RStringF mimeType = iMyStrP.StringF(HTTP::EApplicationXWwwFormUrlEncoded, RHTTPSession::GetTable());

	// Create , open and push in the CS a Transaction in mySession 
	RHTTPTransaction myTransaction;
	myTransaction = mySession.OpenTransactionL(testURI, *this, iMyStrP.StringF(HTTP::EPOST,RHTTPSession::GetTable()));
	CleanupClosePushL(myTransaction);
	iEngine->Utils().LogIt(_L("Transaction Created in mySession"));

	// Get a handle of the request in myTransaction
	RHTTPRequest myRequest = myTransaction.Request();
	RHTTPHeaders myHeaders = myRequest.GetHeaderCollection();
	// provide  some headers 
	THTTPHdrVal v2(textPlain);
	THTTPHdrVal v3(textHtml);
	THTTPHdrVal v4(6);
	THTTPHdrVal v5(mimeType);

	myHeaders.SetFieldL(iMyStrP.StringF(HTTP::EAccept, RHTTPSession::GetTable()),v2 );
	myHeaders.SetFieldL(iMyStrP.StringF(HTTP::EAccept, RHTTPSession::GetTable()),v3);
	myHeaders.SetFieldL(iMyStrP.StringF(HTTP::EContentLength, RHTTPSession::GetTable()), v4);
	myHeaders.SetFieldL(iMyStrP.StringF(HTTP::EContentType, RHTTPSession::GetTable()), v5);

	TSrvAddrVal::LogUsing8BitDesL(iEngine, newUrlPtr8);
	iEngine->Utils().LogIt(_L("Method:Post"));
	iEngine->Utils().LogIt(_L("Accept:test/plain,text/html"));
	iEngine->Utils().LogIt(_L("Content-Type: application/x-www-form-urlencoded"));
	iEngine->Utils().LogIt(_L("Content-Length: 4"));
	myRequest.SetBody(*this);
	iEngine->Utils().LogIt(_L("Transaction terminated"));

	// Close strings used in this session before closing the session
	//close transaction and session
	myTransaction.Close();
	iEngine->Utils().LogIt(_L("Transaction terminated"));
	mySession.Close();
	iEngine->Utils().LogIt(_L("Session terminated"));
	if (iTestFail==1)
		{
		User::Leave(-1);
		}
	CleanupStack::Pop(2); // mySession,myTansaction
	CleanupStack::PopAndDestroy(newUrl8);
	}
void CMdSSqLiteConnection::OpenDbL( const TDesC& aDbFileName )
    {
    _LIT8( KMdsSqlDbaConfig, "cache_size=2000; page_size=2048; encoding=\"UTF-16\";");
    _LIT8( KBlacklistSqlDbaConfig, "cache_size=1500; page_size=1024; encoding=\"UTF-16\";");

    delete iDbFileName;
    iDbFileName = NULL; // in case AllocL leaves
    iDbFileName = aDbFileName.AllocL();

    TBool setupForMdsServer( EFalse );
    // Check if it is MDS server DB that is accessed, otherwise setup will be for Blacklist Server
    if( iDbFileName->Des().FindF( KMdsSqlDbDefaultName ) != KErrNotFound )
        {
        setupForMdsServer = ETrue;
        }
    
    TInt err = KErrNone;
    
    // we need to set up policy, because we use secure database
	TSecurityPolicy defaultPolicy(TSecurityPolicy::EAlwaysPass);
    RSqlSecurityPolicy sqlSecurityPolicy;
    CleanupClosePushL( sqlSecurityPolicy );
    err = sqlSecurityPolicy.Create( defaultPolicy );

    if ( err != KErrNone )
    	{
    	_LIT( KMdsSecurityCheckFail, "Security check fail" );
    	TraceAndLeaveL( KMdsSecurityCheckFail, err );
    	}
    /**
     * Open database:
     *   First we try to open db. If this fails because db not creater yer, then
     *   try to create it. Otherwise we cannot open it and we leave
     */
    if( setupForMdsServer )
        {
        err = iMdeSqlDb.Open( *iDbFileName, &KMdsSqlDbaConfig );
        }
    else
        {
        err = iMdeSqlDb.Open( *iDbFileName, &KBlacklistSqlDbaConfig );
        }
    if ( err != KErrNone )
        {
        __LOG1( ELogDb, "Cannot open database %d", err );
            
        if( err == KErrNotFound )
            {
            __LOG1( ELogDb, "Cannot find database %d", err );
            if( setupForMdsServer )
                {
                err = iMdeSqlDb.Create( *iDbFileName, sqlSecurityPolicy, &KMdsSqlDbaConfig );
                }
            else
                {
                err = iMdeSqlDb.Create( *iDbFileName, sqlSecurityPolicy, &KBlacklistSqlDbaConfig );
                }
            if( err != KErrNone )
                {
                __LOG1( ELogDb, "Unknown error while creating %d", err );
                User::LeaveIfError( err );
                }
            }
        else if( err == KErrCorrupt ||
                err == KSqlErrCorrupt )
            {
            __LOGLB( ELogDb, "Warning: Database is corrupted, will delete and re-create it." );
            if( setupForMdsServer )
                {
                err = DeleteAndReCreateDB( iDbFileName, sqlSecurityPolicy, &KMdsSqlDbaConfig );
                }
            else
                {
                err = DeleteAndReCreateDB( iDbFileName, sqlSecurityPolicy, &KBlacklistSqlDbaConfig );
                }
        
            if ( KErrNone == err  )
                {
                if( setupForMdsServer )
                    {
                    err = iMdeSqlDb.Open( *iDbFileName, &KMdsSqlDbaConfig );
                    }
                else
                    {
                    err = iMdeSqlDb.Open( *iDbFileName, &KBlacklistSqlDbaConfig );
                    }
                if ( err != KErrNone )
                    {
                    __LOG1( ELogDb, "Cannot open database again after delete and re-create %d", err );
                    User::LeaveIfError( err );
                    }
                } 
            }
        else 
            {
            __LOG1( ELogDb, "Unknown error while accessing database %d", err );
            User::LeaveIfError( err );
            }
        }
    CleanupStack::PopAndDestroy( &sqlSecurityPolicy );
    }
Ejemplo n.º 25
0
// -----------------------------------------------------------------------------
// CBSBrandHandler::ReadElementLC()
// -----------------------------------------------------------------------------
//
MBSElement* CBSBrandHandler::ReadElementLC( const TDesC8& aId, TBool aForceDefault /*= EFalse*/ )
	{
	TRACE( T_LIT( "CBSBrandHandler::ReadElementLC begin aId"));

	if( aForceDefault )
		{
		TRACE( T_LIT( "CBSBrandHandler::ReadElementLC default brand"));
		iStorageManager->BrandHandleL( *iApplicationId,
									   *iDefaultBrandId, iLanguage,
									   *iHandle,
									   iReserved );		
		}
	else
		{
		TInt err = -1;
		TRAP (err, iStorageManager->BrandHandleL( *iApplicationId,
									   *iBrandId, iLanguage,
									   *iHandle,
									   iReserved ));
		if (KErrNone != err)
			{
			iStorageManager->BrandHandleL( *iApplicationId,
										   *iDefaultBrandId, iLanguage,
										   *iHandle,
										   iReserved ); 	
			}
		}
	
	RFileReadStream stream;
	stream.Attach( *iHandle );
	CleanupClosePushL( stream );
	
	VerifyVersionL( stream );
	
	TInt count = stream.ReadInt16L();
	
	MBSElement* returnValue = NULL;

	for( TInt i = 0; i < count; i++ )
		{
		TRAPD( err, returnValue = ReadStreamL( aId, stream ) );
		
		if( err == KErrEof )
			{
			TRACE( T_LIT( "CBSBrandHandler::ReadElementLC EOF!") );
			// the id is not found in this file
			User::Leave( KErrNotFound );
			}
		if( returnValue )
			{
			TRACE( T_LIT( "CBSBrandHandler::ReadElementLC ELEMENT FOUND.. at position %d"), i);
			// we found what we are looking for
			break;
			}
		}
		
	CleanupStack::PopAndDestroy( &stream ); // stream	
	
	TBool popElementFromCleanupStack( EFalse );
	
	/* If retur value is not found and if its read the actual brand, then try in default brand as well. aForceDefault will decide that. */
	if( !returnValue && !aForceDefault)
		{
		TRACE( T_LIT( "CBSBrandHandler::ReadElementLC force default is true") );

		// the element was not found
		// try the default brand if it's not the same as wanted brand
		if( 0 != iBrandId->Compare( *iDefaultBrandId ) )
			{
			TRACE( T_LIT( "CBSBrandHandler::ReadElementLC calling READELEMENTLC again") );

			/* Call ReadElementLC wiht aForceDefault set to TRUE */
			returnValue = ReadElementLC( aId, ETrue );

			if ( returnValue )
			    {
				TRACE( T_LIT( "CBSBrandHandler::ReadElementLC VALUE IS FOUND!!!") );
			    popElementFromCleanupStack = ETrue;
			    }
			else
				{
				TRACE( T_LIT( "CBSBrandHandler::ReadElementLC VALUE IS NOT FOUND!!!") );
				CleanupStack :: Pop (returnValue);
				}
			}
		if( !returnValue )
			{
			TRACE( T_LIT( "CBSBrandHandler::ReadElementLC VALUE not FOUND LEAVING WITH -1 !!!") );
			User::Leave( KErrNotFound );			
			}
		}
	
	CleanupClosePushL( *returnValue );
    // since we make one function call to ReadElementLC in case the default 
	// brand id is used to retrieved the element, we have to pop one returnValue
	// pointer from CleanupStack (otherwise we have two identical pointers on 
	// the stack!!!)
	if ( popElementFromCleanupStack )
   		{
   	 	CleanupStack::Pop( returnValue );
    	}
	
	TRACE( T_LIT( "CBSBrandHandler::ReadElementLC end ") );
	return returnValue;
	}
Ejemplo n.º 26
0
TVerdict CKeyDerivationStep::doTestStepPreambleL()
	{
	ConstructL();
	
	CTlsCryptoAttributes* atts = Provider()->Attributes();
	
	// Reads PSK values if included in INI file.
	ReadPskToBeUsedL();
	
	// Reads if NULL ciphers suites are to be allowed from INI file.
	ReadUseNullCipher();
	
	// read the "server" random
	HBufC8* random = ServerRandomL();
	atts->iMasterSecretInput.iServerRandom.Copy(*random);
	delete random;
	
	// and the client random
	random = ClientRandomL();
	atts->iMasterSecretInput.iClientRandom.Copy(*random);
	delete random;
	
	// we only support null compression...
	atts->iCompressionMethod = ENullCompression;
	
	// read the cipher suite for the test
	atts->iCurrentCipherSuite = CipherSuiteL();
	
	// read the protocol version
	TTLSProtocolVersion version = ProtocolVersionL();
	atts->iNegotiatedProtocol = version;
	atts->iProposedProtocol = version;
	
	// set the session ID and "server" name (localhost)
	atts->iSessionNameAndID.iSessionId = SessionId();
	atts->iSessionNameAndID.iServerName.iAddress = KLocalHost; 
	atts->iSessionNameAndID.iServerName.iPort = 443;
	atts->idomainName.Copy(DomainNameL());
	
	// try and read DH params, this section may not exist
	RInteger gen;
	CleanupClosePushL(gen);
	
	RInteger prime;
	CleanupClosePushL(prime);
	
	// If cipher suite under test is uses PSK (Pre Shared Key)
	if(UsePsk())
		{
		// Populates values for PSK 
		atts->iPskConfigured = true;
		atts->iPublicKeyParams->iKeyType = EPsk;
		atts->iPublicKeyParams->iValue4 = PskIdentity();
		atts->iPublicKeyParams->iValue5 = PskKey();
		}
	else 
		{
		// If cipher suite under test is NOT PSK 
		TRAPD(err, ReadDHParamsL());
		if (err == KErrNone)
			{
			atts->iPublicKeyParams->iKeyType = EDHE;

			// The params are:
			// 1 - Prime
			// 2 - Generator
			// 3 - generator ^ random mod prime

			atts->iPublicKeyParams->iValue1 = Prime().BufferLC();
			CleanupStack::Pop(atts->iPublicKeyParams->iValue1);

			atts->iPublicKeyParams->iValue2 = Generator().BufferLC();
			CleanupStack::Pop(atts->iPublicKeyParams->iValue2);

			atts->iPublicKeyParams->iValue3 = KeyPair()->PublicKey().X().BufferLC();
			CleanupStack::Pop(atts->iPublicKeyParams->iValue3);

			}
		}
		
	CleanupStack::PopAndDestroy(2, &gen); // prime
	
	// No client authentication or dialogs for this test, please
	atts->iClientAuthenticate = EFalse;
	atts->iDialogNonAttendedMode = ETrue;
	
	if(UseNullCipher())
		{
		// Enables null cipher by setting appropiate parameter  
		atts->iAllowNullCipherSuites = ETrue;
 		}
	
	return EPass;
	}
Ejemplo n.º 27
0
/** Perform CTrackStep3 test step.
This test verifies that the Test Protocol Module correctly handles 
a Tracking MO-LR interrupted by X3P (push).

@return TVerdict test result code
*/
TVerdict CTrackStep3::doTestStepL()
	{
	INFO_PRINTF1(_L("\t********************************************************************"));
	INFO_PRINTF1(_L("\tTracking - the MO-LR is interrupted by X3P (push)"));
	INFO_PRINTF1(_L("\t********************************************************************"));
	INFO_PRINTF1(_L("- START -"));

	INFO_PRINTF1(_L("\tLBS -> AdviceSystemStatus (Tracking ON)"));
	iModule->AdviceSystemStatus(CLbsNetworkProtocolBase::ESystemStatusClientTracking);

	// Initiate MO-LR
	TLbsNetSessionId sessionId1(TUid::Uid(0x87654321), 0x1010);
	TLbsNetPosRequestOptionsAssistance options1;
	options1.SetNewClientConnected(ETrue);
	TLbsNetPosRequestQuality quality1;
	options1.SetRequestQuality(quality1);
	TLbsAsistanceDataGroup dataRequestMask1 = EAssistanceDataBadSatList;
	options1.SetDataRequestMask(dataRequestMask1);
	options1.SetPosMode(TPositionModuleInfo::ETechnologyTerminal | TPositionModuleInfo::ETechnologyAssisted);
	INFO_PRINTF1(_L("\tLBS -> RequestSelfLocation"));	
	iModule->RequestSelfLocation(sessionId1, options1);

	// Check network receives MO-LR request
	if (EFail == CheckNetworkCallbackL(
				CNetworkObserver::ERegisterLcsMoLr))
		{
		SetTestStepResult(EFail);
		return TestStepResult();
		}
	INFO_PRINTF1(_L("\t                                            RegisterLcsMoLr -> NET"));
	
	// Generate network Measurement Control
	INFO_PRINTF1(_L("\t                          ProcessMeasurementControlLocation <- NET"));
	TPositionInfo refLoc;
	RLbsAssistanceDataBuilderSet assistData;
	CleanupClosePushL(assistData);
	assistData.OpenL();
	SetDummyAssistanceData(assistData, dataRequestMask1);
	TLbsNetPosRequestQuality quality;
	iNetworkObserver->ProcessMeasurementControlLocationL(refLoc, assistData, quality);
	CleanupStack::PopAndDestroy(&assistData);

	// Check gateway receives Assistance data
	if (EFail == CheckGatewayCallbackL(CGatewayObserver::EProcessAssistanceData))
		{
		SetTestStepResult(EFail);
		return TestStepResult();
		}
	INFO_PRINTF1(_L("\tLBS <- ProcessAssistanceData"));

	// Check gateway receives Network Based location
	if (EFail == CheckGatewayCallbackL(CGatewayObserver::EProcessLocationUpdate))
		{
		SetTestStepResult(EFail);
		return TestStepResult();
		}
	INFO_PRINTF1(_L("\tLBS <- ProcessLocationUpdate"));

	// Check gateway receives Location Request
	if (EFail == CheckGatewayCallbackL(CGatewayObserver::EProcessLocationRequest) ||
		MLbsNetworkProtocolObserver::EServiceSelfLocation != iGatewayObserver->LocType())
		{
		SetTestStepResult(EFail);
		return TestStepResult();
		}
	INFO_PRINTF1(_L("\tLBS <- ProcessLocationRequest"));

	// Start an X3P (Push)
	INFO_PRINTF1(_L("\tLBS -> TransmitLocation (PUSH)"));
	TLbsNetSessionId sessionId2(TUid::Uid(KDummyUid), KX3pSessionId);
	iModule->RequestTransmitLocation(sessionId2, KX3pDestination(), KX3pPriorityPush);

	// Check network receives error for its location request
	if (EFail == CheckNetworkCallbackL(CNetworkObserver::EMeasurementControlFailure) ||
		KErrPositionHighPriorityReceive != iNetworkObserver->MeasurementFailure())
		{
		SetTestStepResult(EFail);
		return TestStepResult();
		}
	INFO_PRINTF1(_L("\tMeasurementControlFailure (KErrPositionHighPriorityReceive) -> NET"));
	
	// Check network session completed
	if (EFail == CheckNetworkCallbackL(CNetworkObserver::EReleaseLcsMoLr) ||
		KErrPositionHighPriorityReceive != iNetworkObserver->SessionCloseReason())
		{
		SetTestStepResult(EFail);
		return TestStepResult();
		}
	INFO_PRINTF1(_L("\t           ReleaseLcsMoLr (KErrPositionHighPriorityReceive) -> NET"));

	// Check tracking session completed
	if (EFail == CheckGatewayCallbackL(CGatewayObserver::EProcessSessionComplete) ||
		sessionId1 != iGatewayObserver->SessionIdValue() ||
		KErrPositionHighPriorityReceive != iGatewayObserver->SessionCloseReason())
		{
		SetTestStepResult(EFail);
		return TestStepResult();
		}
	INFO_PRINTF1(_L("\tLBS <- ProcessSessionComplete (KErrPositionHighPriorityReceive)"));

	// Check network receives X3P request
	if (EFail == CheckNetworkCallbackL(CNetworkObserver::ERegisterLcsMoLr) ||
		KX3pDestination() != iNetworkObserver->X3pDestination())
		{
		SetTestStepResult(EFail);
		return TestStepResult();
		}
	INFO_PRINTF1(_L("\t                                            RegisterLcsMoLr -> NET"));

	INFO_PRINTF1(_L("*** Remainder of X3P is ignored for this test"));

	// Check if more observer activity takes place
	if (iGatewayObserver->IsMoreObserverActivity() ||
		iNetworkObserver->IsMoreObserverActivity())
		{
		SetTestStepResult(EFail);
		return TestStepResult();
		}
	
	INFO_PRINTF1(_L("- END -"));
	SetTestStepResult(EPass);
	return TestStepResult();
	}
//creates a trigger of type aType(EntryTrigger/ExitTrigger), with the coordinates and radius as
//supplied in the argument
bool  QMLBackendMonitorCreateTriggerAO::InitializeTrigger(QGeoAreaMonitorS60* aParent ,
        enTriggerType aType,
        TCoordinate& aCoordinate,
        qreal& aRadius)
{
    TInt ret = KErrGeneral;

    TLbtTriggerId triggerID = NULL;

    //try retrieving the trigger information from the linked list corresponding to the aParent and aType
    CMonitorTriggerInfo* triggerInfo = iTriggerMonitorInfo->getMonitorTriggerInfo(aParent, aType);

    //if no triggerinfo available in the linked list
    if (triggerInfo ==  NULL) {
        //Define the triggering area
        CLbtGeoCircle* trigArea = NULL;

        TRAP(ret, trigArea = CLbtGeoCircle::NewL(
                                 aCoordinate ,//center coordinate
                                 aRadius               //radius in meters. If
                                 //NaN is used, Location
                                 //Triggering Server will
                                 //use minimal size of trigger
                                 //area as the radius of the
                                 //trigger
                             ));

        if ((ret != KErrNone) || !trigArea)
            return FALSE;

        CleanupStack::PushL(trigArea);

        CLbtTriggerConditionArea* cond = NULL;

        if (aType == EntryTrigger) {
            //2: Construct a entry type of trigger condition
            TRAP(ret, cond = CLbtTriggerConditionArea::NewL(
                                 trigArea,
                                 CLbtTriggerConditionArea::EFireOnEnter
                             ));
        } else if (aType == ExitTrigger) {
            TRAP(ret, cond = CLbtTriggerConditionArea::NewL(
                                 trigArea,
                                 CLbtTriggerConditionArea::EFireOnExit
                             ));
        }


        if ((ret != KErrNone) || !cond) {
            CleanupStack::PopAndDestroy(trigArea);
            return FALSE;
        }

        CleanupStack::Pop(trigArea);   //ownership of trigArea is transferred.

        CleanupStack::PushL(cond);

        RRequestorStack reqStack;

        CleanupClosePushL(reqStack);

        //trigger name.
        _LIT(KMyTriggerName, "EntryTrigger");
        TDesC triggerName(KMyTriggerName);

        if (aType == ExitTrigger) {
            _LIT(KMyTriggerName, "ExitTrigger");
            triggerName = KMyTriggerName;
        }

        //Construct requestor
        _LIT(KMyRequestorName, "QTLBTBackend");   //Application name used as requestor identifier

        CRequestor *req = NULL;

        TRAP(ret, req = CRequestor::NewL(
                            CRequestorBase::ERequestorService,
                            CRequestorBase::EFormatApplication,
                            KMyRequestorName
                        ));

        if ((ret != KErrNone) || !req) {
            CleanupStack::PopAndDestroy(&reqStack);
            CleanupStack::PopAndDestroy(cond);
            return FALSE;
        }

        CleanupStack::PushL(req);

        TRAP(ret, reqStack.AppendL(req));

        CleanupStack::Pop(req);

        if (ret != KErrNone) {
            CleanupStack::PopAndDestroy(&reqStack);
            CleanupStack::PopAndDestroy(cond);
            return FALSE;
        }

        TUid managerUid = TUid::Uid(0);

        CLbtSessionTrigger* trig = NULL;

        TRAP(ret, trig =  CLbtSessionTrigger::NewL(
                              triggerName,
                              CLbtTriggerEntry::EStateDisabled,
                              reqStack,
                              managerUid,
                              cond
                          ));

        CleanupStack::PopAndDestroy(&reqStack);

        CleanupStack::Pop(cond);

        trig->SetTimeToRearm(0);

        if ((ret != KErrNone) || (!trig)) {
            CleanupStack::PopAndDestroy(cond);
            return FALSE;
        }

        CleanupStack::PushL(trig);

        //iLbt.CreateTrigger(*trig, triggerID, ETrue, iStatus);

        //CleanupStack::PopAndDestroy(trig );

        TRAP(ret, iActiveSchedulerwait = new(ELeave) CActiveSchedulerWait);

        if ((ret != KErrNone) || !iActiveSchedulerwait) {
            CleanupStack::PopAndDestroy(trig);
            return FALSE;
        }

        iTriggerCreation = FALSE;

        //create a trigger asynchronously
        iLbt.CreateTrigger(*trig, triggerID, ETrue, iStatus);

        SetActive();

        //wait till the iActiveSchedularwait->AsyncStop() is called in RunL
        iActiveSchedulerwait->Start();

        delete iActiveSchedulerwait;

        CleanupStack::PopAndDestroy(trig);

        //if the trigger creation is successful, add the triggerinfo to the linked list
        if (iTriggerCreation == TRUE)
            iTriggerMonitorInfo->addMonitorTriggerInfo(aParent, triggerID, aType);

        delete req;

        return iTriggerCreation;
    } else {     //triggerinfo available in the linked list

        CLbtSessionTrigger* trig = NULL;

        //Define the triggering area
        CLbtGeoCircle* trigArea = NULL;

        TRAP(ret, trigArea = CLbtGeoCircle::NewL(
                                 aCoordinate ,   //center coordinate
                                 aRadius          //radius in meters. If
                                 //NaN is used, Location
                                 //Triggering Server will
                                 //use minimal size of trigger
                                 //area as the radius of the
                                 //trigger
                             ));

        if ((ret != KErrNone) || (!trigArea)) {

            return FALSE;
        }

        CleanupStack::PushL(trigArea);

        //2: Construct a entry type of trigger condition
        CLbtTriggerConditionArea* cond = NULL;

        if (aType == EntryTrigger) {
            //2: Construct a entry type of trigger condition
            TRAP(ret, cond = CLbtTriggerConditionArea::NewL(
                                 trigArea,
                                 CLbtTriggerConditionArea::EFireOnEnter
                             ));
        } else if (aType == ExitTrigger) {
            TRAP(ret, cond = CLbtTriggerConditionArea::NewL(
                                 trigArea,
                                 CLbtTriggerConditionArea::EFireOnExit
                             ));
        }


        if ((ret != KErrNone) || !cond) {
            CleanupStack::PopAndDestroy(trigArea);
            return FALSE;
        }

        CleanupStack::Pop(trigArea);   //ownership of trigArea is transferred.

        CleanupStack::PushL(cond);

        //create a session trigger
        TRAP(ret, trig = CLbtSessionTrigger::NewL());

        if ((ret != KErrNone) || (!trig)) {
            CleanupStack::PopAndDestroy(cond);
            return FALSE;
        }

        //set the condition for the trigger
        trig->SetCondition(cond);

        CleanupStack::Pop(cond);

        CleanupStack::PushL(trig);

        //set the trigger ID
        trig->SetId(triggerInfo->iTriggerID);

        iLbt.SetTriggerStateL(triggerInfo->iTriggerID, CLbtTriggerEntry::EStateDisabled, ELbtTrue);

        //update the trigger with the new condition in LBT server
        TRAP(ret, iLbt.UpdateTriggerL(*trig, CLbtTriggerEntry::EAttributeCondition, ELbtTrue));

        CleanupStack::PopAndDestroy(trig);


        if (ret != KErrNone) {
            return FALSE;;
        }

        return TRUE;
    }
}
Ejemplo n.º 29
0
/**
 * Utility fcn to compare two files ( skip or not skip white space ).
 * @param aSrcFile full filename of a file you want to check/compare.
 * @param aVerificationFile fill filename of a correct output file, aSrcFile will be compared to this to verify it's validity.
 * @param aSkipWhiteSpace do not include whitespace when comparing the two files.
 * @return Symbian OS error code.
 */
TInt CMultipartTestContainer::CompareFilesL( TPtrC aSrcFile, TPtrC aVerificationFile,
																				 TBool aSkipWhiteSpace)
{
    _LIT(KSourceFileError,"Source file error.");
    _LIT(KPatternFileError,"Pattern file error.");
    _LIT(KComparePassed,"Files compare test PASSED.");
    _LIT(KCompareFailed,"Files compare test FAILED.");
    
    TInt nResult = KErrNone;
    
    TBool skipWhite = FALSE;
    TBool foundRes = FALSE;
    TBool foundRef = FALSE;
    
    RFs fs;
	User::LeaveIfError(fs.Connect());
	CleanupClosePushL(fs);
    
    RFile srcFile;
    RFile referenceFile;

    TFileName srcFileName;
	TFileName referenceFileName;
    
  TPtrC SrcFile = aSrcFile;
  TPtrC ReferenceFile = aVerificationFile;
	if (aSkipWhiteSpace)
	 {
		 skipWhite = TRUE;
	 }	
    
    if ( nResult == KErrNone )
	{
		srcFileName.Copy(SrcFile);
		referenceFileName.Copy(ReferenceFile);

	    if(srcFile.Open(fs, srcFileName, EFileStream|EFileRead) == KErrNone)
		{
			// Does reference file exist.
			if(referenceFile.Open(fs, referenceFileName, EFileStream|EFileRead) == KErrNone)
		    {
		        // Integer variables for compare to length of files (result and reference).
		        TInt resSize;
		        TInt refSize;

		        srcFile.Size(resSize);
		        referenceFile.Size(refSize);

	            // Next compare one letter at the time, but only if files have same length.
	            if(skipWhite)
		        {
			        TBuf8<1> resBuf;
			        TBuf8<1> refBuf;
			        nResult = KErrNone;
			        TInt j = 0;
			        TInt i = 0;
			        
			        //for(TInt i = 0; i < Size; i++)
			        while (TRUE)
				    {
				    	foundRes = FALSE;
				    	foundRef = FALSE;
				        // Read result file
				        while(i < (resSize + 1))
				        {
				        	i++;
				        	srcFile.Read(resBuf);
				        	resBuf.Trim();	
				        	if ( resBuf.Length() > 0)
				        	{
				        		foundRes = TRUE;
				        		break;
				        	}
				        }
						
						// Read reference file
				        while(j < (refSize + 1))
				        {
				        	j++;
				        	referenceFile.Read(refBuf);
				        	refBuf.Trim();
				        	if ( refBuf.Length() > 0)
				        	{
				        		foundRef = TRUE;
				        		break;
				        	}
				        }
				        
				        // Compare single letter at the time.
				        if( ( i < resSize ) && ( j < refSize ) && (resBuf[0] != refBuf[0]) )
				        {
					        nResult = KErrGeneral;
					        break;
					    }
					    if( (i == (resSize + 1)) && (j < refSize) && foundRef)
				    	{
					    	nResult = KErrGeneral;
					        break;
				    	}
					    if( (i < resSize) && (j == (refSize + 1)) && foundRes)
				    	{
					    	nResult = KErrGeneral;
					        break;
				    	}
				    	if ((i > resSize) && (j > refSize))
				    		break;
				    }
			    }
		        else
			    {
			        if (resSize != refSize)
			       		nResult = KErrGeneral;
			        else
		        	{
				        TBuf8<1> resBuf;
			        	TBuf8<1> refBuf;
			        	nResult = KErrNone;
			        	for(TInt i = 0; i < resSize; i++)
			        	{
				        	// Read result file
				        	srcFile.Read(resBuf);

					        // Read reference file
					        referenceFile.Read(refBuf);

					        // Compare single letter at the time.

					        if(resBuf[0] != refBuf[0])
					        {
						        nResult = KErrGeneral;
					    	    break;
				        	}
			        	}
		        	}
			    }
	            referenceFile.Close();
	            srcFile.Close();
			}
			else
			{
				nResult = KErrGeneral;
				INFO_PRINTF1(KPatternFileError);
			}
			srcFile.Close();
		}
		else
		{
			nResult = KErrGeneral;
			INFO_PRINTF1(KSourceFileError);
		}
			
	}
	
	CleanupStack::PopAndDestroy(&fs);
	
	if ( nResult == KErrNone)
		{
		INFO_PRINTF1(KComparePassed);
		}
	else
		{
		INFO_PRINTF1(KCompareFailed);
		}

	return nResult;
    }
/** This sanity test method is executed at the start of the test run to verify that UPT methods in
this class are stable before any of the performance tests are carried out

// what tests does it do?
 
@return KErrNone if command was prepared correctly and system wide error code otherwise.
 */
TInt CUptCsvGenerator::TestL()
	{
	//define filepaths for the test csv files according to the test platform.
#ifdef __WINSCW__
	_LIT(KTestFileAppend, "c:\\te_CSVoutputfileAppend.csv");
	_LIT(KTestFileOverwrite, "c:\\te_CSVoutputfileOverwrite.csv");
#else
	_LIT(KTestFileAppend, "e:\\te_CSVoutputfileAppend.csv");
	_LIT(KTestFileOverwrite, "e:\\te_CSVoutputfileOverwrite.csv");
#endif	

	//initialise some generic data to write to csv
	RArray<TInt64> atestdata1;
	RArray<TInt64> atestdata2;
	CleanupClosePushL(atestdata1); 
	CleanupClosePushL(atestdata2); 
		
	//data of the form:
	//0	1	2	3	4	5	6	7	8	9
	TInt data1element=10;
	for(TInt i=0; i!=data1element;i++)
		{
		atestdata1.Append((TInt64) i);
		}		
	//data of the form:
	//0	1000	2000	3000	4000	5000	6000	7000	8000	9000	10000	11000
	TInt data2element=12;
	for(TInt i=0; i!=data2element;i++)
		{
		atestdata2.Append((TInt64) i*1000);
		}
	
	
	//now test the CSV Generator functions
	//test the append data option - outputfile should contain an extra 6 lines of data of the form:
	// 0, 1, 2, 3, 4, 5, 6, 7, 8, 9
	// 0, 1000, 2000, 3000, 4000, 5000, 6000, 7000, 8000, 9000, 10000, 11000
	// 0, 1, 2, 3, 4, 5, 6, 7, 8, 9
	// 0, 1000, 2000, 3000, 4000, 5000, 6000, 7000, 8000, 9000, 10000, 11000
	// 0, 1, 2, 3, 4, 5, 6, 7, 8, 9
	// 0, 1000, 2000, 3000, 4000, 5000, 6000, 7000, 8000, 9000, 10000, 11000
	TInt appendcount=3;
	for(TInt i=0; i!=appendcount;i++)
		{ 
		OpenL(KTestFileAppend, ETrue);
		WriteL(atestdata1);
		WriteNewLineL();
		WriteL(atestdata2);
		WriteNewLineL();
		Close();	
		}

		
	//test the overwrite data option - outputfile should contain only 2 lines of data of the form:
	// 0, 1, 2, 3, 4, 5, 6, 7, 8, 9
	// 0, 1000, 2000, 3000, 4000, 5000, 6000, 7000, 8000, 9000, 10000, 11000
	for(TInt i=0; i!=appendcount;i++)
		{
		OpenL(KTestFileOverwrite, EFalse);
		WriteL(atestdata1);
		WriteNewLineL();
		WriteL(atestdata2);
		WriteNewLineL();
		Close();	
		}

	// read the files back to check they are valid, as an automated check
	
	RFs fsSession;
	RFile appendfile;
	RFile overwritefile;
	TInt filesize;
	User::LeaveIfError(fsSession.Connect());
	
	//sizes in bytes of generated output csv data
	TInt appendsize=appendcount*(sizeof(atestdata1)+sizeof(atestdata2)+2*sizeof(KCsvNewLine)+(data1element+data2element)*sizeof(KCsvComma));
	TInt overwritesize=(sizeof(atestdata1)+sizeof(atestdata2)+2*sizeof(KCsvNewLine)+(data1element+data2element)*sizeof(KCsvComma));
	
	// fill buffers used for data read from the outputted file
	RBuf8 readappendfile;
	readappendfile.CreateL(appendsize);
	RBuf8 readoverwritefile;
	readoverwritefile.CreateL(overwritesize);
	CleanupClosePushL(readappendfile); 
	CleanupClosePushL(readoverwritefile); 

	// comparison data buffers used to contain the expected data
	RBuf8 acompareappend;
	acompareappend.CreateL(appendsize);	
	RBuf8 acompareoverwrite;
	acompareoverwrite.CreateL(overwritesize);
	CleanupClosePushL(acompareappend); 
	CleanupClosePushL(acompareoverwrite); 
		
	//fill comparison array for appended data
	TInt err=FillReferenceBuffer(acompareappend, appendcount, atestdata1, data1element, atestdata2, data2element);

	//first check the appended file by reading back the last 6 lines in the file and comparing with acompareappend
	if(err==KErrNone)
		{
		if(appendfile.Open(fsSession, KTestFileAppend, EFileRead))
			{
			if(appendfile.Size(filesize))	
				{
				if(appendfile.Read((filesize-sizeof(acompareappend)),readappendfile))
					{
					if(!readappendfile.Compare(acompareappend))
						err=KErrGeneral;
					}
				}
			}
		}
	// close test output csv file
	appendfile.Close();
	
	
	//given the above has passed,
	//fill comparison array for overwritten data			
	if(err==KErrNone)
		err=FillReferenceBuffer(acompareoverwrite, (TInt) 0, atestdata1, data1element, atestdata2, data2element);
	
	//check the overwritten file by reading back the only 2 lines in the file and comparing with acompareoverwrite
	//Note: as a thorough check- read from a zero offset
	if(err==KErrNone)
		{
		if(overwritefile.Open(fsSession, KTestFileOverwrite, EFileRead))
			{
			if(overwritefile.Size(filesize))	
				{
				if(overwritefile.Read(0,readoverwritefile))
					{
					if(!readoverwritefile.Compare(acompareoverwrite))
						err=KErrGeneral;
					}
				}
			}
		}
	// close test output csv file
	overwritefile.Close();
	CleanupStack::PopAndDestroy(&atestdata1); 
	CleanupStack::PopAndDestroy(&atestdata2); 
	CleanupStack::PopAndDestroy(&readappendfile); 
	CleanupStack::PopAndDestroy(&readoverwritefile); 
	CleanupStack::PopAndDestroy(&acompareappend); 
	CleanupStack::PopAndDestroy(&acompareoverwrite); 
	return err;
	}