void CSecMgrStore::WriteScriptInfoL(TExecutableID aExecID, CScript& aScriptInfo)
	{
	__UHEAP_MARK;

	HBufC *scriptFile = HBufC::NewLC(KMaxName);
	TPtr ptr(scriptFile->Des());
	User::LeaveIfError (GetScriptFile (ptr,aExecID));

	CFileStore* store = CPermanentFileStore::ReplaceLC (iFsSession, ptr,
			EFileWrite);

	// Must say what kind of file store.
	store->SetTypeL (KPermanentFileStoreLayoutUid);

	// Construct the output stream.
	RStoreWriteStream outstream;
	TStreamId id = outstream.CreateLC (*store);

	aScriptInfo.ExternalizeL (outstream);

	// Commit changes to the stream
	outstream.CommitL ();

	// Cleanup the stream object
	CleanupStack::PopAndDestroy (&outstream);

	// Set this stream id as the root
	store->SetRootL (id);

	// Commit changes to the store
	store->CommitL ();

	CleanupStack::PopAndDestroy (store);
	CleanupStack::PopAndDestroy (scriptFile);
	__UHEAP_MARKEND;
	}
TInt CSecMgrStore::ReadScriptInfo(TExecutableID aExecID, CScript& aScriptInfo)
	{
	__UHEAP_MARK;

	HBufC *scriptFile = HBufC::NewLC(KMaxName);
	TPtr ptr(scriptFile->Des());
	TInt ret(GetScriptFile (ptr, aExecID));

	if ( KErrNone==ret)
		{
		if ( !BaflUtils::FileExists(iFsSession, ptr))
			{
			return ErrInvalidScriptID;
			}

		CFileStore* store=  NULL;
		store=CPermanentFileStore::OpenLC (iFsSession, ptr,
				EFileShareAny);

		if ( KErrNone==ret)
			{
			RStoreReadStream instream;
			instream.OpenLC (*store, store->Root ());

			aScriptInfo.InternalizeL (instream);

			CleanupStack::PopAndDestroy (&instream);
			CleanupStack::PopAndDestroy (store);
			}
		return ret;
		}
	CleanupStack::PopAndDestroy (scriptFile);
	__UHEAP_MARKEND;

	return ret;
	}
// -----------------------------------------------------------------------------
// COMASuplSettings::SaveL
//
// -----------------------------------------------------------------------------
//
void COMASuplSettings::SaveL( COMASuplSettingsRepository* aRepository )
    {
    iTrace->Trace( _L( "COMASuplSettings::SaveL() Start" ), KTraceSuplSettings, __LINE__ );
     
     HBufC* iapn = NULL;                                       
     _LIT(KNull, "");
     TUint32 iapID = 0;                                      
    // Retrieve APN from Comms DB
    TRAPD(err, iapID = IapIdFromWapIdL( iItem->AssociatedIapId() ) );
    if(err == KErrNone)
    {
    	iapn = iItem->AssociatedIapNameL( iapID, iCommsDb );
    	if ( iapn == NULL )
        {
        iTrace->Trace( _L( "Error Retrieving APN from CommsDB" ), 
                                            KTraceSuplSettings, __LINE__ );
    	User::Leave(KErrNotFound);    
        }
    
    	
    }
    
    // Retrieve HSLP Address
    const TDesC& hslp = iItem->ParameterValue( EWPParameterAddr );
    
    if(iapn!=NULL)
    {
    CleanupStack::PushL( iapn );
    aRepository->SaveL(iapn->Des(), hslp);
    CleanupStack::PopAndDestroy();
  	}
		else
		aRepository->SaveL(KNull, hslp);
	
	    
    }
OS_EXPORT
TBool java::debug::startApp(TUid aApplicationUid, HBufC& aUeiParameters, TProcessId& aProcessId)
{
    LOG1(EDebugApi, EInfo, "-->%s", __PRETTY_FUNCTION__);

    Uid appUid;
    TUidToUid(aApplicationUid, appUid);
    TPtr16 ueiPtr(aUeiParameters.Des());
    std::wstring cmdLineOpts(desToWstring(ueiPtr));

    DebugApiImpl debug;
    pid_t pid = 0;
    int rc = debug.startApp(appUid, cmdLineOpts, pid);
    aProcessId = pid;
    if (rc)
    {
        ELOG3(EDebugApi, "startApp() failed: uid=%S, cmdLineOpts=%S err=%d",
              appUid.toString().c_str(), cmdLineOpts.c_str(), rc);
        return EFalse;
    }

    LOG1(EDebugApi, EInfo, "<--%s", __PRETTY_FUNCTION__);
    return ETrue;
}
TInt CSecMgrStore::GetConfigFile(TDes& aConfigFile)
	{
	TInt ret(KErrNone);

	aConfigFile.Append (KCDrive);

	HBufC *privateDir = HBufC::NewLC(KMaxName);
	TPtr ptr(privateDir->Des());
	ret = iFsSession.PrivatePath (ptr);

	if ( KErrNone==ret)
		{
		aConfigFile.Append (ptr);

		ret = iFsSession.MkDirAll (ptr);

		if ( KErrAlreadyExists==ret)
			ret=KErrNone;

		aConfigFile.Append (KConfigFile);
		}
	CleanupStack::PopAndDestroy (privateDir);
	return ret;
	}
TVerdict CNonExistedPortCheckingStep::doTestStepL()
/**
 * @return - TVerdict code
 * Override of base class pure virtual
 * Our implementation only gets called if the base class doTestStepPreambleL() did
 * not leave. That being the case, the current test result value will be EPass.
 */
	{
	  if (TestStepResult()==EPass)
		{
		TInt portNum = 9; // Loopback support only 8 ports
		TBuf<50> msg;
		_LIT(KMsgFmt,"Comm port <%d> cannot be opened");
		HBufC* KNonExistedPortName = AllocPortNameL(portNum);
		CleanupStack::PushL(KNonExistedPortName);
		msg.Format(KMsgFmt, portNum);
		
		TestErrorCodeL(iPortList[0].port.Open(iCommServer, KNonExistedPortName->Des(), ECommExclusive, ECommRoleDCE), KErrNotSupported, msg);

		SetTestStepResult(EPass);
		CleanupStack::PopAndDestroy(KNonExistedPortName);
		}
	  return TestStepResult();
	}
Example #7
0
void CSyntaxTest::DoPerformPrerequisite(TRequestStatus& aStatus)
	{
	HBufC *searchPath = HBufC::NewLC(iPath.Size() + 1);
	TPtr searchPathPtr(searchPath->Des());
	searchPathPtr.Copy(iPath);
	searchPathPtr.Append(_L("*"));
    TInt err = iFs.GetDir(searchPathPtr, KEntryAttNormal, ESortByName, iDirList);
	if (err != KErrNone)
		{
		iConsole.Printf(_L("Error getting directory "));
		iConsole.Printf(searchPathPtr);
		iConsole.Printf(_L("\n"));
		iOut.writeString(_L("Error getting directory "));
		iOut.writeString(searchPathPtr);
		iOut.writeNewLine();
		iFinished = ETrue;
		TRequestStatus* status = &aStatus;
		User::RequestComplete(status, KErrNone);
		SetScriptError(EFileNotFound, searchPathPtr);
		}
	else
		{
		iConsole.Printf(_L("Please view "));
		iConsole.Printf(KSyntaxLogFile);
		iConsole.Printf(_L(" for results\n"));
		iOut.writeString(_L("Please view "));
		iOut.writeString(KSyntaxLogFile);
		iOut.writeString(_L(" for results"));
		iOut.writeNewLine();
		iActionState = EAction;
		TRequestStatus* status = &aStatus;
		User::RequestComplete(status, KErrNone);
		iResult = ETrue;
		}
	CleanupStack::PopAndDestroy(); // searchPath
	}
/**
 * Method to fetch the list of plugin ids associated with Authentication App id,
 * it is called internally by fetchPluginList().
 * @param aAuthAppId ID of the Authentication app
 * @param aArray [out] The array to be updated with plugin ids
 */
void CSmfCredMgrDbUser::readPluginIdL(const TDesC& aAuthAppId, RPointerArray<
                                      HBufC>& aArray)
{
    TInt err(KErrNone);
    RSqlStatement sqlReadStatement;
    TInt paramIndex(KErrNone);
    TInt flag;

    err = sqlReadStatement.Prepare(iDataBase, KSmfDbReadPluginID);
    __ASSERT_DEBUG( (err >= KErrNone), User::Invariant());
    paramIndex = sqlReadStatement.ParameterIndex(_L(":iID"));
    err = sqlReadStatement.BindText(paramIndex, aAuthAppId);
    __ASSERT_DEBUG( (err >= KErrNone), User::Invariant());

    while ((err = sqlReadStatement.Next()) == KSqlAtRow)
    {
        //sometimes sqlStmt.Next returns KSqlAtRow even if no row is present
        if (!sqlReadStatement.IsNull(0))
        {
            flag = sqlReadStatement.ColumnInt(1);
            if (flag > 0)
            {
                TBuf<KMaxBufSize> pluginbuf;
                HBufC* buf = HBufC::NewL(KMaxBufSize);
                sqlReadStatement.ColumnText(0, pluginbuf);
                buf->Des().Copy(pluginbuf);
                aArray.Append(buf);
            }
        }
        else
        {
            __ASSERT_DEBUG( 0, User::Invariant());
        }
    }
    sqlReadStatement.Close();
}
void CBkmrkProperties::TransLoadL()
	{
	TUint32 indexBase = IndexBase();
	TInt low  = 0;
	TInt high = 0;
	TInt err = iRepository->Get( indexBase + KBkmrkLastModifiedLoIndex, low );
	if ( err == KErrNone )
		{
		User::LeaveIfError(iRepository->Get(indexBase + KBkmrkLastModifiedHiIndex, high));					
		TUint32 timeLo = static_cast<TUint32>(low);
		TUint32 timeHi = static_cast<TUint32>(high);
		TInt64 time = MAKE_TINT64(timeHi, timeLo);
		iLastModified = time;
		}
	else
		{
		// Set the time as 1st January 1970 midnight.
		TDateTime dt ( 1970, EJanuary, 1, 0, 0, 0, 0 );
		iLastModified = TTime ( dt );
		}
		
	HBufC* descBuffer = HBufC::NewLC(Bookmark::KMaxDescriptorLength);
	TPtr descPtr = descBuffer->Des();
	User::LeaveIfError(iRepository->Get(indexBase + KCmnDescriptionIndex, descPtr));
	delete iDescription;
	iDescription = NULL;
	iDescription = descPtr.AllocL();
	CleanupStack::PopAndDestroy(descBuffer);
	
	TInt retVal;
	User::LeaveIfError(iRepository->Get(indexBase + KCmnIconIndex, retVal));
	iIconId = static_cast<Bookmark::TAttachmentId>(retVal);
	
	iCustomProperties->TransLoadL();
	SetClean();
	}
// Handles assertions from ArchConfigMisc.h
void
handleAssert( const char* cause, const char* file, int line )
{
#ifndef __WINS__
   char* newStr = new char[strlen(cause) + strlen(file) + 2 + 1 ];
   char* lastSlash = strrchr(file, '/');
   if ( lastSlash == NULL ) {
      lastSlash = strrchr(file, '\\');
   }
   if ( lastSlash != NULL ) {
      file = lastSlash + 1;
   }
   sprintf(newStr, "%s", file);

   int length = strlen( newStr );

   HBufC* buf = HBufC::New( 2*length + 2 );

   // Modifyable buffer from inside the HBufC
   TPtr charBuf = buf->Des();
   
   for ( int i = 0; i < length + 1; ++i ) {
      charBuf.Append( (TChar) newStr[i] );
   }
   charBuf.PtrZ();

   delete [] newStr;
   // Show the assertion
   User::Panic( *buf, line );
#else
   cause = cause; // To remove warnings.
   file = file;
   line = line;
   *((uint8*)(0)) = 0;
#endif
}
//Extract URI components
void CExampleInetProtUtil::RetrieveFileNameL()
	{
	_LIT(KTextRet, "\n\n\nRetrieving filename from....\n");
	iConsole->Printf ( KTextRet );
	
	//Create a Uri 
	_LIT(KUriRetName, "K:\\ws\\direct\\direct.mmp");
	TBuf<40> desUriRetName(KUriRetName);
	CUri8* uriRetName = CUri8::CreateFileUriL(desUriRetName);  
	
	//Display the Uri
	const TDesC8& uriDisp = uriRetName->Uri().UriDes();
	TBuf16<100> desRetrieve;
	desRetrieve.Copy (uriDisp);
	iConsole->Printf ( desRetrieve );
	
	//Parse the Uri
	TUriParser8* uriComp = new(ELeave) TUriParser8();
	uriComp->Parse(uriDisp);
	
	//Get or Extract the Filename from the Uri
	_LIT(KTextGetFilename, "\nGetting the filename....\n");
	iConsole->Printf ( KTextGetFilename );
	
	HBufC* fileName = uriComp->GetFileNameL();
	TPtr uriFileNameDisplay = fileName->Des();
	TBuf16<100> desFileName;
	desFileName.Copy (uriFileNameDisplay);
	iConsole->Printf ( desFileName );

	delete fileName;
	delete uriComp;
	delete uriRetName;
	
	iConsole->Getch();
	}
// ---------------------------------------------------------------------------
// Packages object to HBufC descriptor
// ---------------------------------------------------------------------------
//
EXPORT_C const HBufC* TConnMonWLANNetwork::ToBuf() const
    {
    HBufC* buf = HBufC::New( KMaxWlanNetBufSize );
    if( !buf )
        {
        return buf;
        }

    TPtr ptr( buf->Des() );

    ptr.Append( iName.Length() );
    ptr.Append( iName );
    ptr.Append( iConnectionMode );
    ptr.Append( iSignalStrength );
    ptr.Append( iSecurityMode );
    ptr.Append( KNumberOfExtraFields );

    for( TUint i = 0; i < iBuf.Count(); ++i )
        {
        ptr.Append( iBuf[i] );
        }

    return buf;
    }
Example #13
0
void CSyntaxTest::ConstructL(const TTestActionSpec& aTestActionSpec)
	{
	CTestAction::ConstructL(aTestActionSpec);

	if(nInstances==0)
		{
		nInstances++;
		HBufC* body = HBufC::NewLC(aTestActionSpec.iActionBody.Length());
		iExpectedResults = new (ELeave)RPointerArray<CSyntaxResult>;
		body->Des().Copy(aTestActionSpec.iActionBody);
		TPtrC chainBuf = Input::ParseElement(*body, KPathStart);
		iPath.Copy(chainBuf);
		CleanupStack::PopAndDestroy();
		User::LeaveIfError(iLogFile.Replace(iFs,KSyntaxLogFile,EFileWrite));
		iSyntaxOut = new(ELeave) FileOutput(iLogFile);
		iWriter = new(ELeave) CertWriter(iSyntaxOut);
		LoadResultsL();
		}
	else
		{
		SetScriptError(ESyntax, _L("Only one syntax test can be run in each script"));
		iFinished = ETrue;		
		}
	}
LOCAL_C void CreateNewSmtpSettingsL()
	{
	testUtils->iMsvEntry->SetEntryL(smtpService);
	TMsvId serviceId = smtpService;
	//overwrite the settings with test code one.  Don't want the default settings.
	CImSmtpSettings* settings = new(ELeave) CImSmtpSettings();
	CleanupStack::PushL(settings);
	CEmailAccounts* accounts = CEmailAccounts::NewLC();
	TSmtpAccount smtpAccountId;
	accounts->GetSmtpAccountL( serviceId, smtpAccountId);
	accounts->LoadSmtpSettingsL(smtpAccountId, *settings);
	TInt serverLength = testUtils->MachineName().Length();
	HBufC* serverad = HBufC::NewL(serverLength + 7 ); // 7 is the length of KServerAddress
	CleanupStack::PushL(serverad);
	serverad->Des().Copy(testUtils->MachineName());
	serverad->Des().Append(KServer);	
    settings->SetServerAddressL(*serverad);
    HBufC* emailaddress = HBufC::NewL(serverLength + 8 + serverad->Des().Length() + 1 );
   	CleanupStack::PushL(emailaddress);
   	emailaddress->Des().Copy(testUtils->MachineName());
   	emailaddress->Des().Append(KAt);
   	emailaddress->Des().Append(*serverad);
   	settings->SetEmailAddressL(*emailaddress);
	settings->SetReplyToAddressL(*emailaddress);
	settings->SetReceiptAddressL(*emailaddress);
	settings->SetEmailAliasL(_L("Test Account"));
	settings->SetBodyEncoding(EMsgOutboxMIME);
	settings->SetRequestReceipts(EFalse);
	settings->SetPort(25);
	TSmtpAccount smtpAccount;
 	accounts->GetSmtpAccountL(smtpService, smtpAccount);
	accounts->SaveSmtpSettingsL(smtpAccount, *settings);
	CleanupStack::PopAndDestroy(emailaddress);
	CleanupStack::PopAndDestroy(serverad);
	CleanupStack::PopAndDestroy(2,settings);
	testUtils->WriteComment(_L("Created New SmtpSettings  "));	
		
	}
// ---------------------------------------------------------
// CFepSetupContainer::InstallFepL
// ---------------------------------------------------------
//
void CFepSetupContainer::InstallFepL()
	{
	TBuf<KFormatBufSize> formatingBuf;

    TInt index( 0 );
    CAknListQueryDialog* dlg = new(ELeave) CAknListQueryDialog( &index );
    dlg->PrepareLC( R_FEPSETUP_LIST_QUERY );
    dlg->SetItemTextArray( iNamesOfAvailableFeps );
    dlg->SetOwnershipType( ELbmDoesNotOwnItemArray );

    // Execute the dialog
	TInt answer = dlg->RunLD();

    if( answer == EAknSoftkeyOk )
		{
#ifndef __SERIES60_3X__ // Series60 1.x/2.x API
		iEikonEnv->InfoMsg( TParsePtrC( iFileNamesOfAvailableFeps->MdcaPoint( index )).Name());

		// The code below is to check whether the selected Fep is already installed.
		HBufC* fepToInstall = iFileNamesOfAvailableFeps->MdcaPoint( index ).AllocL();
		CleanupStack::PushL( fepToInstall );
		TPtr fepToInstallPtr( fepToInstall->Des() );
        fepToInstallPtr.LowerCase(); // remove case-sensitivity
		TPtrC fepToInstallPtrC( TParsePtrC( fepToInstallPtr ).Name()); // file name parsing

		HBufC* currentFep = iCoeEnv->NameOfInstalledFepL();
		
		CleanupStack::PushL( currentFep );
		TPtr currentFepPtr( currentFep->Des() );
        currentFepPtr.LowerCase(); // remove case-sensitivity
		TPtrC currentFepPtrC( TParsePtrC( currentFepPtr ).Name()); // file name parsing

		if( fepToInstallPtrC.Compare( currentFepPtrC ) == 0) // Already installed?
			{
			formatingBuf.Format( KFepAlreadyInstalled, &fepToInstallPtrC );
			}
		else
			{
			// Loads the specified FEP DLL into all running applications.
			// The current loaded FEP, if any, will be unloaded.
			iCoeEnv->InstallFepL( iFileNamesOfAvailableFeps->MdcaPoint( index ));

			formatingBuf.Format( KFepInstalled, &fepToInstallPtrC );
			}

		CAknConfirmationNote* confirmationDialog = new(ELeave)CAknConfirmationNote();
		confirmationDialog->ExecuteLD( formatingBuf );

		CleanupStack::PopAndDestroy( 2 ); // currentFep, fepToInstall;

#else // Series60 3.x API

		TPtrC fepToInstallPtr( TParsePtrC( iNamesOfAvailableFeps->MdcaPoint( index )).Name()); // file name parsing
		iEikonEnv->InfoMsg( fepToInstallPtr );

		// The code below is to check whether the selected Fep is already installed.
		TUid fepToInstallUid = iFepUids[index];
		TUid currentFepUid = iEikonEnv->FepUid();
		
		if( currentFepUid == fepToInstallUid )
			{
			formatingBuf.Format( KFepAlreadyInstalled, &fepToInstallPtr );
			}
		else
			{
			// Loads the specified FEP DLL into all running applications.
			// The current loaded FEP, if any, will be unloaded.
			iCoeEnv->InstallFepL( fepToInstallUid );

			formatingBuf.Format( KFepInstalled, &fepToInstallPtr );
			}
		CAknConfirmationNote* confirmationDialog = new(ELeave)CAknConfirmationNote();
		confirmationDialog->ExecuteLD( formatingBuf );			
#endif		
		}
	else
		{
		iEikonEnv->InfoMsg( KNoFep );
		}
	}
// ------------------------------------------------------------------------------------------------
// CArrayPtr<CNpdItem>* CNSmlNotepadDatabase::FetchItemsLC(TBool aIncludeText,
// ------------------------------------------------------------------------------------------------
CArrayPtr<CNpdItem>* CNSmlNotepadDatabase::FetchItemsLC(TBool aIncludeText,
                                                    TInt* aKey)
    {
    _NOTEPAD_DBG_FILE("CNSmlNotepadDatabase::FetchItemsLC(): begin") ;

    CArrayPtr<CNpdItem>* res = new (ELeave) CArrayPtrFlat<CNpdItem> (8);
    CleanupPtrArrayPushL(res);
        
    if(!aKey)
        {
        _NOTEPAD_DBG_FILE("CNSmlNotepadDatabase::FetchItemsLC(): In aKey case");
        RPointerArray<CCalInstance> array;
        CleanupRPtrArrayPushL(array);
        _NOTEPAD_DBG_FILE("CNSmlNotepadDatabase::FetchItemsLC(): After cleaupstack");
        
        TCalTime startDate;
        startDate.SetTimeLocalL(TDateTime(1900, EJanuary, 1, 0, 0, 0, 0));
        TCalTime endDate;
        endDate.SetTimeLocalL(TDateTime(2100, EJanuary, 30, 0, 0, 0, 0));
        CalCommon::TCalTimeRange timeRange(startDate, endDate);
    
        iInstanceView->FindInstanceL(array,CalCommon::EIncludeNotes, timeRange);
        CNpdItem* entry = NULL;
        TInt i = 0;

        while (i < array.Count())
            {
            entry = CNpdItem::NewLC();
            entry->SetKey( array[i]->Entry().LocalUidL() );
            entry->SetModified( array[i]->Entry().LastModifiedDateL().TimeUtcL());
            if(aIncludeText)
                {
                _NOTEPAD_DBG_FILE("CNSmlNotepadDatabase::FetchItemsLC(): aIncludeText true");
                HBufC* content = HBufC::NewL( array[i]->Entry().DescriptionL().Length() );
                content->Des().Copy( array[i]->Entry().DescriptionL() );                
                entry->SetContent( content );
                }
            res->AppendL(entry);
            _NOTEPAD_DBG_FILE("CNSmlNotepadDatabase::FetchItemsLC(): After res->AppendL(entry)");
            CleanupStack::Pop(entry);
            _NOTEPAD_DBG_FILE("CNSmlNotepadDatabase::FetchItemsLC(): After popping (entry)");
            i++;
            }
        _NOTEPAD_DBG_FILE("CNSmlNotepadDatabase::FetchItemsLC(): before pop and destroy");
        CleanupStack::PopAndDestroy(&array);
        _NOTEPAD_DBG_FILE("CNSmlNotepadDatabase::FetchItemsLC(): After While Loop");
        }
    else
        {
        _NOTEPAD_DBG_FILE("CNSmlNotepadDatabase::FetchItemsLC(): In else case");
        CCalEntry* entryTobeFetched(NULL);
        entryTobeFetched = iEntryView->FetchL(*aKey);
        _NOTEPAD_DBG_FILE("CNSmlNotepadDatabase::FetchItemsLC(): After Fetching entry");
        if(entryTobeFetched)
            {
            CleanupStack::PushL(entryTobeFetched); 
            CNpdItem* entry = CNpdItem::NewLC();
            entry->SetKey( entryTobeFetched->LocalUidL() );
            entry->SetModified( entryTobeFetched->LastModifiedDateL().TimeUtcL() );
            if(aIncludeText)
                {
                HBufC* content = HBufC::NewL( entryTobeFetched->DescriptionL().Length() );
                content->Des().Copy( entryTobeFetched->DescriptionL() );                
                entry->SetContent( content );
                }
            res->AppendL(entry);
            CleanupStack::Pop(entry);
            CleanupStack::PopAndDestroy(entryTobeFetched);
            }
        }
    _NOTEPAD_DBG_FILE("CNSmlNotepadDatabase::FetchItemLC(): end");
    return res;
    }
void CSyncTestStep::WriteContactToICCL(TContactICCEntry& aIccEntry, TRequestStatus& aStatus)
/**
 * This method writes the phonebook data passed in the aIccEntry parameter to the ICC.
 */
	{
	CContactDatabase *ContactsDb=NULL;
	TRAPD(err,ContactsDb=CContactDatabase::OpenL());	// First try to open existing database
	if (err != KErrNone)
		{
		TRAP(err,CContactDatabase::CreateL()); // There is no existing database, so create default one
		if (err == KErrNone)
			ContactsDb=CContactDatabase::OpenL();			// Open new database
		}
	CleanupStack::PushL(ContactsDb);
	
	TContactItemId id = ContactsDb->ICCTemplateIdL(); 
	CContactItem* iccTemplate = ContactsDb->ReadContactL(id);
	CleanupStack::PushL(iccTemplate);
	CContactICCEntry* item;
	// If an overwrite is being attempted then ensure an entry with relevant UID is used
	if (aIccEntry.iContactUID > 0)
		{
		TContactItemId realId(GetValidUIDFromContactsDbL());
		item = static_cast<CContactICCEntry*> (ContactsDb->ReadContactL(realId));
		}
	else
		{
		item = CContactICCEntry::NewL(*iccTemplate); // Create an ICC entry
		}
	CleanupStack::PopAndDestroy(iccTemplate);
	CleanupStack::PushL(item);

	// Create phone number field 
	TBuf<RMobilePhone::KMaxMobileTelNumberSize> number;
	if(aIccEntry.iTON==RMobilePhone::EInternationalNumber)
		number.Append(KInternationalPrefix); // Append '+' prefix if International Number
	number.Append(aIccEntry.iNumber);
	AddTextFieldToIccContactL(KStorageTypeText, KUidContactFieldPhoneNumber, KUidContactFieldVCardMapTEL, number, item);

	// Create name field
	TBuf<TContactICCEntry::KMaxPhBkNameSize> name;
	name.Copy(aIccEntry.iName);
	AddTextFieldToIccContactL(KStorageTypeText, KUidContactFieldFamilyName, KUidContactFieldVCardMapUnusedN, name, item);

	if(aIccEntry.iSlotNum!=KSyncIndexNotSupplied) // it is not a new entry so slot number is supplied
		{
		// Create slot number field
		HBufC* buf = HBufC::NewL(5);
		TPtr indexPtr(buf->Des());
		indexPtr.AppendNum(aIccEntry.iSlotNum);
		TPtrC indexPtrC = indexPtr.Mid(0);
		AddTextFieldToIccContactL(KStorageTypeText, KUidContactFieldICCSlot, KUidContactFieldVCardMapNotRequired, indexPtrC, item);
		delete buf;
		}

	// Send a Write-Contact-ICC request
	TRequestStatus status;
	iSession.WriteContact(status, *item, aIccEntry.iSlotNum); 
	User::WaitForRequest(status);
	aStatus = status;
	CleanupStack::PopAndDestroy(2);	// item and ContactsDb
	}
// -----------------------------------------------------------------------------
// CPosLmLocalDatabaseManager::ListDatabasesLC
//
// (other items were commented in a header).
// -----------------------------------------------------------------------------
//
CDesCArray* CPosLmLocalDatabaseManager::ListDatabasesLC()
    {
    CDesCArray* dbArray = new (ELeave) CDesCArrayFlat(KPosDbListGranularity);
    CleanupStack::PushL(dbArray);

    RFs fs;
    CleanupClosePushL(fs);
    User::LeaveIfError(fs.Connect());

    TDriveList driveList;
    User::LeaveIfError(fs.DriveList(driveList));

    RDbs dbSession;
    CleanupClosePushL(dbSession);
    User::LeaveIfError(dbSession.Connect());

    for (TInt drive = EDriveA; drive <= EDriveZ; drive++)
        {
        if ( driveList[drive] && !( driveList[drive] & KDriveAttRemote ) ) // avoid remote drives
            {
            TDriveInfo drvInfo;
            TInt err = fs.Drive( drvInfo, drive );

            if ( !err && drvInfo.iType != EMediaNotPresent )
                {
                CDbDatabaseNames* dbNames = NULL;

                TRAPD(err, dbNames = dbSession.DatabaseNamesL(
                    static_cast<TDriveNumber>(drive), KPosLmDbSecureUid));

                // Ignore all errors except KErrNoMemory (and KErrNone)
                if (err == KErrNone)
                    {
                    CleanupStack::PushL(dbNames);
                    for (TInt i = 0; i < dbNames->Count(); i++)
                        {
                        TPtrC ptr = (*dbNames)[i];

                        if (ptr.Right(KFileExtension().Length()).
                            CompareF(KFileExtension) == 0)
                            {
                            HBufC* fullName = HBufC::NewLC(
                                KFileProtocol().Length() +
                                KProtocolDelimiter().Length() +
                                KDriveAndDelimiterLength +
                                (*dbNames)[i].Length());

                            TChar chr;
                            fs.DriveToChar(drive, chr);

                            TPtr ptr2 = fullName->Des();

                            ptr2.Append(KFileProtocol);
                            ptr2.Append(KProtocolDelimiter);
                            ptr2.Append(chr);
                            ptr2.Append(KDriveDelimiter);
                            ptr2.Append((*dbNames)[i]);

                            dbArray->AppendL(*fullName);
                            CleanupStack::PopAndDestroy(fullName);
                            }
                        }
                    CleanupStack::PopAndDestroy(dbNames);
                    }
                else if (err == KErrNoMemory)
                    {
                    User::Leave(err);
                    }
                }
            }
        }
    CleanupStack::PopAndDestroy(2, &fs); //dbSession
    return dbArray;
    }
/*
-------------------------------------------------------------------------------

    Class: CStifFileParser

    Method: NextSectionL

    Description: Finds n-th (aSeeked) section in file starting from m-th (aOffset) position

    Parameters: const TDesc& aStartTag: in:     Starting tag of a section
                const TDesc& aEndTag:   in:     Ending tag of a section
                TInt& aOffset:          in out: Current offset in file (*)
                TInt aSeeked:           in:     Which section is to be found
    
    Notification: aOffset has different meaning than before adding INCLUDE functionality.
                  If it has 0 value, that means that we need to remove files stack and go
                  back to base file to the beginning. Otherwise we don't change current
                  file read-handler position.

    Return Values: HBufC *: address of a descriptor containing section. Section is returned without tags.
                            Caller must take care about the freeing descriptor.

    Errors/Exceptions:  Leaves if aSeeked is less than 1 or aOffset is negative
    					Leaves if seek command leaves
    					Leaves if cannot allocate buffers
    					Leaves if cannot allocate section
    					Leaves if length of readed line exceeds KMaxLineLength constant

    Status: Proposal

-------------------------------------------------------------------------------
*/
HBufC* CStifFileParser::NextSectionL(const TDesC& aStartTag,
                                     const TDesC& aEndTag,
                                     TInt& aOffset,
                                     TInt aSeeked)
	{
	// Check arguments
	if(aSeeked < 1)
		{		
		User::Leave(KErrArgument);
		}
	if(aOffset < 0)
		{		
		User::Leave(KErrArgument);
		}

	TInt foundSection = 0;
	TInt ret;

	// Alloc buffers to read line
	const TInt KMaxLineLength = 4096; //If length of readed line exceeds this constant, method will leave

	HBufC* buf = HBufC::NewL(KMaxLineLength);
	CleanupStack::PushL(buf);
	TPtr bufPtr(buf->Des());

	HBufC* withoutCommentsBuf = HBufC::NewL(KMaxLineLength);
	CleanupStack::PushL(withoutCommentsBuf);
	TPtr withoutCommentsBufPtr(withoutCommentsBuf->Des());

	HBufC* endOfLine = HBufC::NewL(8);  //After reading a line it contains 0D0A or 0A or null (how readed line is ended)
	CleanupStack::PushL(endOfLine);
	TPtr endOfLinePtr(endOfLine->Des());

	//Set valid position in file
	//but only if offset shows to 0. Otherwise keep previus position
	if(aOffset == 0)
		{
		User::LeaveIfError(iBaseFile.Seek(ESeekStart, aOffset));
		ClearFileStack();
		aOffset = 1;
		}

	//Prepare to read lines
	TBool validSectionBeginFound = EFalse;
	TBool validSectionEndFound = EFalse;
	TSectionFind whatToFindSection = ESectionStart;
	//If no start tag is given start to find end tag immediatly
	if(aStartTag.Length() == 0)
		{
		foundSection++;
		whatToFindSection = ESectionEnd;
		validSectionBeginFound = ETrue;
		}
	if(aEndTag.Length() == 0)
		{
		validSectionEndFound = ETrue;
		}
	TWhatToFind whatToFind = EStart;

	//Perform reading file
	while(ReadLineL(bufPtr, endOfLinePtr))
		{
		if(iCommentType == CStifParser::ECStyleComments)
			{				
			ReplaceCommentsLineL(bufPtr, withoutCommentsBufPtr, whatToFind);
			}
		else
			{
			ReplaceHashCommentsLineL(bufPtr, withoutCommentsBufPtr);
			}
			if(whatToFindSection == ESectionStart)
			{
			//Find in line star tag (if start tag is not given, behave like we've found it)
			if(aStartTag.Length() == 0)
				{
				ret = 0;
				}
			else
				{
				ret = withoutCommentsBuf->Find(aStartTag);
				}
			//If found remember position, move offset of file to actual position
			if(ret >= 0)
				{
				whatToFindSection = ESectionEnd;
				TInt offset = -(bufPtr.Length() + endOfLinePtr.Length() - ret - aStartTag.Length()) * iBytesPerChar;
				User::LeaveIfError(iCurrentFile->Seek(ESeekCurrent, offset));

				whatToFind = EStart; //reset marker, because if we've found tag, we couldn't be in the middle of comment or quota
				foundSection++;
				//Add this line to section lines array
				if(foundSection == aSeeked)
					{
					validSectionBeginFound = ETrue;
					}
				continue;
				}
			}
		else if(whatToFindSection == ESectionEnd)
			{
			//Find in line end tag (if end tag is not given, behave like we've found it)
			if(aEndTag.Length() == 0)
				{
				ret = KErrNotFound;
				}
			else
				{
				ret = withoutCommentsBuf->Find(aEndTag);
				}
				//If found check if this is the one we're looking for
			if(ret >= 0)
				{
				whatToFindSection = ESectionStart;
				TInt offset = -(bufPtr.Length() + endOfLinePtr.Length() - ret - aEndTag.Length()) * iBytesPerChar;
				User::LeaveIfError(iCurrentFile->Seek(ESeekCurrent, offset));

				whatToFind = EStart; //reset marker, because if we've found tag, we couldn't be in the middle of comment or quota
				if(foundSection == aSeeked)
					{
					//Add this line to section lines array
					HBufC* line = HBufC::NewLC(bufPtr.Length());
					TPtr linePtr(line->Des());
					linePtr.Copy(bufPtr.MidTPtr(0, ret));
					User::LeaveIfError(iSectionLines.Append(line));
					CleanupStack::Pop(line);
					validSectionEndFound = ETrue;
					break;
					}
				else
					{
					continue;
					}
				}
			else
				{
				//If we're in section we are looking for, add line to array
				if(foundSection == aSeeked)
					{
					HBufC* line = HBufC::NewLC(bufPtr.Length() + endOfLinePtr.Length());
					TPtr linePtr(line->Des());
					linePtr.Copy(bufPtr);
					linePtr.Append(endOfLinePtr);
					User::LeaveIfError(iSectionLines.Append(line));
					CleanupStack::Pop(line);
					}
				}
			}
		}

	//Clean data
	CleanupStack::PopAndDestroy(endOfLine);
	CleanupStack::PopAndDestroy(withoutCommentsBuf);
	CleanupStack::PopAndDestroy(buf);
	
	//Load into section if found
	HBufC* section = NULL;

	if(validSectionBeginFound && validSectionEndFound)
		{
		//Count amount of memory needed for section
		TInt i;
		TInt size = 0;
		for(i = 0; i < iSectionLines.Count(); i++)
			size += iSectionLines[i]->Length();
		
		//Copy section from array to buffer
		section = HBufC::NewL(size);
		CleanupStack::PushL(section);
		TPtr sectionPtr(section->Des());

		for(i = 0; i < iSectionLines.Count(); i++)
			sectionPtr.Append(*iSectionLines[i]);

		ClearSectionLinesArray();
		
		//Clean local data
		CleanupStack::Pop(section);
		
		return section;
		}
	
	ClearSectionLinesArray();

	//If section was not found, then for compability with CSectionParser leave when not first section was seeking, return NULL when first section was seeking
	if(foundSection != aSeeked)
		{
		if( aSeeked - foundSection > 1)
			{			
			User::Leave(KErrNotFound);
			}
		}

    return section;
	}
Example #20
0
// -----------------------------------------------------------------------------
// CWPMessage::ProcessL
// -----------------------------------------------------------------------------
//
void CWPMessage::ProcessL()
    {
    FLOG( _L( "CWPMessage::ProcessL: Started" ) );

    // Create a phone if one does not already exist
    if( !iPhone )
        {
        iPhone = WPPhoneFactory::CreateL();
        }

    FLOG( _L( "CWPMessage::ProcessL: Creating engine" ) );

    // Read the message into the engine
    CWPEngine* engine = CWPEngine::NewLC(); // on CS

    FLOG( _L( "CWPMessage::ProcessL: Importing document" ) );
    engine->ImportDocumentL( iMessage->Body() );

    FLOG( _L( "CWPMessage::ProcessL: Populating adapters" ) );
    engine->PopulateL();

    FTRACE(RDebug::Print(_L(" WPMessage::ProcessL: Number of settings: (%d)"), engine->ItemCount()));
    // Check if the sender can be trusted
    TPtrC8 orig8( iMessage->Originator() );
    HBufC* originator = HBufC::NewLC( orig8.Length() );
    TPtr orig16( originator->Des() );
    orig16.Copy( orig8 );
    if( engine->ContextExistsL( orig16 ) )
        {
        iMessage->SetAuthenticated( ETrue );
        }
    CleanupStack::PopAndDestroy(); // originator
    
    // Try bootstrapping
    FLOG( _L( "CWPMessage::ProcessL: Bootstrapping" ) );
    CWPBootstrap* bootstrap = CWPBootstrap::NewL( iPhone->SubscriberId() );
    CleanupStack::PushL( bootstrap );

    CWPBootstrap::TBootstrapResult result( 
        bootstrap->BootstrapL( *iMessage, *engine, KNullDesC ) );
    CleanupStack::PopAndDestroy(); // bootstrap

    FTRACE(RDebug::Print(_L(" WPMessage::ProcessL: Bootstrap result: (%d)"), result));
        // See UI specs figure 1 
    TBool haveSettings( engine->ItemCount() > 0 );
    switch( result )
        {
        case CWPBootstrap::ENoBootstrap:
            {
            FLOG( _L( "CWPMessage::ProcessL: Bootstrapping ENoBootstrap" ) );
            // If there's no bootstrap, just save the message
            if( haveSettings )
                {
                StoreMsgL();
                }
            else
                {
                User::Leave( KErrCorrupt );
                }
            break;
            }

        case CWPBootstrap::ENotAuthenticated:
            {
            FLOG( _L( "CWPMessage::ProcessL: Bootstrapping ENotAuthenticated" ) );
            if( haveSettings )
                {
                StoreMsgL();
                }
            else
            {
                
            // Message is ignored and an information SMs is put to Inbox.
            //Information SMs can be Class0,  based on operator requirement.
            TInt auth_value;
            CRepository * rep = 0;
            TRAPD( err, rep = CRepository::NewL( KCRUidOMAProvisioningLV ));
            if(err == KErrNone)
            {
            	rep->Get( KOMAProvAuthFailMsgHandling, auth_value );
            	delete rep;
            	
            	/*if(auth_value == 1)
            	StoreMsgclass0L(R_TEXT_AUTHENTICATION_FAILED);
            	else
            	StoreMsgL(R_TEXT_AUTHENTICATION_FAILED);*/
            	
            	User::Leave( KErrAccessDenied ); 
            }
            else
            {
            //StoreMsgL(R_TEXT_AUTHENTICATION_FAILED);
            User::Leave( KErrAccessDenied );                         
            }
                }
            break;
            }

        case CWPBootstrap::EPinRequired:
            {
            FLOG( _L( "CWPMessage::ProcessL: Bootstrapping EPinRequired" ) );
            
            // If PIN is required, defer authentication to ProvisioningBC
            if( haveSettings )
                {
                StoreMsgL();
                }
            else
                {
                User::Leave( KErrCorrupt );
                }
            break;
            }

        case CWPBootstrap::EAuthenticationFailed:
            {
            FLOG( _L( "CWPMessage::ProcessL: Bootstrapping EAuthenticationFailed" ) );
            
            // Bootstrap is ignored and an information SMS is put to Inbox.
            //Information SMs can be Class0,  based on operator requirement.
            TInt auth_value;
            CRepository * rep = 0;
            TRAPD( err, rep = CRepository::NewL( KCRUidOMAProvisioningLV ));
            if(err == KErrNone)
            {
            	rep->Get( KOMAProvAuthFailMsgHandling, auth_value );
            	delete rep;
            	
            	/*if(auth_value == 1)
            	StoreMsgclass0L(R_TEXT_AUTHENTICATION_FAILED);
            	else
            	StoreMsgL(R_TEXT_AUTHENTICATION_FAILED);*/
            	
            	User::Leave( KErrAccessDenied );
            	
            }
            else
            {
            //StoreMsgL(R_TEXT_AUTHENTICATION_FAILED);
            User::Leave( KErrAccessDenied );
            }
            break;
            }

        case CWPBootstrap::EBootstrapExists:
            {
            FLOG( _L( "CWPMessage::ProcessL: Bootstrapping EBootstrapExists" ) );
            
            if( haveSettings )
                {
                StoreMsgL();
                }
            else
                {
                // Bootstrap is ignored and an information SMS is put to Inbox
                StoreMsgL( R_TEXT_BOOTSTRAP_EXISTS );
                User::Leave( KErrAlreadyExists );
                }
            break;
            }

        case CWPBootstrap::ESucceeded:
            {
            FLOG( _L( "CWPMessage::ProcessL: Bootstrapping ESucceeded" ) );
            
            if( haveSettings )
                {
                StoreMsgL();
                }
            else
                {
                StoreMsgL( R_TEXT_BOOTSTRAPPED );
                }
            break;
            }

        default:
            {
            break;
            }
        }

    CleanupStack::PopAndDestroy(); // engine

    FLOG( _L( "CWPMessage::ProcessL: Finished" ) );
    }
Example #21
0
// ---------------------------------------------------------
// 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);
        }
	}
// -----------------------------------------------------------------------------
// CNSmlDmDevDetailAdapter::FetchLeafObjectL()
// -----------------------------------------------------------------------------
CSmlDmAdapter::TError CNSmlDmDevDetailAdapter::FetchLeafObjectL( const TDesC8& aURI, 
                                                                 CBufBase& aObject )
    {
    _DBG_FILE("CNSmlDmDevDetailAdapter::FetchLeafObjectL(): begin");
    CSmlDmAdapter::TError retValue = CSmlDmAdapter::EOk;

    TInt ret = aURI.LocateReverse(KNSmlDMDevDetailSeparator()[0]);
    if ( ret == KErrNotFound ) 
        {
        ret = -1;
        }
    TInt len = aURI.Length() - ( ret + 1 );
    TPtrC8 segment = aURI.Right( len );
    if ( segment == KNSmlDMDevDetailDevTypNodeName )
        {
        aObject.InsertL( 0, KNSmlDMDevDetailDevTypValue );
        }
    else
    if ( segment == KNSmlDMDevDetailOEMNodeName )
        {
        CNSmlPhoneInfo* phoneInfo = CNSmlPhoneInfo::NewLC();
        HBufC* manufacturer = HBufC::NewLC( 50 );
        TPtr manufacturerPtr = manufacturer->Des();  
        phoneInfo->PhoneDataL( CNSmlPhoneInfo::EPhoneManufacturer, manufacturerPtr );
        HBufC8* manufacturerInUTF8 = NULL;
        NSmlUnicodeConverter::HBufC8InUTF8LC( *manufacturer, manufacturerInUTF8 );
        aObject.InsertL( 0, *manufacturerInUTF8 );
        CleanupStack::PopAndDestroy( 3 ); //manufacturerInUTF8, manufacturer, phoneInfo
        }
    else
    if ( segment == KNSmlDMDevDetailSwVNodeName )
        {
        // fetch software version
        GetDevDetailDataL( aObject, ESwVersion );
        }
    else
    if ( segment == KNSmlDMDevDetailHwVNodeName )
        {
        // fetch hardware version
        GetDevDetailDataL( aObject, EHwVersion );
        }
    else
    if ( segment == KNSmlDMDevDetailLrgObjNodeName )
        {
        aObject.InsertL( 0, KNSmlDMDevDetailLrgObjValue );
        }
    else
    if ( segment == KNSmlDMDevDetailMaxDepthNodeName )
        {
        aObject.InsertL( 0, KNSmlDMDevDetailMaxDepthValue );
        }
    else
    if ( segment == KNSmlDMDevDetailMaxTotLenNodeName )
        {
        aObject.InsertL( 0, KNSmlDMDevDetailMaxTotLenValue );
        }
    else
    if ( segment == KNSmlDMDevDetailMaxSegLenNodeName )
        {
        aObject.InsertL( 0, KNSmlDMDevDetailMaxSegLenValue );
        }
    else
    if ( segment != KNSmlDMDevDetailFwVNodeName )
        {
        retValue = CSmlDmAdapter::EError;
        }
        
    _DBG_FILE("CNSmlDmDevDetailAdapter::FetchLeafObjectL(): end");
    return retValue;
    }
// ---------------------------------------------------------
// CFepSetupContainer::UnInstallFepL
// ---------------------------------------------------------
//
void CFepSetupContainer::UnInstallFepL()
	{
	TBuf<KFormatBufSize> formatingBuf;

#ifndef __SERIES60_3X__ // Series60 1.x/2.x API
	HBufC* currentFep = iCoeEnv->NameOfInstalledFepL();
	CleanupStack::PushL( currentFep );
	
	TPtr currentFepPtr( currentFep->Des() );
    currentFepPtr.LowerCase(); // remove case-sensitivity
	TPtrC currentFepPtrC( TParsePtrC( currentFepPtr ).Name()); // file name parsing

	if( ConeUtils::FileExists( KAknFepFileName )) // 2ndfp2 platform and newer use aknfep.fep
		{
		if( currentFepPtrC.Compare( TParsePtrC( KAknFepFileName ).Name() ) != 0 ) // Already installed?
			{
			iCoeEnv->InstallFepL( KAknFepFileName ); // Install the default Fep
			formatingBuf.Format( KFepUninstalled, &currentFepPtrC );
			}
		else
			{
			formatingBuf.Format( KFepAlreadyInstalled, &currentFepPtrC );
			}
		}
	else // older platforms use T9fep.fep
		{
		if( currentFepPtrC.Compare( TParsePtrC( KT9FepFileName ).Name() ) != 0 ) // Already installed?
			{
			iCoeEnv->InstallFepL( KT9FepFileName ); // Install the default Fep
			formatingBuf.Format( KFepUninstalled, &currentFepPtrC );
			}
		else
			{
			formatingBuf.Format( KFepAlreadyInstalled, &currentFepPtrC );
			}
		}

	CAknConfirmationNote* dialog = new(ELeave)CAknConfirmationNote();
	dialog->ExecuteLD( formatingBuf );

	CleanupStack::PopAndDestroy(); // currentFep
	
#else // Series60 3.x API

	TUid currentFepUid = iEikonEnv->FepUid();
	TInt defaultIndex = iFepUids.Find( KAknFepUid );
	TPtrC defaultFepPtr( TParsePtrC( iNamesOfAvailableFeps->MdcaPoint( defaultIndex )).Name()); // file name parsing
	if( currentFepUid == KAknFepUid )  // Already installed?
		{
		formatingBuf.Format( KFepAlreadyInstalled, &defaultFepPtr );
		}
	else
		{
		iCoeEnv->InstallFepL( KAknFepUid );  // Install the default Fep

		formatingBuf.Format( KFepInstalled, &defaultFepPtr );
		}
	CAknConfirmationNote* confirmationDialog = new(ELeave)CAknConfirmationNote();
	confirmationDialog->ExecuteLD( formatingBuf );			
#endif	
	}
Example #24
0
// --------------------------------------------------------------------------
// CImageCapture::GetNextFileNameLC
// Get the file name
// --------------------------------------------------------------------------
HBufC* CImageCapture::GetNextFileNameLC(const TDesC& aName) const
{
    const TInt KNumberLength = 4; // this is to indicate the file numbering,
                                  // e.g. 0001, 0002, etc.
    const TInt KMaxIndex = 10000;
    const TInt KTimeRecordSize = 512;
    
    TPtrC filePathPtr;
    _LIT(KExtensionpng, ".png");
    _LIT(KSlash,"\\");
    
    // Gets the file extension.
    TPtrC fileExtension;
    fileExtension.Set(KExtensionpng);
   
    filePathPtr.Set(iSettings.iLogPath);
    TInt result = filePathPtr.LocateReverse('\\');
    TPtrC string;
    if(result!=KErrNotFound)
    	string.Set(filePathPtr.Left(result+1));
    
    TBuf8<KTimeRecordSize> fileName;
    fileName.Copy(string);
    
    if(iXmlFileName.Length()>0)
    {
    	TInt pos=iXmlFileName.LocateReverse('.');
    	TPtrC8 ptr;
    	if(pos!=KErrNotFound)
    	{
    		ptr.Set(iXmlFileName.Left(pos));
    		fileName.Append(ptr);
    	}
    	
		fileName.Append(KSlash);
    }
    
    fileName.Append(aName);
    HBufC* newFileName = HBufC::NewLC(fileName.Length()+ KNumberLength + fileExtension.Length() + 1);
    TPtr newFileNamePtr(newFileName->Des());
    newFileNamePtr.Copy(fileName);

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

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

    // If the index greated then KMaxIndex, then rollback to 1
    
    if (index >= KMaxIndex)
    {
    	index = 1;
    }
    
    return newFileName;
}
Example #25
0
void CCmdSetpriority::DoRunL()
	{
	LoadMemoryAccessL();
	TInt err = KErrNone;

	// Fix up priorities that we had to make different to kernel cos fshell can't handle negative arguments
	// See enum TThrdPriority in kern_priv.h for the meaning of these negative numbers
	switch(iPriority)
		{
		case 101: iPriority = -8; break;
		case 102: iPriority = -7; break;
		case 103: iPriority = -6; break;
		case 104: iPriority = -5; break;
		case 105: iPriority = -4; break;
		case 106: iPriority = -3; break;
		case 107: iPriority = -2; break;
		default:
			break;
		}

	if (iName)
		{
		TPtrC8 name8 = iName->Des().Collapse();
		LeaveIfErr(iMemAccess.SetPriorityOverride(iPriority, name8), _L("Couldn't set priority override"));
		iNotifier = new(ELeave) CNewThreadNotifier(*this, iMemAccess);
		iNotifier->Start();
		return;
		}
	
	if (iTids.Count() && iPids.Count())
		{
		LeaveIfErr(KErrArgument, _L("You cannot specify both --tid and --pid - a single priority cannot be valid for thread and process."));
		}

	for (TInt i = 0; i < iTids.Count(); i++)
		{
		TUint id = iTids[i];
		RThread thread;
		err = iMemAccess.RThreadForceOpen(thread, id);
		if (!err) err = iMemAccess.SetThreadPriority(thread, iPriority);
		if (err) PrintError(err, _L("Couldn't set priority for thread %u"), id);
		thread.Close();
		}
	
	for (TInt i = 0; i < iPids.Count(); i++)
		{
		TUint id = iPids[i];
		// Get KProcessFlagPriorityControl flag
		RProcess process;
		err = process.Open(id);
		LeaveIfErr(err, _L("Couldn't open process with ID %u"), id);

		TBool priorityControlAllowed = EFalse;
		TPckg<TProcessKernelInfo> pkg(iProcInfo);
		err = iMemAccess.GetObjectInfoByHandle(EProcess, RThread().Id(), process.Handle(), pkg);
		if (err)
			{
			PrintWarning(_L("Couldn't get priority control flag setting (%d)\r\n"), err);
			}
		else
			{
			if (iProcInfo.iFlags & KProcessFlagPriorityControl) priorityControlAllowed = ETrue;
			}

		if (!priorityControlAllowed)
			{
			PrintError(KErrAccessDenied, _L("This process does not allow setting of its priority"));
			}
		else if (iPriority != EPriorityBackground && iPriority != EPriorityForeground)
			{
			PrintError(KErrAccessDenied, _L("The kernel will ignore requests to set a process priority that isn't Background (250) or Foreground (350). I can't see how to get round this even using memory access. Sorry."));
			}
		process.SetPriority((TProcessPriority)iPriority);
		process.Close();
		}
	Complete(KErrNone);
	}
Example #26
0
 // ---------------------------------------------------------
// CPosTp148::PrintLandmarkFieldsWithDescriptionL
//
// (other items were commented in a header).
// ---------------------------------------------------------
//
void CPosTp148::PrintLandmarkFieldsWithDescriptionL(const CPosLandmark& aLandmark, TBool aTraceFlag)
    {
    iLog->Log(_L("Parsing Description ... \n"));
    
    TPositionFieldId sourceFieldId = aLandmark.FirstPositionFieldId();
    TLocality loc;    

    TInt err;
    TPtrC landmarkName;
    TPtrC landmarkDescription;
    err = aLandmark.GetLandmarkName( landmarkName );
    if ( err == KErrNone )
        {
        
        HBufC* buffer = HBufC::NewLC( landmarkName.Length() + 256 );
        TPtr buf = buffer->Des();
                    
        buf.Append( _L(" \tLandmark Name: "));
        buf.Append( landmarkName );
        iLog->Log( buf );
        if( aTraceFlag ) 
            {
            TraceL( buf );   
            }
            
        CleanupStack::PopAndDestroy( buffer );
        buffer = NULL;  
        }

    err = aLandmark.GetPosition(loc);
    if (err == KErrNone)
        {
        HBufC* buffer = HBufC::NewLC( 1024 );
        TPtr buf = buffer->Des();        
        TRealFormat format( 12, KRealFormatFixed );
        format.iPoint = TChar('.');
        format.iTriLen = KDoNotUseTriads;
        format.iPlaces = 6;
        
        TBuf<20> sLon, sLat, sVacc, sHacc, sAlt, sRad;
        sLon.Num( loc.Longitude(), format );
        sLat.Num( loc.Latitude(), format );
        sAlt.Num( loc.Altitude(), format );
        sVacc.Num( loc.VerticalAccuracy(), format );
        sHacc.Num( loc.HorizontalAccuracy(), format );
        buf.Format(
            _L("\tLM: Long %S Lat %S vertAcc %S horAcc %S alt %S "), 
            &sLon, &sLat, &sVacc, &sHacc, &sAlt);
        
        TReal32 sourceR;
        err = aLandmark.GetCoverageRadius(sourceR);
        if (err == KErrNone )
            {
            sRad.Num( sourceR, format );
            buf.AppendFormat(_L(" srcRadius %S" ), &sRad);
            }
        iLog->Log(buf);
        if (aTraceFlag) TraceL(buf);
        
        CleanupStack::PopAndDestroy( buffer );
        buffer = NULL;  
        }
        
      //Get landmark description  
      err = aLandmark.GetLandmarkDescription(landmarkDescription);
      if (err == KErrNone)
        {
        HBufC* buffer = HBufC::NewLC( landmarkDescription.Length() + 256 );
        TPtr buf = buffer->Des();         
        
        buf.Format(_L("\tLandmark Description: "));
        buf.Append(landmarkDescription);
        iLog->Log(buf);
        if ( aTraceFlag ) 
            {
            TraceL( buf );    
            }
        
        CleanupStack::PopAndDestroy( buffer );
        buffer = NULL;         
        }  
    

    while (sourceFieldId != EPositionFieldNone)
        {
        TPtrC sourceValue;
        aLandmark.GetPositionField(sourceFieldId, sourceValue);
        
        
        HBufC* buffer = HBufC::NewLC( sourceValue.Length() + 256 );
        TPtr buf = buffer->Des();  
                
        buf.Format( _L( "\tIdField Id: %d Value:" ), sourceFieldId );
        buf.Append( sourceValue );
        iLog->Log( buf );
        if ( aTraceFlag ) 
            {
            TraceL( buf );
            }
        sourceFieldId = aLandmark.NextPositionFieldId( sourceFieldId );
        
         CleanupStack::PopAndDestroy( buffer );
        }
    }
void CNcdProtocolDefaultObserver::ConfigurationActionRequestL( 
    MNcdConfigurationProtocolActionRequest* aActionRequest ) 
    {
    DLTRACEIN((""));

    CleanupDeletePushL( aActionRequest );
    
    if( aActionRequest->Type() == MNcdConfigurationProtocolActionRequest::ETypeUpdate &&
        aActionRequest->UpdateDetails() )
    	{
    	DLTRACE(( "Update" ));

    	DLINFO(( _L("Target: %S"), &aActionRequest->Target() ));
       	DLINFO(( _L("Id: %S"), &aActionRequest->UpdateDetails()->Id() ));
    	DLINFO(( _L("Version: %S"), &aActionRequest->UpdateDetails()->Version() ));
    	DLINFO(( _L("Uri: %S"), &aActionRequest->UpdateDetails()->Uri() ));
    	DLINFO(( "Forced: %d", aActionRequest->Force() ));

    	DLINFO(( "Client SID %08x", iContext.SecureId().iId ));    	
    	
    	if ( aActionRequest->Target() == KNcdActionTargetMasterServerUri && 
    	     aActionRequest->UpdateDetails()->Uri().Length() ) 
    	    {
    	    const TDesC& currentMaster( iConfigurationManager.MasterServerAddressL( 
    	        iContext ) );
    	        
    	    // Ensure that request was received from the master server
    	    if ( *iServerUri == currentMaster )
    	        {    	        
    	        /**
    	         * @ Improve this check to notice missing '/' at the end of the URIs
    	         */
    	        if ( aActionRequest->UpdateDetails()->Uri() != currentMaster )
    	            {    	            
            	    DLINFO(("Updating MasterServerUri")); 
            	       
            	    iConfigurationManager.SetMasterServerAddressL( iContext,
            	        aActionRequest->UpdateDetails()->Uri(), 0 );    	    
    	            }
    	        else
    	            {
    	            DLINFO(("MasterServerUri didn't change"));
    	            }
    	        }
    	    else
    	        {
    	        DLERROR(( _L("Invalid update request source! Request source: %S"),
    	            iServerUri ));
    	        }
    	    }
    	else if( aActionRequest->Target() == KNcdActionTargetSkin || 
    	         aActionRequest->Target() == KNcdActionTargetClient ) 
    	    {
        	HBufC* msgQueueName = HBufC::NewLC( KCatalogsUpdateQueueNameFormat().Length() + 8 );
        	msgQueueName->Des().Format( KCatalogsUpdateQueueNameFormat, iContext.SecureId().iId );
        	
        	DLINFO(( _L("Opening client's update message queue: %S"), msgQueueName ));
        	RMsgQueueBase queue;
        	
        	TInt err = queue.OpenGlobal( *msgQueueName );
        	if( err == KErrNone )
        	    {        	    
        	    CleanupClosePushL( queue );
                TInt msgSize = queue.MessageSize();

                // Prepare a buffer to write to update information P&S variable.
                CBufFlat* buffer = CBufFlat::NewL( KCatalogsUpdateInformationMaxSize + msgSize );
                CleanupStack::PushL( buffer );
                
                // Externalize the info to the buffer.
                RBufWriteStream stream( *buffer );
                CleanupClosePushL( stream );
                stream << (TInt32)(aActionRequest->Target().Size() + 
                                   aActionRequest->UpdateDetails()->Id().Size() + 
                                   aActionRequest->UpdateDetails()->Version().Size() +
                                   aActionRequest->UpdateDetails()->Uri().Size() +
                                   sizeof( TInt32 ));
                stream << aActionRequest->Target();
                stream << aActionRequest->UpdateDetails()->Id();
            	stream << aActionRequest->UpdateDetails()->Version();
                stream << aActionRequest->UpdateDetails()->Uri();
                stream << (TInt32)aActionRequest->Force();
                
                // Write the update information to the client's update message queue.
                TInt bytesToSend = buffer->Size();
                for( TInt sendPos = 0; sendPos < bytesToSend; sendPos += msgSize )
                    {
                    const TUint8* sendPtr = buffer->Ptr( sendPos ).Ptr();
                    queue.SendBlocking( sendPtr, msgSize );
                    }
                
                DLINFO(( "Update information sent to message queue" ));
                
                CleanupStack::PopAndDestroy( 3, &queue ); // stream-close, buffer, queue
        	    }
            
            // Clean up the local info buffer.
            CleanupStack::PopAndDestroy( msgQueueName ); 
    	    }
    	else
    	    {
    	    DLINFO(("Unknown Action target"));
    	    }
    	}
    // Action request no longer needed, delete it.
    CleanupStack::PopAndDestroy( aActionRequest );
    }
void CValidateCertChainStep::ValidateL(TTime aValidateTime, TDes& aConfigSection)
	{
	
	CPKIXValidationResult* result = CPKIXValidationResult::NewLC();
	
	iActiveObject = new (ELeave) CValidateCertChainHelper(Logger());
	CleanupStack::PushL(iActiveObject);

	User::LeaveIfError(iActiveObject->PerformTestL(iCertChain, *result, aValidateTime));

	CleanupStack::PopAndDestroy(iActiveObject);
	iActiveObject = NULL;

	TInt expectedError;
	GetIntFromConfig(aConfigSection, KError, expectedError);
		
	if ((result->Error()).iReason != expectedError)
		{
		ERR_PRINTF3(_L("ERROR: Error: %d.  Expected error: %d"), (result->Error()).iReason, expectedError);
		User::Leave(KErrGeneral);
		}
			
	if (expectedError != EValidatedOK)
		{
		//we are expected to error
		TInt certIndex;
		GetIntFromConfig(aConfigSection, KErrorIndex, certIndex);	
		if ((result->Error()).iCert != certIndex)
			{			
			ERR_PRINTF3(_L("ERROR: Error certificate index: %d.  Expected index: %d"), (result->Error()).iCert, certIndex);
			User::Leave(KErrGeneral);			
			}
		else{
			CleanupStack::PopAndDestroy(result);
			return; //we have passed
			}
		}
		
	
	const CArrayFixFlat<TValidationStatus>& warns = result->Warnings();
	RArray<TValidationStatus> resultOldWarnings;
	CleanupClosePushL(resultOldWarnings);	
	TInt i;
	for (i=0; i < warns.Count(); ++i)
		{
		resultOldWarnings.AppendL(warns[i]);
		}

	const RPointerArray<CCertificateValidationWarnings>& certificateWarningsArray = result->ValidationWarnings();	
	
	HBufC* key;

	RArray<TValidationStatus> processedPolicyQualifiers;
	CleanupClosePushL(processedPolicyQualifiers);		
	
	TInt qualifierWarning = 18;

	for (i=0; i < iNumberOfCerts; ++i)
		{
		key = HBufC::NewLC(KCert().Length() + KKeyFormat().Length() + KPolicyIndex().Length()); 
		TPtr ptr(key->Des());
		ptr = KCert();
		ptr.AppendFormat(KKeyFormat(), i);
		ptr.Append(KPolicyIndex());	
		
		TInt policyIndex = 0;
		GetIntFromConfig(aConfigSection, *key, policyIndex);
		
		if (policyIndex > 0)
			{
			TValidationError error = (TValidationError) qualifierWarning;
			processedPolicyQualifiers.AppendL(TValidationStatus(error, policyIndex));
			}

		CleanupStack::PopAndDestroy(key);
		}
	
	//handle 1st part old warnings first - check any warnings we expect are present (later we check no additionals) 
	CheckWarningsPresentAndRemoveL(processedPolicyQualifiers, resultOldWarnings);
	
	RArray<TInt> configOldWarnings;
	CleanupClosePushL(configOldWarnings);
	RArray<TValidationStatus> processedConfigOldWarnings;
	CleanupClosePushL(processedConfigOldWarnings);		
	
	RArray<TValidationStatus> configNewWarnings;
	CleanupClosePushL(configNewWarnings);
	RArray<TPtrC> configCritOids;
	CleanupClosePushL(configCritOids);	
	
	for (TInt cert_index=0; cert_index < iNumberOfCerts; ++cert_index)
		{
		INFO_PRINTF2(_L("Certificate index: %d"), cert_index);
		key = HBufC::NewLC(KCert().Length() + KKeyFormat().Length() + KOldWarnings().Length()); 
		TPtr ptr(key->Des());
		ptr = KCert();
		ptr.AppendFormat(KKeyFormat(), cert_index);
		ptr.Append(KOldWarnings());
		
		GetIntArrayFromConfigL(aConfigSection, *key, configOldWarnings);
		
		processedConfigOldWarnings.Reset();
		for (TInt i=0; i < configOldWarnings.Count(); ++i)
			{
			TValidationError error = (TValidationError) configOldWarnings[i];
			processedConfigOldWarnings.AppendL(TValidationStatus(error, cert_index));
			}
		
		TransferToNewWarningsL(configOldWarnings, configNewWarnings, cert_index);
		
		ptr.Zero();	
		ptr = KCert();
		ptr.AppendFormat(KKeyFormat(), cert_index);
		ptr.Append(KCritOid());
			
		GetStringArrayFromConfigL(aConfigSection, *key, configCritOids);
		
		CleanupStack::PopAndDestroy(key);
		
		//we now have all our arguments from the config file
		
		//handle 1st part old warnings first - check any warnings we expect are present (later we check no additionals) 
		CheckWarningsPresentAndRemoveL(processedConfigOldWarnings, resultOldWarnings);
		
		
		CCertificateValidationWarnings* certWarning = certificateWarningsArray[((iNumberOfCerts - cert_index) - 1)];	//not owned	//warnings returned in reverse order
		
		//check cert and certindex match up correctly		
		if (certWarning->CertIndex() != cert_index)
			{
			ERR_PRINTF3(_L("ERROR: Certificate indexes do not match.  Certificate index: %d.  Expected index: %d"), certWarning->CertIndex(), cert_index);
			User::Leave(KErrGeneral);
			}
		
		key = HBufC::NewLC(KCert().Length() + KKeyFormat().Length() + KPolicyIndex().Length()); 
		TPtr pt(key->Des());
		pt = KCert();
		pt.AppendFormat(KKeyFormat(), cert_index);
		pt.Append(KPolicyIndex());	
			
		TInt policyIndex = 0;
		GetIntFromConfig(aConfigSection, *key, policyIndex);
			
		if (policyIndex > 0)
			{
			TValidationError error = (TValidationError) qualifierWarning;
			configNewWarnings.AppendL(TValidationStatus(error, policyIndex));
			}

		CleanupStack::PopAndDestroy(key);
			
		//check new warnings behave correctly
		CheckWarningsPresentAndRemoveL(certWarning->Warnings(), configNewWarnings);
		
		if (configNewWarnings.Count() != 0)
			{
			for (TInt err=0; err < configNewWarnings.Count(); ++err)
				{
				ERR_PRINTF2(_L("ERROR: Warning(new API) not reported: %d"), (configNewWarnings[err]).iReason);
				}
			User::Leave(KErrGeneral);
			}
		
		
		//check critoids behave correctly
		CheckCriticalExtsPresentAndRemoveL(certWarning->CriticalExtensionsFound(), configCritOids);
		if (configCritOids.Count() != 0)
			{
			for (TInt err=0; err < configCritOids.Count(); ++err)
				{
				ERR_PRINTF2(_L("ERROR: Critical extension not reported: %S"), &configCritOids[err]);
				}			
			User::Leave(KErrGeneral);
			}
			
		configOldWarnings.Reset();
		configNewWarnings.Reset();
		configCritOids.Reset();		
		}
		
	CleanupStack::PopAndDestroy(5, &processedPolicyQualifiers);	
		
	//check if any warnings in old api we weren't expecting	
	if (resultOldWarnings.Count() != 0)
		{	
		for (TInt warn=0; warn < resultOldWarnings.Count(); ++warn)
			{
			ERR_PRINTF3(_L("ERROR: Warning(old API) not reported: %d.  Index: %d"), (resultOldWarnings[warn]).iReason, (resultOldWarnings[warn]).iCert);
			}		
		User::Leave(KErrGeneral);
		}
	
	CleanupStack::PopAndDestroy(2, result);
	}
Example #29
0
/**
Protected constructor.

Extracts the initialisation data provided by the calling functions: ConstructSourceL() and 
ConstructSinkL(). Creates a file server session and sets up file name. If there is a file name and 
it cannot be found this function leaves. If there is no file name the function leaves. Does not 
attempt to open the file or check whether the file exists.

If aInitData contains a TMMFFileHandleParams instead of TMMFFileParams, the source/sink is constructed from 
the file handle provided by the caller

@param  aInitData
Initialisation data packaged in a TMMFFileParams or in a TMMFFileHandleParams (File Handle)
*/
void CFileMultimediaSource::ConstructL(const TDesC8& aInitData,TMMFileMode aFileMode)
    {
    User::LeaveIfError(iFsSession.Connect());
    // on IPCv2 we auto attach
    User::LeaveIfError(iFsSession.ShareAuto());
    
    User::LeaveIfError(iFsSession.ShareProtected());
    
    TBool fileInit = EFalse;
    HBufC* filename = NULL; 
    TBool filenamePushed = EFalse;
    
    iCAFParameters = new (ELeave) CCAFParameters;
    TBool drmContent = EFalse;
    RDesReadStream stream(aInitData);
    CleanupClosePushL(stream);

    TUid initUid;
    
    initUid = TUid::Uid(stream.ReadInt32L());
    
    if (initUid == KMMFileHandleSourceUid)
        {
        TPckgBuf<RFile*> fileptr;
        stream.ReadL(fileptr);
        
        iHandle.Duplicate(*fileptr());
        
        TInt length;
        length = stream.ReadInt32L();
        if (length>0)
            {
            iCAFParameters->iUniqueId = HBufC::NewL(length);
            TPtr16 ptr = iCAFParameters->iUniqueId->Des();
            stream.ReadL(ptr, length);
            }
        iFileHandle = ETrue;
        filename = HBufC::NewMaxL(KMaxFileName);
        TPtr ptr = filename->Des();
        iHandle.Name(ptr);
        fileInit = ETrue;
        drmContent = ETrue;
        
        iCAFParameters->iEnableUI = stream.ReadInt32L();
        }
    
    else if (initUid == KMMFileSourceUid)
        {
        TInt length;
        length = stream.ReadInt32L();
        filename = HBufC::NewMaxLC(length);
        TPtr ptr = filename->Des();
        stream.ReadL(ptr, length);
        
        length = stream.ReadInt32L();
        if (length>0)
            {
            iCAFParameters->iUniqueId = HBufC::NewMaxL(length);
            ptr.Set(iCAFParameters->iUniqueId->Des());
            stream.ReadL(ptr, length);
            }
        CleanupStack::Pop(filename);
        
        fileInit = ETrue;
        drmContent = ETrue;
        iFileHandle = EFalse; 
        iCAFParameters->iEnableUI = stream.ReadInt32L();
        }
    else
        {
        //		TODO If the UID is unknown we should reject, but  currently
        //		code also used for older calls that just supply filename.
        //		User::Leave(KErrNotSupported);
        }
    
    CleanupStack::PopAndDestroy(&stream);
    
    if (!fileInit && aInitData.Length() == sizeof(TMMFFileHandleParams))
        {
        TMMFFileHandleParams params;
        TPckgC<TMMFFileHandleParams> config(params);
        config.Set(aInitData);
        params = config();
        
        
        if (params.iUid == KFileHandleUid)
            {
            fileInit = ETrue;
            User::LeaveIfError(iHandle.Duplicate(*params.iFile));
            TInt pos = 0;
            // make sure the duplicate handle is at the start of the file - the usage of the file handle really requires this
            User::LeaveIfError(iHandle.Seek(ESeekStart, pos));
            iFileHandle = ETrue;
            filename = HBufC::NewMaxLC(KMaxFileName);
            filenamePushed = ETrue;
            TPtr ptr = filename->Des();
            User::LeaveIfError(iHandle.Name(ptr));
            }
        }
    
    if (!fileInit) // do old case as last resort
        {
        TMMFFileParams params;
        TPckgC<TMMFFileParams> config(params);
        config.Set(aInitData);
        params = config();
        
        filename = params.iPath.AllocL();
        fileInit = ETrue;
        }
    
    if (!filenamePushed)
        {
        // from now on it is assumed pushed.
        CleanupStack::PushL(filename);
        }
    
    TParse parser ;
    User::LeaveIfError(parser.Set(*filename, NULL, NULL));
    CleanupStack::PopAndDestroy(filename);
    if ( !( parser.NamePresent() ) && !( parser.ExtPresent() ) )
        User::Leave( KErrBadName ) ;
    
    iFullFileName.Copy( parser.FullName() ) ;	
    iFileName = parser.Name().AllocL() ;
    iFileExt = parser.Ext().AllocL() ;
    iFilePath = parser.Path().AllocL() ;
    iFileDrive = parser.Drive().AllocL() ;
    
    // in order to simulate old behaviour we are not passing error out
    // but will try to create Content again during PrimeL()
    if (fileInit && drmContent && aFileMode==ESourceMode)
        {
        TInt contentError;
        if (iFileHandle)
            {
            TRAP(contentError, 
                iFile = CContentFile::NewL(iHandle, UniqueId(), iCAFParameters->iEnableUI);
            );
            }
Example #30
0
 // ---------------------------------------------------------
// CPosTp148::PrintParsedDataFromEncoderL
//
// (other items were commented in a header).
// ---------------------------------------------------------
//
void CPosTp148::PrintParsedDataFromEncoderL(
    const TDesC& aFile, 
    const TDesC8&  aBuffer, 
    TInt aExpectedStatusCode,
    const TDesC8& aMimeType)
    {
    iLog->Log(_L("===== PrintParsedDataFromEncoderL ======="));
    
    iLandmarkParser = CPosLandmarkParser::NewL(aMimeType);

    if (aFile != KNullDesC)
        {
        TFileName file( aFile );
        iLog->Log(_L("FILE (%S)"), &file );
        TraceL(_L("----->Using FILE<-------"));
        TraceL(file);
        iLandmarkParser->SetInputFileL(file);
        }
    else
        {
        iLog->Log(_L("BUFFER (size %d)"), aBuffer.Size() );
        TraceL(_L("----->Using BUFFER<-------"));
        iLandmarkParser->SetInputBuffer(aBuffer);
        }

    iOperation = iLandmarkParser->ParseContentL();
    TRequestStatus status = KPosLmOperationNotComplete;
    TReal32 progress;
    TInt number = 0;

    RArray<TPosLmItemId> array;
    CleanupClosePushL(array);

    while (status == KPosLmOperationNotComplete)
        {
        iLog->Log(_L("--- Parsing ---------------------------"));
        TraceL(_L("------------------------------"));
        iOperation->NextStep(status, progress);

        // Wait for NextStep to complete
        User::WaitForRequest(status);
        if (status != KPosLmOperationNotComplete && status != KErrNone)
            {
            iLog->Log(_L("Parsing Complete"));
            
            HBufC* buffer = HBufC::NewLC( 128);
            TPtr buf = buffer->Des();
                       
            buf.Format(_L("\tStatus %d"), status.Int());
            iLog->Log(buf);
            TraceL(buf);
            
            CleanupStack::PopAndDestroy( buffer );
            buffer = NULL;              
            }
        else
            {
            iLog->Log(_L("Parsing element"));
            
            if ( iLandmarkParser->NumOfParsedLandmarks() )
                {
                // Get last parsed landmark
                CPosLandmark* lm = iLandmarkParser->LandmarkLC();
                TPtrC lmName;
                TPtrC catName;
                lm->GetLandmarkName(lmName);
                lm->GetCategoriesL(array);
                //iLog->Log(lmName);
                for (TInt i=0;i<array.Count();i++)
                    {                    
                    CPosLandmarkCategory* category = iLandmarkParser->LandmarkCategoryLC( array[i] );
                    category->GetCategoryName( catName );
                     
                    HBufC* buffer = HBufC::NewLC( 128 + catName.Length());
                    TPtr buf = buffer->Des();
                                            
                    if ( category->GlobalCategory()) 
                        {
                        buf.Append(_L("\tGlobal category: "));    
                        }
                    else 
                        {
                        buf.Append(_L("\tLocal category: "));    
                        }                        
                                        
                    buf.Append( catName );
                    iLog->Log( buf );
                    TraceL( buf );

                    CleanupStack::PopAndDestroy( buffer );
                    buffer = NULL;
                                       
                    CleanupStack::PopAndDestroy(category);
                    }
                    
               	PrintLandmarkFieldsWithDescriptionL(*lm, ETrue);	
               
                
                number++;
                CleanupStack::PopAndDestroy(lm);
                }
            }
        }

    iLog->Log(_L("--- Parsing end ---------------------------"));
    TraceL(_L("------------------------------"));
    CleanupStack::PopAndDestroy(&array);

    if (status.Int() != aExpectedStatusCode)
        {
        HBufC* buffer = HBufC::NewLC( 128 );
        TPtr buf = buffer->Des();
                    
        buf.Format(_L("\tERROR: Wrong status returned, was %d, should be %d"), status.Int(), aExpectedStatusCode);
        iLog->Log( buf );
        iErrorsFound++;
        
        CleanupStack::PopAndDestroy( buffer );
        buffer = NULL;        
        }

    TUint32 nr = iLandmarkParser->NumOfParsedLandmarks();
    
    HBufC* buffer = HBufC::NewLC( 256 );
    TPtr buf = buffer->Des();
    
    buf.Format(_L("\tNr of Parsed landmarks %d, should be %d"), nr, number);
    iLog->Log(buf);
    TraceL(buf);

    CleanupStack::PopAndDestroy( buffer );
    buffer = NULL;
    
    if (nr != (TUint32)number)
        {
        iLog->Log(_L("\tERROR: Wrong number of landmarks parsed returned!"));
        iErrorsFound++;
        }

    TPosLmCollectionDataId lmId = iLandmarkParser->FirstCollectionDataId();

    iLog->Log(_L("--- CollectionData ---"));
    TraceL(_L("--- CollectionData ---"));

    if (lmId != EPosLmCollDataNone)
        {
        TPtrC first = iLandmarkParser->CollectionData(lmId);
        
        HBufC* buffer = HBufC::NewLC( first.Length() + 256 );
        TPtr buf = buffer->Des();
            
        buf.Zero();
        buf.Format(_L("\t(1)Collection Id: %d CollectionData: "), lmId);
        buf.Append(first);
        iLog->Log(buf);
        TraceL(buf);
        
        CleanupStack::PopAndDestroy( buffer );
        buffer = NULL;      
        
        }
    else 
        {
        iLog->Log(_L("\tNo collection data found 1"));    
        }

    while (lmId != EPosLmCollDataNone)
        {
        lmId = iLandmarkParser->NextCollectionDataId(lmId);
        if (lmId != EPosLmCollDataNone)
        {
            TPtrC first = iLandmarkParser->CollectionData(lmId);
            
            HBufC* buffer = HBufC::NewLC( first.Length() + 256 );
            TPtr buf = buffer->Des();         
            
            buf.Zero();
            buf.Format(_L("\t(2)Collection Id: %d CollectionData: "), lmId);
            buf.Append(first);
            iLog->Log(buf);
            TraceL(buf);
            
            CleanupStack::PopAndDestroy( buffer );
            buffer = NULL;              
        }
        else 
            {
            iLog->Log(_L("\tNo collection data found 2"));   
            }
        }

    iLog->Log(_L("--- CollectionData ---"));
    TraceL(_L("--- CollectionData ---"));

    delete iOperation;
    iOperation = NULL;
    delete iLandmarkParser;
    iLandmarkParser = NULL;
    iLog->Log(_L("====== PrintParsedDataFromEncoderL Done ========\n"));
    }