void CIniFileParser::DoParseIniFileL(TDesC& aIniFile) /* * * The force flush state is only updated if it is not already set to something other * than ENoValue. If force flush option is not found in ini file, force flush is set * to off. */ { TInt fileLength; TInt ret = KErrNone; RFile iniFile; // Open file User::LeaveIfError(iniFile.Open(iFs, aIniFile, EFileShareAny)); CleanupClosePushL(iniFile); // as we have been able to open the file, set the media to default. // If the ini file is parsed correctly, this then gets overwritten. // Otherwise the caller should pass thru a mesg to get the default enabled. if (iLoggingMediaString.Length() == 0) { iLoggingMediaString = KDefaultMedia; } User::LeaveIfError(iniFile.Size(fileLength)); HBufC8* iniContents = HBufC8::NewLC(fileLength); TPtr8 hbufPtr = iniContents->Des(); User::LeaveIfError(iniFile.Read(hbufPtr)); TLex8 lex(*iniContents); //OK, file is open and ready for parsing. Make a tempory array and if there is a //problem in the ini file leave settings as they were, leave, and //the error will get picked up. delete iIniSettings; iIniSettings = NULL; CIniLoggingPairs* iniSettings = CIniLoggingPairs::NewL(); CleanupStack::PushL(iniSettings); TNameTag tempTag; TNameTag tempTag2; TChar tempChar; FOREVER { ret = GetNextTokenAndCheck(lex,hbufPtr); if (ret != KErrNone) { break; } if (hbufPtr.Find(KCommentKeyword)!=KErrNotFound) //found a Comment { tempChar = lex.Get(); while (!lex.Eos() && TUint(tempChar) != KCarriageReturn && TUint(tempChar) != KLineFeed) { tempChar = lex.Get(); } } else if (hbufPtr.CompareF(KMediaKeyword)==0) //MediaSetting { User::LeaveIfError(GetNextTokenAndCheck(lex,hbufPtr)); if (hbufPtr.Length()>KMaxMediaStringLength) { User::Leave(KErrGeneral); } iLoggingMediaString = hbufPtr; } else if (hbufPtr.CompareF(KLogKeyword)==0) //LOG { User::LeaveIfError(GetNextTokenAndCheck(lex,hbufPtr)); if (hbufPtr.Length()>KMaxTagLength) { tempTag = hbufPtr.Left(KMaxTagLength); } else { tempTag = hbufPtr; } User::LeaveIfError(GetNextTokenAndCheck(lex,hbufPtr)); if (hbufPtr.Length()>KMaxTagLength) { tempTag2 = hbufPtr.Left(KMaxTagLength); } else { tempTag2 = hbufPtr; } iniSettings->AddSettingL(tempTag, tempTag2); } else if (hbufPtr.CompareF(KForceFlushKeyword)==0) //ForceFlush { if (iForceFlushState == ENoValue) { iForceFlushState = EFlushOn; } } else if (hbufPtr.CompareF(KLogPathKeyword) == 0) //LogPath { User::LeaveIfError(GetNextTokenAndCheck(lex,hbufPtr)); if (hbufPtr.Length()>KMaxName) { User::Leave(KErrOverflow); } iLoggingPathString.Copy(hbufPtr); } else if (hbufPtr.CompareF(KWin32DbgPortKeyword)==0) //Win32DebugPort { iWin32DebugEnabled = ETrue; } else User::Leave(KErrBadName); if (lex.Eos()) { break; } } iIniSettings = iniSettings; CleanupStack::Pop(iniSettings); CleanupStack::PopAndDestroy(); //iniContents CleanupStack::PopAndDestroy(); //iniFile if (iForceFlushState == ENoValue) { iForceFlushState = EFlushOff; } }
// ----------------------------------------------------------------------------- // CLibxml2Tester::TestUseExternalDataL // test deserialize from file, using external data // (other items were commented in a header). // ----------------------------------------------------------------------------- // TInt CLibxml2Tester::TestUseExternalDataInfosetL(CStifItemParser& aItem) { TInt err; TPtrC pDeserializerType; aItem.GetNextString( pDeserializerType ); TPtrC pInputFile; aItem.GetNextString( pInputFile ); TPtrC pBinary; aItem.GetNextString( pBinary ); TPtrC pFile; aItem.GetNextString(pFile); TPtrC pOutputFile; aItem.GetNextString( pOutputFile ); TPtrC pDirtyReturn; aItem.GetNextString( pDirtyReturn ); TLex inputNum (pDirtyReturn); TInt dirtyReturn; inputNum.Val(dirtyReturn); TInt nContainers = 3; RFile fileHandle; RFs aRFs; aRFs.Connect(); CleanupClosePushL( aRFs ); SetupDocumentL(); HBufC8* binbuf = ReadFileToBufferL(pBinary); CleanupStack::PushL(binbuf); TBufC<100> chunkName(_L("ChunkContainer") ); TInt size = 2000; TInt maxSize = 10000; TInt offset = 0; TInt binarySize = CID_2().Length(); // TBool isReadOnly = EFalse; RChunk chunk; chunk.CreateGlobal(chunkName, size, maxSize); CleanupClosePushL(chunk); RFile fp; User::LeaveIfError( fp.Open(aRFs, pFile, EFileRead) ); CleanupClosePushL(fp); TXmlEngBinaryContainer bincont = iDoc.CreateBinaryContainerL(CID_1(), binbuf->Des()); TXmlEngChunkContainer chunkcont = iDoc.CreateChunkContainerL(CID_2(), chunk, offset, binarySize); TXmlEngFileContainer filecont = iDoc.CreateFileContainerL(CID_3(), fp); iDoc.DocumentElement().AppendChildL(bincont); iDoc.DocumentElement().AppendChildL(chunkcont); iDoc.DocumentElement().AppendChildL(filecont); User::LeaveIfError( fileHandle.Replace( aRFs, pOutputFile, EFileStream | EFileWrite | EFileShareExclusive)); CleanupClosePushL( fileHandle ); CTestHandler* testHandle = CTestHandler::NewLC( fileHandle ); RArray<TXmlEngDataContainer> list; CleanupClosePushL(list); //// iDoc.GetDataContainerList(list); CXmlEngDeserializer* des; if( pDeserializerType.FindF( XOP ) != KErrNotFound ) { des = CXmlEngDeserializer::NewL( *testHandle, EDeserializerXOP ); CleanupStack::PushL( des ); des->SetInputFileL( pInputFile ); des->UseExternalDataL( list ); TRAP(err,des->DeserializeL()); } else if( pDeserializerType.FindF( INFOSET ) != KErrNotFound ) { des = CXmlEngDeserializer::NewL( *testHandle, EDeserializerXOPInfoset ); CleanupStack::PushL( des ); des->SetInputFileL( pInputFile ); des->UseExternalDataL( list ); TRAP(err,des->DeserializeL()); } if(list.Count() != nContainers) User::Leave(KErrGeneral); CleanupStack::PopAndDestroy( 8 ); if ( err == dirtyReturn ) return KErrNone; else return err; }
/** * Load and initialise an audio file. */ TVerdict CTestMmfVclntOpenFile0522::DoTestStepL() { TVerdict ret = EFail; INFO_PRINTF1(_L("Test : Video Recorder - OpenFileL(RFile&)")); RFs fs; RFile file; User::LeaveIfError(fs.Connect()); CleanupClosePushL(fs); User::LeaveIfError(fs.ShareProtected()); iError = KErrTimedOut; TPtrC filename; if(!GetStringFromConfig(iSectName,iKeyName,filename)) { return EInconclusive; } User::LeaveIfError(file.Open(fs,filename,EFileWrite)); CleanupClosePushL(file); CVideoRecorderUtility* rec = CVideoRecorderUtility::NewL(*this); CleanupStack::PushL(rec); const TUid KVidTstControllerUid = {KMmfVideoTestControllerUid}; TRAP(iError,rec->OpenFileL(file, NULL, KVidTstControllerUid, KUidMdaBmpClipFormat)); if(iError == KErrNone) { INFO_PRINTF1(_L("CVideoRecorderUtility: Open file")); // Wait for initialisation callback CActiveScheduler::Start(); } if(iError == KErrNotSupported) { ret = EPass; } // Check for errors. if ((iError == KErrNone) && (rec != NULL)) { rec->Prepare(); CActiveScheduler::Start(); if(iError != KErrNone) { INFO_PRINTF2(_L("Prepare callback : error %d"), iError); return EInconclusive; } if(iRec) { iError = KErrTimedOut; rec->Record(); INFO_PRINTF1(_L("CVideoRecorderUtility: Record")); // Wait for init callback CActiveScheduler::Start(); if(iError == KErrNone) { ret = EPass; } User::After(1000000); rec->Stop(); } else { ret = EPass; } } rec->Close(); INFO_PRINTF1(_L("CVideoRecorderUtility: Destroy")); CleanupStack::PopAndDestroy(rec); User::After(KOneSecond); // wait for deletion to shut down devsound if(iError != KErrNone) { ERR_PRINTF2( _L("CVideoRecorderUtility failed with error %d"),iError ); } CleanupStack::PopAndDestroy(2,&fs); return ret; }
TVerdict CTestMmfAclntOpenFile7905::DoTestStepL() { INFO_PRINTF1( _L("TestRecorder : Record File")); TVerdict ret = EFail; iError = KErrTimedOut; RFs fs; RFile file; User::LeaveIfError(fs.Connect()); CleanupClosePushL(fs); User::LeaveIfError(fs.ShareProtected()); TPtrC filename; if(!GetStringFromConfig(iSectName, iKeyName, filename)) { return EInconclusive; } CMdaAudioRecorderUtility* recUtil = CMdaAudioRecorderUtility::NewL(*this); CleanupStack::PushL(recUtil); TUid invalidAudioController; invalidAudioController.iUid = KInvalidAudioController; User::LeaveIfError(file.Replace(fs,filename,EFileWrite)); CleanupClosePushL(file); recUtil->OpenFileL(file, invalidAudioController, KNullUid, KNullUid, KFourCCNULL); INFO_PRINTF1( _L("Initialise CMdaAudioRecorderUtility")); CActiveScheduler::Start(); if( iError == KErrNotFound ) { ret = EPass; } if(iError == KErrNone) { iError = KErrTimedOut; recUtil->RecordL(); INFO_PRINTF1( _L("Record CMdaAudioRecorderUtility")); CActiveScheduler::Start(); // open -> record User::After(KFiveSeconds); recUtil->Stop(); } CleanupStack::PopAndDestroy(2, recUtil); recUtil = NULL; // Playback the file if (iError == KErrNone) { if (filename.Right(4).Compare(_L(".wav"))==0) { // Wav file playback CMdaAudioPlayerUtility* playUtil = CMdaAudioPlayerUtility::NewL(*this); CleanupStack::PushL(playUtil); TRAPD(err, playUtil->OpenFileL(filename)); if (err != KErrNone) { INFO_PRINTF2(_L("Error opening file for playback err = %d"), err); ret = EFail; } CActiveScheduler::Start(); if (iError != KErrNone) { INFO_PRINTF2(_L("Error opening file for playback iError = %d"), iError); ret = EFail; } playUtil->Play(); CActiveScheduler::Start(); CleanupStack::PopAndDestroy(playUtil); if (iError != KErrNone) { INFO_PRINTF2(_L("Error during playback of recorded file iError=%d"), iError); ret = EFail; } } } if( iError == KErrNone ) { RFile file; TInt size = 0; User::LeaveIfError(file.Open(fs,filename,EFileRead)); CleanupClosePushL(file); User::LeaveIfError(file.Size(size)); if(size > 0) { ret = EPass; } CleanupStack::PopAndDestroy(); //file } CleanupStack::PopAndDestroy(); // fs ERR_PRINTF2( _L("CMdaAudioRecorderUtility completed with error %d"),iError ); User::After(KOneSecond); return ret; }
// ----------------------------------------------------------------------------- // CLibxml2Tester::TestSetInputBufferL // test setting input buffer // (other items were commented in a header). // ----------------------------------------------------------------------------- // TInt CLibxml2Tester::TestSetInputBufferInfosetL(CStifItemParser& aItem) { TPtrC pType; aItem.GetNextString(pType); TPtrC pDoc; aItem.GetNextString(pDoc); TPtrC pOut; aItem.GetNextString(pOut); iDoc = parser.ParseFileL(pDoc); TBufC<100> chunkName(_L("ChunkContainer") ); TInt size = 2000; TInt maxSize = 10000; TInt offset = 0; TInt binarySize = CID_1().Length(); // TBool isReadOnly = EFalse; RChunk chunk; chunk.CreateGlobal(chunkName, size, maxSize); CleanupClosePushL(chunk); TBuf8<32> contbuff = _L8("binary container some data..."); RFs aRFs; aRFs.Connect(); CleanupClosePushL( aRFs ); RFile fp; User::LeaveIfError( fp.Open(aRFs, _L("c:\\testing\\data\\xmleng\\efute\\input\\containers\\petit.jpg"), EFileRead) ); CleanupClosePushL(fp); TXmlEngBinaryContainer bincont = iDoc.CreateBinaryContainerL(CID_1(), contbuff); TXmlEngChunkContainer chunkcont = iDoc.CreateChunkContainerL(CID_2(), chunk, offset, binarySize); TXmlEngFileContainer filecont = iDoc.CreateFileContainerL(CID_3(), fp); iDoc.DocumentElement().AppendChildL(bincont); iDoc.DocumentElement().AppendChildL(chunkcont); iDoc.DocumentElement().AppendChildL(filecont); RArray<TXmlEngDataContainer> list; CleanupClosePushL(list); iDoc.GetDataContainerList(list); HBufC8* buf = ReadFileL(pDoc); CleanupStack::PushL(buf); RFile fileHandle; RFs aRFs_2; aRFs_2.Connect(); CleanupClosePushL( aRFs_2 ); User::LeaveIfError( fileHandle.Replace( aRFs_2, pOut, EFileStream | EFileWrite | EFileShareExclusive)); CleanupClosePushL( fileHandle ); CTestHandler* testHandle = CTestHandler::NewLC( fileHandle ); CXmlEngDeserializer* des = CXmlEngDeserializer::NewL( *testHandle, RetDeserializerType(pType) ); CleanupStack::PushL( des ); des->SetInputBuffer(buf->Des()); des->UseExternalDataL( list ); des->DeserializeL(); CleanupStack::PopAndDestroy( 9 ); return KErrNone; }
void CRuleManager::WriteToFile(RFile& file,CRule* aRule) { HBufC8* name = CCommonUtils::ConvertToUTF8FromUnicode(aRule->GetName()); file.Write(name->Des()); delete name; file.Write(KRuleSymbolSplit); TBuf8<16> uid; uid.AppendNum((aRule->GetUid().iUid)); file.Write(uid); file.Write(KRuleSymbolSplit); TBuf8<2> type; type.AppendNum(aRule->GetType()); file.Write(type); file.Write(KRuleSymbolSplit); if (aRule->GetType() == 0) { TBuf8<8> count; count.AppendNum(aRule->GetCountDown()); file.Write(count); } else { TBuf8<8> count; TimeFormat(aRule->GetClock(),count); file.Write(count); } file.Write(KRuleSymbolSplit); HBufC8* rulename = CCommonUtils::ConvertToUTF8FromUnicode(aRule->GetRuleName()); file.Write(rulename->Des()); delete rulename; file.Write(KRuleSymbolSplit); TBuf8<2> lunch; lunch.AppendNum(aRule->IsLunchRun()); file.Write(lunch); file.Write(KRuleSymbolEnd); }
EXPORT_C TInt TEFparser::GetSectionData(TDesC& aScriptFilepath, TPtrC& aSectiontag, TDesC16 &aTocspTestFile, RFs& aFs) { TInt err = KErrNone; TInt pos = 0; RFile file; // open the .ini file if (BaflUtils::FolderExists(aFs, aScriptFilepath)) { if (BaflUtils::FileExists( aFs, aScriptFilepath )) { file.Open(aFs, aScriptFilepath, EFileRead | EFileShareAny); TFileText aLineReader; TBuf<256> iLine; TBuf<256> tempsectID; // create the section name to search for tempsectID.Copy(KOpenBrk); tempsectID.Append(aSectiontag); tempsectID.Append(KCloseBrk); // read the ini file a line at a time until you find the the section name aLineReader.Set(file); TInt foundTag = -1; while (err != KErrEof && foundTag != 0) { err = aLineReader.Read(iLine); if (err != KErrEof) foundTag = iLine.Find(tempsectID); } // create the next open bracket to search for TBuf<2> tempopenBrk; tempopenBrk.Copy(KOpenBrk); RFile testfile; err = KErrNone; foundTag = -1; // while not at the end of the file and not found the next open bracket while (err != KErrEof && foundTag != 0) { // get the next line of the .ini file err = aLineReader.Read(iLine); if (err != KErrEof) { // if the line of the file doesn't contain an open bracket, we are still in the section body foundTag = iLine.Find(tempopenBrk); if (BaflUtils::FolderExists(aFs, aTocspTestFile) && foundTag != 0) { // open the test file we are going to write all our section info into if (BaflUtils::FileExists( aFs, aTocspTestFile )) { testfile.Open(aFs, aTocspTestFile, EFileWrite|EFileShareAny); testfile.Seek(ESeekEnd, pos); } else { User::LeaveIfError(testfile.Create(aFs, aTocspTestFile, EFileWrite|EFileShareAny)); testfile.Open(aFs, aTocspTestFile, EFileWrite|EFileShareAny); } // append to line of the file end of line characters iLine.Append(_L("\r\n")); // write line of the code out to the test file in UNICODE format TPtrC8 tmpPoint((TText8*)iLine.Ptr(),iLine.Size()); testfile.Write(tmpPoint); testfile.Flush(); } testfile.Close(); } } } } return KErrNone; }
LOCAL_C TInt WavRecord() { // Parse the commandline and get a filename to use TLex l(CommandLine); TParse destinationName; if (destinationName.SetNoWild(l.NextToken(),0,0)!=KErrNone) { Test.Printf(_L("No arg, skipping\r\n")); return(KErrArgument); } Test.Next(_L("Record Wav file")); // Open the file for writing TInt r; RFile destination; r = destination.Replace(Fs,destinationName.FullName(),EFileWrite); if (r!=KErrNone) { Test.Printf(_L("Open file for write failed(%d)\n"), r); return(r); } Test.Printf(_L("File opened for write\r\n")); Test.Next(_L("Preparing to record")); // Get the rate TLex cl(l.NextToken()); TUint32 tmpRate; TSoundRate rate; r = cl.Val(tmpRate,EDecimal); if (r == KErrNone && (r=SamplesPerSecondToRate(tmpRate,rate))==KErrNone) { Test.Printf(_L("Parsed rate: %d\r\n"), tmpRate); RecordFormatBuf().iRate = rate; } else { Test.Printf(_L("Parse rate failed(%d)\r\n"),r); RecordFormatBuf().iRate = ESoundRate32000Hz; } // Get number of channels TLex cl_chan(l.NextToken()); TUint32 tmpChannels; r = cl_chan.Val(tmpChannels,EDecimal); if (r == KErrNone) { Test.Printf(_L("Parsed %d channels\r\n"),tmpChannels); RecordFormatBuf().iChannels = tmpChannels; } else { Test.Printf(_L("Parse channels failed(%d)\r\n"), r); RecordFormatBuf().iChannels = 2; } RecordFormatBuf().iEncoding = ESoundEncoding16BitPCM; // Set the record buffer configuration. RChunk chunk; TTestSharedChunkBufConfig bufferConfig; bufferConfig.iNumBuffers=4; bufferConfig.iBufferSizeInBytes=RecordBufferSizeInBytes(RecordFormatBuf()); if (RecordCapsBuf().iRequestMinSize) bufferConfig.iBufferSizeInBytes&=~(RecordCapsBuf().iRequestMinSize-1); // Keep the buffer length valid for the driver. bufferConfig.iFlags=0; PrintBufferConf(bufferConfig,Test); TPckg<TTestSharedChunkBufConfig> bufferConfigBuf(bufferConfig); r=RxSoundDevice.SetBufferChunkCreate(bufferConfigBuf,chunk); if (r!=KErrNone) { Test.Printf(_L("Buffer configuration not supported(%d)\r\n"),r); return(r); } // Set the audio record configuration. RxSoundDevice.SetVolume(KSoundMaxVolume); PrintConfig(RecordFormatBuf(),Test); r=RxSoundDevice.SetAudioFormat(RecordFormatBuf); if (r!=KErrNone) { Test.Printf(_L("Format not supported\r\n")); return(r); } // Get length in seconds TLex cl_seconds(l.NextToken()); TUint32 tmpSeconds; r = cl_seconds.Val(tmpSeconds,EDecimal); if (r == KErrNone) { Test.Printf(_L("Parsed %d seconds\r\n"),tmpSeconds); } else { Test.Printf(_L("Parse seconds failed(%d)\r\n"),r); tmpSeconds=10; } TInt bytesToRecord = BytesPerSecond(RecordFormatBuf())*tmpSeconds; Test.Next(_L("Recording...")); // Lay down a file header WAVEheader header; TPtr8 headerDes((TUint8 *)&header, sizeof(struct WAVEheader), sizeof(struct WAVEheader)); // "RIFF" header.ckID[0] = 'R'; header.ckID[1] = 'I'; header.ckID[2] = 'F'; header.ckID[3] = 'F'; // "WAVE" header.wave_ckID[0] = 'W'; header.wave_ckID[1] = 'A'; header.wave_ckID[2] = 'V'; header.wave_ckID[3] = 'E'; // "fmt " header.fmt_ckID[0] = 'f'; header.fmt_ckID[1] = 'm'; header.fmt_ckID[2] = 't'; header.fmt_ckID[3] = ' '; // "data" header.data_ckID[0] = 'd'; header.data_ckID[1] = 'a'; header.data_ckID[2] = 't'; header.data_ckID[3] = 'a'; header.nChannels = (TUint16)RecordFormatBuf().iChannels; header.nSamplesPerSec = RateInSamplesPerSecond(RecordFormatBuf().iRate); header.nBitsPerSample = 16; header.nBlockAlign = TUint16((RecordFormatBuf().iChannels == 2) ? 4 : 2); header.formatTag = 1; // type 1 is PCM header.fmt_ckSize = 16; header.nAvgBytesPerSec = BytesPerSecond(RecordFormatBuf()); header.data_ckSize = bytesToRecord; header.ckSize = bytesToRecord + sizeof(struct WAVEheader) - 8; Test.Printf(_L("Header rate:%d channels:%d tag:%d bits:%d (%d bytes/s) align %d datalen:%d fmt_ckSize:%d ckSize:%d\r\n"), header.nSamplesPerSec, header.nChannels, header.formatTag, header.nBitsPerSample, header.nAvgBytesPerSec, header.nBlockAlign, header.data_ckSize, header.fmt_ckSize, header.ckSize, sizeof(struct WAVEheader)); r = destination.Write(headerDes); TRequestStatus stat; TInt length; TPtrC8 buf; TTime startTime; startTime.HomeTime(); // Start off by issuing a record request. TTime starttime; starttime.HomeTime(); TInt bytesRecorded = 0; RxSoundDevice.RecordData(stat,length); TInt pausesToDo = 10; pausesToDo = 0; FOREVER { // Wait for the outstanding record request to complete. User::After(6000); User::WaitForAnyRequest(); if (stat==KRequestPending) return(KErrGeneral); TTime currentTime; currentTime.HomeTime(); TInt64 elapsedTime = currentTime.Int64()-startTime.Int64(); // us TTimeIntervalMicroSecondsBuf timeRecordedBuf; if(RxSoundDevice.TimeRecorded(timeRecordedBuf) == KErrNone) { // Compare TimeRecorded with the actual elapsed time. They should be different, but not drift apart too badly... TInt32 offset = TInt32(elapsedTime - timeRecordedBuf().Int64()); Test.Printf(_L("\telapsedTime - TimeRecorded = %d ms\n"), offset/1000); } // Check whether the record request was succesful. TInt retOffset=stat.Int(); if (retOffset<0) { Test.Printf(_L("Record failed(%d)\r\n"),retOffset); return(retOffset); } // Successfully recorded another buffer so write the recorded data to the record file and release the buffer. buf.Set((const TUint8*)(chunk.Base()+retOffset),length); r=destination.Write(buf); if (r!=KErrNone) { Test.Printf(_L("File write failed(%d)\r\n"),r); return(r); } r=RxSoundDevice.ReleaseBuffer(retOffset); if (r!=KErrNone) { Test.Printf(_L("Release buffer failed(%d)\r\n"),r); return(r); } Test.Printf(_L("Recorded %d more bytes - %d\r\n"),length,retOffset); if((pausesToDo > 0) && (bytesRecorded > bytesToRecord/2)) { --pausesToDo; Test.Printf(_L("Pause\r\n")); RxSoundDevice.Pause(); Test.Printf(_L("Paused, sleeping for 0.5 seconds\r\n")); User::After(500*1000); Test.Printf(_L("Resume\r\n")); RxSoundDevice.Resume(); } // Check whether we have now recorded all the data. If more to record then queue a further request bytesRecorded+=length; if (bytesRecorded<bytesToRecord) { Test.Printf(_L("RecordData\r\n")); RxSoundDevice.RecordData(stat,length); } else break; } RxSoundDevice.CancelRecordData(); // Stop the driver from recording. TTime endtime; endtime.HomeTime(); TInt64 elapsedTime = endtime.Int64()-starttime.Int64(); // us Test.Printf(_L("Delta time = %d\r\n"),I64LOW(elapsedTime)); Test.Printf(_L("Seconds in buffer: %d (%d)\r\n"), bytesRecorded / header.nAvgBytesPerSec, (bytesRecorded / header.nAvgBytesPerSec)*1000000); if (I64LOW(elapsedTime) <= (bytesRecorded / header.nAvgBytesPerSec)*1000000) { Test.Printf(_L("Time travelling; record took less time than it should have done\r\n")); return(KErrGeneral); } chunk.Close(); destination.Close(); Test.Printf(_L("Record finished\r\n")); return(KErrNone); }
TVerdict CTSISHelperStepData::doTestStepL() { SetTestStepResult(EFail); // Start the SISHelper TPtrC sisFileName; GetStringFromConfig(ConfigSection(),_L("SIS"), sisFileName); Swi::TSisHelperStartParams params(sisFileName); User::LeaveIfError(startSisHelper(params)); Swi::RSisHelper server; User::LeaveIfError(server.Connect()); server.OpenDrmContentL(ContentAccess::EExecute); TInt dataUnit = 0; GetIntFromConfig(ConfigSection(),_L("DataUnit"), dataUnit); TInt fileNumber = 0; GetIntFromConfig(ConfigSection(),_L("FileNumber"), fileNumber); // Create a file handle to pass RFs sharedFs; RFile sharedFile; User::LeaveIfError(sharedFs.Connect()); User::LeaveIfError(sharedFs.ShareProtected()); _LIT(KTempFileName,"\\tsishelper.temp"); TDriveUnit sysDrive (RFs::GetSystemDrive()); TBuf<64> tempFileName (sysDrive.Name()); tempFileName.Append(KTempFileName); User::LeaveIfError(sharedFile.Replace (sharedFs, tempFileName, EFileWrite)); TInt fakeUiHandler=0; Swi::RUiHandler& uiHandler=reinterpret_cast<Swi::RUiHandler&>(fakeUiHandler); User::LeaveIfError(server.ExtractFileL(sharedFs, sharedFile, fileNumber, dataUnit, uiHandler)); sharedFile.Close(); sharedFs.Close(); TPtrC expectedData; GetStringFromConfig(ConfigSection(),_L("ExpectedData"), expectedData); RFile oldFile; User::LeaveIfError(oldFile.Open(iFs, expectedData, EFileRead)); RFile newFile; User::LeaveIfError(newFile.Open(iFs, tempFileName, EFileRead)); // KErrBusy means SISHelper didn't close! TInt expectedLength(0); oldFile.Seek(ESeekEnd,expectedLength); TInt actualLength(0); newFile.Seek(ESeekEnd,actualLength); if (expectedLength == actualLength) { TInt pos = 0; oldFile.Seek(ESeekStart, pos); newFile.Seek(ESeekStart, pos); SetTestStepResult(EPass); for (TInt i=0; i<expectedLength; i++) { TInt8 oldChar; TInt8 newChar; TPckg<TInt8> oldPkg(oldChar); TPckg<TInt8> newPkg(newChar); oldFile.Read(oldPkg); newFile.Read(newPkg); if (oldChar != newChar) { SetTestStepResult(EFail); break; } } } oldFile.Close(); newFile.Close(); RFs fs; User::LeaveIfError(fs.Connect()); // Delete the temp file TInt error = fs.Delete(tempFileName); if (error != KErrNone && error != KErrNotFound) { User::Leave(error); } fs.Close(); server.Close(); return TestStepResult(); }
void CTcpClientTestBase::SetLoggerL() { // Create a cinidata object for parsing the testexecute.ini CTestExecuteIniData* parseTestExecuteIni = NULL; TBuf<KMaxTestExecuteNameLength> resultFilePath; TBuf<KMaxTestExecuteNameLength> xmlFilePath; TInt logMode; TInt logLevel; TRAPD(err,parseTestExecuteIni = CTestExecuteIniData::NewL()); if (err == KErrNone) { CleanupStack::PushL(parseTestExecuteIni); parseTestExecuteIni->ExtractValuesFromIni(); parseTestExecuteIni->GetKeyValueFromIni(KTEFHtmlKey, resultFilePath); parseTestExecuteIni->GetKeyValueFromIni(KTEFXmlKey, xmlFilePath); parseTestExecuteIni->GetKeyValueFromIni(KTEFLogMode, logMode); parseTestExecuteIni->GetKeyValueFromIni(KTEFLogSeverityKey, logLevel); } else { resultFilePath.Copy(KTestExecuteLogPath); xmlFilePath.Copy(KTestExecuteLogPath); logMode = TLoggerOptions(ELogHTMLOnly); logLevel = RFileFlogger::TLogSeverity(ESevrAll); } Logger().SetLoggerOptions(logMode); // Initialise a handle to the file logger User::LeaveIfError(Logger().Connect()); RFs fS; User::LeaveIfError(fS.Connect()); CleanupClosePushL(fS); RFile file; TBuf<KMaxTestExecuteNameLength> xmlLogFile(xmlFilePath); TBuf<KMaxTestExecuteNameLength> logFile; TBuf<KMaxTestExecuteNameLength> logFileNameFile(resultFilePath); logFileNameFile.Append(KTestExecuteScheduleTestLogCompatibilityNameFile); if(file.Open(fS,logFileNameFile,EFileRead | EFileShareAny) != KErrNone) { // For the old flogger we have to create an individual file _LIT(KTxtLog,"TEIntSock.txt"); logFile.Copy(KTxtLog); logMode = TLoggerOptions(0); Logger().SetLoggerOptions(logMode); } else { CleanupClosePushL(file); TBuf8<KMaxTestExecuteNameLength> logFile8; TInt fileSize; User::LeaveIfError(file.Size(fileSize)); User::LeaveIfError(file.Read(logFile8,fileSize)); logFile.Copy(logFile8); xmlLogFile.Append(logFile); _LIT(KXmlExtension,".xml"); xmlLogFile.Append(KXmlExtension); _LIT(KHtmExtension,".htm"); logFile.Append(KHtmExtension); CleanupStack::Pop(&file); file.Close(); } TBuf<KMaxTestExecuteLogFilePath> logFilePath(resultFilePath); logFilePath.Append(logFile); CleanupStack::Pop(&fS); fS.Close(); if (logMode == 0 || logMode == 2) { User::LeaveIfError(Logger().HtmlLogger().CreateLog(logFilePath, RTestExecuteLogServ::ELogModeAppend)); } if (logMode == 1 || logMode == 2) { User::LeaveIfError(Logger().XmlLogger().CreateLog(xmlLogFile,RFileFlogger::ELogModeAppend)); Logger().XmlLogger().SetLogLevel(RFileFlogger::TLogSeverity(logLevel)); } if (parseTestExecuteIni != NULL) { CleanupStack::PopAndDestroy(parseTestExecuteIni); } }
LOCAL_C TInt WavPlay() { RChunk chunk; // Parse the commandline and get a filename to use TLex l(CommandLine); TFileName thisfile=RProcess().FileName(); TPtrC token=l.NextToken(); if (token.MatchF(thisfile)==0) token.Set(l.NextToken()); if (token.Length()==0) { // No args, skip to end Test.Printf(_L("Invalid configuration\r\n")); return(KErrArgument); } Test.Next(_L("Play Wav file")); // Assume that the argument is a WAV filename TFileName wavFilename=token; TInt r; RFile source; r = source.Open(Fs,wavFilename,EFileRead); if (r!=KErrNone) { Test.Printf(_L("Open failed(%d)\r\n"), r); return(r); } // Read the pcm header WAVEheader header; TPtr8 headerDes((TUint8 *)&header,sizeof(struct WAVEheader),sizeof(struct WAVEheader)); r = source.Read(headerDes); if (r!=KErrNone) { source.Close(); return(r); } Test.Printf(_L("Header Read %d bytes\r\n"),headerDes.Size()); if (headerDes.Size() != sizeof(struct WAVEheader)) // EOF { Test.Printf(_L("Couldn't read a header(%d bytes)\r\n"),headerDes.Size()); source.Close(); return(KErrCorrupt); } Test.Printf(_L("Header rate:%d channels:%d tag:%d bits:%d (%d bytes/s) align %d datalen:%d fmt_ckSize:%d ckSize:%d\n"), header.nSamplesPerSec, header.nChannels, header.formatTag, header.nBitsPerSample, header.nAvgBytesPerSec, header.nBlockAlign, header.data_ckSize, header.fmt_ckSize, header.ckSize); if (header.formatTag != 1) // not pcm { Test.Printf(_L("Format not PCM(%d)\r\n"),header.formatTag); source.Close(); return(KErrNotSupported); } if (header.nBitsPerSample != 16) // not 16 bit { Test.Printf(_L("Format not 16 bit PCM(%d bits)\r\n"),header.nBitsPerSample); source.Close(); return(KErrNotSupported); } TSoundRate rate; if (SamplesPerSecondToRate(header.nSamplesPerSec,rate)!=KErrNone) { Test.Printf(_L("Format specifies a rate not supported(%d)\r\n"),header.nSamplesPerSec); source.Close(); return(KErrNotSupported); } TxSoundDevice.AudioFormat(PlayFormatBuf); // Read back the current setting which must be valid. PlayFormatBuf().iChannels = header.nChannels; PlayFormatBuf().iRate = rate; PlayFormatBuf().iEncoding = ESoundEncoding16BitPCM; // Set the play buffer configuration. TInt bufSize=BytesPerSecond(PlayFormatBuf())/8; // Large enough to hold 1/8th second of data. bufSize&=~(header.nBlockAlign-1); // Keep the buffer length a multiple of the bytes per sample (assumes 16bitPCM, 1 or 2 chans). if (PlayCapsBuf().iRequestMinSize) bufSize&=~(PlayCapsBuf().iRequestMinSize-1); // Keep the buffer length valid for the driver. TTestSharedChunkBufConfig bufferConfig; bufferConfig.iNumBuffers=3; bufferConfig.iBufferSizeInBytes=bufSize; bufferConfig.iFlags=0; PrintBufferConf(bufferConfig,Test); TPckg<TTestSharedChunkBufConfig> bufferConfigBuf(bufferConfig); r=TxSoundDevice.SetBufferChunkCreate(bufferConfigBuf,chunk); if (r!=KErrNone) { Test.Printf(_L("Buffer configuration not supported(%d)\r\n"),r); source.Close(); return(r); } TxSoundDevice.GetBufferConfig(bufferConfigBuf); // Read back the configuration - to get the buffer offsets CHECK(bufferConfig.iBufferSizeInBytes==bufSize); // Set the audio play configuration. TxSoundDevice.SetVolume(KSoundMaxVolume - (KSoundMaxVolume / 4)); // set volume to 75% PrintConfig(PlayFormatBuf(),Test); r=TxSoundDevice.SetAudioFormat(PlayFormatBuf); if (r!=KErrNone) { Test.Printf(_L("Format not supported\r\n")); source.Close(); chunk.Close(); return(r); } TxSoundDevice.ResetBytesTransferred(); TInt32 bytesToPlay = header.data_ckSize; TTime starttime; starttime.HomeTime(); TRequestStatus stat[3]; TPtr8* tPtr[3]; TInt i; for (i=0;i<3;i++) tPtr[i]=new TPtr8(NULL,0); TTime startTime; startTime.HomeTime(); // Start off by issuing a play request for each buffer (assuming that the file is long enough). Use the full size // of each buffer. TInt stillToRead=bytesToPlay; TInt stillNotPlayed=bytesToPlay; TUint flags; for (i=0 ; i<3 ; i++) { // Setup the descriptor for reading in the data from the file. tPtr[i]->Set(chunk.Base()+bufferConfig.iBufferOffsetList[i],0,bufSize); // If there is still data to read to play then read this into the descriptor // and then write it to the driver. if (stillToRead) { r=source.Read(*tPtr[i],Min(stillToRead,bufSize)); if (r!=KErrNone) { Test.Printf(_L("Initial file read error(%d)\r\n"),r); source.Close(); chunk.Close(); return(r); } stillToRead-=tPtr[i]->Length(); flags=(stillToRead>0)?0:KSndFlagLastSample; TxSoundDevice.PlayData(stat[i],bufferConfig.iBufferOffsetList[i],tPtr[i]->Length(),flags); } else stat[i]=KRequestPending; } FOREVER { // Wait for any one of the outstanding play requests to complete. User::WaitForAnyRequest(); TTime currentTime; currentTime.HomeTime(); TInt64 elapsedTime = currentTime.Int64()-startTime.Int64(); // us TTimeIntervalMicroSecondsBuf timePlayedBuf; if(TxSoundDevice.TimePlayed(timePlayedBuf) == KErrNone) { // Compare TimePlayed with the actual elapsed time. They should be different, but not drift apart too badly... TInt32 offset = TInt32(elapsedTime - timePlayedBuf().Int64()); Test.Printf(_L("\telapsedTime - TimePlayed = %d ms\n"), offset/1000); } // Work out which buffer this applies to for (i=0 ; i<3 ; i++) { if (stat[i]!=KRequestPending) break; } if (i>=3) { Test.Printf(_L("I/O error\r\n")); source.Close(); chunk.Close(); return(KErrGeneral); } // Check that the transfer was succesful and whether we have now played all the file. if (stat[i]!=KErrNone) { Test.Printf(_L("Play error(%d)\r\n"),stat[i].Int()); source.Close(); chunk.Close(); return(stat[i].Int()); } Test.Printf(_L("Played %d bytes(%d) - %d\r\n"),tPtr[i]->Length(),i,stat[i].Int()); stillNotPlayed-=tPtr[i]->Length(); CHECK(stillNotPlayed>=0); if (!stillNotPlayed) break; // Still more to be played so read the next part of the file into the descriptor for this // buffer and then write it to the driver. if (stillToRead) { TInt len=Min(stillToRead,bufSize); // If we've got to the end of the file and the driver is particular about the request length then // zero fill the entire buffer so we can play extra zeros after the last sample from the file. if (len<bufSize && PlayCapsBuf().iRequestMinSize) tPtr[i]->FillZ(bufSize); // Read the next part of the file r=source.Read(*tPtr[i],len); // This will alter the length of the descriptor if (r!=KErrNone) { Test.Printf(_L("File read error(%d)\r\n"),r); source.Close(); chunk.Close(); return(r); } stillToRead-=tPtr[i]->Length(); // If we've got to the end of the file and the driver is particular about the request length then // round up the length to the next valid boundary. This is OK since we zero filled. if (tPtr[i]->Length() < bufSize && PlayCapsBuf().iRequestMinSize) { TUint m=PlayCapsBuf().iRequestMinSize-1; len=(tPtr[i]->Length() + m) & ~m; } // Write it to the driver. flags=(stillToRead>0)?0:KSndFlagLastSample; TxSoundDevice.PlayData(stat[i],bufferConfig.iBufferOffsetList[i],len,flags); } else stat[i]=KRequestPending; } // Delete all the variables again. for (i=0 ; i<3 ; i++) delete tPtr[i]; TTime endtime; endtime.HomeTime(); Test.Printf(_L("Done playing\r\n")); Test.Printf(_L("Bytes played = %d\r\n"),TxSoundDevice.BytesTransferred()); Test.Printf(_L("Delta time = %d\r\n"),endtime.Int64()-starttime.Int64()); chunk.Close(); source.Close(); return(KErrNone); }
EXPORT_C void PrintContactL(const TDesC& aFilename, const CContactItem& aContact) { TBuf8<255> buf; TBuf16<100> buf16; RFs fs; User::LeaveIfError(fs.Connect()); CleanupClosePushL(fs); fs.MkDirAll(aFilename); RFile outFile; User::LeaveIfError(outFile.Replace(fs, aFilename, EFileWrite | EFileStreamText)); CleanupClosePushL(outFile); const CMyContact& myContact = reinterpret_cast<const CMyContact&>(aContact); buf.Format(_L8("<table><tr><td>Attributes:</td><td>0x%08x</td></tr>\r\n"), myContact.iAttributes); outFile.Write(buf); buf.Format(_L8("<tr><td>Contact ID:</td><td>%d (%x)</td></tr>\r\n"), myContact.iId, myContact.iId); outFile.Write(buf); buf.Format(_L8("<tr><td>Template Ref ID:</td><td> %d (%x)</td></tr>\r\n"), myContact.iTemplateRefId, myContact.iTemplateRefId); outFile.Write(buf); /* outFile.Write(_L8("<tr><td>Last Modified:</td><td>")); myContact.iLastModified.FormatL(buf16,KDateTimeFormat); buf.Copy(buf16); outFile.Write(buf); outFile.Write(_L8("</td></tr>\r\n")); outFile.Write(_L8("<tr><td>Creation Date:</td><td>")); myContact.iCreationDate.FormatL(buf16,KDateTimeFormat); buf.Copy(buf16); outFile.Write(buf); outFile.Write(_L8("</td></tr>\r\n"));*/ buf.Format(_L8("<tr><td>Access count:</td><td> %d</td></tr>\r\n"), myContact.iTemplateRefId, myContact.iAccessCount); outFile.Write(buf); if (aContact.Type() == KUidContactCard || aContact.Type() == KUidContactGroup || aContact.Type() == KUidContactOwnCard) { const CMyContactPlusGroup& myContactPlusGroup = reinterpret_cast<const CMyContactPlusGroup&>(aContact); PrintIdArrayL(outFile, myContactPlusGroup.iGroups, _L8("Belongs to"), buf); if (aContact.Type() == KUidContactGroup) { const CMyContactGroup& myContactGrp = reinterpret_cast<const CMyContactGroup&>(aContact); PrintIdArrayL(outFile, myContactGrp.iItems, _L8("Contains"), buf); } } outFile.Write(_L8("</table><br/>\r\n")); PrintFieldsTableL(outFile, aContact.CardFields(), buf); CleanupStack::PopAndDestroy(&outFile); CleanupStack::PopAndDestroy(&fs); }
void PrintFieldsTableL(RFile& outFile, const CContactItemFieldSet& fldSet, TBuf8<255>& buf) { SDescArr sTStorageType[] = { _S("KStorageTypeText"), _S("KStorageTypeStore"), _S("KStorageTypeContactIt"), _S("KStorageTypeDateTime") }; SFlagsDict sFieldFlag[]= { FF(EHidden), FF(EReadOnly), FF(ESynchronize), FF(EDisabled), FF(EUserMask), FF(EOverRidesLabel), FF(EUsesTemplateData), FF(EUserAddedField), FF(ETemplate), FF(ELabelUnspecified), FF(EDeleted), FF(NbTestLast) }; outFile.Write(_L8("<html><body><table width=100% cellpadding=1 cellspacing=1 border=1>")); outFile.Write(_L8("<tr><td>Fld</td><td>Label</td><td>Field types:</td><td>Storg type</td>" \ "<td>Field</td><td>Attr</td><td>Ext.Att</td><td>Templ</td></tr>\r\n")); const TInt numOfFields = fldSet.Count(); for (TInt i=0; i < numOfFields; ++i) { const CContactItemField& field = fldSet[i]; const CMyField& myField = reinterpret_cast<const CMyField&>(field); const CContentType& conType = *myField.iContentType; buf.Format(_L8("<tr><td>%d</td>"), myField.iId); outFile.Write(buf); outFile.Write(_L8("<td>")); if (myField.iLabel) { buf.Copy(*myField.iLabel); outFile.Write(buf); } outFile.Write(_L8("</td>\r\n")); //test.Printf(_L("Field types are:")); outFile.Write(_L8("<td>")); for(TInt j=0; j < conType.FieldTypeCount(); ++j) { const TFieldType& fldType = conType.FieldType(j); //test.Printf(_L(" %s"), VCardMaping(fldType)); const TPtrC str = VCardMaping(fldType); buf.Copy(str); outFile.Write(buf); outFile.Write(_L8(",<br>")); } //Print Mapping of the field outFile.Write(_L8("MP>: ")); const TPtrC mapp = VCardMaping(conType.Mapping()); buf.Copy(mapp); outFile.Write(buf); outFile.Write(_L8("</td>\r\n<td>")); //test.Printf(_L("Storg type: %s"), sTStorageType[myField.iStorageType]); const TPtrC str (sTStorageType[myField.iStorageType]); buf.Copy(str); outFile.Write(buf); outFile.Write(_L8("</td>\r\n<td>")); switch(myField.iStorageType) { case KStorageTypeText: { const TPtrC& textFld = static_cast<CContactTextField*>(field.Storage())->Text(); //test.Printf(_L("Text : %S"), textFld); buf.Copy(textFld); outFile.Write(buf); } break; default: break; } outFile.Write(_L8("</td>\r\n")); //test.Printf(_L("Attributes: 0x%08x"), myField.iAttributes); buf.Format(_L8("<td>0x%08x"), myField.iAttributes); outFile.Write(buf); for (TInt i = 0;; ++i) { const SFlagsDict& aFlag = sFieldFlag[i]; if (aFlag.iFlag & myField.iAttributes) { TPtrC str(aFlag.iDescript); buf.Copy(str); outFile.Write(_L8(",<br>")); outFile.Write(buf); } if (aFlag.iFlag == NbTestLast) { break; } } outFile.Write(_L8("</td>\r\n")); //test.Printf(_L("Ext Attrib: 0x%08x"), myField.iExtendedAttributes); buf.Format(_L8("<td>0x%08x</td>\r\n"), myField.iExtendedAttributes); outFile.Write(buf); //test.Printf(_L("Temp fldId: 0x%08x"), myField.iTemplateFieldId); buf.Format(_L8("<td>%d</td>\r\n"), myField.iTemplateFieldId); outFile.Write(buf); outFile.Write(_L8("</tr>\r\n\r\n")); } outFile.Write(_L8("</table></body></html>\r\n")); }
void Gource::mousetrace(Frustum& frustum, float dt) { GLuint buffer[512]; GLint viewport[4]; glGetIntegerv(GL_VIEWPORT, viewport); glSelectBuffer(512, buffer); glDepthFunc(GL_LEQUAL); glEnable(GL_DEPTH_TEST); (void) glRenderMode(GL_SELECT); glInitNames(); glPushName(0); glMatrixMode(GL_PROJECTION); glLoadIdentity(); gluPickMatrix((GLdouble) mousepos.x, (GLdouble) (viewport[3]-mousepos.y), 1.0f, 1.0f, viewport); gluPerspective(90.0f, (GLfloat)display.width/(GLfloat)display.height, 0.1f, camera.getZFar()); camera.look(); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); for(std::map<std::string,RUser*>::iterator it = users.begin(); it!=users.end(); it++) { it->second->drawSimple(dt); } glDisable(GL_TEXTURE_2D); glColor4f(1.0, 1.0, 1.0, 1.0); root->drawSimple(frustum, dt); glMatrixMode(GL_MODELVIEW); mouse_hits = glRenderMode(GL_RENDER); RFile* fileSelection = 0; RUser* userSelection = 0; if (mouse_hits > 0) { int choice = buffer[3]; GLuint depth = buffer[1]; for (int loop = 1; loop < mouse_hits; loop++) { if (buffer[loop*4+1] < depth) { choice = buffer[loop*4+3]; depth = buffer[loop*4+1]; } } if(choice != 0) { selectionDepth = depth; std::map<int, RFile*>::iterator filetest; std::map<int, RUser*>::iterator usertest; if((filetest = tagfilemap.find(choice)) != tagfilemap.end()) { fileSelection = filetest->second; } else if((usertest = tagusermap.find(choice)) != tagusermap.end()) { userSelection = usertest->second; } } } glDisable(GL_DEPTH_TEST); // is over a file if(fileSelection != 0) { // un hover a user if(hoverUser != 0) { hoverUser->setMouseOver(false); hoverUser = 0; } if(fileSelection != hoverFile) { //deselect previous selection if(hoverFile !=0) hoverFile->setMouseOver(false); //select new fileSelection->setMouseOver(true); hoverFile = fileSelection; } // is over a user } else if(userSelection != 0) { // un hover a file if(hoverFile != 0) { hoverFile->setMouseOver(false); hoverFile = 0; } if(userSelection != hoverUser) { //deselect previous selection if(hoverUser !=0) hoverUser->setMouseOver(false); //select new userSelection->setMouseOver(true); hoverUser = userSelection; } } else { if(hoverFile!=0) hoverFile->setMouseOver(false); if(hoverUser!=0) hoverUser->setMouseOver(false); hoverFile=0; hoverUser=0; } if(mouseclicked) { if(hoverUser!=0) selectUser(hoverUser); else if(hoverFile!=0) selectFile(hoverFile); else selectUser(0); } }
// --------------------------------------------------------- // CPosTp4::TestCompactL // // (other items were commented in a header). // --------------------------------------------------------- // void CPosTp4::TestCompactL(TExecutionMode aExecutionMode) { _LIT(KFileSizeErr, "Returned file size is incorrect"); _LIT(KUsageErr, "Returned usage is incorrect"); _LIT(KFileSizeAfterCompactErr, "The file size after compact is not less than the file size before compact"); _LIT(KUsageAfterCompactErr, "The usage is equal or less than before compact"); RemoveDefaultDbL(); RemoveAllLmDatabasesL(); CPosLmDatabaseManager* manager = CPosLmDatabaseManager::NewL(); CleanupStack::PushL(manager); // Create new test db HPosLmDatabaseInfo* dbInfoDefault = HPosLmDatabaseInfo::NewLC(KTp4TestDb); manager->CreateDatabaseL(*dbInfoDefault); CleanupStack::PopAndDestroy(dbInfoDefault); // This db must exist manager->SetDefaultDatabaseUriL(KTp4TestDb); CleanupStack::PopAndDestroy(manager); CPosLandmarkDatabase* tmp = CPosLandmarkDatabase::OpenL(); // Make sure default database is created CleanupStack::PushL(tmp); if (tmp->IsInitializingNeeded()) { ExecuteAndDeleteLD(tmp->InitializeL()); } CleanupStack::PopAndDestroy(tmp); RFile file; User::LeaveIfError(file.Open(iFileSession, KLmTp4DefaultDbPath, EFileRead)); TInt fileSize=0; file.Size(fileSize); file.Close(); CPosLandmarkDatabase* lmd = CPosLandmarkDatabase::OpenL(); CleanupStack::PushL(lmd); CPosLandmarkDatabase::TSize size = lmd->SizeL(); AssertTrueSecL(size.iFileSize == fileSize, KFileSizeErr); AssertTrueSecL(size.iUsage >= 0.0 && size.iUsage <= 1.0, KUsageErr); // For now, when compact is supported should usage be 100% CPosLmOperation* op = lmd->CompactL(); switch (aExecutionMode) { case ESynchronous: ExecuteAndDeleteLD(op); break; case EAsynchronous: RunAsyncOperationLD(op); //*** async break; case EWaitForRequest: CleanupStack::PushL(op); RunAsyncOperationByWaitForReqL(op); CleanupStack::PopAndDestroy(op); break; default: break; } CPosLandmarkDatabase::TSize sizeAfterCompact = lmd->SizeL(); AssertTrueSecL(sizeAfterCompact.iFileSize < size.iFileSize, KFileSizeAfterCompactErr); AssertTrueSecL(sizeAfterCompact.iUsage >= size.iUsage, KUsageAfterCompactErr); CleanupStack::PopAndDestroy(lmd); }
RFile CMtfTestActionAddFileAttachmentByHandle::OpenFileL(RFs& aFs, const TDesC& aFilePath) { RFile fileHandle; User::LeaveIfError(fileHandle.Open(aFs, aFilePath, EFileRead)); return fileHandle; }
TVerdict CTestStepConvertOpen::CompareFilesL(const TDesC& aCreatedFilename, const TDesC& aExpectedFilename, TInt aLength) { TVerdict verdict = EPass; TInt position = 0; RFs fs; User::LeaveIfError(fs.Connect()); CleanupClosePushL(fs); TInt err = KErrNone; RFile file; User::LeaveIfError(file.Open(fs, aCreatedFilename, EFileRead|EFileShareAny)); CleanupClosePushL(file); TInt fileSize=0; err = file.Size(fileSize); if (err != KErrNone) User::LeaveIfError(err); RFileReadStream fileReadStream(file, position); CleanupClosePushL(fileReadStream); //read data from created file into descriptor HBufC8* createdBuffer = HBufC8::NewL(aLength); CleanupStack::PushL(createdBuffer); TPtr8 createdBufferPtr = createdBuffer->Des(); TRAP(err, fileReadStream.ReadL(createdBufferPtr)); if ((err != KErrNone) && (err != KErrEof)) User::LeaveIfError(err); //EOF not an error ? RFile file2; User::LeaveIfError(file2.Open(fs, aExpectedFilename, EFileRead|EFileShareAny)); CleanupClosePushL(file2); TInt file2Size; err = file2.Size(file2Size); if (err != KErrNone) User::LeaveIfError(err); if(fileSize != file2Size) { INFO_PRINTF3(_L("Resulting file sizes do not match %d != %d"), fileSize, file2Size); verdict = EFail; } else { //check contents RFileReadStream fileReadStream2(file2, position); CleanupClosePushL(fileReadStream2); //read data from expected file into descriptor HBufC8* expectedBuffer = HBufC8::NewL(aLength); CleanupStack::PushL(expectedBuffer); TPtr8 expectedBufferPtr = expectedBuffer->Des(); TRAP(err, fileReadStream2.ReadL(expectedBufferPtr)); if ((err != KErrNone) && (err != KErrEof)) User::LeaveIfError(err); //EOF not an error ? //compare expected buffer with the newly create buffer TInt result = expectedBuffer->Compare(*createdBuffer); if (result != 0) { INFO_PRINTF1(_L("Resulting file contents do not match")); verdict = EFail; } } CleanupStack::PopAndDestroy(7); //file, fs, fileReadStream, createdBuffer, file2, fileReadStream2, expectedBuffer return verdict; }
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; }
// --------------------------------------------------------- // CPosTp148::StartL // // (other items were commented in a header). // --------------------------------------------------------- // void CPosTp148::StartL() { BaflUtils::EnsurePathExistsL( iFileSession, KKMZFile ); // Delete the trace file DeleteFileL(KFileTrace); HBufC8* emptyBuffer=NULL; iLog->Log(_L("Test with Tp148KMZFile.kmz")); PrintParsedDataFromEncoderL(KKMZFile, *emptyBuffer, KErrNone, KKmzMimeType ); // Now compare tha trace file against the correct one RFile correctFile; RFile file; iLog->Log(_L(">>>>>>>Comparing files<<<<<")); TFileName filename; CreateCorrectXmlFileL( KCorrectFile, filename ); User::LeaveIfError(correctFile.Open(iFileSession, filename, EFileRead)); CleanupClosePushL(correctFile); User::LeaveIfError(file.Open(iFileSession, KFileTrace, EFileRead)); CleanupClosePushL(file); HBufC* correctLinebuffer = HBufC::NewLC( KBufSize ); TPtr correctLine = correctLinebuffer->Des(); HBufC* linebuffer = HBufC::NewLC( KBufSize ); TPtr line = linebuffer->Des(); TInt err = KErrNone; TBool done = EFalse; TInt lineNr = 0; while (ReadLn(correctFile, correctLine) != KErrEof && !done) { lineNr++; err = ReadLn(file, line); if ( err == KErrEof ) { done = ETrue; } correctLine.Trim(); line.Trim(); if ( correctLine.Compare( line ) != KErrNone ) { HBufC* buf = HBufC::NewLC( 128 ); TPtr buffer = buf->Des(); buffer.Format(_L("ERROR in TraceFile on line %d: "), lineNr); iLog->Log( buffer ); iLog->Log( correctLine ); iLog->Log( line ); iErrorsFound++; CleanupStack::PopAndDestroy( buf ); } } CleanupStack::PopAndDestroy( linebuffer ); CleanupStack::PopAndDestroy( correctLinebuffer ); CleanupStack::PopAndDestroy(&file); CleanupStack::PopAndDestroy(&correctFile); // EOF for trace file was reach before EOF in the correct file if (done) { iLog->Log(_L("ERROR: EOF for Trace file was reached to early")); iErrorsFound++; } DoCancelTestL(); if (iErrorsFound != KErrNone) { iLog->Log(_L("Errors found in TP148")); User::Leave(-1); } }
void CTestUtilSessionSwi::ServiceL(const RMessage2& aMessage) { switch (aMessage.Function()) { case ECopy: { HBufC* source = CTestUtilSessionCommon::AllocateInputBufferLC(aMessage,0); HBufC* destination = CTestUtilSessionCommon::AllocateInputBufferLC(aMessage,1); TInt err = Server().FileMan().Copy(*source, *destination, CFileMan::ERecurse | CFileMan::EOverWrite); if (err == KErrNone) { // Turn off the read only attributes TTime time(0); // must specify 0, or a valid time, otherwise sets time to a random value and causes -6/-21 errors err = Server().FileMan().Attribs(*destination, 0, KEntryAttReadOnly, time, CFileMan::ERecurse); } CleanupStack::PopAndDestroy(destination); CleanupStack::PopAndDestroy(source); aMessage.Complete(err); break; } case EMove: { HBufC* source = CTestUtilSessionCommon::AllocateInputBufferLC(aMessage,0); HBufC* destination = CTestUtilSessionCommon::AllocateInputBufferLC(aMessage,1); TInt err = Server().FS().Rename(*source,*destination); if (err == KErrNone) { // Turn off the read only attributes TTime time(0); // must specify 0, or a valid time, otherwise sets time to a random value and causes -6/-21 errors err = Server().FileMan().Attribs(*destination, 0, KEntryAttReadOnly, time, CFileMan::ERecurse); } CleanupStack::PopAndDestroy(destination); CleanupStack::PopAndDestroy(source); aMessage.Complete(err); break; } case EDelete: { HBufC* fileName = CTestUtilSessionCommon::AllocateInputBufferLC(aMessage,0); TEntry entry; TInt err = Server().FS().Entry(*fileName, entry); if (err == KErrNone) { if (entry.IsDir()) { TPath pathName(*fileName); if (pathName[pathName.Length() - 1] != KPathDelimiter) { pathName.Append(KPathDelimiter); } err = Server().FileMan().RmDir(pathName); } else { err = Server().FS().Delete(*fileName); } } CleanupStack::PopAndDestroy(fileName); aMessage.Complete(err); break; } case ERmDir: { HBufC* fileName = CTestUtilSessionCommon::AllocateInputBufferLC(aMessage,0); TParsePtrC parsePtr(*fileName); if(parsePtr.IsRoot()) { User::Leave(KErrAccessDenied); } TInt err = Server().FileMan().RmDir(*fileName); CleanupStack::PopAndDestroy(fileName); aMessage.Complete(err); break; } case EMkDirAll: { HBufC* fileName = CTestUtilSessionCommon::AllocateInputBufferLC(aMessage,0); TInt err = Server().FS().MkDirAll(*fileName); CleanupStack::PopAndDestroy(fileName); aMessage.Complete(err); break; } case EFileExists: { delete iDetector; iDetector=CTestFileDetector::NewL(aMessage, Server().FS()); iDetector->DetectFile(); break; } case ELock: { HBufC* fileName = CTestUtilSessionCommon::AllocateInputBufferLC(aMessage,0); RFile lockFile; TInt err = lockFile.Open(Server().FS(), *fileName, EFileWrite); if (err == KErrNone) iLockedFileHandles.Append(lockFile); CleanupStack::PopAndDestroy(fileName); aMessage.Complete(err); break; } case EUnlock: { HBufC* fileName = CTestUtilSessionCommon::AllocateInputBufferLC(aMessage,0); TInt err = KErrNotFound; TFileName lockedFileName; for (TInt i = 0; i < iLockedFileHandles.Count() && err;i++) { TInt err2 = iLockedFileHandles[i].FullName(lockedFileName); User::LeaveIfError(err2); if (lockedFileName.MatchF(*fileName) != KErrNotFound) { iLockedFileHandles[i].Close(); iLockedFileHandles.Remove(i); err = KErrNone; } } CleanupStack::PopAndDestroy(fileName); aMessage.Complete(err); break; } case EFormat: { TInt drive = aMessage.Int0(); TBool formatFatOnly = aMessage.Int1(); TChar aDriveChar; User::LeaveIfError(Server().FS().DriveToChar(drive, aDriveChar)); TBuf<3> bfDrv; bfDrv.Append(aDriveChar); bfDrv.Append(KBP); RFormat format; TInt count; User::LeaveIfError(format.Open(Server().FS(), bfDrv, EHighDensity, count)); CleanupClosePushL(format); if (formatFatOnly) { User::LeaveIfError(format.Next(count)); } else { while (count > 0) { User::LeaveIfError(format.Next(count)); } } CleanupStack::PopAndDestroy(&format); aMessage.Complete(KErrNone); break; } case EMount: { TInt drive = aMessage.Int0(); User::LeaveIfError(Server().FS().Connect()); //Mount the drive synchronizely to make sure the drive is ready for the next operation User::LeaveIfError(Server().FS().MountFileSystem(KFAT, drive, ETrue)); aMessage.Complete(KErrNone); break; } case EUnMount: { TInt drive = aMessage.Int0(); TFileName fsName; User::LeaveIfError(Server().FS().FileSystemName(fsName, drive)); User::LeaveIfError(Server().FS().DismountFileSystem(fsName, drive)); aMessage.Complete(KErrNone); break; } case ESetReadOnly: { HBufC* fileName = CTestUtilSessionCommon::AllocateInputBufferLC(aMessage,0); TInt setReadOnly = aMessage.Int1(); TUint setmask; TUint clearmask; if (setReadOnly) { // Setting read only attribute setmask = KEntryAttReadOnly; clearmask = 0; } else { // Clearing read only attribute setmask = 0; clearmask = KEntryAttReadOnly; } // Turn off the read only attributes TTime time(0); TInt err = Server().FileMan().Attribs(*fileName, setmask, clearmask, time); CleanupStack::PopAndDestroy(fileName); aMessage.Complete(err); break; } case EGetFileHandle: { HBufC* fileName = CTestUtilSessionCommon::AllocateInputBufferLC(aMessage,0); RFile file; CleanupClosePushL(file); User::LeaveIfError(file.Open(Server().FS(), *fileName, EFileRead | EFileShareReadersOnly)); User::LeaveIfError(file.TransferToClient(aMessage, 1)); CleanupStack::PopAndDestroy(2, fileName); // file break; } case EWatchFile: { if (iFileWatcher) { if (iFileWatcher->IsActive()) { aMessage.Complete(KErrServerBusy); break; } else { delete iFileWatcher; iFileWatcher = NULL; } } // Create a new file watcher for this session iFileWatcher = CFileWatcher::NewL(Server().FS(), aMessage); break; } case EWatchFileCancel: { if (iFileWatcher) { iFileWatcher->Cancel(); aMessage.Complete(KErrNone); } else { // No file watch request to cancel! aMessage.Complete(KErrNotReady); } break; } case EGetNumFiles: { HBufC* dirPath = CTestUtilSessionCommon::AllocateInputBufferLC(aMessage,0); CDir* dirContents = NULL; User::LeaveIfError(Server().FS().GetDir(*dirPath, KEntryAttNormal, ESortNone, dirContents)); TPckg<TInt> numFiles(dirContents->Count()); delete dirContents; aMessage.WriteL(1, numFiles); aMessage.Complete(KErrNone); CleanupStack::PopAndDestroy(dirPath); break; } case ERegenerateCache: { #ifndef SYMBIAN_UNIVERSAL_INSTALL_FRAMEWORK Swi::RSisRegistryWritableSession session; User::LeaveIfError(session.Connect()); CleanupClosePushL(session); session.RegenerateCacheL(); CleanupStack::PopAndDestroy(&session); aMessage.Complete(KErrNone); #else aMessage.Complete(KErrNotSupported); #endif break; } case EGetFileHash: { HBufC* fileNameA = CTestUtilSessionCommon::AllocateInputBufferLC(aMessage,0); CMessageDigest* digest = CalculateFileHashLC(*fileNameA); aMessage.WriteL(1, digest->Final()); aMessage.Complete(KErrNone); CleanupStack::PopAndDestroy(2, fileNameA); break; } default: { PanicClient(aMessage,EPanicIllegalFunction); break; } } }
// -------------------------------------------------------------------------- // CUPnPFileSharingEngine::StoreSharedContainerIDsL // Creates main containers and starts sharing them // -------------------------------------------------------------------------- // TInt CUpnpSelectionWriter::StoreSharedContainerIDsL() const { __LOG8_1( "%s begin.", __PRETTY_FUNCTION__ ); // Leave if aIdArray = NULL if ( !iFileArray ) { User::Leave(KErrArgument); } RFs fs; RFile file; User::LeaveIfError( fs.Connect() ); CleanupClosePushL(fs); TFileName directory; // Get private directory path fs.SessionPath(directory); // Try to create directory TInt error = fs.MkDir(directory); // it's ok if directory already exists if (!(error != KErrNone && error != KErrAlreadyExists)) { // Add file name if ( iMediaType == EImageAndVideo ) { directory.Append( KVisualFile ); } else if ( iMediaType == EPlaylist ) { directory.Append( KMusicFile ); } error = file.Replace(fs, directory, EFileWrite ); if ( !error ) { CleanupClosePushL( file ); RFileWriteStream writeStream(file); CleanupClosePushL( writeStream ); for (TInt index = 0; index < iFileArray->Count(); index++) { // check that sharing of the container was succesful if ( iOkItems.Find( index ) != KErrNotFound ) { // Write identifiers to the file writeStream << iFileArray->MdcaPoint(index); } } // Clean up CleanupStack::PopAndDestroy(&writeStream); // Close writeStream CleanupStack::PopAndDestroy(&file); // Close file } } CleanupStack::PopAndDestroy(&fs); __LOG8_1( "%s end.", __PRETTY_FUNCTION__ ); return error; }
// --------------------------------------------------------------------------------- // CUpnpTmServerDescriptionProvider::GetFile // // --------------------------------------------------------------------------------- // TInt CUpnpTmServerDescriptionProvider::GetFile( const TDesC8& /*aUri*/, RFile& aFile ) { OstTraceFunctionEntry0( CUPNPTMSERVERDESCRIPTIONPROVIDER_GETFILE_ENTRY ); return ( aFile.Open( iFs, iFilePath, EFileShareReadersOnly | EFileRead )); }
// ----------------------------------------------------------------------------- // CLibxml2Tester::DeserializeL // deserialize from file, using setter SetInputFileL // (other items were commented in a header). // ----------------------------------------------------------------------------- // TInt CLibxml2Tester::DeserializeInfosetL( CStifItemParser& aItem) { TInt err; TPtrC pDeserializerType; aItem.GetNextString( pDeserializerType ); TPtrC pInputFile; aItem.GetNextString( pInputFile ); TPtrC pOutputFile; aItem.GetNextString( pOutputFile ); TPtrC pDirtyReturn; aItem.GetNextString( pDirtyReturn ); TLex inputNum (pDirtyReturn); TInt dirtyReturn; inputNum.Val(dirtyReturn); iDoc = parser.ParseFileL(pInputFile); TBufC<100> chunkName(_L("ChunkContainer") ); TInt size = 2000; TInt maxSize = 10000; TInt offset = 0; TInt binarySize = CID_1().Length(); // TBool isReadOnly = EFalse; RChunk chunk; chunk.CreateGlobal(chunkName, size, maxSize); CleanupClosePushL(chunk); TBuf8<32> contbuff = _L8("binary container some data..."); RFs aRFs; aRFs.Connect(); CleanupClosePushL( aRFs ); RFile fp; User::LeaveIfError( fp.Open(aRFs, _L("c:\\testing\\data\\xmleng\\efute\\input\\containers\\petit.jpg"), EFileRead) ); CleanupClosePushL(fp); TXmlEngBinaryContainer bincont = iDoc.CreateBinaryContainerL(CID_1(), contbuff); TXmlEngChunkContainer chunkcont = iDoc.CreateChunkContainerL(CID_2(), chunk, offset, binarySize); TXmlEngFileContainer filecont = iDoc.CreateFileContainerL(CID_3(), fp); iDoc.DocumentElement().AppendChildL(bincont); iDoc.DocumentElement().AppendChildL(chunkcont); iDoc.DocumentElement().AppendChildL(filecont); RArray<TXmlEngDataContainer> list; CleanupClosePushL(list); iDoc.GetDataContainerList(list); RFile fileHandle; RFs aRFs_2; aRFs_2.Connect(); CleanupClosePushL( aRFs_2 ); User::LeaveIfError( fileHandle.Replace( aRFs_2, pOutputFile, EFileStream | EFileWrite | EFileShareExclusive)); CleanupClosePushL( fileHandle ); CTestHandler* testHandle = CTestHandler::NewLC( fileHandle ); if( pDeserializerType.FindF( DEFAULT ) != KErrNotFound ) { CXmlEngDeserializer* des = CXmlEngDeserializer::NewL( *testHandle, EDeserializerDefault ); CleanupStack::PushL( des ); des->SetInputFileL( pInputFile ); TRAP(err,des->DeserializeL()); } else if( pDeserializerType.FindF( XOP ) != KErrNotFound ) { CXmlEngDeserializer* des = CXmlEngDeserializer::NewL( *testHandle, EDeserializerXOP ); CleanupStack::PushL( des ); des->SetInputFileL( pInputFile ); TRAP(err,des->DeserializeL()); } else if( pDeserializerType.FindF( INFOSET ) != KErrNotFound ) { CXmlEngDeserializer* des = CXmlEngDeserializer::NewL( *testHandle, EDeserializerXOPInfoset ); CleanupStack::PushL( des ); des->SetInputFileL( pInputFile ); des->UseExternalDataL( list ); TRAP(err,des->DeserializeL()); } else if( pDeserializerType.FindF( GZIP ) != KErrNotFound ) { CXmlEngDeserializer* des = CXmlEngDeserializer::NewL( *testHandle, EDeserializerGZip ); CleanupStack::PushL( des ); des->SetInputFileL( pInputFile ); TRAP(err,des->DeserializeL()); } CleanupStack::PopAndDestroy( 8 ); if ( err == dirtyReturn ) return KErrNone; else return err; }
/** Reads the contents of the file passed in and checks whether it contains any of the specified virus signatures @return A value depending on whether a known virus is found within the file. @param aFile A CFileCB object which can be used to read the file. @internalComponent */ TInt CTestVirusHook::ScanFile(const TDesC& aName) { TInt r = KErrNone; TInt pos = 0; TInt size = 0; // Rename the file TPtrC tmpFile = _L("VS_RENAMED.VSH"); TParse parse; parse.Set(aName, NULL, NULL); parse.Set(parse.DriveAndPath(), &tmpFile, NULL); r = iFs.Rename(aName, parse.FullName()); if(r != KErrNone) return r; RFile file; r = file.Open(iFs, parse.FullName(), EFileRead); if(r == KErrNone) { r = file.Size(size); } //If the file size is 0, then the file //has just been created - so it can't contain //a virus. if(r != KErrNone || size == 0) { file.Close(); // Rename the file back TInt err = iFs.Rename(parse.FullName(), aName); if(err != KErrNone) return err; return r; } do { r = file.Read(pos, iScanBuf); if (r != KErrNone) { break; } r = ScanBuffer(); pos += iScanBuf.Length(); } while ((r == KErrNotFound) && (iScanBuf.Length() == iScanBuf.MaxLength())); file.Close(); // Rename the file back TInt err = iFs.Rename(parse.FullName(), aName); if(err != KErrNone) return err; if (r > 0) { //We've found an infection return KErrAccessDenied; } else { return KErrNone; } }
// ----------------------------------------------------------------------------- // CLibxml2Tester::TestDisableFeatureL // test setter disable feature // (other items were commented in a header). // ----------------------------------------------------------------------------- // TInt CLibxml2Tester::TestDisableFeatureInfosetL(CStifItemParser& aItem) { TPtrC pType; aItem.GetNextString(pType); TPtrC pDoc; aItem.GetNextString(pDoc); TPtrC pOut1; aItem.GetNextString(pOut1); TPtrC pOut2; aItem.GetNextString(pOut2); iDoc = parser.ParseFileL(pDoc); TBufC<100> chunkName(_L("ChunkContainer") ); TInt size = 2000; TInt maxSize = 10000; TInt offset = 0; TInt binarySize = CID_1().Length(); // TBool isReadOnly = EFalse; RChunk chunk; chunk.CreateGlobal(chunkName, size, maxSize); CleanupClosePushL(chunk); TBuf8<32> contbuff = _L8("binary container some data..."); RFs aRFs; aRFs.Connect(); CleanupClosePushL( aRFs ); RFile fp; User::LeaveIfError( fp.Open(aRFs, _L("c:\\testing\\data\\xmleng\\efute\\input\\containers\\petit.jpg"), EFileRead) ); CleanupClosePushL(fp); TXmlEngBinaryContainer bincont = iDoc.CreateBinaryContainerL(CID_1(), contbuff); TXmlEngChunkContainer chunkcont = iDoc.CreateChunkContainerL(CID_2(), chunk, offset, binarySize); TXmlEngFileContainer filecont = iDoc.CreateFileContainerL(CID_3(), fp); iDoc.DocumentElement().AppendChildL(bincont); iDoc.DocumentElement().AppendChildL(chunkcont); iDoc.DocumentElement().AppendChildL(filecont); RArray<TXmlEngDataContainer> list; CleanupClosePushL(list); iDoc.GetDataContainerList(list); RFile fileHandle_1; RFile fileHandle_2; // create session 1 RFs fs_1; fs_1.Connect(); CleanupClosePushL( fs_1 ); // create session 2 RFs fs_2; fs_2.Connect(); CleanupClosePushL( fs_2 ); User::LeaveIfError( fileHandle_1.Replace( fs_1, pOut1, EFileStream | EFileWrite | EFileShareExclusive ) ); CleanupClosePushL( fileHandle_1 ); CTestHandler* testHandle_1 = CTestHandler::NewLC( fileHandle_1 ); User::LeaveIfError( fileHandle_2.Replace( fs_2, pOut2, EFileStream | EFileWrite | EFileShareExclusive ) ); CleanupClosePushL( fileHandle_2 ); CTestHandler* testHandle_2 = CTestHandler::NewLC( fileHandle_2 ); CXmlEngDeserializer* des = CXmlEngDeserializer::NewL( *testHandle_1, RetDeserializerType(pType) ); CleanupStack::PushL( des ); des->UseExternalDataL( list ); des->EnableFeature( EReportNamespaceMapping ); des->DisableFeature( EReportNamespaceMapping ); if ( des->IsFeatureEnabled( EReportNamespaceMapping ) ) User::Leave(KErrGeneral); des->DeserializeL( pDoc ); des->EnableFeature( EReportNamespaceMapping ); des->SetContentHandlerL( *testHandle_2 ); des->DisableFeature(EReportNamespaceMapping ); des->DeserializeL( fs_2, pDoc ); if(des->IsFeatureEnabled(EReportNamespaceMapping)) User::Leave(KErrGeneral); CleanupStack::PopAndDestroy( 11 ); return KErrNone; }
/** Read the virus definition file C:\virusdef.txt and parse its contents. Any virus definitions found in that file are added to the KnownSignatures array so they can be used by the virus scanning hook. @internalComponent @return KErrNone if the file was read and parsed successfuly. */ TInt CTestVirusHook::ReadVirusDefinitionFile() { TInt r = iFs.Connect(); if (r != KErrNone) return r; r = iFs.SetNotifyChange(EFalse); // Disable change notifications if (r != KErrNone) return r; //Open the virus definition file RFile vsDefFile; r = vsDefFile.Open(iFs, _L("C:\\virusdef.txt"), EFileShareAny); if (r != KErrNone) return r; TInt fileSize=0; r = vsDefFile.Size(fileSize); if (r != KErrNone) { vsDefFile.Close(); return r; } HBufC8* defBuf=NULL; TRAP(r,defBuf = HBufC8::NewL(fileSize)); if (r != KErrNone) { vsDefFile.Close(); return r; } TPtr8 ptr(defBuf->Des()); r = vsDefFile.Read(ptr); if (r != KErrNone) { delete defBuf; vsDefFile.Close(); return r; } //Now parse the definition file, putting the definitions into the hook's //array of known virus signatures. TInt bytesParsed = 0; TInt stringBeginPos = 0; TInt stringEndPos = 0; TInt stringLength = 0; HBufC8* signatureBuf = NULL; while (bytesParsed < fileSize) { ptr.Set(defBuf->Des()); ptr.Set(&ptr[bytesParsed], fileSize-bytesParsed, fileSize-bytesParsed); stringBeginPos = ptr.MatchF(_L8(":*;*")); if (stringBeginPos < 0) { break; } stringBeginPos += 1; //: stringBeginPos += bytesParsed; ptr.Set(defBuf->Des()); ptr.Set(&ptr[stringBeginPos], fileSize-stringBeginPos, fileSize-stringBeginPos); stringEndPos = ptr.MatchF(_L8("*;*")); if (stringEndPos < 0) { break; } stringEndPos += bytesParsed; stringLength = stringEndPos - stringBeginPos + 1; ptr.Set(defBuf->Des()); TRAP(r,signatureBuf = HBufC8::NewL(stringLength)); TPtrC8 actualSig(ptr.Mid(stringBeginPos, stringLength)); TPtr8 ptr2(signatureBuf->Des()); ptr2.Append(actualSig); iKnownSignatures[iSignaturesLoaded] = signatureBuf; iSignaturesLoaded++; bytesParsed += 1; //: bytesParsed += stringLength; bytesParsed += 1; //; } //Cleanup delete defBuf; vsDefFile.Close(); return r; }
// --------------------------------------------------------- // CPosTp17::StartL // // (other items were commented in a header). // --------------------------------------------------------- // void CPosTp17::StartL() { #ifdef __WINS__ _LIT(KNotSupported, "Test case is not supported on WINS, exucute it on target!"); LogErrorAndLeave(KNotSupported); #else _LIT(KErrors, "One or several Dll's have an incorrect size"); SetupTestDataL(); RFs session; User::LeaveIfError(session.Connect()); CleanupClosePushL(session); RFile file; TBuf<1> drive= _L("c"); TBuf<KMaxDllFileNameLength> name; name.Copy(iDllNames[0]); name.Replace(0,1,drive); if (file.Open(session, name, EFileRead) != KErrNone) { iLog->Put(_L("(Flashed) Use Drive Z:")); drive.Copy(_L("z")); } else iLog->Put(_L("(Nonflashed) Use Drive C:")); file.Close(); TBool errors=EFalse; for (TInt i=0; i<iDllNames.Count(); i++) { name.Copy(iDllNames[i]); name.Replace(0,1,drive); //User::LeaveIfError(file.Open(session, name, EFileRead)); TInt err = file.Open(session, name, EFileRead); if (err != KErrNone) { TBuf<70> buffe; buffe.Append(_L("Error when opening file ")); buffe.Append(name); LogErrorAndLeave(buffe, err); } CleanupClosePushL(file); TInt fileSize=0; file.Size(fileSize); if (fileSize > iFootprints[i]) { errors = ETrue; _LIT(KDllSizeErr, "ERROR: %S is to big (%d), Max allowed ROM footprint is %d"); TBuf<255> info; HBufC* temp = name.Alloc(); info.Format(KDllSizeErr, temp, fileSize, iFootprints[i]); delete temp; iLog->Put(info); } else { // Always log .dll size _LIT(KDllSizeDebug, "%S is (%d), Max allowed ROM footprint is %d"); TBuf<255> info; HBufC* temp = name.Alloc(); info.Format(KDllSizeDebug, temp, fileSize, iFootprints[i]); delete temp; iLog->Put(info); } CleanupStack::PopAndDestroy(&file); } CleanupStack::PopAndDestroy(&session); if (errors) { LogErrorAndLeave(KErrors); } #endif }
/** * Installs a component by file handle using opaque arguments/results */ static TInt sifByHandleAndArgsAndResultsInstallL() { // Open file handle to the installation file RFs fs; TInt err = fs.Connect(); if (KErrNone != err) { ELOG1(EJavaConverters, "testsifapi: sifByHandleAndArgsAndResultsInstallL: Cannot connect to RFs, err %d", err); User::Leave(err); } CleanupClosePushL(fs); // If the file server session is not shared, USIF server crashes with KERN-EXEC 44 err = fs.ShareProtected(); if (KErrNone != err) { ELOG1(EJavaConverters, "testsifapi: sifByHandleAndArgsAndResultsInstallL: Cannot share RFs, err %d", err); User::Leave(err); } // TEMP TEST RFile installFile; err = installFile.Open(fs, KTestMIDlet3, EFileShareReadersOnly | EFileRead); if (KErrNone != err) { ELOG1(EJavaConverters, "testsifapi: sifByHandleAndArgsAndResultsInstallL: Cannot open " "E:\\stopwatch10midp2.jad, err %d", err); User::Leave(err); } CleanupClosePushL(installFile); LOG(EJavaConverters, EInfo, "testsifapi: sifByHandleAndArgsAndResultsInstallL: installFile handle opened"); RSoftwareInstall installer; err = installer.Connect(); if (KErrNone != err) { ELOG1(EJavaConverters, "testsifapi: sifByHandleAndArgsAndResultsInstallL: Cannot connect to RSoftwareInstall, err %d", err); User::Leave(err); } CleanupClosePushL(installer); LOG(EJavaConverters, EInfo, "testsifapi: sifByHandleAndArgsAndResultsInstallL: RSoftwareInstall connected"); TRequestStatus status; COpaqueNamedParams *arguments = COpaqueNamedParams::NewL(); CleanupStack::PushL(arguments); COpaqueNamedParams *results = COpaqueNamedParams::NewL(); CleanupStack::PushL(results); // Silent installation request arguments->AddIntL(KSifInParam_InstallSilently, 1); // drive E: arguments->AddIntL(KSifInParam_Drive, 4); // 0 is TSifPolicy::EUserAllowed == Yes arguments->AddIntL(KSifInParam_PerformOCSP, 0); arguments->AddIntL(KSifInParam_IgnoreOCSPWarnings, 0); arguments->AddIntL(KSifInParam_AllowUpgrade, 0); arguments->AddIntL(KSifInParam_AllowUntrusted, 0); arguments->AddIntL(KSifInParam_AllowOverwrite, 0); arguments->AddIntL(KSifInParam_AllowDownload, 0); // TEMP TEST prevent overflow // arguments->AddStringL(KSifInParam_UserName, KUserName); // arguments->AddStringL(KSifInParam_Password, KPassWord); arguments->AddStringL(KSifInParam_SourceUrl, KSourceUrl); arguments->AddIntL(KSifInParam_IAP, 3); arguments->AddStringL(KSifInParam_Charset, KEmptyString); arguments->AddStringL(KSifInParam_MimeType, KJadMimeType); LOG(EJavaConverters, EInfo, "testsifapi: sifByHandleAndArgsAndResultsInstallL: arguments created"); installer.Install(installFile, *arguments, *results, status); User::WaitForRequest(status); LOG1(EJavaConverters, EInfo, "testsifapi: sifByHandleAndArgsAndResultsInstallL: The return status of install operation was %d", status.Int()); TInt componentId = 0; TBool idExisted = results->GetIntByNameL(KSifOutParam_ComponentId, componentId); if ( idExisted ) { LOG1(EJavaConverters, EInfo, "testsifapi: sifByHandleAndArgsAndResultsInstallL: Component id was %d", componentId); } else { LOG(EJavaConverters, EInfo, "testsifapi: sifByHandleAndArgsAndResultsInstallL: No component id was returned"); } // free resources before returning CleanupStack::PopAndDestroy(5); return componentId; }
/** Compares 2 vcf fie @param aExpectedFile The expected vcf file @param aFile This is the vcf file produced, and will be compared against aExpectedFile @param aProperty This is the property we are interested in */ void CTestCompareCntFiles::CompareFileL(const TDesC& aExpectedFile, const TDesC& aFile, TDes8& aProperty) { RFile fileExpected; RFile fileOutput; CleanupClosePushL(fileExpected); CleanupClosePushL(fileOutput); TInt err = KErrNone; err = fileExpected.Open(iFsSession, aExpectedFile, EFileRead); if (err != KErrNone) { ERR_PRINTF2(_L("Unable to open file: %S"), &aExpectedFile); SetTestStepResult(EFail); SetTestStepError(err); } err = fileOutput.Open(iFsSession, aFile, EFileRead); if (err != KErrNone) { ERR_PRINTF2(_L("Unable to open file: %S"), &aFile); SetTestStepResult(EFail); SetTestStepError(err); } RFileReadStream streamExpected(fileExpected); RFileReadStream streamOutput(fileOutput); CleanupClosePushL(streamExpected); CleanupClosePushL(streamOutput); TBuf8<0x80> bufExpected,bufOutput; TBool isProperty = EFalse; TBool isPropertyExpected = EFalse; TBool foundBothProperty = EFalse; TBool flag = EFalse; TInt err1 = KErrNone; do // This do loop iterates through both files, until the end of file is found { do // This do loop iterates thorugh both files until both properties are found and compares them { foundBothProperty = EFalse; if (!isProperty) { TRAP(err, streamExpected.ReadL(bufExpected, KLinefeedChar)); } if (!isPropertyExpected) { TRAP(err1, streamOutput.ReadL(bufOutput, KLinefeedChar)); } if (err != KErrEof || err1 != KErrEof) { isProperty = IsPropertyPresent(bufExpected, aProperty); // checks if aProperty if(isProperty && err1 == KErrEof) { break; } isPropertyExpected = IsPropertyPresent(bufOutput, aProperty); // checks if aProperty } else { break; } if ((isProperty) && (isPropertyExpected)) { foundBothProperty = ETrue; flag = ETrue; } } while (!foundBothProperty); // exit 2nd do loop when both properties found // Exists 2nd do loop, so both properties are found if (err != KErrEof && err1 != KErrEof) { if(aProperty != KRevision) { CompareLinesL(bufExpected, bufOutput); // compares both properties } else { break; } } // After comparing, gets the next property parameters in vcs file, if we have not reached end of file TRAP(err, streamExpected.ReadL(bufExpected, KLinefeedChar)); TRAP(err1, streamOutput.ReadL(bufOutput, KLinefeedChar)); } while (err != KErrEof || err1 != KErrEof); // exits 2nd do loop when its reached the end of either file TBuf<KMaxLengthField> buf; buf.Copy(aProperty); TPtrC ptr(buf); if(flag) { INFO_PRINTF2(_L("Property: %S Exported properly"), &ptr); } else { INFO_PRINTF2(_L("Property: %S not exported"), &ptr); SetTestStepResult(EFail); } CleanupStack::PopAndDestroy(4, &fileExpected); }
void CDstIntUtils::GenerateVCalL(RFs& aFs, const TDesC& aFileName, const TDesC& aStartTime, const TDesC& aEndTime) { RFile file; file.Replace(aFs, aFileName, EFileWrite); TBuf8<64> buf; file.Write(_L8("BEGIN:VCALENDAR\r\n")); file.Write(_L8("VERSION:1.0\r\n")); file.Write(_L8("BEGIN:VEVENT\r\n")); file.Write(_L8("CATEGORIES:MEETING\r\n")); file.Write(_L8("DTSTART:")); buf.Copy(aStartTime); file.Write(buf); file.Write(_L8("\r\n")); file.Write(_L8("DTEND:")); buf.Copy(aEndTime); file.Write(buf); file.Write(_L8("\r\n")); file.Write(_L8("SUMMARY:TestMeeting\r\n")); file.Write(_L8("DESCRIPTION:Test\r\n")); file.Write(_L8("END:VEVENT\r\n")); file.Write(_L8("END:VCALENDAR\r\n")); file.Flush(); file.Close(); }