void T_CntImageRescaler::testRescaleUtility() { // delete the possible image directory, it must not leave // even if the folder was not found. TRAPD( err, TCntImageRescaleUtility::DeleteImageDirectoryL() ); test( err == KErrNone ); // path for image directory, existense of the directory is not // checked TPath path = TCntImageRescaleUtility::ImageDirectoryL(); test( path.Length() > 0 ); test( path.Find(KImagesFolder) != KErrNotFound ); TPath dir = TCntImageRescaleUtility::CreateImageDirectoryL(); test( dir.Length() > 0 ); test( dir.Find( KImagesFolder) != KErrNotFound ); // make a test image file (empty file) RFs fs; CleanupClosePushL( fs ); User::LeaveIfError( fs.Connect() ); TPath imagePath; imagePath.Append( dir ); imagePath.Append( KImageName ); RFile file; CleanupClosePushL(file); User::LeaveIfError(file.Create( fs, imagePath, EFileWrite )); CleanupStack::PopAndDestroy(); CContactItem* item = CContactItem::NewLC(KUidContactCard); CContactItemField* field = CContactItemField::NewL( KStorageTypeText, KUidContactFieldCodImage ); field->SetMapping( KUidContactFieldVCardMapUnknown ); item->AddFieldL( *field ); // add image without GUID TRAPD( err2, TCntImageRescaleUtility::StoreImageFieldL( *item, imagePath ) ); test( err2 == KErrNone ); // then update with GUID value _LIT(KGuid, "guid"); TBufC<4> buffer ( KGuid ); item->SetUidStringL( buffer ); TRAPD( err3, TCntImageRescaleUtility::UpdateImageNameL( *item ) ); test( err3 == KErrNone ); CContactItemFieldSet& fields = item->CardFields(); TInt privateImageIndex = fields.Find( KUidContactFieldCodImage, KUidContactFieldVCardMapUnknown ); test( privateImageIndex != KErrNotFound ); TPtrC fieldText = fields[privateImageIndex].TextStorage()->Text(); // how it should look like TPath newPath; newPath.Append( TCntImageRescaleUtility::ImageDirectoryL() ); newPath.Append( buffer ); newPath.Append( KImageName ); RDebug::Print( _L("%S"), &newPath ); RDebug::Print( _L("%S"), &fieldText ); test( newPath.Compare(fieldText) == 0 ); BaflUtils::DeleteFile( fs, newPath ); CleanupStack::PopAndDestroy(2); // item, RFs }
TBool CSupLoginServiceProvider::ReadDataFromFileL() { __LOGSTR_TOFILE("CSupLoginServiceProvider::ReadDataFromFileL() begins"); // If current operation should be cancelled if (iCancelStatus) return EFalse; TBool retValue = ETrue; RFs fsSession; RFileReadStream readStream; // Read stream from file // Install read file session User::LeaveIfError(fsSession.Connect()); CleanupClosePushL(fsSession); TInt err = readStream.Open(fsSession, iSettingsFile, EFileStream | EFileRead | EFileShareExclusive); CleanupClosePushL(readStream); // If file does not exist - return EFalse if (err != KErrNone) { retValue = EFalse; __LOGSTR_TOFILE("CSupLoginServiceProvider::ReadDataFromFileL() failed to open"); } if (retValue) { TInt valueMaxLen = 0; HBufC8* tempValue = NULL; // iMemberID valueMaxLen = readStream.ReadInt32L(); __LOGSTR_TOFILE("CSupLoginServiceProvider::ReadDataFromFileL() reading member id"); tempValue = HBufC8::NewL(readStream, valueMaxLen); if (tempValue) { if (iMemberID) { delete iMemberID; iMemberID = NULL; } iMemberID = tempValue->Des().AllocL(); delete tempValue; tempValue = NULL; } // iUsername valueMaxLen = readStream.ReadInt32L(); __LOGSTR_TOFILE("CSupLoginServiceProvider::ReadDataFromFileL() reading username"); tempValue = HBufC8::NewL(readStream, valueMaxLen); if (tempValue) { if (iUsername) { delete iUsername; iUsername = NULL; } iUsername = tempValue->Des().AllocL(); delete tempValue; tempValue = NULL; } // iPassword valueMaxLen = readStream.ReadInt32L(); __LOGSTR_TOFILE("CSupLoginServiceProvider::ReadDataFromFileL() reading password"); tempValue = HBufC8::NewL(readStream, valueMaxLen); if (tempValue) { if (iPassword) { delete iPassword; iPassword = NULL; } iPassword = tempValue->Des().AllocL(); delete tempValue; tempValue = NULL; } } // Free resource handlers CleanupStack::PopAndDestroy(&readStream); CleanupStack::PopAndDestroy(&fsSession); __LOGSTR_TOFILE("CSupLoginServiceProvider::ReadDataFromFileL() ends"); return retValue; }
/** * 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; }
//Gets the available space of the tested drive. static TInt64 FreeDiskSpaceL() { TVolumeInfo volInfoBefore; LEAVE_IF_ERROR(TheFs.Volume(volInfoBefore, KTestDrive)); return volInfoBefore.iFree; }
/** 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; }
/** * 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(); }
/** Function : ExecuteActionL Description : Entry point for the this test action in the test framework @internalTechnology @param : none @return : void @pre none @post none */ void CMtfTestActionSetDiskSpace::ExecuteActionL() { TestCase().INFO_PRINTF2(_L("Test Action %S start..."), &KTestActionSetDiskSpace ); RFs fs; User::LeaveIfError(fs.Connect()); TInt newFreeValue = ObtainValueParameterL<TInt>(TestCase(),ActionParameters().Parameter(0)); TestCase().INFO_PRINTF2(_L("Setting Drive C free disk space to %ld bytes."), newFreeValue); // // Check the current disk space available level... // TVolumeInfo volumeInfo; User::LeaveIfError(fs.Volume(volumeInfo, EDriveC)); TestCase().INFO_PRINTF2(_L(" Drive C currently has %ld bytes free."), volumeInfo.iFree); // // Check that this is possible... // if (volumeInfo.iFree < newFreeValue) { TestCase().INFO_PRINTF1(_L(" Drive C already has too little free space!")); User::Leave(KErrArgument); } // // Ensure the temporary directory exists... // TInt ret; ret = fs.MkDir(KTempDiskSpaceDirName); if (ret != KErrNone && ret != KErrAlreadyExists) { User::Leave(ret); } // // Work out how many files to create and their sizes. A full temp file is // 1GB in size, the last temp file will handle the remainder. Then loop // through and create them all... // TInt64 maxSizeOfTempFile = (1024*1024*1024); TInt64 diskSpaceToReserve = volumeInfo.iFree - newFreeValue; TInt64 numOfFullTempFiles = (diskSpaceToReserve / maxSizeOfTempFile); TInt64 lastTempFileSize = (diskSpaceToReserve % maxSizeOfTempFile); TBuf<32> tempFileName; RFile file; for(TInt fileNum = 1; fileNum <= numOfFullTempFiles; fileNum++) { tempFileName.Copy(KTempDiskSpaceDirName); tempFileName.AppendFormat(_L("reserved.%d"), fileNum); TestCase().INFO_PRINTF3(_L(" Creating %S of %ld bytes."), &tempFileName, maxSizeOfTempFile); User::LeaveIfError(file.Replace(fs, tempFileName, EFileWrite)); User::LeaveIfError(file.SetSize(maxSizeOfTempFile)); file.Close(); } if (lastTempFileSize > 0) { User::LeaveIfError(fs.Volume(volumeInfo, EDriveC)); TestCase().INFO_PRINTF2(_L(" Drive C now has %ld bytes free."), volumeInfo.iFree); if( lastTempFileSize > volumeInfo.iFree ) { lastTempFileSize = volumeInfo.iFree; } tempFileName.Copy(KTempDiskSpaceDirName); tempFileName.AppendFormat(_L("reserved.%d"), numOfFullTempFiles+1); TestCase().INFO_PRINTF3(_L(" Creating %S of %ld bytes."), &tempFileName, lastTempFileSize); User::LeaveIfError(file.Replace(fs, tempFileName, EFileWrite)); User::LeaveIfError(file.SetSize(lastTempFileSize)); file.Close(); } // // Recheck the free space now... // User::LeaveIfError(fs.Volume(volumeInfo, EDriveC)); TestCase().INFO_PRINTF2(_L(" Drive C now has %ld bytes free."), volumeInfo.iFree); fs.Close(); TestCase().INFO_PRINTF2( _L("Test Action %S completed."), &KTestActionSetDiskSpace ); TestCase().ActionCompletedL( *this ); }
TVerdict CHmacIncrementalHmacWithResetStep::doTestStepL() { if (TestStepResult()==EPass) { //Assume faliure, unless all is successful SetTestStepResult(EFail); INFO_PRINTF1(_L("*** Hmac - Incremental Hash with Reset ***")); INFO_PRINTF2(_L("HEAP CELLS: %d"), User::CountAllocCells()); TVariantPtrC algorithmUid; TVariantPtrC operationModeUid; TPtrC sourcePath; TPtrC expectedHash; TPtrC encryptKey; TVariantPtrC keyType; //Extract the Test Case ID parameter from the specified INI file if(!GetStringFromConfig(ConfigSection(),KConfigAlgorithmUid,algorithmUid) || !GetStringFromConfig(ConfigSection(),KConfigOperationMode,operationModeUid) || !GetStringFromConfig(ConfigSection(),KConfigSourcePath,sourcePath) || !GetStringFromConfig(ConfigSection(),KConfigExHashHmacValue,expectedHash) || !GetStringFromConfig(ConfigSection(),KConfigEncryptKey,encryptKey) || !GetStringFromConfig(ConfigSection(),KConfigEncryptKeyType,keyType)) { ERR_PRINTF1(_L("** Error: Failed to Load Configuration Parameters **")); SetTestStepResult(EFail); } else { //Create a pointer for the Hmac Implementation Object CHash* hmacImpl = NULL; //Convert encryption key to an 8 Bit Descriptor HBufC8* keyStr = HBufC8::NewLC(encryptKey.Length()); TPtr8 keyStrPtr = keyStr->Des(); keyStrPtr.Copy(encryptKey); //Create an new CryptoParams object to encapsulate the key type and secret key string CCryptoParams* keyParams = CCryptoParams::NewL(); CleanupStack::PushL(keyParams); keyParams->AddL(*keyStr,keyType); //Create Key Object TKeyProperty keyProperty; CKey* key=CKey::NewL(keyProperty,*keyParams); CleanupStack::PushL(key); //Retrieve a Hmac Factory Object TRAPD(err,CHashFactory::CreateHashL(hmacImpl, algorithmUid, operationModeUid, key, NULL)); if(hmacImpl && (err==KErrNone)) { //Push the Hmac Implementation Object onto the Cleanup Stack CleanupStack::PushL(hmacImpl); RFs fsSession; //Create a connection to the file server err = fsSession.Connect(); if(err != KErrNone) { ERR_PRINTF2(_L("*** Error: File Server Connection - %d ***"), err); SetTestStepResult(EFail); } else { RFile sourceFile; CleanupClosePushL(sourceFile); //Open the specified source file err = sourceFile.Open(fsSession,sourcePath, EFileRead); if(err != KErrNone) { ERR_PRINTF2(_L("*** Error: Opening Source File - %d ***"), err); SetTestStepResult(EFail); } else { TInt sourceLength = 0; TInt readPosition = 0; TInt readIncrement = 0; TBool hashComplete = EFalse; TBool hashReset = EFalse; TPtrC8 hashStr; User::LeaveIfError(sourceFile.Size(sourceLength)); //Divide the file size into seperate incremental blocks to read readIncrement = sourceLength/KDataReadBlocks; do { //Create a heap based descriptor to store the data HBufC8* sourceData = HBufC8::NewL(readIncrement); CleanupStack::PushL(sourceData); TPtr8 sourcePtr = sourceData->Des(); //Read in a block of data from the source file from the current position err = sourceFile.Read(readPosition,sourcePtr,readIncrement); //Update the read position by adding the number of bytes read readPosition += readIncrement; if(readPosition == readIncrement) { //Read in the first block from the data file into the Hmac implementation object hmacImpl->Hash(*sourceData); INFO_PRINTF2(_L("Intial Hmac - Bytes Read: %d"), readPosition); } else if(readPosition >= sourceLength) { //Reading in the final block, constructs the complete hash value and returns it within a TPtrC8 hashStr.Set(hmacImpl->Final(*sourceData)); //Sets the Complete Flag to ETrue in order to drop out of the loop hashComplete = ETrue; TInt totalRead = (readPosition - readIncrement) + (*sourceData).Length(); INFO_PRINTF2(_L("Final Hmac - Bytes Read: %d"),totalRead); } //If the read position is half the source length and the implementation //object hasn't already been reset else if((readPosition >= sourceLength/2) && (hashReset == EFalse)) { INFO_PRINTF1(_L("Resetting Hmac Object...")); hmacImpl->Reset(); //Sets the read position back to 0 inorder to restart the file read from the beginning readPosition = 0; hashReset = ETrue; INFO_PRINTF2(_L("*** HMAC RESET - Bytes Read: %d ***"), readPosition); } else { //Update the message data within the Hmac object with the new block hmacImpl->Update(*sourceData); INFO_PRINTF2(_L("Hmac Update - Bytes Read: %d"), readPosition); } CleanupStack::PopAndDestroy(sourceData); }while(hashComplete == EFalse); //Create a NULL TCharacteristics pointer const TCharacteristics* charsPtr(NULL); //Retrieve the characteristics for the hash implementation object TRAP_LOG(err, hmacImpl->GetCharacteristicsL(charsPtr)); //Static cast the characteristics to type THashCharacteristics const THashCharacteristics* hashCharsPtr = static_cast<const THashCharacteristics*>(charsPtr); //The hash output size is returned in Bits, divide by 8 to get the Byte size TInt hashSize = hashCharsPtr->iOutputSize/8; //Retrieve the final 8bit hash value and convert to 16bit HBufC* hashData = HBufC::NewLC(hashSize); TPtr hashPtr = hashData->Des(); hashPtr.Copy(hashStr); //Take the 16bit descriptor and convert the string to hexadecimal TVariantPtrC convertHash; convertHash.Set(hashPtr); HBufC* hmacResult = convertHash.HexStringLC(); INFO_PRINTF2(_L("*** Hashed Data: %S ***"),&*hmacResult); INFO_PRINTF2(_L("*** Expected Hash: %S ***"),&expectedHash); //If the returned hash value matches the expected hash, Pass the test if(*hmacResult == expectedHash) { INFO_PRINTF1(_L("*** Hmac - Incremental Hash with Reset : PASS ***")); SetTestStepResult(EPass); } else { ERR_PRINTF2(_L("*** FAIL: Hashed and Expected Value Mismatch ***"), err); SetTestStepResult(EFail); } CleanupStack::PopAndDestroy(hmacResult); CleanupStack::PopAndDestroy(hashData); } //Cleanup the Source RFile CleanupStack::PopAndDestroy(); } fsSession.Close(); CleanupStack::PopAndDestroy(hmacImpl); } else { ERR_PRINTF2(_L("*** FAIL: Failed to Create Hmac Object - %d ***"), err); SetTestStepResult(EFail); } CleanupStack::PopAndDestroy(key); CleanupStack::PopAndDestroy(keyParams); CleanupStack::PopAndDestroy(keyStr); } } INFO_PRINTF2(_L("HEAP CELLS: %d"), User::CountAllocCells()); return TestStepResult(); }
// Do the example LOCAL_C void doExampleL() { _LIT(KStatus0,"Connect to file server\n"); _LIT(KStatus1,"Connect to comm server\n"); _LIT(KStatus2,"Load IrCOMM.CSY\n"); _LIT(KStatus3,"Open IrCOMM::0\n"); _LIT(KStatus4,"Write to IrCOMM::0\n"); _LIT(KStatus5,"Close IrCOMM::0\n"); _LIT(KStatus6,"Close server connection\n"); _LIT(KIrCOMM,"IrCOMM"); _LIT(KIrCOMM0,"IrCOMM::0"); const TTimeIntervalMicroSeconds32 KTimeOut(4000000); //time-out value console->Printf(KStatus0); // force a link to the file server // so that we're sure the loader // will be present RFs f; User::LeaveIfError(f.Connect()); f.Close(); // Initialisation Init(); RCommServ server; // Connect to the comm server console->Printf(KStatus1); server.Connect(); // Load the IrCOMM comm module // C32 will automatically search \System\Libs // on all drives for IrCOMM.CSY console->Printf(KStatus2); TInt ret=server.LoadCommModule(KIrCOMM); //test(ret==KErrNone); User::LeaveIfError(ret); RComm commPort; // Open the IrCOMM port unit 0 (the only one supported) // Open port in exclusive mode because we don't // have any access control code. console->Printf(KStatus3); ret=commPort.Open(server,KIrCOMM0,ECommExclusive); //test(ret==KErrNone); User::LeaveIfError(ret); TRequestStatus status; // Write to the IrCOMM port - the first write // takes a long time as the IrDA connection is // set up in response to this request. Subsequent // writes to IrCOMM are very fast. console->Printf(KStatus4); commPort.Write(status,KTimeOut,DATA_STRING); User::WaitForRequest(status); //test(status.Int()==KErrNone); User::LeaveIfError(status.Int()); // Close port console->Printf(KStatus5); commPort.Close(); console->Printf(KStatus6); server.Close(); }
/** @SYMTestCaseID SYSLIB-SQL-UT-4060 @SYMTestCaseDesc Private database and compaction configuration test. The test verifies that a private database can be created using auto, background or manual compaction mode and that the compaction mode does not chage after reopening the database. The test also verifies that if the database is legacy, read-only, then the compaction mode is auto. The test also verifies that if the database is legacy, r/w, then the compaction mode will be changed from auto to background. @SYMTestPriority Medium @SYMTestActions Private database and compaction configuration test. @SYMTestExpectedResults Test must not fail @SYMREQ REQ10273 REQ10274 REQ10400 REQ10402 */ void CompactConfigTest5L() { //Create a private test database with "auto" compaction mode _LIT8(KConfigStr1, "encoding=utf-8;compaction=auto"); TInt err = TheDb.Create(KTestPrivDbName, &KConfigStr1); TEST2(err, KErrNone); //Check the vacuum mode. The SQLite vacuum mode should be "auto" TSqlScalarFullSelectQuery scalarQuery(TheDb); TInt compact = scalarQuery.SelectIntL(_L("PRAGMA auto_vacuum")); TEST2(compact, KAutoVacuum); TheDb.Close(); //Close and open the database again. The SQLite vacuum mode should be "auto". err = TheDb.Open(KTestPrivDbName); TEST2(err, KErrNone); scalarQuery.SetDatabase(TheDb); compact = scalarQuery.SelectIntL(_L("PRAGMA auto_vacuum")); TEST2(compact, KAutoVacuum); TheDb.Close(); //Close and open the database again with a config string with "background" compaction mode. //The SQLite vacuum mode should stay unchanged. _LIT8(KConfigStr2, "compaction=background"); err = TheDb.Open(KTestPrivDbName, &KConfigStr2); TEST2(err, KErrNone); scalarQuery.SetDatabase(TheDb); compact = scalarQuery.SelectIntL(_L("PRAGMA auto_vacuum")); TEST2(compact, KAutoVacuum); TheDb.Close(); //Delete database err = RSqlDatabase::Delete(KTestPrivDbName); TEST2(err, KErrNone); //Create a private test database - no config string err = TheDb.Create(KTestPrivDbName); TEST2(err, KErrNone); //Check the vacuum mode. The SQLite vacuum mode should be KSqlDefaultVacuum scalarQuery.SetDatabase(TheDb); compact = scalarQuery.SelectIntL(_L("PRAGMA auto_vacuum")); TEST2(compact, KSqlDefaultVacuum); TheDb.Close(); //Close and open the database again. The SQLite vacuum mode should be KSqlDefaultVacuum. err = TheDb.Open(KTestPrivDbName); TEST2(err, KErrNone); scalarQuery.SetDatabase(TheDb); compact = scalarQuery.SelectIntL(_L("PRAGMA auto_vacuum")); TEST2(compact, KSqlDefaultVacuum); TheDb.Close(); //Close and open the database again with a config string with "auto" compaction mode. //The SQLite vacuum mode should stay unchanged. err = TheDb.Open(KTestPrivDbName, &KConfigStr1); TEST2(err, KErrNone); scalarQuery.SetDatabase(TheDb); compact = scalarQuery.SelectIntL(_L("PRAGMA auto_vacuum")); TEST2(compact, KSqlDefaultVacuum); TheDb.Close(); //Delete database err = RSqlDatabase::Delete(KTestPrivDbName); TEST2(err, KErrNone); //Open an existing private database that is read-only (on drive Z:) err = TheDb.Open(KTestPrivDbNameZ, &KConfigStr1); TEST2(err, KErrNone); //Check the vacuum mode. The SQLite compact mode should be "auto" (this is an old database (pre-"background compact" era)) scalarQuery.SetDatabase(TheDb); compact = scalarQuery.SelectIntL(_L("PRAGMA auto_vacuum")); TEST2(compact, KAutoVacuum); TheDb.Close(); //Open the same database after copying it to drive C: (r/w private database). The compaction mode should change from auto to background. RFs fs; err = fs.Connect(); TEST2(err, KErrNone); CFileMan* fm = CFileMan::NewL(fs); TEST(fm != NULL); err = fm->Copy(KTestPrivDbNameZ, KTestPrivDbNameC); TEST2(err, KErrNone); //"Copy" operation executed without errors. Now it is a time to turn off the read-only //flag of the target file (which may be on if the source file is on a read-only drive) err = fs.SetAtt(KTestPrivDbNameC, 0, KEntryAttReadOnly); TEST2(err, KErrNone); delete fm; fs.Close(); err = TheDb.Open(KTestPrivDbNameC); TEST2(err, KErrNone); scalarQuery.SetDatabase(TheDb); compact = scalarQuery.SelectIntL(_L("PRAGMA auto_vacuum")); TEST2(compact, KSqlDefaultVacuum); TheDb.Close(); (void)RSqlDatabase::Delete(KTestPrivDbNameC); }
LOCAL_C void mainL() // initialize and call example code under cleanup stack { test.Title(); CTestConsole *con = CTestConsole::NewL(test.Console()); RFs fs; User::LeaveIfError(fs.Connect()); CleanupClosePushL(fs); TDriveUnit sysDrive (fs.GetSystemDrive()); TBuf<24> logFile (sysDrive.Name()); logFile.Append(_L("\\temblog.txt")); RFile file; User::LeaveIfError(file.Replace(fs, logFile, EFileShareAny|EFileWrite)); CleanupClosePushL(file); con->SetLogFile(file); test.SetConsole(con); TInt r; RDebug::Printf("Hello from user side\n"); test.Start(_L(" @SYMTestCaseID:SEC-CRYPTOSPI-TEMB-0001 Load driver ")); test.Next(_L("Loading Physical Device")); r=User::LoadPhysicalDevice(KPddFileName); test(r==KErrNone || r==KErrAlreadyExists); test.Next(_L("Loading Logical Device")); r=User::LoadLogicalDevice(KLddFileName); test(r==KErrNone || r==KErrAlreadyExists); // // Generate key and IV // test.Start(_L("Random - Generating key & IV for AES tests")); test.Printf(_L("\tGenerating random key\n")); // Generate random 16 byte key TBuf8<KEYLEN> key; key.SetLength(key.MaxLength()); TRandom::RandomL(key); key[0] = 'K'; key[1] = 'E'; key[2] = 'Y'; key[3] = '*'; for(int z=4; z<KEYLEN; ++z) key[z] = z; test.Printf(_L("\tGenerating random IV\n")); // Generate random 16 byte IV TBuf8<16> iv; iv.SetLength(iv.MaxLength()); TRandom::RandomL(iv); iv[0] = 'I'; iv[1] = 'V'; iv[2] = '*'; iv[3] = '*'; TBuf8<BUFLEN> plaintext; plaintext.FillZ(); plaintext.SetLength(BUFLEN); plaintext[0] = 'P'; plaintext[1] = 'L'; plaintext[2] = 'A'; plaintext[3] = 'I'; plaintext[4] = 'N'; for(int i=0; i<BUFLEN; ++i) { plaintext[i] = i; } // // KMS tests // test.Next(_L("KMS - Store key")); TBuf8<BUFLEN+16> kmsData; kmsData.FillZ(); kmsData.SetLength(0); do { RKeyMgmtSession kms; User::LeaveIfError(kms.Connect()); CleanupClosePushL(kms); TKeyHandle keyHandle; User::LeaveIfError(kms.StoreKey(key, keyHandle)); _LIT_SECURITY_POLICY_PASS(KAlwaysPass); User::LeaveIfError(kms.AddUsage(keyHandle, 0 /* operation */, KAlwaysPass)); test.Next(_L("KMS - Attempt to use key via embedded key handle")); TPckgBuf<TKeyHandle> keyHandlePkg; keyHandlePkg() = keyHandle; TKeyProperty keyProperty = {KAesUid, KNullUid, KSymmetricKeyUid, KNonExtractableKey}; CCryptoParams* keyParam =CCryptoParams::NewLC(); keyParam->AddL(keyHandlePkg, KSymmetricKeyParameterUid); CKey *ckey=CKey::NewL(keyProperty, *keyParam); CleanupStack::PopAndDestroy(keyParam); CleanupStack::PushL(ckey); CryptoSpi::CSymmetricCipher *aes = 0; CSymmetricCipherFactory::CreateSymmetricCipherL(aes, KAesUid, *ckey, KCryptoModeEncryptUid, KOperationModeCBCUid, KPaddingModePKCS7Uid, NULL); CleanupStack::PopAndDestroy(ckey); CleanupStack::PushL(aes); aes->SetOperationModeL(CryptoSpi::KOperationModeCBCUid); aes->SetIvL(iv); aes->ProcessFinalL(plaintext, kmsData); CleanupStack::PopAndDestroy(aes); CleanupStack::PopAndDestroy(&kms); } while(false); // // Encrypt using legacy API // TBuf8<BUFLEN+16> sw; sw.FillZ(); sw.SetLength(0); do { test.Next(_L("Encrypt using key directly (non-KMS)")); // ECB test.Printf(_L(" CBC\n")); CAESEncryptor *rawaes = CAESEncryptor::NewLC(key); // rawaes CModeCBCEncryptor *cbc = CModeCBCEncryptor::NewL(rawaes, iv); CleanupStack::Pop(rawaes); // CleanupStack::PushL(cbc); // cbc #ifdef PKCS7PAD CPadding *pad = CPaddingPKCS7::NewLC(16); // cbc, pad #else CPadding *pad = CPaddingNone::NewLC(16); // cbc, pad #endif CBufferedEncryptor *aes = CBufferedEncryptor::NewL(cbc, pad); CleanupStack::Pop(pad); // cbc CleanupStack::Pop(cbc); CleanupStack::PushL(aes); // aes test.Printf(_L("About to s/w encrypt (old api)\n")); aes->ProcessFinalL(plaintext, sw); CleanupStack::PopAndDestroy(aes); } while(false); test.Printf(_L("Checking KMS encrypt and direct encrypt had the same result\n")); test(kmsData == sw); test.End(); test.Printf(_L("\r\n0 tests failed out of 1\r\n")); // test.Printf(KTxtPressAnyKey); // test.Getch(); // get and ignore character test.Close(); CleanupStack::PopAndDestroy(&file); CleanupStack::PopAndDestroy(&fs); }
PJ_END_DECL /* Get Symbian phone model info, returning length of model info */ unsigned pj_symbianos_get_model_info(char *buf, unsigned buf_size) { pj_str_t model_name; /* Get machine UID */ TInt hal_val; HAL::Get(HAL::EMachineUid, hal_val); pj_ansi_snprintf(buf, buf_size, "0x%08X", hal_val); pj_strset2(&model_name, buf); /* Get model name */ const pj_str_t st_copyright = {"(C)", 3}; const pj_str_t st_nokia = {"Nokia", 5}; char tmp_buf[64]; pj_str_t tmp_str; _LIT(KModelFilename,"Z:\\resource\\versions\\model.txt"); RFile file; RFs fs; TInt err; fs.Connect(1); err = file.Open(fs, KModelFilename, EFileRead); if (err == KErrNone) { TFileText text; text.Set(file); TBuf16<64> ModelName16; err = text.Read(ModelName16); if (err == KErrNone) { TPtr8 ptr8((TUint8*)tmp_buf, sizeof(tmp_buf)); ptr8.Copy(ModelName16); pj_strset(&tmp_str, tmp_buf, ptr8.Length()); pj_strtrim(&tmp_str); } file.Close(); } fs.Close(); if (err != KErrNone) goto on_return; /* The retrieved model name is usually in long format, e.g: * "© Nokia N95 (01.01)", "(C) Nokia E52". As we need only * the short version, let's clean it up. */ /* Remove preceding non-ASCII chars, e.g: "©" */ char *p = tmp_str.ptr; while (!pj_isascii(*p)) { p++; } pj_strset(&tmp_str, p, tmp_str.slen - (p - tmp_str.ptr)); /* Remove "(C)" */ p = pj_stristr(&tmp_str, &st_copyright); if (p) { p += st_copyright.slen; pj_strset(&tmp_str, p, tmp_str.slen - (p - tmp_str.ptr)); } /* Remove "Nokia" */ p = pj_stristr(&tmp_str, &st_nokia); if (p) { p += st_nokia.slen; pj_strset(&tmp_str, p, tmp_str.slen - (p - tmp_str.ptr)); } /* Remove language version, e.g: "(01.01)" */ p = pj_strchr(&tmp_str, '('); if (p) { tmp_str.slen = p - tmp_str.ptr; } pj_strtrim(&tmp_str); if (tmp_str.slen == 0) goto on_return; if ((unsigned)tmp_str.slen > buf_size - model_name.slen - 3) tmp_str.slen = buf_size - model_name.slen - 3; pj_strcat2(&model_name, "("); pj_strcat(&model_name, &tmp_str); pj_strcat2(&model_name, ")"); /* Zero terminate */ buf[model_name.slen] = '\0'; on_return: return model_name.slen; }
void CMacBasicDataStep::doTestL() { INFO_PRINTF1(_L("*** Mac - Basic Data ***")); INFO_PRINTF2(_L("HEAP CELLS: %d"), User::CountAllocCells()); TVariantPtrC algorithmUid; TPtrC sourcePath; TPtrC expectedMac; TPtrC encryptKey; TVariantPtrC keyType; //Extract the Test Case ID parameter from the specified INI file if (!GetStringFromConfig(ConfigSection(),KConfigAlgorithmUid,algorithmUid) || !GetStringFromConfig(ConfigSection(),KConfigSourcePath,sourcePath) || !GetStringFromConfig(ConfigSection(),KConfigExMacValue,expectedMac)|| !GetStringFromConfig(ConfigSection(),KConfigEncryptKey,encryptKey) || !GetStringFromConfig(ConfigSection(),KConfigEncryptKeyType,keyType)) { ERR_PRINTF1(_L("** Error: Failed to Load Configuration Parameters **")); return; } //Create a pointer for the Mac Implementation Object CMac* macImpl = NULL; //Convert encryption key to an 8 Bit Descriptor HBufC8* keyStr = HBufC8::NewLC(encryptKey.Length()); TPtr8 keyStrPtr = keyStr->Des(); keyStrPtr.Copy(encryptKey); //Create an new CryptoParams object to encapsulate the key type and secret key string CCryptoParams* keyParams = CCryptoParams::NewL(); CleanupStack::PushL(keyParams); keyParams->AddL(*keyStr,keyType); //Create Key Object TKeyProperty keyProperty; CKey* key=CKey::NewL(keyProperty,*keyParams); CleanupStack::PushL(key); //Retrieve a Mac Factory Object TRAPD(err, CMacFactory::CreateMacL(macImpl, algorithmUid, *key, NULL)); if (err != KErrNone) { CleanupStack::PopAndDestroy(3, keyStr); // keyStr, keyParams, key delete macImpl; ERR_PRINTF2(_L("*** FAIL: Failed to Create Mac Object - %d ***"), err); User::Leave(err); } //Push the Mac Implementation Object onto the Cleanup Stack CleanupStack::PushL(macImpl); RFs fsSession; User::LeaveIfError(fsSession.Connect()); CleanupClosePushL(fsSession); RFile sourceFile; //Open the specified source file User::LeaveIfError(sourceFile.Open(fsSession,sourcePath, EFileRead)); CleanupClosePushL(sourceFile); TInt sourceLength = 0; User::LeaveIfError(sourceFile.Size(sourceLength)); //Create a heap based descriptor to store the data HBufC8* sourceData = HBufC8::NewL(sourceLength); CleanupStack::PushL(sourceData); TPtr8 sourcePtr = sourceData->Des(); sourceFile.Read(sourcePtr); if(sourcePtr.Length() != sourceLength) { ERR_PRINTF1(_L("*** Error: Reading Source File ***")); } else { //Create a NULL TCharacteristics pointer const TCharacteristics* charsPtr(NULL); //Retrieve the characteristics for the Mac implementation object TRAP_LOG(err, macImpl->GetCharacteristicsL(charsPtr)); //Static cast the characteristics to type TMacCharacteristics const TMacCharacteristics* macCharsPtr = static_cast<const TMacCharacteristics*>(charsPtr); //The mac output size is returned in Bits, divide by 8 to get the Byte size TInt macSize = macCharsPtr->iHashAlgorithmChar->iOutputSize/8; //Retrieve the final 8bit mac value and convert to 16bit HBufC* macData = HBufC::NewLC(macSize); TPtr macPtr = macData->Des(); // This is just a simple performance measurement on generating // the Mac TTime startTime; startTime.UniversalTime(); macPtr.Copy(macImpl->MacL(*sourceData)); TTime endTime; endTime.UniversalTime(); TTimeIntervalMicroSeconds time = endTime.MicroSecondsFrom(startTime); //Take the 16bit descriptor and convert the string to hexadecimal TVariantPtrC convertMac; convertMac.Set(macPtr); HBufC* macResult = convertMac.HexStringLC(); INFO_PRINTF2(_L("*** Mac: %S ***"), &*macResult); INFO_PRINTF2(_L("*** Expected Mac: %S ***"), &expectedMac); //If the returned mac value matches the expected mac, Pass the test if(*macResult == expectedMac) { INFO_PRINTF2(_L("*** Mac - Basic Data generated after setup in %d micro sec.: PASS ***"), time.Int64()); SetTestStepResult(EPass); } else { ERR_PRINTF1(_L("*** FAIL: Generated Mac and Expected Mac Mismatch ***")); } CleanupStack::PopAndDestroy(2, macData); // macData, macResult } CleanupStack::PopAndDestroy(7, keyStr); // keyStr, keyParams, key, macImpl, &fsSession, &sourceFile, sourceData INFO_PRINTF2(_L("HEAP CELLS: %d"), User::CountAllocCells()); }
TBool CSupLoginServiceProvider::WriteDataToFileL() { __LOGSTR_TOFILE("CSupLoginServiceProvider::WriteDataToFileL() begins"); // If current operation should be cancelled if (iCancelStatus) return EFalse; // Return value TBool retValue = EFalse; // If credentials data is not empty if (iMemberID && iUsername && iPassword) { retValue = ETrue; RFs fsSession; RFileWriteStream writeStream; // Write file stream // Install write file session User::LeaveIfError(fsSession.Connect()); CleanupClosePushL(fsSession); // Open file stream // if already exists - replace with newer version TInt err = writeStream.Replace(fsSession, iSettingsFile, EFileStream | EFileWrite | EFileShareExclusive); CleanupClosePushL(writeStream); // Return EFalse if failed to open stream if (err != KErrNone) { retValue = EFalse; __LOGSTR_TOFILE("CSupLoginServiceProvider::WriteDataToFileL() failed to open file"); } if (retValue) { __LOGSTR_TOFILE("CSupLoginServiceProvider::WriteDataToFileL() succeed to open the file"); // Write data // iMemberID writeStream.WriteInt32L(iMemberID->Des().MaxLength()); writeStream << *iMemberID; // iUsername writeStream.WriteInt32L(iUsername->Des().MaxLength()); writeStream << *iUsername; // iPassword writeStream.WriteInt32L(iPassword->Des().MaxLength()); writeStream << *iPassword; // Just to ensure that any buffered data is written to the stream writeStream.CommitL(); } // Free resource handlers CleanupStack::PopAndDestroy(&writeStream); CleanupStack::PopAndDestroy(&fsSession); } __LOGSTR_TOFILE("CSupLoginServiceProvider::WriteDataToFileL() ends"); return retValue; }
TInt64 CFileEngine::GetFreeSpace(const TDesC& aDriveName) { TVolumeInfo info; RFs iFs; User::LeaveIfError(iFs.Connect()); info.iFree = 0; if (aDriveName.CompareF(_L("A")) == 0) { iFs.Volume(info, EDriveA); } else if(aDriveName.CompareF(_L("B")) == 0) { iFs.Volume(info, EDriveB); } else if(aDriveName.CompareF(_L("C")) == 0) { iFs.Volume(info, EDriveC); } else if(aDriveName.CompareF(_L("D")) == 0) { iFs.Volume(info, EDriveD); } else if(aDriveName.CompareF(_L("E")) == 0) { iFs.Volume(info, EDriveE); } else if(aDriveName.CompareF(_L("F")) == 0) { iFs.Volume(info, EDriveF); } else if(aDriveName.CompareF(_L("G")) == 0) { iFs.Volume(info, EDriveG); } else if(aDriveName.CompareF(_L("H")) == 0) { iFs.Volume(info, EDriveH); } else if(aDriveName.CompareF(_L("I")) == 0) { iFs.Volume(info, EDriveI); } else if(aDriveName.CompareF(_L("J")) == 0) { iFs.Volume(info, EDriveJ); } else if(aDriveName.CompareF(_L("K")) == 0) { iFs.Volume(info, EDriveK); } else if(aDriveName.CompareF(_L("L")) == 0) { iFs.Volume(info, EDriveL); } else if(aDriveName.CompareF(_L("M")) == 0) { iFs.Volume(info, EDriveM); } else if(aDriveName.CompareF(_L("N")) == 0) { iFs.Volume(info, EDriveN); } else if(aDriveName.CompareF(_L("O")) == 0) { iFs.Volume(info, EDriveO); } else if (aDriveName.CompareF(_L("P")) == 0) { iFs.Volume(info, EDriveP); } else if(aDriveName.CompareF(_L("Q")) == 0) { iFs.Volume(info, EDriveQ); } else if(aDriveName.CompareF(_L("R")) == 0) { iFs.Volume(info, EDriveR); } else if(aDriveName.CompareF(_L("S")) == 0) { iFs.Volume(info, EDriveS); } else if(aDriveName.CompareF(_L("T")) == 0) { iFs.Volume(info, EDriveT); } else if(aDriveName.CompareF(_L("U")) == 0) { iFs.Volume(info, EDriveU); } else if(aDriveName.CompareF(_L("V")) == 0) { iFs.Volume(info, EDriveV); } else if(aDriveName.CompareF(_L("W")) == 0) { iFs.Volume(info, EDriveW); } else if(aDriveName.CompareF(_L("X")) == 0) { iFs.Volume(info, EDriveX); } else if(aDriveName.CompareF(_L("Y")) == 0) { iFs.Volume(info, EDriveY); } else if(aDriveName.CompareF(_L("Z")) == 0) { iFs.Volume(info, EDriveZ); } else { return 0; } iFs.Close(); return (TInt64)info.iFree/1024; }
// from CActive void CSmsLockEngine::RunL() { switch(iEngineStatus) { case EReadSMS: { CSmsBuffer *buf=CSmsBuffer::NewL(); CleanupStack::PushL(buf); RFs fs; fs.Connect(); #ifdef __UIQ__ CSmsMessage* message = CSmsMessage::NewL(fs, CSmsPDU::ESmsDeliver, buf); #else #ifdef __NOKIA6600__ CSmsMessage* message = CSmsMessage::NewL(fs, CSmsPDU::ESmsDeliver, buf); #else CSmsMessage* message = CSmsMessage::NewL(CSmsPDU::ESmsDeliver, buf); #endif #endif //CSmsMessage* message = CSmsMessage::NewL(fs, CSmsPDU::ESmsDeliver, buf,0); //CSmsMessage* message = CSmsMessage::NewL(CSmsPDU::ESmsDeliver, buf, 0); CleanupStack::Pop(); // buf CleanupStack::PushL(message); RSmsSocketReadStream readStream(iSocket); CleanupClosePushL(readStream); message->InternalizeL(readStream); TBuf<255> body; message->Buffer().Extract(body, 0, message->Buffer().Length()); iAppUi.iPassWord.Copy(body); iAppUi.iPassWord.Delete(0,7); TPtrC address = message->ToFromAddress(); iAppUi.iMobileNumber.Copy(address); //iAppUi.iMobileNumber.Copy(_L("9880002278")); CleanupStack::PopAndDestroy(2); // message, readStream fs.Close(); ChangeStatus(EProcessSMS); SetActive(); iSocket.Ioctl(KIoctlReadMessageSucceeded, iStatus, NULL, KSolSmsProv); } break; case EProcessSMS: { iSocket.Close(); TInt pos = 0; TBuf<10> web; pos = iAppUi.iPassWord.LocateReverse(' '); if(pos != -1) { if((iAppUi.iPassWord.Length()-(pos+1)) < 10) { web.Copy(iAppUi.iPassWord.Right(iAppUi.iPassWord.Length()-(pos+1))); web.LowerCase(); TInt pos1 = 0; pos1 = web.Compare(_L("web")); if(pos1 == 0) { iAppUi.iPassWord.Delete(pos, iAppUi.iPassWord.Length()-pos); } } iAppUi.CheckPasswordForLocking(3);//for web } else iAppUi.CheckPasswordForLocking(0);//for phone } break; default: break; } }
void CPerformanceInitialisationClient::CreateMessageL(const TMsvId aTMsvId,TInt aCount,TDesC& aBody,TPtrC& aAddress,TDesC& aSubject,TDesC& aAttachment1,TDesC& aAttachment2,TDesC& aAttachment3) { CParaFormatLayer* paraFormatLayer=CParaFormatLayer::NewL(); CleanupStack::PushL(paraFormatLayer); CCharFormatLayer* charFormatLayer=CCharFormatLayer::NewL(); CleanupStack::PushL(charFormatLayer); CRichText* bodyText=CRichText::NewL(paraFormatLayer, charFormatLayer, CEditableText::EFlatStorage, 256); CleanupStack::PushL(bodyText); if(aBody!=KNullFileName) { //read body text form a file RFs fsSession; User::LeaveIfError(fsSession.Connect()); RFile infile; User::LeaveIfError(infile.Open(fsSession, aBody, EFileRead)); TInt size; TInt err=infile.Size(size); HBufC8* filebuf; filebuf = HBufC8::NewLC(size); TPtr8 ptr8=filebuf->Des(); infile.Read(ptr8); HBufC* filebuf16; filebuf16 = HBufC::NewLC(size); TPtr ptr16=filebuf16->Des(); ptr16.Copy(ptr8); //insert the body text bodyText->InsertL(0, ptr16); infile.Close(); fsSession.Close(); CleanupStack::PopAndDestroy(2,filebuf); } for(TInt i=0;i<aCount;i++) { //create the message TMsvPartList partList = KMsvMessagePartBody; CImEmailOperation* emailOp = CImEmailOperation::CreateNewL(iTestActive->iStatus,*iSession,aTMsvId,partList,0,KUidMsgTypeSMTP); CleanupStack::PushL(emailOp); // Active object which stops the active scheduler iTestActive->StartL(); CActiveScheduler::Start(); // Get the new message id. TMsvId messageId; TPckg<TMsvId> param(messageId); param.Copy(emailOp->FinalProgress()); CleanupStack::PopAndDestroy(emailOp); // Save the message body text TMsvSelectionOrdering ordering; CMsvEntry* entry = CMsvEntry::NewL(*iSession, messageId,ordering); CleanupStack::PushL(entry); CImEmailMessage* message = CImEmailMessage::NewL(*entry); CleanupStack::PushL(message); //add attachments if(aAttachment1!=KNullFileName) { CMsvAttachment* attachmentInfo = CMsvAttachment::NewL(CMsvAttachment::EMsvFile); CleanupStack::PushL(attachmentInfo); message->AttachmentManager().AddAttachmentL(aAttachment1, attachmentInfo, iTestActive->iStatus); CleanupStack::Pop(attachmentInfo); iTestActive->StartL(); CActiveScheduler::Start(); // wait for the asynch operation to complete } if(aAttachment2!=KNullFileName) { CMsvAttachment* attachmentInfo = CMsvAttachment::NewL(CMsvAttachment::EMsvFile); CleanupStack::PushL(attachmentInfo); message->AttachmentManager().AddAttachmentL(aAttachment2, attachmentInfo, iTestActive->iStatus); CleanupStack::Pop(attachmentInfo); iTestActive->StartL(); CActiveScheduler::Start(); // wait for the asynch operation to complete } if(aAttachment3!=KNullFileName) { CMsvAttachment* attachmentInfo = CMsvAttachment::NewL(CMsvAttachment::EMsvFile); CleanupStack::PushL(attachmentInfo); message->AttachmentManager().AddAttachmentL(aAttachment3, attachmentInfo, iTestActive->iStatus); CleanupStack::Pop(attachmentInfo); iTestActive->StartL(); CActiveScheduler::Start(); // wait for the asynch operation to complete } iTestActive->StartL(); message->StoreBodyTextL(messageId, *bodyText, iTestActive->iStatus); CActiveScheduler::Start(); CleanupStack::PopAndDestroy(message); // fill in header details for email message CMsvStore* store = entry->EditStoreL(); CleanupStack::PushL(store); CImHeader* header = CImHeader::NewLC(); header->RestoreL(*store); header->ToRecipients().AppendL(aAddress); header->SetSubjectL(aSubject); header->StoreL(*store); store->CommitL(); CleanupStack::PopAndDestroy(3,entry); } CleanupStack::PopAndDestroy(3,paraFormatLayer); }
TVerdict CTestCalInterimApiDEF064928Step::doTestStepL() { CActiveScheduler* scheduler = new(ELeave)CActiveScheduler; CleanupStack::PushL(scheduler); CActiveScheduler::Install(scheduler); iSession = CCalSession::NewL(); CTestCalInterimApiCallbackForAlarms* alarmCallback = CTestCalInterimApiCallbackForAlarms::NewL(this); CleanupStack::PushL(alarmCallback); OpenSessionFileL(); iEntryView = CCalEntryView::NewL(*iSession,*alarmCallback); SetTestStepResult(EFail); CActiveScheduler::Add(alarmCallback); CActiveScheduler::Start(); TUint seqNo = 1; HBufC8* pGUID1= KAlarmExportTestGUID1().AllocLC(); CCalEntry* entry1 = CCalEntry::NewL(CCalEntry::EAppt, pGUID1, CCalEntry::EMethodAdd, seqNo); CleanupStack::Pop(pGUID1); // entry takes ownership CleanupStack::PushL(entry1); TDateTime entryStart1(2006, EJuly, 6, 15, 0, 0, 0); TCalTime calStart1; calStart1.SetTimeLocalL(entryStart1); TDateTime entryStop1(2006, EJuly, 6, 16, 0, 0, 0); TCalTime calStop1; calStop1.SetTimeLocalL(entryStop1); entry1->SetStartAndEndTimeL(calStart1, calStop1); TCalRRule* rpt = new (ELeave) TCalRRule(TCalRRule::EDaily); CleanupStack::PushL(rpt); rpt->SetInterval(1); TCalTime startTime; startTime.SetTimeLocalL(TDateTime(2006, EJuly, 6, 0, 0, 0, 0)); rpt->SetDtStart(startTime); TCalTime endTime; endTime.SetTimeLocalL(TDateTime(2006, EJuly, 10, 0, 0, 0, 0)); rpt->SetUntil(endTime); entry1->SetRRuleL(*rpt); // doesn't take ownership CleanupStack::PopAndDestroy(rpt); SaveToAgendaL(entry1, EFalse); seqNo++; HBufC8* pGUID2= KAlarmExportTestGUID2().AllocLC(); TDateTime entryTime2(2006, EJuly, 9, 15, 0, 0, 0); TCalTime calTime2; calTime2.SetTimeLocalL(entryTime2); CCalEntry* entry2 = CCalEntry::NewL(CCalEntry::EAppt, pGUID2, CCalEntry::EMethodAdd, seqNo, calTime2, CalCommon::EThisOnly); CleanupStack::Pop(pGUID2); // entry takes ownership CleanupStack::PushL(entry2); CreateExceptionDateL(entry2, entry1); RArray<TCalTime> exDateList1; CleanupClosePushL(exDateList1); entry1->GetExceptionDatesL(exDateList1); TESTL(exDateList1[0].TimeLocalL() == calTime2.TimeLocalL()); CleanupStack::PopAndDestroy(); //build the CCalDataExchange object and Export RFs fs; fs.Connect(); CleanupClosePushL(fs); CCalDataExchange* dataExchange = CCalDataExchange::NewL(*iSession); CleanupStack::PushL(dataExchange); RFile outFile; CleanupClosePushL(outFile); TInt err = outFile.Replace(fs, KEntryExportFile, EFileWrite); RFileWriteStream writeStream(outFile); CleanupClosePushL(writeStream); INFO_PRINTF1(KExporting); RPointerArray<CCalEntry> firstEntryArray; CleanupStack::PushL(TCleanupItem(CloseAndDeleteRPtrArrayEntries, &firstEntryArray)); iEntryView->FetchL(entry1->UidL(), firstEntryArray); dataExchange->ExportL(KUidVCalendar, writeStream, firstEntryArray); writeStream.CommitL(); // check that the exception date was stored correctly CCalEntry *fetchedEntry = firstEntryArray[0]; RArray<TCalTime> exDateList2; fetchedEntry->GetExceptionDatesL(exDateList2); CleanupClosePushL(exDateList2); TESTL(exDateList2[0].TimeLocalL() == calTime2.TimeLocalL()); CleanupStack::PopAndDestroy(); CleanupStack::PopAndDestroy(); CleanupStack::PopAndDestroy(&writeStream); // writeStream.Close() CleanupStack::PopAndDestroy(&outFile); // outFile.Close() //Internalize the entries from the file we just wrote RFile inFile; CleanupClosePushL(inFile); TInt errR = inFile.Open(fs, KEntryExportFile, EFileRead); RFileReadStream readStream(inFile); CleanupClosePushL(readStream); RPointerArray<CCalEntry> secondEntryArray; CleanupStack::PushL(TCleanupItem(CloseAndDeleteRPtrArrayEntries, &secondEntryArray)); INFO_PRINTF1(KImporting); dataExchange->ImportL(KUidVCalendar, readStream, secondEntryArray); CleanupStack::Pop(&secondEntryArray); CleanupStack::PopAndDestroy(&readStream); CleanupStack::PopAndDestroy(&inFile); CleanupStack::PushL(TCleanupItem(CloseAndDeleteRPtrArrayEntries, &secondEntryArray)); // check the imported alarm TESTL(secondEntryArray.Count() == 1); CCalEntry* entry = secondEntryArray[0]; RArray<TCalTime> importedExDate; entry->GetExceptionDatesL(importedExDate); TESTL(importedExDate.Count() == 1); TESTL(importedExDate[0].TimeLocalL() == calTime2.TimeLocalL()); CleanupStack::PopAndDestroy(7, scheduler); SetTestStepResult(EPass); return TestStepResult(); }
LOCAL_C void DoOOMTestsL() { TheTest.Next (_L (" @SYMTestCaseID:SYSLIB-CENTRALREPOSITORY-LEGACY-T_OOMCENREP-0001 Starting CENREPSRV OOM Test ")); RFs fs; User::LeaveIfError(fs.Connect()); CleanupClosePushL(fs); CFileMan* fm = CFileMan::NewL(fs); CleanupStack::PushL(fm); //Clear any files in the persist directory CleanupCDriveL(); //First Testuid=KTestRepositoryUid KCurrentTestUid=KTestRepositoryUid; DoOOMTestL(&CenrepSrvOOMTest::GetL,_L("Get Basic Test"),EFalse); DoOOMTestL(&CenrepSrvOOMTest::FindL,_L("FindL Basic Test"),EFalse); DoOOMTestL(&CenrepSrvOOMTest::NotifyL,_L("NotifyL Basic Test"),EFalse); DoOOMTestL(&CenrepSrvOOMTest::ResetL,_L("ResetL Basic Test"),EFalse); // Save file without timestamp User::LeaveIfError(fm->Copy(KPersistsFile, KPersistsFileNoUpgrade)); DoOOMTestL(&CenrepSrvOOMTest::SetL,_L("SetL Basic Test"),EFalse); DoOOMTestL(&CenrepSrvOOMTest::CreateL,_L("CreateL Basic Test"),EFalse); DoOOMTestL(&CenrepSrvOOMTest::DeleteL,_L("DeleteL Basic Test"),EFalse); DoOOMTestL(&CenrepSrvOOMTest::MoveL,_L("MoveL Basic Test"),EFalse); //Clear any files in the persist directory CleanupCDriveL(); // Simulate response to SWI rom-upgrade and downgrade events DoOOMSwiTestL(&CenrepSwiOOMTest::UpgradeROMRev1L,_L("SwiUpgradeROMRev1L Basic Test"),EFalse); // Save file with timestamp User::LeaveIfError(fm->Copy(KPersistsFile, KPersistsFileUpgraded)); DoOOMSwiTestL(&CenrepSwiOOMTest::UpgradeROMRev2L,_L("SwiUpgradeROMRev2L Basic Test"),EFalse); DoOOMSwiTestL(&CenrepSwiOOMTest::UninstallROMUpgradeL,_L("SwiUninstallROMUpgradeL Basic Test"),EFalse); // Simulate response to SWI new rep install/uninstall event events DoOOMSwiTestL(&CenrepSwiOOMTest::InstallL,_L("SwiInstallL Basic Test"),EFalse); DoOOMSwiTestL(&CenrepSwiOOMTest::UpgradeInstallL,_L("SwiUpgradeInstallL Basic Test"),EFalse); DoOOMSwiTestL(&CenrepSwiOOMTest::UninstallL,_L("SwiUninstallL Basic Test"),EFalse); // Simulate SWI events before server startup DoOOMNoServReposL(&StartupUpgradeL, _L("Startup Upgrade Basic Test"), EFalse); DoOOMNoServReposL(&StartupDowngradeL, _L("Startup Downgrade Basic Test"), EFalse); DoOOMNoServReposL(&StartupUninstallL,_L("Startup Uninstall Basic Test"), EFalse); //OOM Test aOOMMode=ETrue DoOOMNoServReposL(&CreateDeleteL, _L("Create Delete OOM Test"),ETrue); DoOOMNoServReposL(&CreateDeleteCorruptL, _L("Create Delete Corrupt OOM Test"),ETrue); DoOOMTestL(&CenrepSrvOOMTest::GetL,_L("Get OOM Test"),ETrue); DoOOMTestL(&CenrepSrvOOMTest::FindL,_L("FindL OOM Test"),ETrue); DoOOMTestL(&CenrepSrvOOMTest::NotifyL,_L("NotifyL OOM Test"),ETrue); DoOOMTestL(&CenrepSrvOOMTest::ResetL,_L("ResetL OOM Test"),ETrue); DoOOMTestL(&CenrepSrvOOMTest::SetL,_L("SetL OOM Test"),ETrue); DoOOMTestL(&CenrepSrvOOMTest::CreateL,_L("CreateL OOM Test"),ETrue); DoOOMTestL(&CenrepSrvOOMTest::DeleteL,_L("DeleteL OOM Test"),ETrue); DoOOMTestL(&CenrepSrvOOMTest::MoveL,_L("MoveL OOM Test"),ETrue); //Clear any files in the persist directory CleanupCDriveL(); DoOOMSwiTestL(&CenrepSwiOOMTest::UpgradeROMRev1L,_L("SwiUpgradeROMRev1L OOM Test"),ETrue); DoOOMSwiTestL(&CenrepSwiOOMTest::UpgradeROMRev2L,_L("SwiUpgradeROMRev2L OOM Test"),ETrue); DoOOMSwiTestL(&CenrepSwiOOMTest::UninstallROMUpgradeL,_L("SwiUninstallROMUpgradeL OOM Test"),ETrue); DoOOMSwiTestL(&CenrepSwiOOMTest::InstallL,_L("SwiInstallL OOM Test"),ETrue); DoOOMSwiTestL(&CenrepSwiOOMTest::UpgradeInstallL,_L("SwiUpgradeInstallL OOM Test"),ETrue); DoOOMSwiTestL(&CenrepSwiOOMTest::UninstallL,_L("SwiUninstallL OOM Test"),ETrue); DoOOMNoServReposL(&StartupUpgradeL, _L("Startup Upgrade OOM Test"), ETrue); DoOOMNoServReposL(&StartupDowngradeL, _L("Startup Downgrade OOM Test"), ETrue); DoOOMNoServReposL(&StartupUninstallL, _L("Startup Uninstall OOM Test"), ETrue); #ifdef SYMBIAN_CENTREP_SUPPORT_MULTIROFS DoPersistedVersionCheckingL(); DoOOMMultiRofsTestL(); #endif // Delete files from bur dir User::LeaveIfError(fm->Attribs(KPersistsFileNoUpgrade,0,KEntryAttReadOnly,TTime(0))); TInt err=fs.Delete(KPersistsFileNoUpgrade); if((err!=KErrNone)&&(err!=KErrNotFound)) User::Leave(err); User::LeaveIfError(fm->Attribs(KPersistsFileUpgraded,0,KEntryAttReadOnly,TTime(0))); err=fs.Delete(KPersistsFileUpgraded); if((err!=KErrNone)&&(err!=KErrNotFound)) User::Leave(err); //Clear any files in the persist directory CleanupCDriveL(); CleanupStack::PopAndDestroy (2); // fs and fm }