EXPORT_C void StartApplicationL(const TUid& aUid, const TDesC& aDocumentName, TInt aRetryInterval, TApaCommand aCommand)
	{
		TUid appToBeStarted = aUid;
		TInt pushed=0;
#ifdef DEBUG
		RFs fs; User::LeaveIfError(fs.Connect()); 
		CleanupClosePushL(fs); pushed++;
		RFile f; User::LeaveIfError(f.Replace(fs, _L("c:\\processmanagement.txt"), EFileWrite));
		CleanupClosePushL(f); pushed++;

		f.Write(_L8("starting\n"));
#endif
		TInt retries=0;
		LOG(_L8("new'ing ls session..."));
		RApaLsSession *lsp;
		lsp=new (ELeave) RApaLsSession;
		LOG(_L8("\n"));
		CleanupStack::PushL(lsp); ++pushed;
		RApaLsSession& ls(*lsp);

		while(retries<80) {
			TInt i_pushed=0;
			LOG(_L8("connecting ls session..."));
			TInt err=ls.Connect();
			LOG(_L8(": "));
			TBuf8<12> msg; msg.Num(err); msg.Append(_L("\n"));
			LOG(msg);
			if (err==KErrNone) {
				CleanupClosePushL(ls); ++i_pushed;
				pushed+=i_pushed;
				break;
			} else {
				CleanupStack::PopAndDestroy(i_pushed);
			}
			LOG(_L8("waiting..."));
			retries++;
			User::After(TTimeIntervalMicroSeconds32(aRetryInterval*1000));
			LOG(_L8("done.\n"));
		}
		LOG(_L8("ls session created\n"));

		LOG(_L8("creating info..."));
		TApaAppInfo* infop=0;
		infop=new (ELeave) TApaAppInfo;
		LOG(_L8("1 "));
		CleanupStack::PushL(infop); ++pushed;
		LOG(_L8("2 "));
		TApaAppInfo& info(*infop);
		LOG(_L8("done\n"));
	
		RWsSession ws;
		User::LeaveIfError(ws.Connect());
		CleanupClosePushL(ws); ++pushed;
		TApaTaskList tl(ws);
		TApaTask app_task=tl.FindApp(aUid);
		TBool exists=app_task.Exists();
		while( !exists && retries<80) {
			TInt pushed=0;

			LOG(_L8("getting info..."));
			TInt err=ls.GetAppInfo(info, appToBeStarted);
			LOG(_L8("done: "));
			TBuf8<12> msg; msg.Num(err); msg.Append(_L("\n"));
			LOG(msg);
			if (err==KErrNone) {
#ifndef __S60V3__
				CApaCommandLine* cmd=CApaCommandLine::NewLC(info.iFullName); pushed++;
#else
				CApaCommandLine* cmd=CApaCommandLine::NewLC(); pushed++;
				cmd->SetExecutableNameL(info.iFullName);
#endif
				cmd->SetCommandL( aCommand );
				if ( aDocumentName.Length() > 0 )
					{					
					cmd->SetDocumentNameL(aDocumentName);
					}
#ifndef __S60V3__
				TRAP(err, EikDll::StartAppL(*cmd));
#else
				err=ls.StartApp(*cmd);
#endif
				CleanupStack::PopAndDestroy(pushed);
				LOG(_L8("StartAppL: "));
				msg.Num(err); msg.Append(_L("\n"));
				LOG(msg);
				if (err==KErrNone) break;	
			} else {
				LOG(_L8("popping..."));
				CleanupStack::PopAndDestroy(pushed);
				LOG(_L8("done\n"));
			}
			LOG(_L8("waiting..."));
			retries++;
			User::After(TTimeIntervalMicroSeconds32(aRetryInterval*1000));
			LOG(_L8("done.\n"));
		}
		LOG(_L8("done\n"));
		CleanupStack::PopAndDestroy(pushed);
	}
/**
 * Reads the parameter	asociated to the specified command
 * @param aSectName	Section on ini file
 * @param aKeyName		Name of the parameter
 * @param aResult			descriptor containing parameter
 * @return TBool  ETrue for found, EFalse for not found 
 */
TBool CDataWrapperBase::GetCommandStringParameterL(const TDesC& aSectName, const TDesC& aKeyName, TPtrC& aResult)
	{
	TBool	ret=EFalse;

	if ( aSectName.Length()!=0 )
		{
		ret=CDataWrapper::GetStringFromConfig(aSectName, aKeyName, aResult);

		for ( TInt index=iInclude.Count(); (index>0) && (!ret); )
			{
			ret=iInclude[--index]->FindVar(aSectName, aKeyName, aResult);
			}
		}

	if ( ret )
		{
		if ( aResult.Match(KMatch)!=KErrNotFound )
			{
			//	We have an entry of the format
			//	entry =*{section,entry}*
			//	where * is one or more characters
			//	We need to construct this from other data in the ini file replacing {*,*}
			//	with the data from
			//	[section]
			//	entry =some_value
			HBufC*	buffer=HBufC::NewLC(aResult.Length());
			buffer->Des().Copy(aResult);

			TInt	startLength=KStart().Length();
			TInt	sparatorLength=KSeparator().Length();
			TInt	endLength=KEnd().Length();
			TInt	bufferLength;
			TInt	start;
			TInt	sparator;
			TInt	end;
			TPtrC	remaining;
			TLex	lex;
			do
				{
				bufferLength=buffer->Length();
				start=buffer->Find(KStart);

				remaining.Set(buffer->Des().Right(bufferLength-start-startLength));
				sparator=remaining.Find(KSeparator);
				remaining.Set(remaining.Right(remaining.Length()-sparator-sparatorLength));
				sparator += (start + startLength);

				end=remaining.Find(KEnd) + sparator + sparatorLength;

				TPtrC	sectionName(buffer->Ptr()+start+startLength, sparator-start-startLength);
				TPtrC	keyName(buffer->Ptr()+sparator+sparatorLength, end-sparator-sparatorLength);
				sectionName.Set(TLex(sectionName).NextToken());
				keyName.Set(TLex(keyName).NextToken());

				TInt	entrySize=0;
				TPtrC	entryData;
				TBool	found=CDataWrapper::GetStringFromConfig(sectionName, keyName, entryData);
				for ( TInt index=iInclude.Count(); (index>0) && (!found);  )
					{
					found=iInclude[--index]->FindVar(sectionName, keyName, entryData);
					}
				if ( found )
					{
					entrySize=entryData.Length();
					}

				TInt	newLength=start + bufferLength - end - endLength + entrySize;
				HBufC*	bufferNew=HBufC::NewLC(newLength);
				bufferNew->Des().Copy(buffer->Ptr(), start);
				if ( entrySize>0 )
					{
					bufferNew->Des().Append(entryData);
					}
				bufferNew->Des().Append(buffer->Ptr() + end + endLength, bufferLength - end - endLength);
				CleanupStack::Pop(bufferNew);
				CleanupStack::PopAndDestroy(buffer);
				buffer=bufferNew;
				CleanupStack::PushL(buffer);
				}
			while ( buffer->Match(KMatch)!=KErrNotFound );
			iBuffer.Append(buffer);
			CleanupStack::Pop(buffer);
			aResult.Set(*buffer);
			INFO_PRINTF4(KDataRead, &aSectName, &aKeyName , &aResult);
			}
		}

	return ret;
	}
TInt RCdlSession::IsPluginInRom(const TDesC& aFileName, TBool& aIsInRom) const
	{
	TPckg<TBool> isInRom(aIsInRom);
	TIpcArgs p(&aFileName, aFileName.Length(), &isInRom);
	return SendReceive(ECdlServCmdIsPluginInRom, p);
	}
Exemple #4
0
void CTextWindow::DrawCharJustified(const TDesC &aText)
	{
	iGc->SetCharJustification(Size().iWidth-10-iTmpFont->TextWidthInPixels(aText),aText.Length()-1);
	PrintLine(iTmpFont, aText);
	}
/*
-------------------------------------------------------------------------------

    Class: CStifSectionParser

    Method: ParseStartAndEndPos

    Description: Start and end position parser.

    Parameters: TPtrC aSection: in: Parsed section
                const TDesC& aStartTag: in: Start tag of parsing
                TTagToReturnValue aTagIndicator: in: Will aStartTag included to
                the returned values
                TInt& aStartPos: inout: Start point of parsing
                TInt& aEndPos: inout: End point of parsing
                TInt& aLength: inout: Length of parsed section

    Return Values: TInt: Error code

    Errors/Exceptions: None

    Status: Proposal

-------------------------------------------------------------------------------
*/
TInt CStifSectionParser::ParseStartAndEndPos( TPtrC aSection,
                                            const TDesC& aStartTag,
                                            TTagToReturnValue aTagIndicator,
                                            TInt& aStartPos,
                                            TInt& aEndPos,
                                            TInt& aLength )
    {
    TLex lex( aSection );
    lex.SkipAndMark( iSkipAndMarkPos );

    // Check is aStartTag given
    if ( aStartTag.Length() == 0 )
        {
        // Skip line break, tabs, spaces etc.
        lex.SkipSpace();
        aStartPos = lex.Offset();
        }
    else
        {
        // While end of section and aStartTag is given
        while ( !lex.Eos() )
            {
            lex.SkipSpace();
            TPtrC line = SubstractLine( lex.Remainder() );
            TInt tagStartPos = 0;
            TInt tagEndPos = 0;
            if ( FindTag( line, aStartTag, tagStartPos, tagEndPos ) == KErrNone )
            	{
            	if ( aTagIndicator == ETag )
            		{
            		aStartPos = lex.Offset();
            		}
            	else
            		{
            		aStartPos = lex.Offset() + tagEndPos;
            		if ( line.Length() - tagEndPos == 0 )
            			{
            			return KErrNotFound;
            			}
            		}
            	break;
            	}
                
            GotoEndOfLine( lex );
            }
        }

    // End tag parsing starts and if we are end of the section
    if( lex.Eos() )
        {
        return KErrNotFound;
        }

    // "Delete" white spaces(includes line break) 
    aEndPos = GotoEndOfLine( lex );
    // Position where start next parsing.(End position, includes white spaces)
    iSkipAndMarkPos = lex.Offset();
    // The length includes spaces and end of lines
    aLength = ( aEndPos - aStartPos );

    return KErrNone;

    }
// -----------------------------------------------------------------------------
// CAtomFeedParser::SetItemIdStrAttributeL
//
// Determine and set the unique IdStr attribute (unique to the feed that is).
// -----------------------------------------------------------------------------
//
void CAtomFeedParser::SetItemIdStrAttributeL(TXmlEngElement aItemNode, 
        MFeedParserObserver& aObserver)
    {    
    const TInt  KStrChunk = 30;
    
    TDesC*    content = NULL;
    TDesC*    summary = NULL;
    TDesC*    description = NULL;
    TDesC*    title = NULL;
    HBufC*    url = NULL;
    HBufC*    idStr = NULL;
    TXmlEngElement  node;

    // If the id node is present use it.
    node = iXmlUtils.GetFirstNamedChild(aItemNode, KId);
    if (node.NotNull())
        {
        ElementHandlerCDataL(*this, iXmlUtils, node, EItemAttributeIdStr, aObserver);        
        return;
        }

    // Otherwise create a idStr from the first 30 chars of the description and title
    // and the last 30 chars of the url.  This doesn't guarantee a unique id, but 
    // it very likely.
    node = iXmlUtils.GetFirstNamedChild(aItemNode, KSummary);
    summary = iXmlUtils.ExtractSimpleTextL(node, KStrChunk);
    CleanupStack::PushL(summary);
        
    node = iXmlUtils.GetFirstNamedChild(aItemNode, KContent);
    content = iXmlUtils.ExtractSimpleTextL(node, KStrChunk);
    CleanupStack::PushL(content);

    node = iXmlUtils.GetFirstNamedChild(aItemNode, KTitle);
    title = iXmlUtils.ExtractSimpleTextL(node, KStrChunk);
    CleanupStack::PushL(title);
    
    node = iXmlUtils.GetFirstNamedChild(aItemNode, KLink);
    url = iXmlUtils.ExtractSimpleTextL(node, KStrChunk, ETrue);
    CleanupStack::PushL(url);

    // Determine whether content or summary will be used for the description.
    description = summary;
    
    if (content != NULL)
        {
        if (summary == NULL)
            {
            description = content;
            }
        else if (content->Length() > summary->Length())
            {
            description = content;
            }
        }

    // Construct the idStr from the parts.
    TInt  len = 0;
    
    if (description != NULL)
        {
        len += description->Length();
        }
    if (title != NULL)
        {
        len += title->Length();
        }
    if (url != NULL)
        {
        len += url->Length();
        }
    
    idStr = HBufC::NewL(len);
    CleanupStack::PushL(idStr);

    TPtr  ptr(idStr->Des());
    
    if (description != NULL)
        {
        ptr.Append(*description);
        }
    if (title != NULL)
        {
        ptr.Append(*title);
        }
    if (url != NULL)
        {
        ptr.Append(*url);
        }
        
    // Replace any chars that may interfere with the database.
    _LIT(KSpace, " ");
    
    for (TInt i = 0; i < ptr.Length(); i++)
        {
        if (ptr[i] == '\'')
            {
            ptr.Replace(i, 1, KSpace());
            }
        }
    
    // Set the idStr attribute.
    aObserver.AddAttributeL(EItemAttributeIdStr, *idStr);
    
    CleanupStack::PopAndDestroy(idStr);    
    CleanupStack::PopAndDestroy(url);    
    CleanupStack::PopAndDestroy(title);    
    CleanupStack::PopAndDestroy(content);    
    CleanupStack::PopAndDestroy(summary);    
    }
/**
Finds the keystring from the source string and replaces it with the
replacement string. The formated string is stored in the destination
descriptor.
*/
TInt CResourceLoader::Formater(TDes& aDest, const TDesC& aSource, const TDesC& aKey, const TDesC& aSubs, TBidiText::TDirectionality aDirectionality)    
    {
    // substitute string must not contain KSubStringSeparator, 
    // or results will be unpredictable 
    __ASSERT_DEBUG(aSubs.Locate(KSubStringSeparator) == KErrNotFound, 
        User::Panic(KPanicCategory, EInvalidSubstitute));

    TInt keylength(aKey.Length());

    //aDest must be empty.
    aDest.Zero();

    // offset indicates end of last handled key in source
    TInt offset(0);

    // offset in destination string
    TInt desOffset(0);

    // Substring directionalities are adjusted after all changes are done.
    TBool checkSubstringDirectionalities(EFalse);

    // count is the position in the source from which the substring starts
    TInt count(0);

    // Replaced parameters count
    TInt replaceCount(0);

    while (count != KErrNotFound)
        {
        // desCount is the position of the substring starts in destination.
        TInt desCount(0);

        TPtrC remainder = aSource.Right(aSource.Length() - offset);
        count = remainder.Find(aKey);

        TInt maxSubLength = -1;
        if (count != KErrNotFound)
            {
            replaceCount++;
            desOffset += count;
            offset += count;
            count = offset;
            desCount = desOffset;

            // copy source to destination if first time
            if (aDest.Length() == 0)
                aDest.Append(aSource);

            // delete found key from destination
            aDest.Delete(desCount, keylength);

            offset += keylength; // increase offset by key length

            if (count + keylength < (aSource.Length()-1)) // aKey is not at the end of string
                {
                if (aSource[count+keylength] == '[') // Key includes max datalength
                    {
                    maxSubLength = 10*(aSource[count+keylength+1]-'0') 
                                   + (aSource[count+keylength+2]-'0');
                    aDest.Delete(desCount,4); // Length information stored->delete from descriptor
                    offset += 4; // increase offset by max sub length indicator
                    }
                }
         
            aDest.Insert(desCount, aSubs);
        
            desOffset = desCount + aSubs.Length();

            if (maxSubLength > 0 && aSubs.Length() > maxSubLength)
                {
                aDest.Delete(desCount+maxSubLength-1, aSubs.Length()+1-maxSubLength);     
                TText ellipsis(KEllipsis);
                aDest.Insert(desCount+maxSubLength-1, TPtrC(&ellipsis,1));
                desOffset = desCount + maxSubLength;
                }

            TBidiText::TDirectionality subsDir =
                TBidiText::TextDirectionality(aDest.Mid(desCount, desOffset - desCount));

            // If inserted string has different directionality,
            // insert directionality markers so that bidi algorithm works in a desired way.
            if (aDirectionality != subsDir)
                {
                checkSubstringDirectionalities = ETrue;

                TInt freeSpace = aDest.MaxLength() - aDest.Length();

                // Protect the directionality of the inserted string.
                if (freeSpace >= KExtraSpaceForSubStringDirMarkers)
                    {
                    TBuf<1> subsMarker;
                    subsMarker.Append(subsDir == TBidiText::ELeftToRight ?
                        KLRMarker : KRLMarker);

                    aDest.Insert(desOffset, subsMarker);
                    aDest.Insert(desCount, subsMarker);
                    desOffset += KExtraSpaceForSubStringDirMarkers;
                    }
                }
            }
        }

    // Adjust substring directionality markers if necessary
    // and if there is enough room in destination string
    if (checkSubstringDirectionalities)
        {
        TText mainMarker = (aDirectionality == TBidiText::ELeftToRight ? 
            KLRMarker : KRLMarker);

        TInt freeSpace = aDest.MaxLength() - aDest.Length();

        // If not already done, protect the directionality of the original string
        // and all of the KSubStringSeparator separated substrings.
        if (freeSpace > 0 
            && aDest.Length()
            && aDest[0] != mainMarker 
            && aDest[0] != KSubStringSeparator
            && aDest[0] != KDirNotFound)  
            {
            aDest.Insert(0, TPtrC(&mainMarker, 1));
            freeSpace--;
            }

        // Find and protect KSubStringSeparator separated substrings.
        // Go through string backwards so that any changes will not affect indexes 
        // that are not yet checked.
        TInt j(aDest.Length()-1);
        while (freeSpace > 0 && j >= 0) 
            {
            if (aDest[j] == KSubStringSeparator && j < (aDest.Length() - 1) 
                && aDest[j+1] != mainMarker && aDest[j+1] != KDirNotFound)
                {
                aDest.Insert(j+1, TPtrC(&mainMarker, 1));
                freeSpace--;
                }
            j--;
            }
        }

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

    TInt rSuccess = KErrNotFound;
    TInt size = 0;

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


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

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

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

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

        size = pref->valueSize();

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

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

                RFileReadStream readStream;

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

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

        CleanupStack::PopAndDestroy( k );
    }

    return rSuccess;

}
// ----------------------------------------------------------------------------
// WidgetPreferences::SetPreferenceL
// set Preference for a key
//
//
// ----------------------------------------------------------------------------
void WidgetPreferences::setPreferenceL( const TDesC& akey, const TDesC& avalue)
{
    if ( !m_basepath || (m_basepath->Length() <= 0) )
        return;

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

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

        // if hash has the key and its value
        // delete the old value later when the new value was successfully updated
        PrefElement* prefExisting = NULL;
        prefExisting = m_preferences->Find( *k );

        if ( avalue.Length() <= KMaxKeyValueSize ) {
            PrefElement* pref = new (ELeave) PrefElement;
            CleanupStack::PushL( pref );
            pref->setValueL( avalue );
            pref->setValueSize( avalue.Length() );
            m_preferences->InsertL( k, pref );
            CleanupStack::Pop(); //pref
        }
        else {
            // create a temp file and save the value in temp file.
            // m_value member of PrefElement contains the temp file name.
            RFs fs;
            RFile file;
            if ( fs.Connect() == KErrNone ) {
                CleanupClosePushL( fs );

                // create and write to file
                TFileName tempFileName;
                file.Temp( fs, *m_basepath, tempFileName, EFileWrite|EFileShareExclusive );
                CleanupClosePushL( file );
                HBufC* filePath = HBufC::NewLC( tempFileName.Length() );
                TPtr fName( filePath->Des() );
                fName.Append( tempFileName );
                RFileWriteStream writeStream( file );
                CleanupClosePushL( writeStream );
                TRAPD( err,
                       writeStream.WriteInt32L( avalue.Length() );
                       writeStream.WriteL( avalue );
                       writeStream.CommitL(); );
                // If an error occured while writing to the file, delete the temp file
                // This should be the case when disk is full
                if ( err != KErrNone )
                {
                    CleanupStack::PopAndDestroy( ); //writeStream
                    file.Close();
                    fs.Delete( *filePath );
                    User::Leave( err );
                }

                // create new preference element
                PrefElement* pref = new ( ELeave ) PrefElement;
                CleanupStack::PushL( pref );
                pref->setValueSize( avalue.Length() );
                pref->setValueL( *filePath );
                // update new preference element
                m_preferences->InsertL( k, pref );

                CleanupStack::Pop( pref );
                CleanupStack::PopAndDestroy( ); //writeStream
                CleanupStack::PopAndDestroy( 3 ); //filePath,file,fs
            }
// ---------------------------------------------------------
// CContextbookContainer::ConstructL(const TRect& aRect)
// EPOC two phased constructor
// ---------------------------------------------------------
//
void CContextbookContainer::ConstructL(const TRect& aRect, phonebook_i* i_book, bool i_searchable, const TDesC& title, Cfile_output_base * aLog, CAknIconArray * aIconlist, TInt current_item_index, TInt top_item_index, TBuf<20> current_filter)
{
	CALLSTACKITEM(_L("CContextbookContainer::ConstructL"));

	iCurrentContactId=KErrNotFound;

	iconlist = new (ELeave) CAknIconArray(30);
	//copy
	for (TInt i = 0; i< aIconlist->Count();i++)
	{
		CGulIcon * ic, *icon_from; 
		icon_from= (*aIconlist)[i];
		ic=CGulIcon::NewL( icon_from->Bitmap(), icon_from->Mask());
		ic->SetBitmapsOwnedExternally(ETrue);
		iconlist->AppendL( ic );
	}
	
	iLog = aLog;
	CreateWindowL();

	CEikStatusPane* sp=iEikonEnv->AppUiFactory()->StatusPane();
	CAknTitlePane* tp=(CAknTitlePane*)sp->ControlL(TUid::Uid(EEikStatusPaneUidTitle));

	HBufC* t=HBufC::NewL(title.Length());
	*t=title;
	tp->SetText(t);

	if (iLog) {
		iLog->write_time();
		iLog->write_to_output(_L("Showing "));
		iLog->write_to_output(title);
		iLog->write_nl();
	}

	sendui=CSendAppUi::NewL(0);

	searchable=i_searchable;

	resource_files=new (ELeave) CArrayFixFlat<TInt>(5);

	// for phonebook dialogs
	TFileName resfile=_L("z:\\System\\data\\PBKVIEW.rSC");
	BaflUtils::NearestLanguageFile(iEikonEnv->FsSession(), resfile); //for localization
	resource_files->AppendL(iEikonEnv->AddResourceFileL(resfile)); 
	
	book=i_book;
	book->set_observer(this);

	listbox=new (ELeave) doublelinebox(book,iLog);
	listbox->SetContainerWindowL(*this);
	listbox->ConstructL(this, EAknListBoxSelectionList);
	listbox->SetItemHeightL(40);
	listbox->View()->SetMatcherCursor(EFalse);

	listbox->ItemDrawer()->FormattedCellData()->SetIconArray(iconlist);

	listbox->SetListBoxObserver(this);
	listbox->Model()->SetItemTextArray(book->get_array());
	
	listbox->Model()->SetOwnershipType(ELbmDoesNotOwnItemArray);
	listbox->CreateScrollBarFrameL(ETrue);
	listbox->ScrollBarFrame()->SetScrollBarVisibilityL( CEikScrollBarFrame::EOff, CEikScrollBarFrame::EAuto);
	
	listbox->SetCurrentItemIndex(current_item_index);
	listbox->SetTopItemIndex(top_item_index);

	if (is_searchable()) 
	{
		edit=new (ELeave) CEikEdwin;
		edit->SetBorder(TGulBorder::ESingleBlack);
		edit->SetContainerWindowL(*this);
		edit->ConstructL();
		edit->AddEdwinObserverL(this);
		edit->SetFocus(ETrue);
		edit->SetTextL(&current_filter);
		filter();
		
	}

	phone=new (ELeave) phonehelper;
	phone->ConstructL();

	globalNote=CAknGlobalNote::NewL();

	pbkengine=CPbkContactEngine::Static();
	if (pbkengine) {
		owns_engine=false;
	} else {
		pbkengine=CPbkContactEngine::NewL();
		owns_engine=true;
	}
	SetRect(aRect);
   
	ActivateL();
}
Exemple #11
0
TInt XAPlaySessionImpl::load(const TDesC& aURI)
{
    TInt retVal;
    XAresult xaRes;
    XAEngineItf engineItf;
    XADynamicSourceItf dynamicSourceItf;
    XAboolean required[MAX_NUMBER_INTERFACES];
    XAInterfaceID iidArray[MAX_NUMBER_INTERFACES];
    XAuint32 noOfInterfaces = 0;
    TInt i;

    XAmillisecond dur(0);
    TPtr8 uriPtr(0,0,0);
    TPtr8 mimeTypePtr(0,0,0);

#ifdef USE_VIDEOPLAYERUTILITY
    TRAP(m_VPError, mVideoPlayUtil->OpenFileL(_L("C:\\data\\test.3gp")));
    if (m_VPError)
        return 0;

    if(!mActiveSchedulerWait->IsStarted())
        mActiveSchedulerWait->Start();

    if (m_VPError)
        return 0;
    
    mVideoPlayUtil->Prepare();

    if(!mActiveSchedulerWait->IsStarted())
        mActiveSchedulerWait->Start();

    return 0;
#endif

    delete mURIName;
    mURIName = NULL;
    TRAP(retVal, mURIName = HBufC8::NewL(aURI.Length()+1));
    RET_ERR_IF_ERR(retVal);
    uriPtr.Set(mURIName->Des());
    
    // This has to be done here since we can not destroy the Player
    // in the Resource Lost callback.
    if (mbMediaPlayerUnrealized) {
        if (mMOPlayer) {
            (*mMOPlayer)->Destroy(mMOPlayer);
            mMOPlayer = NULL;
        }
    }
    
    //py uri name into local variable 
    //TODO fix copy issue from 16 bit to 8 bit
    uriPtr.Copy(aURI);

    //If media player object already exists, just switch source
    //using dynamic source interface
    if (mMOPlayer && mPlayItf) {
        dynamicSourceItf = NULL;
        xaRes = (*mMOPlayer)->GetInterface(mMOPlayer, XA_IID_DYNAMICSOURCE, &dynamicSourceItf);
        retVal = mapError(xaRes, ETrue);
        RET_ERR_IF_ERR(retVal);

        //Setup the data source
        //TODO Hard coded locator type
        mUri.locatorType = XA_DATALOCATOR_URI;
        
        //append zero terminator to end of URI
        mUri.URI = (XAchar*) uriPtr.PtrZ();
        
        //TODO Hard coded locator type
        mMime.containerType = XA_CONTAINERTYPE_WAV;
        
        //TODO Hard coded locator type
        mMime.formatType = XA_DATAFORMAT_MIME;
        mimeTypePtr.Set(mWAVMime->Des());
        mMime.mimeType = (XAchar*)mimeTypePtr.Ptr();
        mDataSource.pFormat = (void*)&mMime;
        mDataSource.pLocator = (void*)&mUri;
        
        xaRes = (*dynamicSourceItf)->SetSource(dynamicSourceItf, &mDataSource);
        retVal = mapError(xaRes, ETrue);
        RET_ERR_IF_ERR(retVal);
    }
    else { // Create media player object

        // Setup the data source
        // TODO Hard coded locator type
        mUri.locatorType = XA_DATALOCATOR_URI;
        
        //append zero terminator to end of URI
        mUri.URI = (XAchar*) uriPtr.PtrZ();
        
        //TODO Hard coded locator type
        mMime.containerType = XA_CONTAINERTYPE_WAV;
        
        //TODO Hard coded locator type
        mMime.formatType = XA_DATAFORMAT_MIME;
        mimeTypePtr.Set(mWAVMime->Des());
        mMime.mimeType = (XAchar*)mimeTypePtr.Ptr();
        mDataSource.pFormat = (void*)&mMime;
        mDataSource.pLocator = (void*)&mUri;
        
           //Setup the audio data sink
        mLocatorOutputDevice.locatorType = XA_DATALOCATOR_IODEVICE;
        mLocatorOutputDevice.deviceType = 6;
        mAudioSink.pLocator = (void*) &mLocatorOutputDevice;
        mAudioSink.pFormat = NULL;

        //Init arrays required[] and iidArray[]
        for (i = 0; i < MAX_NUMBER_INTERFACES; i++) {
            required[i] = XA_BOOLEAN_FALSE;
            iidArray[i] = XA_IID_NULL;
        }
        
        noOfInterfaces = 0;
        required[noOfInterfaces] = XA_BOOLEAN_FALSE;
        iidArray[noOfInterfaces] = XA_IID_SEEK;
        noOfInterfaces++;
        required[noOfInterfaces] = XA_BOOLEAN_FALSE;
        iidArray[noOfInterfaces] = XA_IID_DYNAMICSOURCE;
        noOfInterfaces++;
        required[noOfInterfaces] = XA_BOOLEAN_FALSE;
        iidArray[noOfInterfaces] = XA_IID_METADATAEXTRACTION;
        noOfInterfaces++;
        required[noOfInterfaces] = XA_BOOLEAN_FALSE;
        iidArray[noOfInterfaces] = XA_IID_NOKIALINEARVOLUME;
        noOfInterfaces++;
        required[noOfInterfaces] = XA_BOOLEAN_FALSE;
        iidArray[noOfInterfaces] = XA_IID_NOKIAVOLUMEEXT;
        noOfInterfaces++;
        required[noOfInterfaces] = XA_BOOLEAN_FALSE;
        iidArray[noOfInterfaces] = XA_IID_PREFETCHSTATUS;
        noOfInterfaces++;
        required[noOfInterfaces] = XA_BOOLEAN_FALSE;
        iidArray[noOfInterfaces] = XA_IID_STREAMINFORMATION;
        noOfInterfaces++;
        required[noOfInterfaces] = XA_BOOLEAN_FALSE;
        iidArray[noOfInterfaces] = XA_IID_PLAYBACKRATE;
        noOfInterfaces++;
        required[noOfInterfaces] = XA_BOOLEAN_FALSE;
        iidArray[noOfInterfaces] = XA_IID_VIDEOPOSTPROCESSING;
        noOfInterfaces++;

        xaRes = (*mEOEngine)->GetInterface(mEOEngine, XA_IID_ENGINE, (void**) &engineItf);
        retVal = mapError(xaRes, ETrue);
        RET_ERR_IF_ERR(retVal);

        xaRes = (*engineItf)->CreateMediaPlayer(engineItf,
                                                &mMOPlayer,
                                                &mDataSource,
                                                NULL,
                                                &mAudioSink,
                                                &mVideoSink,
                                                NULL,
                                                NULL,
                                                noOfInterfaces,
                                                iidArray,
                                                required);
        retVal = mapError(xaRes, ETrue);
        RET_ERR_IF_ERR(retVal);

        xaRes = (*mMOPlayer)->Realize(mMOPlayer, XA_BOOLEAN_FALSE);
        retVal = mapError(xaRes, ETrue);
        RET_ERR_IF_ERR(retVal);

        mbMediaPlayerUnrealized = FALSE;
        
        xaRes = (*mMOPlayer)->RegisterCallback(mMOPlayer, MediaPlayerCallback, (void*)this);
        retVal = mapError(xaRes, ETrue);
        RET_ERR_IF_ERR(retVal);

           xaRes = (*mMOPlayer)->GetInterface(mMOPlayer, XA_IID_PLAY, &mPlayItf);
        retVal = mapError(xaRes, ETrue);
        RET_ERR_IF_ERR(retVal);

        xaRes = (*mPlayItf)->RegisterCallback(mPlayItf, PlayItfCallback, (void*)this);
        retVal = mapError(xaRes, ETrue);
        RET_ERR_IF_ERR(retVal);

        xaRes = (*mPlayItf)->SetPositionUpdatePeriod(mPlayItf, (XAmillisecond)KPlayPosUpdatePeriod);
        retVal = mapError(xaRes, ETrue);
        RET_ERR_IF_ERR(retVal);

        xaRes = (*mPlayItf)->SetCallbackEventsMask(    mPlayItf,
                                                    ( XA_PLAYEVENT_HEADATEND |
                                                      XA_PLAYEVENT_HEADATNEWPOS |
                                                      XA_PLAYEVENT_HEADMOVING )
                                                  );
        retVal = mapError(xaRes, ETrue);
        RET_ERR_IF_ERR(retVal);

        xaRes = (*mMOPlayer)->GetInterface(mMOPlayer, XA_IID_SEEK, &mSeekItf);
        retVal = mapError(xaRes, ETrue);
        
        //Metadata
        xaRes = (*mMOPlayer)->GetInterface(mMOPlayer, XA_IID_METADATAEXTRACTION, &mMetadataExtItf);
        if(mapError(xaRes, ETrue)==KErrNone) {
            mbMetadataAvailable = ETrue;
            setupALKeyMap(); //done only once at creation of meadia player
        }
        
        //volume
        xaRes = (*mMOPlayer)->GetInterface(mMOPlayer, XA_IID_NOKIALINEARVOLUME, &mNokiaLinearVolumeItf);
        if(mapError(xaRes, ETrue)==KErrNone)
            mbVolEnabled = ETrue;

        xaRes = (*mMOPlayer)->GetInterface(mMOPlayer, XA_IID_NOKIAVOLUMEEXT, &mNokiaVolumeExtItf);
        if(mapError(xaRes, ETrue)==KErrNone)
            mbMuteEnabled = ETrue;
        
        //buffer status
        xaRes = (*mMOPlayer)->GetInterface(mMOPlayer, XA_IID_PREFETCHSTATUS, &mPrefetchStatusItf);
        if(mapError(xaRes, ETrue)==KErrNone) {
            mbPrefetchStatusChange = ETrue;
            (*mPrefetchStatusItf)->RegisterCallback(mPrefetchStatusItf, PrefetchItfCallback, (void*)this);
            (*mPrefetchStatusItf)->SetCallbackEventsMask(mPrefetchStatusItf, XA_PREFETCHEVENT_FILLLEVELCHANGE);
        }

        //stream information
        xaRes = (*mMOPlayer)->GetInterface(mMOPlayer, XA_IID_STREAMINFORMATION, &mStreamInformationItf);
        if(mapError(xaRes, ETrue)==KErrNone) {
            mbStreamInfoAvailable = ETrue;
            mParent.cbStreamInformation(ETrue); //indicate first time
            (*mStreamInformationItf)->RegisterStreamChangeCallback(mStreamInformationItf, StreamInformationItfCallback, (void*)this);
        }

        //playback rate 
        xaRes = (*mMOPlayer)->GetInterface(mMOPlayer, XA_IID_PLAYBACKRATE, &mPlaybackRateItf);
        if(mapError(xaRes, ETrue)==KErrNone)
            mbPlaybackRateItfAvailable = ETrue;


        //videopostprocessing 
        xaRes = (*mMOPlayer)->GetInterface(mMOPlayer, XA_IID_VIDEOPOSTPROCESSING, &mVideoPostProcessingItf);
        if(mapError(xaRes, ETrue)==KErrNone)
            mbScalable = ETrue;

    }

    if(mbMetadataAvailable) {
        keyMap.clear();
        extendedKeyMap.clear();
        setupMetaData(); //done every time source is changed
    }
    else { //send signal for seekable
        mParent.cbSeekableChanged(ETrue);
    }

    mCurPosition = 0;
    mParent.cbPositionChanged(mCurPosition);

    xaRes = (*mPlayItf)->GetDuration(mPlayItf, &dur);
    retVal = mapError(xaRes, ETrue);
    RET_ERR_IF_ERR(retVal);

    mDuration = dur;
    mParent.cbDurationChanged(mDuration);

    return retVal;
}
void CMdsClauseBuffer::AppendL( const TDesC& aDes, const TInt aAdditional )
	{
	ReserveSpaceL( iBuffer->Size() + aDes.Length() + 1 + aAdditional );

	iBuffer->Des().Append( aDes );
	}
Exemple #13
0
// ---------------------------------------------------------
// TDdParser::ParseL()
// ---------------------------------------------------------
//
void TDdParser::ParseL( const TDesC& aBuf, CCodData& aData, const TBool aIsDd2, TBool& aIsLicenseTag )
    {
    CLOG(( EParse, 2, _L("-> TDdParser::ParseL") ));
    CDUMP(( EParse, 2, _S("Buf:"), _S("    "), \
        (const TUint8*)aBuf.Ptr(), aBuf.Size() ));
    iError = KErrNone;
    iData = &aData;
    // XML Parser expects the buffer contain a BOM and be in
    // network byte order (this is hard-coded into cXmlParser).
    // We already have the buffer converted to UCS-2, native byte order, BOM
    // removed, and this cannot be changed without changing API.
    // So we have to re-add BOM and convert the buffer back to network byte
    // order. This is an annoying a waste, luckily a DD file is small
    // enough not to be significant.
    HBufC* buf = HBufC::NewLC( aBuf.Length() + 1 );
    buf->Des().Append( 0xFFFE );    // Add BOM, little endian as aBuf.
    buf->Des().Append( aBuf );      // Append buffer.
    // Now turn the whole buffer big-endian.
    TUint8* ptr = (TUint8*)buf->Ptr();
    for ( TInt i = 0; i < buf->Size(); i += 2 )
        {
        TUint8 tmp = ptr[i];
        ptr[i] = ptr[i + 1];
        ptr[i + 1] = tmp;
        }
    NW_WBXML_Dictionary_t* dictArray[ 1 ] = 
        { (NW_WBXML_Dictionary_t*)&NW_DdDummy_WBXMLDictionary };
    RNwWbxmlDictionary wbxmlDict;
    User::LeaveIfError( wbxmlDict.Initialize( 1, dictArray ) );
    CleanupClosePushL<RNwWbxmlDictionary>( wbxmlDict );

    NW_TinyDom_Handle_t domHandle;
    NW_Status_t stat;
    CNwDomDocumentNode* docNode = new (ELeave) CNwDomDocumentNode();
    CleanupStack::PushL( docNode );
    docNode->iDocNode = CXML_DOM_DocumentNode_BuildTree
        ( 
        &domHandle, 
        (NW_Byte*)buf->Ptr(), 
        (NW_Int32)buf->Size(), 
        /*encoded=*/NW_FALSE, 
        /*publicID=*/NW_DdDummy_PublicId, 
        /*extTNotStringTable=*/NW_FALSE,
        &stat
        );
    LeaveIfNwErrorL( stat );
    User::LeaveIfNull( docNode->iDocNode ); // Safety code.
    if (!aIsDd2)
	{
	  DocNodeL( docNode->iDocNode );
	}
    else
	{
	  iIsLicenseTag = EFalse;
	  ParseDd2DocNodeL( docNode->iDocNode );
	}
    CleanupStack::PopAndDestroy( 3, buf );  // docNode, close wbxmlDict, buf

#ifdef __TEST_COD_LOG
    TPtrC ptr16;
    TPtrC8 ptr8;
    CLOG(( EParse, 3, _L("TCodParser::ParseL data:") ));
    ptr16.Set( aData.Name() );
    CLOG(( EParse, 3, _L("  Name<%S>"), &ptr16 ));
    ptr16.Set( aData.Vendor() );
    CLOG(( EParse, 3, _L("  Vendor<%S>"), &ptr16 ));
    ptr16.Set( aData.Description() );
    CLOG(( EParse, 3, _L("  Desc<%S>"), &ptr16 ));
    CLOG(( EParse, 3, _L("  Size(%d)"), aData.Size() ));
    ptr8.Set( aData.InstallNotify() );
    CLOG(( EParse, 3, _L8("  InstNotif<%S>"), &ptr8 ));
    ptr8.Set( aData.NextUrl() );
    CLOG(( EParse, 3, _L8("  NextUrl<%S>"), &ptr8 ));
    ptr8.Set( aData.NextUrlAtError() );
    CLOG(( EParse, 3, _L8("  NextUrlAtErr<%S>"), &ptr8 ));
    ptr8.Set( aData.InfoUrl() );
    CLOG(( EParse, 3, _L8("  InfoUrl<%S>"), &ptr8 ));
    ptr16.Set( aData.Price() );
    CLOG(( EParse, 3, _L("  Price<%S>"), &ptr16 ));
    ptr8.Set( aData.Icon() );
    CLOG(( EParse, 3, _L8("  Icon<%S>"), &ptr8 ));

//TODO add logs for OMA 2
#endif /* def __TEST_COD_LOG */
	
	//If there are no media objects present to download, 
    if( !iData->Count() )
    	{
    	User::Leave( KErrCodInvalidDescriptor );	
    	}
    	
    // NULL data for clarity. These are never used later, but don't keep
    // pointers to objects which are out of reach.
    iData = NULL;
    User::LeaveIfError( iError );
    aIsLicenseTag = iIsLicenseTag;
    CLOG(( EParse, 2, _L("<- TDdParser::ParseL") ));
    }
Exemple #14
0
TLineBuffer::TLineBuffer(const TDesC &aBuffer) : iRemainder(aBuffer.Length()), iTail(aBuffer)
	{
	}
// -----------------------------------------------------------------------------
// CSatSendSsHandler::ProcessForwardingL
// -----------------------------------------------------------------------------
void CSatSendSsHandler::ProcessForwardingL(
        TAction aAction,
        TForwardingProcedure aForwarding,
        const TDesC& aNumber,
        const TDesC& aBasicCode,
        const TDesC& aTimer )
    {
    LOG( SIMPLE, "CSatSendSsHandler::ProcessForwardingL calling" )

    TBasicServiceGroups bsc = ChangeToBsc( aBasicCode );
    ConnectToSsEngineL();

    TCallDivertSetting setDivert;
    setDivert.iNumber.Copy( aNumber );
    setDivert.iServiceGroup = EServiceGroupVoice;
    setDivert.iStatus = EDivertingStatusUnknown;
    setDivert.iNoReplyTimer = 0;// all unconditional

    LOG2( NORMAL, 
    "CSatSendSsHandler::ProcessForwardingL aForwarding: %d", aForwarding )
    switch ( aForwarding )
        {
        case EForwardingNotReachable:
            {
            LOG( NORMAL, 
            "CSatSendSsHandler::ProcessForwardingL EForwardingNotReachable" )
            setDivert.iCondition = EDivertConditionNotReachable;
            break;
            }

        case EForwardingNoReply:
            {
            LOG( NORMAL, 
            "CSatSendSsHandler::ProcessForwardingL EForwardingNoReply" )
            if ( aTimer.Length() != 0 )
                {
                TLex input( aTimer );
                User::LeaveIfError( input.Val( setDivert.iNoReplyTimer ) );
                }
            else
                {
                LOG( NORMAL, 
                "CSatSendSsHandler::ProcessForwardingL iNoReplyTimer" )
                setDivert.iNoReplyTimer = iDivert->GetTimerValueL();
                }
            setDivert.iCondition = EDivertConditionNoReply;
            break;
            }

        case EForwardingBusy:
            {
            LOG( NORMAL, 
            "CSatSendSsHandler::ProcessForwardingL EForwardingBusy" )
            setDivert.iCondition = EDivertConditionBusy;
            break;
            }

        case EForwardingUnconditional:
            {
            LOG( NORMAL, 
            "CSatSendSsHandler::ProcessForwardingL EForwardingUnconditional" )
            setDivert.iCondition = EDivertConditionUnconditional;
            break;
            }

        case EForwardingAll:
            {
            LOG( NORMAL, 
            "CSatSendSsHandler::ProcessForwardingL EForwardingAll" )
            setDivert.iCondition = EDivertConditionAllCalls;
            break;
            }

        case EForwardingAllConditional:
            {
            LOG( NORMAL, 
            "CSatSendSsHandler::ProcessForwardingL \
            EForwardingAllConditional" )
            setDivert.iCondition = EDivertConditionAllConditionalCases;
            break;
            }

        default:
            {
            LOG( NORMAL, 
            "CSatSendSsHandler::ProcessForwardingL Unknown forwarding" )
            break;
            }
        }

    switch ( aAction )
        {
        case EActivate:
            {
            LOG( NORMAL, "CSatSendSsHandler::EActivate" )
            setDivert.iSetting = EActivateDiverting;
            iDivert->SetDivertingL( setDivert, bsc );
            break;
            }

        case EDeactivate:
            {
            LOG( NORMAL, "CSatSendSsHandler::EDeactivate" )
            setDivert.iSetting = ECancelDiverting;
            iDivert->SetDivertingL( setDivert, bsc );
            break;
            }

        case EInterrogate:
            {
            LOG( NORMAL, "CSatSendSsHandler::EInterrogate" )
            iDivert->GetDivertingStatusL( EServiceGroupVoice,
                setDivert.iCondition, bsc );
            break;
            }

        case ERegister:
            {
            LOG( NORMAL, "CSatSendSsHandler::ERegister" )
            setDivert.iSetting = ERegisterDiverting;
            iDivert->SetDivertingL( setDivert, bsc );
            break;
            }

        case EErase:
            {
            LOG( NORMAL, "CSatSendSsHandler::EErase" )
            setDivert.iSetting = EEraseDiverting;
            iDivert->SetDivertingL( setDivert, bsc );
            break;
            }

        default:
            {
            LOG( NORMAL, "  Unknown action" )
            break;
            }
        }

    LOG( SIMPLE, "CSatSendSsHandler::ProcessForwardingL exiting" )
    }
/**
Search algorithm for searching e-mail addresses

@param aText Text that will be parsed
@return ETrue if any EMail items were found else returns EFalse
@leave KErrNone, if successful; otherwise one of the other system-wide error codes.
@panic ETulPanicDescriptorLength in debug build if item's position 
and/or length is out of the document's range.
*/
TBool CTulAddressStringTokenizer::SearchMailAddressL( const TDesC& aText )
    {
    TInt searchStart = 0;
    TInt searchResult = 0;
    const TInt end = aText.Length(); // end of document

    do
        {
        TPtrC segment = aText.Right( end - searchStart );
        searchResult = segment.LocateF('@');

        if (searchResult != KErrNotFound)
            { // @ found
            // There should be valid characters (not a period) before and after the @ character
            if ( searchResult == 0 // first char
                || (searchResult >= segment.Length() - 1) // last char 
                || !(IsValidEmailChar(segment[searchResult - 1])) 
                || !(IsValidEmailHostChar(segment[searchResult + 1]))
                || segment[searchResult - 1] == '.' 
                || segment[searchResult + 1] == '.'
               )
                {
                searchStart += searchResult + 1;
                continue;
                }

            TBool wasPeriod = EFalse; // To prevent sequential periods
            // Get TLex from the pointer to get a better API for parsing
            TLexMark startPos;
            TLexMark endPos;
            TLex token = segment;
            
            // Go to searchResult and un-get until the beginning of e-mail address is reached
            token.Inc( searchResult );
            token.Mark();
            do
                {
                token.UnGet();
                if ( token.Peek() == '.' )
                    { // If it was a period
                    if (wasPeriod)	// and if the former was also -> break
                        break;
                    else	// else mark that this one was a period
                        wasPeriod = ETrue;
                    }
                else
                    wasPeriod = EFalse;
                }
            while (token.Offset() > 0 && IsValidEmailChar(token.Peek()));
            
            if (token.Offset() != 0 || !IsValidEmailChar(token.Peek()))
                token.Inc();

            // Get rid of periods from the start of address
            // Does it have to start with a number or char(abc...).
            // If it does, the loop should check that it gets rid of all special chars also.
            while (token.Peek() == '.')
                token.Inc();

            token.Mark( startPos ); // Mark the beginning of address
            token.UnGetToMark();
            wasPeriod = EFalse;
            
            do	// Go forward until a nonvalid character
                {
                token.Inc();
                if ( token.Peek() == '.' )
                    { // If it was a period
                    if ( wasPeriod )	// and if the former was also -> break
                        break;
                    else	// else mark that this one was a period
                        wasPeriod = ETrue;
                    }
                else
                    wasPeriod = EFalse;
                }
            while ( !token.Eos() && IsValidEmailHostChar( token.Peek() ) );
            
            // If address ends with a period take it away
            token.UnGet();
            if (token.Peek() != '.')
                token.Inc();

            token.Mark( endPos ); // Mark the beginning of address

            // Append the found string to the array
            __ASSERT_DEBUG( searchStart + token.MarkedOffset( startPos ) 
                            + token.MarkedOffset( endPos ) 
                            - token.MarkedOffset( startPos ) <= aText.Length(), 
                            Panic(ETulPanicDescriptorLength) );
            AddItemL( searchStart + token.MarkedOffset( startPos ), 
                      token.MarkedOffset( endPos ) - token.MarkedOffset( startPos ), 
                      EFindItemSearchMailAddressBin);
            searchStart += token.MarkedOffset( endPos ) + 1;
            }
        }
    while ( searchResult != KErrNotFound && searchStart < end );

    return (iFoundItems->Count() > 0);
    }
void DeprecatedString::setBufferFromDes(const TDesC& des)
{
    setUnicode((const DeprecatedChar *)des.Ptr(), (unsigned)des.Length());
}
/**
Search algorithm for searching phone numbers

@param aText Text that will be parsed
@return ETrue if any Phone Number items were found else returns EFalse
@leave KErrNone, if successful; otherwise one of the other system-wide error codes.
@panic ETulPanicDescriptorLength in debug build if item's position 
and/or length is out of the document's range.
*/
TBool CTulAddressStringTokenizer::SearchPhoneNumberL( const TDesC& aText )
    {
    TLexMark startMark; // Points to the start of the found phone number
    TLexMark endMark; // Points to the end of the found phone number
    TLexMark mark;
    const TInt end = aText.Length();

    TLex number = aText;

    while ( !(number.Eos()) )
        {
        TInt numberCount = 0; // How many real numbers (1234567890)
        TInt bracketsOpen = 0; // How many brackets are currently open
        TInt brackets = 0; // How many brackets overall

        TChar charac = number.Peek();

        while( (!(IsValidPhoneNumberChar( charac ) || charac == '+'
               || charac == '(' ) || charac == '-' || charac == '.' || charac == '/') 
			   && !(number.Eos()) && number.Offset() < end )
            {
            number.Inc();
            charac = number.Peek();
            }

        if ( number.Offset() >= end )
            break;
        
        if ( number.Peek() == '#' )
			{
			number.Inc();
			if (number.Peek() == '.' )
				continue;

			number.UnGet();
			}

        if ( number.Peek() == '+' )
            { // '+' has to be followed by a number (not # or * ...)
            number.Inc();
            if ( !(number.Peek().IsDigit()) )
                continue;

            number.UnGet();
            }

        if ( number.Peek() == '(' )
            { // '(' has to be followed by valid phone number 
              // character (whitespaces are allowed before) or '+' is a next character
            number.Inc();
            if ( !(number.Peek() == '+') )
                {
                number.Mark(mark);
                number.SkipSpace();
                charac = number.Peek();
                if ( !( IsValidPhoneNumberChar(charac) || charac == '+' 
                    || charac == '(' ) || charac == '-' || charac == '.' || charac == '/')
                    {
                    number.Inc();
                    continue;
                    }
                else
                    {
                    number.UnGetToMark(mark);
                    number.UnGet();
                    number.Mark(startMark);
                    }
                } 
            else
                {
                number.UnGet();
                number.Mark(startMark);
                number.Inc();
                }

            bracketsOpen++;
            brackets++;
            }
        else
            number.Mark(startMark);

        if ( number.Peek().IsDigit() )	// If the character was a number
            numberCount++;
        else if ( bracketsOpen > 0 ) 
            { 
            number.Inc();
            TChar next  = number.Peek();
            TInt bracketsOpen2 = bracketsOpen;
            while( (IsValidPhoneNumberChar( next ) || next.IsSpace()
                || next == '(' || next == ')' || next == 'p' || next == '+'
                || next == 'w' ) && !(number.Eos()) && number.Offset() < end)
                {
                if ( next == '(' )
                    bracketsOpen2++;
                else if ( next == ')' )
                    bracketsOpen2--;
                
                if ( bracketsOpen2 == 0 )
                    break;

                number.Inc();
                next = number.Peek();
                }

            number.UnGetToMark(startMark);
            if ( bracketsOpen2 != 0 )
                {
                number.Inc();
                continue;
                }
            }

        number.Inc();
        while ( number.Peek() == '(' && !(number.Eos()) && bracketsOpen > 0 )
            {
            number.Inc();
            bracketsOpen++;
            }

        if ( number.Peek() == '+' && bracketsOpen > 0 )
            number.Inc();

        // a Valid first character has been found. Let's go forward as long as valid characters are found.
        charac = number.Peek();

        while( (IsValidPhoneNumberChar( charac ) || charac.IsSpace()
            || charac == '(' || charac == ')' || charac == 'p'
            || charac == 'w' ) && !(number.Eos()) && number.Offset() < end
            && charac != KCharLinefeed && charac != KCharFormfeed 
            && charac != KCharCarriageReturn
            && charac != KCharLineSeparator
            && charac != KCharParagraphSeparator )
            {
            if ( number.Peek() == '(' )
                { // '(' can't be the last character in phone number
                number.Mark(mark);
                number.Inc();
                
                TChar spaceJump = number.Peek();
                while ( !number.Eos() && spaceJump.IsSpace() && spaceJump != KCharLinefeed 
                        && spaceJump != KCharFormfeed && spaceJump != KCharCarriageReturn 
                        && charac != KCharLineSeparator && spaceJump != KCharParagraphSeparator)
                    {
                    number.Inc();
                    spaceJump = number.Peek();
                    }
                
                if ( !(IsValidPhoneNumberChar(number.Peek())) && number.Peek() != ')'
                     && number.Peek() != '(' )
                    {
                    number.UnGetToMark(mark);
                    break;
                    }

                TChar next  = number.Peek();
                TInt bracketsOpen2 = bracketsOpen + 1;
                while( (IsValidPhoneNumberChar( next ) || next.IsSpace()
                    || next == '(' || next == ')' || next == 'p'
                    || next == 'w' ) && !(number.Eos()) && number.Offset() < end)
                    {
                    if ( next == '(' )
                        bracketsOpen2++;
                    else if ( next == ')' )
                        bracketsOpen2--;

                    if ( bracketsOpen2 == 0 )
                        break;

                    number.Inc();
                    next = number.Peek();
                    }

                number.UnGetToMark(mark);

                if ( bracketsOpen2 != 0 )
                    break;

                bracketsOpen++;
                brackets++;
                }
            else if ( number.Peek() == ')' )
                {
                if ( bracketsOpen <= 0 )	// there has to be equal number of brackets
                    break;

                bracketsOpen--;
				number.Mark(mark);
                number.Inc();
				if ( number.Peek() == '.' )	// '.' is not allowed after ')'
                    break;

                number.UnGetToMark(mark);
                }
            else if ( number.Peek() == '-' || number.Peek() == 'w' 
                        || number.Peek() == 'p' || number.Peek() == '.' || number.Peek() == '/')
                { // Hyphen mark and 'p' & 'w' chars must be followed by a number
				TChar last = number.Peek();
                number.Mark(mark);
                number.Inc();
                
                TChar spaceJump = number.Peek();
                while ( !number.Eos() && spaceJump.IsSpace() && spaceJump != KCharLinefeed 
                        && spaceJump != KCharFormfeed && spaceJump != KCharCarriageReturn 
                        && charac != KCharLineSeparator && spaceJump != KCharParagraphSeparator )
                    {
                    number.Inc();
                    spaceJump = number.Peek();
                    }
                    
                if ( !(number.Peek().IsDigit()) )
                    {
					if (last == '.' && number.Peek() == ')' && bracketsOpen > 0 )
						continue;
					else
						{
						number.UnGetToMark(mark);
						break;
						}
                    }

                number.UnGetToMark(mark);
                }
            else if ( number.Peek().IsDigit() )
                numberCount++;

            number.Inc();
            charac = number.Peek();
            }

        // Get rid of whitespaces from the end
        number.UnGet();
        while( number.Peek().IsSpace() && !(number.Eos()))
            number.UnGet();

        number.Inc();
        // ------------------------------------
        number.Mark(endMark);

        // If they exist, remove brackets from the beginning and the end
        number.Mark(mark); // Let's mark where to continue the search
        TBool endBrackets = ETrue;
        do
            {
            number.UnGet();

            if ( number.Peek() == ')' )
                {
                number.UnGetToMark(startMark);
                if ( number.Peek() == '(' )
                    {
                    // If there's more than one pair of brackets -> don't strip them.
                    if ( brackets > 1 )
                        break;

                    number.Inc();
                    number.Mark(startMark);
                    number.UnGetToMark(endMark);
                    number.UnGet();
                    number.Mark(endMark);
                    // Get rid of whitespaces and periods from the end and from the beginning
					number.UnGet();
                    while ( (number.Peek().IsSpace() || number.Peek() == '.') 
                            && number.Offset() > number.MarkedOffset(startMark) )     
                        { // from the end
                        number.UnGet();
                        }
					number.Inc();
                    number.Mark(endMark);
                    number.UnGetToMark(startMark);
                    while ( (number.Peek().IsSpace() || number.Peek() == '.') 
                            && number.Offset() < number.MarkedOffset(endMark) )     
                        { // from the beginning
                        number.Inc();
                        }
                    number.Mark(startMark);
                    number.UnGetToMark(endMark);
                    // ----
                    }
                else
                    endBrackets = EFalse;
                }
            else
                endBrackets = EFalse;
            }
        while ( endBrackets );

        number.UnGetToMark(mark);
        // ----------------        

        if ( numberCount <= KFindItemMaxNumbers && numberCount >= iMinNumbers )
            {
			TPtrC tokenPtr = number.MarkedToken(startMark);
			TInt tokensEnd = tokenPtr.Length();
			TInt numbers = 0;
			TInt partialNumber = 0;
			TBool wasValidPhoneNumber = ETrue;
			TInt i = 0;

			for ( ; i < tokensEnd; i++ )
				{
				if ( tokenPtr[i] == '.' )
					partialNumber = 0;
				else if ( ((TChar)tokenPtr[i]).IsDigit() )
					{
					numbers++;
					partialNumber++;
					}

				if ( ( partialNumber == 1 || partialNumber == 2 ) && i + 1 < tokensEnd )
					{
					if ( tokenPtr[i + 1] == '.' )
						wasValidPhoneNumber = EFalse;
					}
				}
				
			if (!wasValidPhoneNumber && numbers > 6)
				wasValidPhoneNumber = ETrue;
			
			if (wasValidPhoneNumber)
				{
	            __ASSERT_DEBUG( number.MarkedOffset(startMark) + number.MarkedOffset(endMark) 
	                            - number.MarkedOffset(startMark) <= aText.Length(), 
	                            Panic(ETulPanicDescriptorLength) );

	            AddItemL( number.MarkedOffset(startMark), 
	                      number.MarkedOffset(endMark) - number.MarkedOffset(startMark), 
	                      EFindItemSearchPhoneNumberBin );
				}
			}

        }

    return (iFoundItems->Count() > 0);
    }
//从文件路径拆分出文件名
void GetFileNameByUrl(const TDesC& aUrl, TDes& aFileName)
{
	TInt order = aUrl.LocateReverse('/');
	TInt sourceLength = aUrl.Length() - order -1; 
	aFileName = aUrl.Mid(order + 1, sourceLength);
}
/**
Search fixed start URLs, i.e. URLs without schema (www., wap.).
Also finds IPv4 addresses (*.*.*.*).
As a special case, supports deprecated hardcoded schematic addresses finding 
(http://, https://, rtsp://) to make sure deprecated search cases work 
as they did previously.

@param aText Text that will be parsed
@param aFindFixedSchemas If true, will find old fixed schematic URLs also
@return ETrue if any URL are found else returns EFalse
@leave KErrNone, if successful; otherwise one of the other system-wide error codes.
@panic ETulPanicDescriptorLength in debug build if item's position and/or length is out of the document's range.
*/
TBool CTulAddressStringTokenizer::SearchUrlL( const TDesC& aText, const TBool aFindFixedSchemas )
    {
    TLex text = aText;
    while ( !text.Eos() )
        {
        while( !(text.Eos()) && !IsValidUrlChar( text.Peek() ) )
            text.Inc();

        text.Mark();
        while( !(text.Eos()) && IsValidUrlChar( text.Peek() ) )
            text.Inc();

        TPtrC tokenPtr = text.MarkedToken();
        TBool wasValidUrl = EFalse;

        if ( aFindFixedSchemas )	// Search for http://
            wasValidUrl = ParseUrlL( KHttpUrlAddress, tokenPtr, text.Offset() );
        
        if (aFindFixedSchemas && !wasValidUrl)	// Search for https://
            wasValidUrl = ParseUrlL( KHttpsUrlAddress, tokenPtr, text.Offset() );

        if (aFindFixedSchemas && !wasValidUrl) // Search for rtsp://
            wasValidUrl = ParseUrlL( KRtspUrlAddress, tokenPtr, text.Offset() );

        if ( !wasValidUrl )	// Search for www.
            wasValidUrl = ParseUrlL( KWwwUrlAddress, tokenPtr, text.Offset() );

        if ( !wasValidUrl )	// Search for wap.
            wasValidUrl = ParseUrlL( KWapUrlAddress, tokenPtr, text.Offset() );

        if ( !wasValidUrl )	// Search for IP-address (xxx.xxx.xxx.xxx)
            { 
            if ( tokenPtr.Match( KIPAddress ) != KErrNotFound )
                {
                TInt periods = 0;
                wasValidUrl = ETrue;
                TBool endWithPunctuation = EFalse;
                TBool betweenBrackets = EFalse;

                // First see if token ends with ",",".","!","?",";" or ":"
                TChar charac = tokenPtr[tokenPtr.Length() - 1];
                TChar charac0 = tokenPtr[0];
                if ( charac == ',' || charac == '.' ||
                     charac == '!' || charac == '?' ||
                     charac == ';' || charac == ':' )
                    {
                    endWithPunctuation = ETrue;
                    }
                // Or if it starts and ends with brackets or quotation marks
                else if ( ( charac0 == '(' && charac == ')' )
                       || ( charac0 == '"' && charac == '"' )
                       || ( charac0 == '[' && charac == ']' )
                       || ( charac0 == '<' && charac == '>' ) )
                    {
                    betweenBrackets = ETrue;
                    }

                TInt i = 0;
                TInt tokensEnd = tokenPtr.Length();
                if ( endWithPunctuation )
                    tokensEnd--;
                else if ( betweenBrackets )
                    {
                    i = 1;
                    tokensEnd--;
                    }

                // Take a closer look to see if a valid IP-address
                TBuf<3> ipPart;
                TInt numbers = 0;
                for ( ; i < tokensEnd; i++ )
                    {
                    if ( !( ((TChar)tokenPtr[i]).IsDigit() || tokenPtr[i] == '.' ) )
                        {
                        wasValidUrl = EFalse;
                        break;
                        }

                    if ( tokenPtr[i] == '.' )
                        periods++;
                    else
                        numbers++;

                    if ( numbers > KNumbersInIpAddress || periods > KDotsInIpAddress )
                        {
                        wasValidUrl = EFalse;
                        break;
                        }

                    if ( ((TChar)tokenPtr[i]).IsDigit() )
                        {
                        ipPart.Append( tokenPtr[i] );
                        TBool checkInt = EFalse;
                        if ( i + 1 < tokensEnd )
                            {
                            if ( tokenPtr[i+1] == '.' )
                                checkInt = ETrue;
                            }

                        if ( i == tokensEnd - 1 || checkInt )
                            {
                            TLex val = ipPart;
                            TInt numberInt;
                            TInt error = val.Val( numberInt );
                            if ( error != KErrNone || numberInt > 255 )
                                {
                                wasValidUrl = EFalse;
                                break;
                                }

                            numbers = 0;
                            ipPart.Delete( 0, ipPart.Length() );
                            }
                        }
                    }

                if ( wasValidUrl && periods == KDotsInIpAddress )
                    {
                    TInt startPos = text.Offset() - tokenPtr.Length();
                    TInt length = tokenPtr.Length();
                    // If there was a punctuation at the end or brackets, let's take it/them away
                    if ( endWithPunctuation || betweenBrackets)
                        {
                        length--;
                        if ( betweenBrackets )
                            {
                            startPos++;
                            length--;
                            }
                        }

                    __ASSERT_DEBUG( startPos + length <= aText.Length(), Panic(ETulPanicDescriptorLength) );
                    AddItemL( startPos, length, EFindItemSearchURLBin );
                    }
                }
            }
        }

    return (iFoundItems->Count() > 0);
    }
/**
Counts the number of parameters in the text. 
Needed for correct memory allocations.
*/
TInt CResourceLoader::GetParamCount(const TDesC& aText, TInt aIndex)
    {
    TInt paramCount(0);
    TInt i(0);
    TBool singleIndex((aIndex < 0) || (aIndex > KNumOfParams) ? EFalse : ETrue);

    while (i < aText.Length())
        {
        TPtrC remainder = aText.Right(aText.Length() - i);
        TInt nextKey = remainder.Locate(KKeyPrefix);
        i += nextKey;

        if (nextKey != KErrNotFound && i < aText.Length() - 1)
            {
            TInt lastCharInKey = i + 1;

            // skip possible key index
            TText t = aText[lastCharInKey];
            TInt foundIndex(-1);
            
            if (t >= '0' && t <= '9')
                {
                lastCharInKey++;
                foundIndex = t - '0';

                if (lastCharInKey < aText.Length())
                    {
                    t = aText[lastCharInKey];
                    if (t >= '0' && t <= '9')
                        {
                        foundIndex *= 10;
                        foundIndex += t - '0';
                        lastCharInKey++;
                        }
                    }
                }

            // lastCharInKey is now the index of 'N' or 'U' in the key

            if (lastCharInKey < aText.Length())
                {
                // Only count parameter, if index matches
                if (!singleIndex || (foundIndex == aIndex))
                    {
                    TText t = aText[lastCharInKey];
                    if (t == 'U' || t == 'N')
                        {
                        // found legit key, count it
                        paramCount++;
                        // continue search after index
                        i = lastCharInKey + 1;
                        }
                    else if (t == '%')
                        i = lastCharInKey;
                    else    // continue search after index
                        i = lastCharInKey + 1;
                    }
                else    // continue search after index
                    i = lastCharInKey + 1;
                }
            else    // end of string encountered - stop
                break;
            }
        else     // no key found - stop
            break;
        }

    return paramCount;
    }
Exemple #22
0
void TCafUtils::WriteDescriptor16L(RWriteStream& aStream, const TDesC& aDescriptor)
	{
	// Write unicode data to the stream
	aStream.WriteInt32L(aDescriptor.Length());
	aStream.WriteL(aDescriptor);
	}	
void CSMSSender::CreateSMSMessageL(const TDesC& aText, const TDesC& aAddress)
/**
	Prepare SMS specific objects ready to send via ESOCK
	@param aText buffer containing ascii contents of message to send
	@param aAddress buffer with telephone number of SMS receiver 
*/
	{
#ifndef __WINS__
	TSmsAddr smsAddr;
    smsAddr.SetSmsAddrFamily(ESmsAddrSendOnly);
    smsAddr.SetPort(smsAddr.Port() + 1);//ycf
    __LOGSTR_TOFILE("sockent bind");
	iSocket.Bind(smsAddr);

	CSmsBuffer* smsBuffer = CSmsBuffer::NewL();
	//CleanupStack::PushL(smsBuffer) is NOT used because CSmsMessage takes ownership of our buffer :-)
	CSmsMessage* smsMsg = CSmsMessage::NewL(iFs, CSmsPDU::ESmsSubmit, smsBuffer);
	CleanupStack::PushL(smsMsg);
	
	TSmsUserDataSettings smsSettings;
    smsSettings.SetAlphabet(TSmsDataCodingScheme::ESmsAlphabetUCS2);
	smsSettings.SetTextCompressed(EFalse);
	smsMsg->SetUserDataSettingsL(smsSettings);
	
	TBuf<KMaxAddressSize> toAddress;
	toAddress.Copy(aAddress);
	smsMsg->SetToFromAddressL(toAddress);

	//Get service centre address.
	// The method used here assumes the SMS settings are provisioned, which is true in known cases.
	// There are alternative partner-only APIs, however this allow this source to be kept public
	#ifdef EKA2
		CSmsSettings* smsSCSettings = CSmsSettings::NewL();
		CleanupStack::PushL(smsSCSettings);
    	CSmsAccount* smsAccount=CSmsAccount::NewLC();
    	smsAccount->LoadSettingsL(*smsSCSettings);
 		// index of the default service centre address for this service
 		TInt defIndex;
		User::LeaveIfError(defIndex = smsSCSettings->DefaultServiceCenter());
 		// Get the service center address
		CSmsServiceCenter&  scAddr = smsSCSettings->GetServiceCenter(defIndex);
	
		TPtrC theAddress=scAddr.Address();
		HBufC* serviceCentreAddress=HBufC::NewLC(theAddress.Length());
		*serviceCentreAddress=theAddress;
		smsMsg->SmsPDU().SetServiceCenterAddressL(*serviceCentreAddress);
		CleanupStack::PopAndDestroy(serviceCentreAddress);//
		CleanupStack::PopAndDestroy(smsAccount);
		CleanupStack::PopAndDestroy(smsSCSettings);	
				
	#else
		TMsvId		serviceId;
		CObserver* pObserver = new (ELeave) CObserver();
		CleanupStack::PushL(pObserver);
		CMsvSession* pSession = CMsvSession::OpenSyncL(*pObserver);
		CleanupStack::PushL(pSession);
		TSmsUtilities::ServiceIdL(*pSession, serviceId, KUidMsgTypeSMS);
		CMsvEntry* service = pSession->GetEntryL(serviceId);
		CleanupStack::PushL(service);
		CMsvStore* msvstore = service->ReadStoreL();
		CleanupStack::PushL(msvstore);
		CSmsSettings* smsSCSettings = CSmsSettings::NewL();
		CleanupStack::PushL(smsSCSettings);
		smsSCSettings->RestoreL(*msvstore);
		TInt defIndex;
		User::LeaveIfError(defIndex = smsSCSettings->DefaultSC());
		defIndex = smsSCSettings->DefaultSC();
 		// Get the default service center address
		CSmsNumber&  scAddr = smsSCSettings->SCAddress(defIndex);
		TPtrC theAddress=scAddr.Address();
		HBufC* serviceCentreAddress=HBufC::NewLC(theAddress.Length());
		*serviceCentreAddress=theAddress;
		smsMsg->SmsPDU().SetServiceCenterAddressL(*serviceCentreAddress);
		CleanupStack::PopAndDestroy(serviceCentreAddress);//
		CleanupStack::PopAndDestroy(smsSCSettings); //smsSettings
		CleanupStack::PopAndDestroy(msvstore);
		CleanupStack::PopAndDestroy(service);
		CleanupStack::PopAndDestroy(pSession);
		CleanupStack::PopAndDestroy(pObserver);		
	#endif
	
	//convert to wide
	HBufC* payload = HBufC::NewL(aText.Length());
	CleanupStack::PushL(payload);
	TPtr pPayload=payload->Des();
	pPayload.Copy(aText); //copy from narrow to wide and convert
	smsBuffer->InsertL(0, pPayload); //copies payload
	RSmsSocketWriteStream writeStream(iSocket);
	CleanupClosePushL(writeStream);
	writeStream << *smsMsg; // remember << operator _CAN_ leave
	__LOGSTR_TOFILE("write stream commit");
	writeStream.CommitL();
	CleanupStack::PopAndDestroy(&writeStream);
	CleanupStack::PopAndDestroy(2);//smsMsg, payload	
#endif
	}
EXPORT_C void AppendCheckingSpaceL(TDes& aString, const TDesC& toAppend)
{
	CheckStringSpaceL(aString, toAppend.Length());
	aString.Append(toAppend);
}
// -----------------------------------------------------------------------------
// CWPPushMessage::AuthenticateL
// The method first checks if there is security information in the message
// with aMessage.SEC(). If yes, the authentication code described in OMA
// Provisioning Bootstrap specification is calculated and compared to the
// one in message header. If the codes match, authentication has been 
// performed succesfully.
// -----------------------------------------------------------------------------
//
EXPORT_C TInt CWPPushMessage::AuthenticateL( const TDesC& aIMSI, 
                                            const TDesC& aPIN )
    {
    FLOG( _L( "[Provisioning] CWPPushMessage::AuthenticateL:" ) );
    
    TInt result( KWPAuthResultAuthenticated );

    // Retrieve the MAC from message
    ParseHeaderL();

    // The HMAC is in ASCII HEX format. Convert to binary.
    HBufC8* headerMac = PackLC( MAC() );

    // Create space for key
    HBufC8* key = HBufC8::NewLC( Max( 1, aIMSI.Length() + aPIN.Length() ) );
    TPtr8 keyPtr( key->Des() );
    // Check if only NETWPIN authentication is allowed, from central repository.
    TInt value( 0 );
	CRepository* repository = CRepository::NewLC( KOMAProvAuthenticationLV );
	User::LeaveIfError( repository->Get( KOMAProvAuthenticationLVFlag, value ) );
	CleanupStack::PopAndDestroy(); // repository

    // We support only security type NETWPIN
    switch( SEC() )
        {
        case KSECNETWPIN:
            {
            FLOG( _L( "[Provisioning] CWPPushMessage::AuthenticateL: KSECNETWPIN" ) );
            // Get the key to be used in HMAC calculation
            ConvertIMSIL( aIMSI, keyPtr );
            break;
            }

        case KSECUSERPIN:
            {
            FLOG( _L( "[Provisioning] CWPPushMessage::AuthenticateL: KSECUSERPIN" ) );
            if (EAuthNETWPINOnly != value)
            	{
            	if( aPIN.Length() == 0 )
                	{
                	result = KWPAuthResultPinRequired;
                	FLOG( _L( "[Provisioning] CWPPushMessage::AuthenticateL: KWPAuthResultPinRequired" ) );
                	}
            	keyPtr.Copy( aPIN );
            	}
            else
               	{
               	result = KWPAuthResultAuthenticationFailed;
               	FLOG( _L( "[Provisioning] CWPPushMessage::AuthenticateL: KWPAuthResultAuthenticationFailed" ) );
               	}
            break;
            }

        case KSECUSERNETWPIN:
            {
            FLOG( _L( "[Provisioning] CWPPushMessage::AuthenticateL: KSECUSERNETWPIN" ) );
            if (EAuthNETWPINOnly != value)
            	{
            	if( aPIN.Length() == 0 )
                	{
	                result = KWPAuthResultPinRequired;
	                FLOG( _L( "[Provisioning] CWPPushMessage::AuthenticateL: KWPAuthResultPinRequired" ) );
    	            }

        	    ConvertIMSIL( aIMSI, keyPtr );
	            keyPtr.Append( aPIN );
            	}
            else
            	{
				result = KWPAuthResultAuthenticationFailed;   
				FLOG( _L( "[Provisioning] CWPPushMessage::AuthenticateL: KWPAuthResultAuthenticationFailed" ) );         		
            	}
            break;
            }

        case KSECUSERPINMAC:
            {
            FLOG( _L( "[Provisioning] CWPPushMessage::AuthenticateL: KSECUSERPINMAC" ) );
            if (EAuthNETWPINOnly != value)
            	{
	            if( aPIN.Length() == 0 )
    	            {
        	        result = KWPAuthResultPinRequired;
        	        FLOG( _L( "[Provisioning] CWPPushMessage::AuthenticateL: KWPAuthResultPinRequired" ) );
            	    }
            	keyPtr.Copy( aPIN );
            	}
            else
           		{
				result = KWPAuthResultAuthenticationFailed;            	    	
				FLOG( _L( "[Provisioning] CWPPushMessage::AuthenticateL: KWPAuthResultAuthenticationFailed" ) );
           	    }
            break;
            }

        default:
            {
            FLOG( _L( "[Provisioning] CWPPushMessage::AuthenticateL: default" ) );
            if (EAuthNETWPINOnly == value || EAuthNoSecurity == value )
            	{
            	result = KWPAuthResultAuthenticationFailed;
            	FLOG( _L( "[Provisioning] CWPPushMessage::AuthenticateL: KWPAuthResultAuthenticationFailed" ) );
            	}
            else
            	{
            	result = KWPAuthResultNoAuthentication;	
            	FLOG( _L( "[Provisioning] CWPPushMessage::AuthenticateL: KWPAuthResultNoAuthentication" ) );
            	}            	
            break;
            }
        }
         
    if( result == KWPAuthResultAuthenticated )
        {
        FLOG( _L( "[Provisioning] CWPPushMessage::AuthenticateL: KWPAuthResultAuthenticated" ) );
        CMessageDigest* digest = CSHA1::NewL();
        CleanupStack::PushL( digest );

        if( SEC() == KSECUSERPINMAC )
            {
            // key C is a concatenation of pin K and digest m
            TPtrC8 K( key->Left( key->Length()/2 ) );
            TPtrC8 m( key->Right( key->Length()/2 ) );

            // M' = HMAC-SHA(K, A)
            CHMAC* hmac = CHMAC::NewL( K, digest );
            CleanupStack::Pop( digest );
            CleanupStack::PushL( hmac );
            TPtrC8 MM( hmac->Hash( Body() ) );
    
            // Create m' (renamed to mm)
            HBufC8* mm = HBufC8::NewLC( m.Length() );
            TPtr8 ptr( mm->Des() );
            for( TInt i( 0 ); i < m.Length(); i++ )
                {
                ptr.Append( (MM[i]%10)+KZero );
                }

            // Compare the MACs and mark the message as authenticated
            if( *mm != m )
                {
                result = KWPAuthResultAuthenticationFailed;
                }
            CleanupStack::PopAndDestroy(); // mm
            }
        else
            {
            FLOG( _L( "[Provisioning] CWPPushMessage::AuthenticateL: not KWPAuthResultAuthenticated" ) );
            // Create the HMAC from body
            CHMAC* hmac = CHMAC::NewL( *key, digest );
            CleanupStack::Pop( digest );
            CleanupStack::PushL( hmac );
    
            // Compare the MACs and mark the message as authenticated
            if( headerMac->Length() == 0 
                || hmac->Hash( Body() ) != *headerMac )
                {
                result = KWPAuthResultAuthenticationFailed;
                }
            }
        CleanupStack::PopAndDestroy(); // hmac
        }
            
    CleanupStack::PopAndDestroy( 2 ); // key, headerMac

    return result;
    }
//===============================================
//		CNSmlProfileContentHandler::Charecters()
//		
//		
//===============================================	
TInt CNSmlProfileContentHandler::Charecters(TDesC& aBuf, TInt /*aStart*/, TInt /*aLength*/)
{	

	TInt aValue;
	if (iDSSettingInProgress)
	{
		
		if(iState == EProfileDisplayName)
		{
			if(aBuf.Length() > KNSmlMaxProfileNameLength)
			{
			iCustomProfileArray->At(iCounter)->SetStrValue( EDSProfileDisplayName, KEmpty) ;
			}
			else
			{
			iCustomProfileArray->At(iCounter)->SetStrValue( EDSProfileDisplayName, aBuf) ;
			}
			iState = EStateHandled;		
		}
		if(iState == EProfileServerURL)
		{
			if(aBuf.Length() > KDSMaxURLLength)
			{
			iCustomProfileArray->At(iCounter)->SetStrValue( EDSProfileDisplayName, KEmpty) ;
			}
			else
			{
			SetServerURL(aBuf);
			}
			iState = EStateHandled;		
		}
		if(iState == EProfileIAPId)
		{
		
			if(aBuf.Length() > KAccessPointNameMaxLen)
			{
			_LIT(KDefaultValue ,"-1");
			aBuf = KDefaultValue;	
			}
			
			TInt iapId = AccessPointIdL(aBuf);
			iCustomProfileArray->At(iCounter)->SetIntValue( EDSProfileIAPId, iapId) ;
			iState = EStateHandled;		
		}
		if(iState == EProfileTransportId)
		{
			_LIT16(KHexCode,"0x");
			TBuf<64> tempBuf(aBuf);
			TInt temp = tempBuf.Find(KHexCode); 
			tempBuf.Delete(0, temp + 2);

			iLex = tempBuf;
			TInt64 aVal;
			User::LeaveIfError(iLex.Val(aVal ,EHex));
			if (aVal != KUidNSmlMediumTypeInternet.iUid && aVal != KUidNSmlMediumTypeBluetooth.iUid)
				{
				aVal = KUidNSmlMediumTypeInternet.iUid;	
				}
			iCustomProfileArray->At(iCounter)->SetIntValue( EDSProfileTransportId, aVal) ;
			iState = EStateHandled;		
		}
		
		if(iState == EProfileSyncServerUsername)
		{
			if(aBuf.Length() > KNSmlMaxUsernameLength)
			{
			iCustomProfileArray->At(iCounter)->SetStrValue( EDSProfileDisplayName, KEmpty) ;
			}
			else
			{
			iCustomProfileArray->At(iCounter)->SetStrValue( EDSProfileSyncServerUsername, aBuf) ;
			}
			iState = EStateHandled;	
		}
		if(iState == EProfileSyncServerPassword)
		{
			if(aBuf.Length() > KNSmlMaxPasswordLength)
			{
			iCustomProfileArray->At(iCounter)->SetStrValue( EDSProfileDisplayName, KEmpty) ;
			}
			else
			{
			iCustomProfileArray->At(iCounter)->SetStrValue( EDSProfileSyncServerPassword, aBuf) ;
			}
			iState = EStateHandled;	
		}
		if(iState == EProfileServerAlertedAction)
		{
			iLex = aBuf;
			User::LeaveIfError(iLex.Val(aValue));
			TInt typeId = ServerAlertType(aValue);
			
			if(aValue != ESmlEnableSync && aValue != ESmlConfirmSync && aValue != ESmlDisableSync)
				{
				aValue = ESmlEnableSync;
				}
			
			iCustomProfileArray->At(iCounter)->SetIntValue( EDSProfileServerAlertedAction, typeId) ;
			iState = EStateHandled;		
		}
	
		if(iState == EProfileHidden)
		{
			iLex = aBuf;
			User::LeaveIfError(iLex.Val(aValue));
			SetVisibility(aValue);
			iState = EStateHandled;		
		}
		
		if(iState == EProfileHttpAuthUsed)
		{
			iLex = aBuf;
			User::LeaveIfError(iLex.Val(aValue));
			if (aValue != 0 && aValue != 1)
			{
				aValue = 1;
			}
			iCustomProfileArray->At(iCounter)->SetIntValue( EDSProfileHttpAuthUsed, aValue) ;
			iState = EStateHandled;		
		}
		
		if(iState == EProfileHttpAuthUsername)
		{	
			if(iCustomProfileArray->At(iCounter)->IntValue(EDSProfileTransportId) 
											== KUidNSmlMediumTypeBluetooth.iUid 
				|| !iCustomProfileArray->At(iCounter)->IntValue(EDSProfileHttpAuthUsed))
				{
				iCustomProfileArray->At(iCounter)->SetStrValue( EDSProfileHttpAuthUsername, KEmpty) ;
				}
			else if (aBuf.Length() > KNSmlMaxHttpAuthUsernameLength)
			{
			iCustomProfileArray->At(iCounter)->SetStrValue( EDSProfileDisplayName, KEmpty) ;
			}
			else
			{
			iCustomProfileArray->At(iCounter)->SetStrValue( EDSProfileHttpAuthUsername, aBuf) ;
			}
			iState = EStateHandled;
		}
		
		if(iState == EProfileHttpAuthPassword)
		{	
			if(iCustomProfileArray->At(iCounter)->IntValue(EDSProfileTransportId) 
											== KUidNSmlMediumTypeBluetooth.iUid 
				|| !iCustomProfileArray->At(iCounter)->IntValue(EDSProfileHttpAuthUsed))
				{
				iCustomProfileArray->At(iCounter)->SetStrValue( EDSProfileHttpAuthPassword, KEmpty) ;
				}
			else if(aBuf.Length() > KNSmlMaxHttpAuthPasswordLength)
			{
			iCustomProfileArray->At(iCounter)->SetStrValue( EDSProfileDisplayName, KEmpty) ;
			}
			else
			{
			iCustomProfileArray->At(iCounter)->SetStrValue( EDSProfileHttpAuthPassword, aBuf) ;
			}
			iState = EStateHandled;	
		}
		
		if(iState == EProfileServerId)
		{
			if(aBuf.Length() > KNSmlMaxServerIdLength)
			{
			iCustomProfileArray->At(iCounter)->SetStrValue( EDSProfileDisplayName, KEmpty) ;
			}
			else
			{
			iCustomProfileArray->At(iCounter)->SetStrValue( EDSProfileServerId, aBuf) ;						
			}
			iState = EStateHandled;	
		}
		if(iState == EProfileProtocolVersion)
		{
			iLex = aBuf;
			User::LeaveIfError(iLex.Val(aValue));
			
			if(aValue != ESmlVersion1_1_2 && aValue != ESmlVersion1_2)
				{
				aValue = ESmlVersion1_2;
				}
			iCustomProfileArray->At(iCounter)->SetIntValue( EDSProfileProtocolVersion, aValue) ;
			iState = EStateHandled;		
		}
		
		if(iState == ESyncType)
		{
			TInt syncType = SyncType (aBuf);
			iSyncTypeArray->AppendL(syncType);
			iState = EStateHandled;		
		}
		
		if(iState == EDefaultProfile)
        {
            if(aBuf.Compare(_L("true")) == 0)
                {
                aValue = 1;
                }
            else
                {
                aValue = 0;
                }
            iCustomProfileArray->At(iCounter)->SetIntValue( EDSProfileDefaultProfile, aValue );
            iState = EStateHandled;     
        }
	}
	else if (iDSContentInProgress)
	{
		if(iState == EProfileDisplayName)
		{
			if(aBuf.Length() > KNSmlMaxProfileNameLength)
			{
			iContentArray->At(iContentCounter)->SetStrValue( EXMLDSProfileName, KEmpty) ;
			iInvalidContent = ETrue;
			}
			else
			{
			iContentArray->At(iContentCounter)->SetStrValue( EXMLDSProfileName ,aBuf);
			}
			iState = EStateHandled;
		}
		if(iState == EProfileServerId)
		{	
			if(aBuf.Length() > KNSmlMaxServerIdLength || iInvalidContent)
			{
			iContentArray->At(iContentCounter)->SetStrValue( EXMLDSProfileName, KEmpty) ;
			iContentArray->At(iContentCounter)->SetStrValue( EXMLDSServerId, KEmpty) ;
			}
			else
			{
			iContentArray->At(iContentCounter)->SetStrValue( EXMLDSServerId ,aBuf);
			}
			iState = EStateHandled;
		}
		if(iState == EAdapterServerDataSource )
		{	
			if(aBuf.Length() > KDSMaxRemoteNameLength)
			{
			iContentArray->At(iContentCounter)->SetStrValue( EXMLDSServerDataSource, KEmpty) ;
			}
			else
			{
			iContentArray->At(iContentCounter)->SetStrValue( EXMLDSServerDataSource, aBuf);
			}
			iState = EStateHandled;
		}
		if(iState == EAdapterImplementationId )
		{	
			if(aBuf.Length() > KNSmlMaxAdapterIdLength)
			{
			iContentArray->At(iContentCounter)->SetStrValue( EXMLDSAdapaterId, KEmpty) ;
			}
			else
			{
			iContentArray->At(iContentCounter)->SetStrValue( EXMLDSAdapaterId, aBuf);
			}
			iState = EStateHandled;
		}
		

	}

	return 1;
}
// -----------------------------------------------------------------------------
// CSendObject::GetFullPathNameL
// Get the full path name of the object to be saved
// @param aFileName, on entry, contains the file name of the object,
// on return, contains the full path name of the object to be saved
// -----------------------------------------------------------------------------
//
TBool CSendObject::GetFullPathNameL( const TDesC& aFileName )
    {
    PRINT1( _L("MM MTP => CSendObject::GetFullPathNameL aFileName = %S"), &aFileName );

    TBool result( EFalse );

    TParsePtrC parser( aFileName );
    if ( aFileName.Length() > 0 )
        {
        iFullPath.Zero();
        iFullPath.Append( *iParentSuid );

        // TODO: need to be done in derived class
        // Only add extension for alb to pass winlogo test cases
        TInt length = iFullPath.Length() + aFileName.Length();

        TBool isAlbWithoutExt =
            ( ( iObjectFormat == EMTPFormatCodeAbstractAudioAlbum ) && ( !parser.ExtPresent() ) );
        if ( isAlbWithoutExt )
            length += KTxtExtensionALB().Length();

        if ( length < KMaxFileName )
            {
            iFullPath.Append( aFileName );
            if ( isAlbWithoutExt )
                iFullPath.Append( KTxtExtensionALB );
            PRINT1( _L( "MM MTP <> CSendObject::GetFullPathNameL iFullPath = %S" ), &iFullPath );
            result = iFramework.Fs().IsValidName( iFullPath );
            }
        }

    if ( result && ( iObjectFormat != MmMtpDpUtility::FormatFromFilename( iFullPath ) ) )
        {
        if ( ( iObjectFormat == EMTPFormatCode3GPContainer ) && ( parser.Ext().CompareF( KTxtExtensionODF ) == 0))
            {
            PRINT( _L( "MM MTP <> might happen if function is called before physical file arrives" ) );
            // might happen if function is called before physical file arrives
            // do nothing
            }
        else if ( iObjectFormat == EMTPFormatCodeASF )
            {
            // happens on some buggy PC implementation, default formatcode to WMA or WMV if extension matches
            PRINT( _L( "MM MTP <> happens on some buggy PC implementation, default formatcode to WMA or WMV if extension matches" ) );
            if ( parser.Ext().CompareF( KTxtExtensionWMA ) == 0 )
                iObjectFormat = EMTPFormatCodeWMA;
            else if ( parser.Ext().CompareF( KTxtExtensionWMV ) == 0 )
                iObjectFormat = EMTPFormatCodeWMV;
            else
                result = EFalse;
            }
        else
            {
            PRINT2( _L( "MM MTP <> %S does not match 0x%x" ), &iFullPath, iObjectFormat );
            result = EFalse;
            }
        }

    PRINT1( _L( "MM MTP <= CSendObject::GetFullPathNameL result = %d" ), result );

    return result;
    }
void CAMPreInstallApp::ListPreInstalledAppL(const TDesC& installDocPath)
    {

    RDEBUG("Clist_PreInstallAppUi: ListPreInstalledApp: <<<<");
    CDir* dir= NULL;
    TInt err = iFs.GetDir(installDocPath, KEntryAttNormal, ESortByName, dir);
   // _LIT(KInstallpath,"C:\\private\\10202dce\\");
    //TInt err = iFs.GetDir(KInstallpath, KEntryAttNormal, ESortByName, dir);
    RDEBUG_2("Clist_PreInstallAppUi: ListPreInstalledApp: err in getting dir list : %d",err);
    
    if (err==KErrNone)
        {
        CleanupStack::PushL(dir);
        RDEBUG_2("Clist_PreInstallAppUi: ListPreInstalledApp: no of dir's : %d",dir->Count());
        for (TInt i(0); i < dir->Count(); i++)
            {

	    RDEBUG_2("Clist_PreInstallAppUi: ListPreInstalledApp: <<<< dir entry %d", i);
            TEntry entry;
            entry = (*dir)[i];
            HBufC* pathAndName = HBufC::NewLC(installDocPath.Length()
                    + entry.iName.Length() );
            TPtr ptrPathAndName = pathAndName->Des();
            ptrPathAndName.Append(installDocPath);
            ptrPathAndName.Append(entry.iName);

            HBufC* mimeType = HBufC::NewLC(KMaxDataTypeLength);
            //Recognize     
            if (!RecognizeL(*pathAndName, mimeType))
                {
                CleanupStack::PopAndDestroy(mimeType);
                CleanupStack::PopAndDestroy(pathAndName);
                continue;
                }

#ifdef RD_MULTIPLE_DRIVE
            if (TParsePtrC(installDocPath).Path().CompareF(KPreInstallPath)
                    == 0)
#else
            if (installDocPath.CompareF(iPreInstallPath) == 0)
#endif
                {

		RDEBUG("Clist_PreInstallAppUi: ListPreInstalledApp: <<<< Entered installDocPath.CompareF(iPreInstallPath)");
                Swi::RSisRegistrySession regSession;
                CleanupClosePushL(regSession);
                User::LeaveIfError(regSession.Connect() );

                RArray<TUid> uids;
                CleanupClosePushL(uids);

                regSession.InstalledUidsL(uids);

                RFile temp;
                User::LeaveIfError(temp.Open(iFs, *pathAndName,
                        EFileShareReadersOnly | EFileRead) );
                CleanupClosePushL(temp);

                TUid appUid;
                TInt uidLen = sizeof(TInt32);
                TInt seekLen = sizeof(TInt32) + sizeof(TInt32);

                User::LeaveIfError(temp.Seek(ESeekStart, seekLen));

                TPckg<TInt32> uid1(appUid.iUid);
                User::LeaveIfError(temp.Read(uid1, uidLen));
                if (uid1.Length() != uidLen)
                    {
                    User::Leave(KErrUnderflow);
                    }

                //checking whether this is installed or not
                TBool installed = regSession.IsInstalledL(appUid);
                Swi::RSisRegistryEntry registryEntry;
                TInt regEntryError = registryEntry.Open(regSession, appUid);
		RDEBUG_2("Clist_PreInstallAppUi: ListPreInstalledApp: RegEntryError : %d",regEntryError);

		//User::LeaveIfError(regEntryError);
		if (regEntryError == KErrNone)
		    {
                CleanupClosePushL(registryEntry);
                TBool isPreInstalled = registryEntry.PreInstalledL();
               // TBool isPreInstalled = ETrue;

                RDEBUG_4("Clist_PreInstallAppUi: ListPreInstalledApp: UID is : '0x%X', installed:, preinstalled %d  %d",appUid,installed,isPreInstalled);

                for (TInt i(0); isPreInstalled && i < uids.Count(); i++)
                    {
                    if (appUid == uids[i])
                        {

			RDEBUG("Clist_PreInstallAppUi: appUid == uids[i]");
                        Swi::CSisRegistryPackage* sisRegistry = NULL;
                        TRAPD( err, sisRegistry = regSession.SidToPackageL( uids[i] ) ) ;
                        //User::LeaveIfError(err);
			if(err == KErrNone)
			{

			RDEBUG("Clist_PreInstallAppUi: err == KErrNone");
                        TPreInstalledAppParams *params =
                                new (ELeave) TPreInstalledAppParams;
                        params->iPreInstalledAppame.Copy(sisRegistry->Name());
                        params->iPreInstalledAppVendorName.Copy(
                                sisRegistry->Vendor());
                        params->iPreInstalledAppUid = sisRegistry->Uid();
                        params->iMimeType.Copy(*mimeType);
                        //Get version
                        TVersion version = registryEntry.VersionL();
                        TBuf8<KVersionLength> pkgDes;
                        pkgDes.AppendNum(version.iMajor);
                        pkgDes.Append(KLiteralPeriod);
                        pkgDes.AppendNum(version.iMinor);
                        params->iVersion.Copy(pkgDes);

                        iPreInstalledAppParams.AppendL(params);

                        RDEBUG_2("Clist_PreInstallAppUi: ListPreInstalledApp: Installed App UID is : '0x%X'",appUid);
                        RDEBUG_2("Clist_PreInstallAppUi: ListPreInstalledApp: Installed App Name is: %S",&(sisRegistry->Name()));
                        RDEBUG_2("Clist_PreInstallAppUi: ListPreInstalledApp: Installed App Vendor is: %S",&(sisRegistry->Vendor()));
                        RDEBUG_2("Clist_PreInstallAppUi: ListPreInstalledApp: Installed App UID is : '0x%X'",sisRegistry->Uid());
                        delete sisRegistry;
			}
                        continue;
                        }
                    }

                CleanupStack::PopAndDestroy(&registryEntry);
		    }
                CleanupStack::PopAndDestroy(&temp);
                CleanupStack::PopAndDestroy(&uids);
                CleanupStack::PopAndDestroy(&regSession);
                CleanupStack::PopAndDestroy(mimeType);
                CleanupStack::PopAndDestroy(pathAndName);
                }
            }
         CleanupStack::PopAndDestroy(dir);
        }
    }
Exemple #29
0
/**
 * Extracts the real phone number from a contacts phone number field.
 * This method strips away any DTMF strings or extended services. An empty
 * descriptor is returned in aRawNumber if the field doesn't have a valid phone
 * number.
 *
 * @param aTextualNumber Descriptor containing a contacts model phone number field
 * @param aRawNumber Descriptor to write the raw number to (loaned by caller)
 */
void CContactDefaultPhoneNumberParser::ExtractRawNumber(const TDesC& aTextualNumber, TDes& aRawNumber)
{
    aRawNumber.Zero();

    TInt length = aTextualNumber.Length();
    if (length==0)
    {
        return;
    }


    TPtrC numberPtr( aTextualNumber );
    TUint firstChar = numberPtr[0];

    //gobble spaces
    while (TChar(firstChar).IsSpace())
    {
        --length;
        if (length==0)
        {
            return;
        }

        numberPtr.Set(numberPtr.Right(length));
        firstChar = numberPtr[0];
    }

    // Get left hand side
    if ( firstChar == KSymbolAsterisk || firstChar == KSymbolHash )
    {
        //Check if there is plus on first five chars:
        TInt newStartPlace = numberPtr.Locate( KSymbolPlus );
        if ( newStartPlace>=KPlusWithinChars || newStartPlace==KErrNotFound )
        {
            // There is always star or hash...
            newStartPlace = Max( numberPtr.LocateReverse(KSymbolAsterisk ) ,numberPtr.LocateReverse( KSymbolHash) );
        }

        length = length - newStartPlace -1;
        if ( length <= 0 )
        {
            return;
        }
        numberPtr.Set( numberPtr.Right( length ) );
        firstChar = numberPtr[0];
    }

    //test condition to satisfy the removal of '(' the next if
    //statement removes the '+' if needed
    if ( firstChar == KSymbolOpenBrace )
    {
        length--;
        numberPtr.Set( numberPtr.Right( length ) );
        // This may be the only character in the descriptor so only access if
        // 1 or more characters left.
        if (length > 0 )
        {
            firstChar = numberPtr[0];
        }
    }

    if ( firstChar == KSymbolPlus )
    {
        length--;
        numberPtr.Set( numberPtr.Right( length ) );
    }

    if (length==0)
    {
        return;
    }

    // Find right hand side
    TLex numberLexer( numberPtr );
    for ( ; ; )
    {
        TChar nextChar = numberLexer.Peek();
        if ( !nextChar )
        {
            break;
        }

        if ( nextChar.IsDigit() )
        {
            aRawNumber.Append( nextChar );
            numberLexer.Inc();
        }
        else if ( nextChar == KSymbolAsterisk || nextChar == KSymbolHash )
        {
            aRawNumber.Zero();
            return;
        }
        else
        {
            nextChar.LowerCase();
            if ( nextChar == KSymbolPause
                    || nextChar == KSymbolWait
                    || nextChar == KSymbolPlus)
            {
                break;
            }
            numberLexer.Inc();
        }
    }
}
// ---------------------------------------------------------
// CNSmlDsProvisioningAdapter::StoreAttributesL
// ---------------------------------------------------------
void CNSmlDsProvisioningAdapter::StoreAttributesL( const TDesC& aType )
    {
    _DBG_FILE("CNSmlDsProvisioningAdapter::StoreAttributesL(): begin");
    
    TInt iDataProvElementCount = iProfiles[iProfiles.Count()-1]->iDataProvElement.Count()-1;
	// Leave if aType cannot be assigned
    if( ( aType.Length() > 0 ) &&
        ( iProfiles[iProfiles.Count()-1]->iDataProvElement[iDataProvElementCount]->iRemoteDBUri ) )
        {
        TBool dataProvIdFoundInZ = FALSE;
        TSmlDataProviderId firstDataProvIdFound = 0;
        TSmlDataProviderId uidFound = 0;

        TBool doSearch = ETrue;
        if ( aType.FindF( KXVcardMimeType ) != KErrNotFound )
            {
            if ( IsOperatorProfile( *iProfiles[iProfiles.Count()-1] ) )
                {
                const CNSmlDsProfileElement& profile = *iProfiles[iProfiles.Count()-1];
                StoreOperatorUrlL( *profile.iHostAddress );
                
                // Do not make a search through adapter implementations
                doSearch = EFalse;
                uidFound = OperatorAdapterUid();
                if ( !uidFound )
                    {
                    // If OperatorAdapterUid returns 0, do a search
                    doSearch = ETrue;
                    }
                }
            }
		// look through every implementation adapter until one found
		// which supports MIME type in question
		
		// The first one located in ROM is chosen. If none found in ROM then
		// the first adapter found is chosen.

		HBufC8 *type = HBufC8::NewLC(aType.Size());
		TPtr8 typePtr = type->Des();
		CnvUtfConverter::ConvertFromUnicodeToUtf8( typePtr, aType);

		// get list of dataproviderIds
		RImplInfoPtrArray implArray;
		CleanupStack::PushL( PtrArrCleanupItemRArr( CImplementationInformation, &implArray ) );
		TUid ifUid = { KNSmlDSInterfaceUid };
		REComSession::ListImplementationsL( ifUid, implArray );
		
        if ( doSearch )
            {
            TInt countProviders = implArray.Count();
            for( TInt i = 0; i < countProviders; i++ )
                {
                CImplementationInformation* implInfo = implArray[i];

                RSyncMLDataProvider dataProvider;
                dataProvider.OpenL( iSession, implInfo->ImplementationUid().iUid );
                CleanupClosePushL( dataProvider );

                TInt mimeTypeCount = dataProvider.MimeTypeCount();
                for( TInt j = 0; j < mimeTypeCount; j++ )
                    {
                    HBufC* mimeType = dataProvider.MimeType( j ).AllocLC();
                    TPtrC8 convMimeType = ConvertTo8LC( *mimeType );
                    if( typePtr.Find( convMimeType ) == 0)
                        {
                        // MIME type in question was found
                        uidFound = implInfo->ImplementationUid().iUid;

                        if( firstDataProvIdFound == 0 )
                            {
                            // save the first in case of none found from ROM
                            firstDataProvIdFound = uidFound;
                            }
					
                        // check whether the provider is located in ROM (drive Z)
                        if( implInfo->Drive() == EDriveZ )
                            {
                            dataProvIdFoundInZ = TRUE;
                            }
                        }
				
                    CleanupStack::PopAndDestroy(2); // mimetype, ConvertTo8LC

                    if( uidFound )
                        {
                        break;
                        }
                    }
				
                CleanupStack::PopAndDestroy(); // dataProvider
			
                if ( dataProvIdFoundInZ )
                    {
                    break;
                    }
                else
                    {
                    uidFound = firstDataProvIdFound;
                    }
                }
            }
        
		REComSession::FinalClose();
		CleanupStack::PopAndDestroy( 2 ); // type, implArray

		if( uidFound )
			{
			iProfiles[iProfiles.Count()-1]->iDataProvElement[iDataProvElementCount]->iUid = uidFound;
			}		
        }
	
	_DBG_FILE("CNSmlDsProvisioningAdapter::StoreAttributesL(): end");
	}