This code can also be found in
examples\AppProts\InetProtUtil\
// ExampleInetProtUtil.h
//
// Copyright (c) Symbian Software Ltd 2005. All rights reserved.
//
/**
ExampleInetProtUtil is sample code for understanding the applicability of InetProtUtil.
It is intended as an example and introduction to the INETPROTUTIL API's.
Users should have a brief understanding of URIs and the different concepts
associated with them, like URLs and URI components.
*/
// Local include
//
#include "Uri8.h"
#include "DelimitedParser8.h"
#include "inetprottextutils.h"
#include "EscapeUtils.h"
#include "e32cons.h"
////////////////////////////////////////////////////////
// CExampleInetProtUtil //
////////////////////////////////////////////////////////
class CExampleInetProtUtil : public CBase
{
public :
CExampleInetProtUtil();
virtual ~CExampleInetProtUtil();
void ConstructL();
static void NewL();
//Create an URI
void CreateUri();
//Modify URI components
void ModifyUriComponents();
//Resolve
void ResolveUri();
//Parse the URI
void ParseUri();
//Validate URI components
void ValidateUriComponents();
//Extract URI components
void ExtractUriComponents();
//Retrieve Filename from a given Uri
void RetrieveFileName();
//Add and Trim delimiters
void ModifyDelimiter();
//Text Utilities
void WhiteSpaceRemover();
//Escape encode and decode
void EscapeEncodeDecode();
private:
CConsoleBase* iConsole;
};
////////////////////////////////////////////////////////
// CExampleDelimiterModifier //
////////////////////////////////////////////////////////
class CExampleDelimiterModifier : public TDelimitedParserBase8 //, public CDelimitedDataBase8
{
public: // Methods
inline TBool CheckFrontDelimiter() const;
inline TBool CheckBackDelimiter() const;
CExampleDelimiterModifier();
inline void Parse(const TDesC8& aData);
inline void SetDelimiter(TChar );
};
void CExampleDelimiterModifier::SetDelimiter(TChar aChar)
{
TDelimitedParserBase8::SetDelimiter(aChar);
}
void CExampleDelimiterModifier::Parse(const TDesC8& aData)
{
TDelimitedParserBase8::Parse(aData);
}
CExampleDelimiterModifier::CExampleDelimiterModifier()
{
}
TBool CExampleDelimiterModifier::CheckFrontDelimiter() const
{
TBool frontDelimiter = FrontDelimiter();
return frontDelimiter;
}
TBool CExampleDelimiterModifier::CheckBackDelimiter() const
{
TBool backDelimiter = BackDelimiter();
return backDelimiter;
}
/ DelimitedPath8.h
//
// Copyright (c) 2001 Symbian Ltd. All rights reserved.
//
#ifndef __DELIMITEDPATH8_H__
#define __DELIMITEDPATH8_H__
/**
@file DelimitedPath8.h
Comments : This file contains the API definition for the classes
TDelimitedPathParser8 and CDelimitedPath16.
*/
// System includes
//
#include <e32base.h>
// Local includes
//
#include "delimitedparser8.h"
/**
Dependencies : TDelimitedParserBase8
Comments : Derived class from TDelimitedParserBase providing a class for parsing
paths delimited by a '/' as defined in RFC2396.
@publishedAll
@released
@since 6.0
*/
class TDelimitedPathParser8 : public TDelimitedParserBase8
{
public: // Methods
IMPORT_C TDelimitedPathParser8();
IMPORT_C void Parse(const TDesC8& aPath);
IMPORT_C void ParseReverse(const TDesC8& aPath);
};
/**
Dependencies : CDelimitedStringBase8
Comments : Provides functionality to create a delimited path where components of the
path delimited by '/' as defined in RFC2396.
@publishedAll
@released
@since 6.0
*/
class CDelimitedPath8 : public CDelimitedDataBase8
{
public: // Methods
/**
@fn NewL(const TDesC8& aPath)
Intended Usage : Static factory constructor. Uses two phase construction and leaves nothing
on the CleanupStack.
@exception KErrNoMemory.
@since 6.0
@param aPath A descriptor with the initial path.
@return A pointer to created object.
@post Nothing left on the CleanupStack.
@cat Construction and Destruction
*/
IMPORT_C static CDelimitedPath8* NewL(const TDesC8& aPath);
/**
@fn NewLC(const TDesC8& aPath)
Intended Usage : Static factory constructor. Uses two phase construction and leaves a
pointer to created object on the CleanupStack.
@exception KErrNoMemory.
@since 6.0
@param aPath A descriptor with the initial path.
@return A pointer to created object.
@post Pointer to created object left of CleanupStack.
@cat Construction and Destruction
*/
IMPORT_C static CDelimitedPath8* NewLC(const TDesC8& aPath);
/**
@fn ~CDelimitedPath8()
Intended Usage : Destructor.
@since 6.0
@cat Construction and Destruction
*/
IMPORT_C ~CDelimitedPath8();
/**
@fn InsertAndEscapeCurrentL(const TDesC8& aSegment)
Intended Usage : Escape encodes the segment then inserts the escaped version in a
position before the current parsed segment. The new segment should only contain a
single path segment, as any path delimiters in the segment will be converted to an
escape triple. The parser is left in a state where its current segment is the same
one as before the insertion.
@exception KErrNoMemory.
@since 6.0
@param aSegment A descriptor with the unescaped path segment.
@pre The path must have been initially parsed.
@post The path will have been extended to include the new segment. The
current segment will remain as the one before the insertion.
*/
IMPORT_C void InsertAndEscapeCurrentL(const TDesC8& aSegment);
/**
@fn PushAndEscapeFrontL(const TDesC8& aSegment)
Intended Usage : Escape encodes the segment then inserts the escaped version at
the front of the path. The new segment should only contain a single path segment,
as any path delimiters in the segment will be converted to an escape triple. The
parser is left in a state where its current segment is the same one as before
the insertion.
@exception KErrNoMemory.
@warning A re-parse is required to ensure that the parser is valid.
@since 6.0
@param aSegment A descriptor with the unescaped path segment.
@pre The delimiter must have been set.
@post The path will have been extended to include the new segment.
*/
IMPORT_C void PushAndEscapeFrontL(const TDesC8& aSegment);
/**
@fn PushAndEscapeBackL(const TDesC8& aSegment)
Intended Usage : Escape encodes the segment then inserts the escaped version at
the back of the path. The new segment should only contain a single path segment,
as any path delimiters in the segment will be converted to an escape triple. The
parser is left in a state where its current segment is the same one as before
the insertion.
@exception KErrNoMemory.
@warning A re-parse is required to ensure that the parser is valid.
@since 6.0
@param aSegment A descriptor with the unescaped path segment.
@pre The delimiter must have been set.
@post The path will have been extended to include the new segment.
*/
IMPORT_C void PushAndEscapeBackL(const TDesC8& aSegment);
private: // Methods
/**
@fn CDelimitedPath8()
Intended Usage : Constructor. First phase of two-phase construction method. Does
non-allocating construction.
@since 6.0
@cat Construction and Destruction
*/
CDelimitedPath8();
/**
@fn ConstructL(const TDesC8& aPath)
Intended Usage : Second phase of two-phase construction method. Does any allocations required
to fully construct the object.
@exception KErrNoMemory.
@since 6.0
@param aPath A descriptor with the initial path.
@pre First phase of construction is complete.
@post The object is fully constructed.
@cat Construction and Destruction
*/
void ConstructL(const TDesC8& aPath);
};
#endif // __DELIMITEDPATH8_H__
// EscapeUtils.h
//
// Copyright (c) 200-20051 Symbian Ltd. All rights reserved.
//
/**
@file EscapeUtils.h
Comments : This file contains the API definition for escape enoding functionality
and UNICODE/UTF8 conversion. Escape encoding is performed as specified
by RFC2396.
*/
#ifndef __ESCAPEUTILS_H__
#define __ESCAPEUTILS_H__
// System includes
//
#include <e32base.h>
// Local includes
//
#include "uriutilscommon.h"
/**
Comments : Provides an API to allow data to be escape encoded and decoded.
Also provide an API for converting a UNICODE data (16-bit descriptor) into
UTF8 data (8-bit descriptor) and vice-verse.
@publishedAll
@released
@since 6.0
*/
class EscapeUtils
{
public: // Enums
/**
@enum TEscapeMode
Enum defining escaping modes. Each mode has a different set of reserved characters.
These are based on various uri components, as decribed in RFC2396.
*/
enum TEscapeMode
{
/** Default mode, which has no reserved characters */
EEscapeNormal = 0,
/** Mode specifying reserved characters in a uri query - ;/?:@&=+$,[] */
EEscapeQuery,
/** Mode specifying reserved characters in a uri path - /;=?[] */
EEscapePath,
/** Mode specifying reserved characters in a uri authority - /;:@?[] */
EEscapeAuth,
/** Mode specifying reserved characters in a URL ;/?:@&=+$[]!\'()~ */
EEscapeUrlEncoded
};
public: // Methods
IMPORT_C static HBufC8* EscapeEncodeL(const TDesC8& aData, TEscapeMode aMode);
IMPORT_C static HBufC16* EscapeEncodeL(const TDesC16& aData, TEscapeMode aMode);
IMPORT_C static HBufC8* EscapeEncodeL(const TDesC8& aData, const TDesC8& aReservedChars);
IMPORT_C static HBufC16* EscapeEncodeL(const TDesC16& aData, const TDesC16& aReservedChars);
IMPORT_C static HBufC8* EscapeDecodeL(const TDesC8& aData);
IMPORT_C static HBufC16* EscapeDecodeL(const TDesC16& aData);
IMPORT_C static HBufC8* ConvertFromUnicodeToUtf8L(const TDesC& aData);
IMPORT_C static HBufC* ConvertToUnicodeFromUtf8L(const TDesC8& aData);
IMPORT_C static TBool IsExcludedChar(TChar aChar);
IMPORT_C static TBool IsEscapeTriple(const TDesC8& aData, TInt& aHexValue);
IMPORT_C static TBool IsEscapeTriple(const TDesC16& aData, TInt& aHexValue);
static HBufC8* ReEscapeEncodeL(const TDesC8& aData);
};
#endif // __ESCAPEUTILS_H__
#include <e32test.h>
const TInt KMaxUserEntrySize = 128;
/** CHttpExampleUtils is a class that provides some user input utilities and holds a RTest used throughout
*/
class CHttpExampleUtils : public CBase
{
public:
static void InitCommsL();
static CHttpExampleUtils* NewL(const TDesC& aTestName);
~CHttpExampleUtils();
void GetAnEntry(const TDesC& ourPrompt, TDes& currentstring);
TInt GetSelection(const TDesC& ourPrompt, const TDesC& validChoices);
void PressAnyKey();
void LogIt(TRefByValue<const TDesC> aFmt, ...);
RTest& Test();
private:
CHttpExampleUtils(const TDesC& aTestName);
private:
RTest iTest;
};
// InetProtTextUtils.h
//
// Copyright (c) 2001 Symbian Ltd. All rights reserved.
#ifndef __INETPROTTEXTUTILS_H__
#define __INETPROTTEXTUTILS_H__
#include <e32base.h>
/**
@publishedAll
@released
*/
class InetProtTextUtils
{
public: // Enums
/** @enum TRemoveMode
Enum defining whitespace removal modes.
*/
enum TRemoveMode
{
/** Specifies removal any contiguous whitespace characters at the
beginning of some data.
*/
ERemoveLeft = 0,
/** Specifies removal any contiguous whitespace characters at the end of
some data.
*/
ERemoveRight,
/** Specifies removal any contiguous whitespace characters at the
beginning and end of some data.
*/
ERemoveBoth
};
public: // Methods
IMPORT_C static TInt RemoveWhiteSpace(TPtrC8& aData, TRemoveMode aMode);
IMPORT_C static TInt RemoveWhiteSpace(TPtrC16& aData, TRemoveMode aMode);
IMPORT_C static void ConvertIntToDescriptorL(TInt aInt, HBufC8*& aBuffer);
IMPORT_C static void ConvertIntToDescriptorL(TInt aInt, HBufC16*& aBuffer);
IMPORT_C static void ConvertHexToDescriptorL(TInt aHex, HBufC8*& aBuffer);
IMPORT_C static void ConvertHexToDescriptorL(TInt aHex, HBufC16*& aBuffer);
IMPORT_C static TInt ConvertDescriptorToInt(const TDesC8& aData, TInt& aInt);
IMPORT_C static TInt ConvertDescriptorToInt(const TDesC16& aData, TInt& aInt);
IMPORT_C static TInt ConvertDescriptorToHex(const TDesC8& aData, TInt& aHex);
IMPORT_C static TInt ConvertDescriptorToHex(const TDesC16& aData, TInt& aHex);
IMPORT_C static TInt ExtractNextTokenFromList(TPtrC8& aBuffer, TPtrC8& aToken, TChar aSeparator);
IMPORT_C static TInt ExtractNextTokenFromList(TPtrC16& aBuffer, TPtrC16& aToken, TChar aSeparator);
IMPORT_C static TInt ExtractNextTokenFromList(TPtrC8& aBuffer, TPtrC8& aToken, const TDesC8& aSeparators);
IMPORT_C static TInt ExtractNextTokenFromList(TPtrC16& aBuffer, TPtrC16& aToken, const TDesC16& aSeparators);
IMPORT_C static TInt ExtractQuotedStringL(TPtrC8& aBuffer, TPtrC8& aQuotedString);
IMPORT_C static TInt ExtractQuotedStringL(TPtrC16& aBuffer, TPtrC16& aQuotedString);
};
#endif // __INETPROTTEXTUTILS_H__
// Uri8.h
//
// Copyright (c) Symbian Software Ltd 2001-2005. All rights reserved.
//
/**
@file Uri8.h
Comments : This file contains the API definition for the classes TUriC8 and
CUri8. These classes provide non-modifying (TUriC8) and modifying
(CUri8) functionality for the components of a Uri as described in
RFC2396.
*/
#ifndef __URI8_H__
#define __URI8_H__
// System includes
//
#include <e32base.h>
#include <f32fsys.h>
// Local includes
//
#include "uricommon.h"
/**
Dependencies : TUriComponent.
Comments : Provides non-modifying functionality on the components of a uri object as
defined in RFC2396. There are 5 components; scheme, authority, path, query and fragment.
The object holds descriptor pointers to the parsed uri components and a descriptor pointer
to the uri. It is non-owning. It uses 8-bit descriptors.
The functionality provided by this API allows the uri components to be extracted from the
parsed uri, checked for their presence in the uri and be compared with those in another
TUriC8 object.
@publishedAll
@released
@since 6.0
*/
class TUriC8
{
public: // Methods
IMPORT_C HBufC* GetFileNameL() const;
IMPORT_C HBufC* GetFileNameL(TUriFileName aType) const;
IMPORT_C const TDesC8& Extract(TUriComponent aComponent) const;
IMPORT_C void UriWithoutFragment(TPtrC8& aUriNoFrag) const;
IMPORT_C TBool IsPresent(TUriComponent aComponent) const;
IMPORT_C TBool IsSchemeValid() const;
IMPORT_C TInt Compare(const TUriC8& aUri, TUriComponent aComponent) const;
IMPORT_C const TDesC8& UriDes() const;
IMPORT_C TInt Validate() const;
IMPORT_C TInt Equivalent(const TUriC8& aUri) const;
IMPORT_C HBufC* DisplayFormL(TUriComponent aComponent = EUriComplete) const;
protected: // Methods
IMPORT_C TUriC8();
void Reset();
protected: // Attributes
/** The array of descriptor pointers to the uri components.
*/
TPtrC8 iComponent[EUriMaxComponents];
/** The descriptor pointer to the uri.
*/
TPtrC8 iUriDes;
/**
A friend class.
@see CUri8
@since 6.0
@cat Friend class
*/
friend class CUri8;
/**
A friend class used for testing.
@see TUriC8StateAccessor
@since 6.0
@cat Friend class
@internal
*/
friend class TUriC8StateAccessor;
};
/**
Dependencies : TUriC8
Comments : Provides functionality to parse a descriptor into the components of a uri as
defined in RFC2396. There are 5 components; scheme, authority, path, query and fragment.
It uses 8-bit descriptors.
Format of a uri is; scheme://authority path?query\#fragment
@warning The descriptor that is parsed by an object of this class will be referenced
by that object. If the original descriptor is no longer in scope there will be undefined
behaviour.
@publishedAll
@released
@since 6.0
*/
class TUriParser8 : public TUriC8
{
public: // Methods
IMPORT_C TUriParser8();
IMPORT_C TInt Parse(const TDesC8& aUri);
};
class CUri8 : public CBase
/**
Dependencies : CBase, TUriC8.
Comments : Provides modifying functionality on the components of a uri object, as
defined in RFC2396. There are 5 components; scheme. authority, path, query and fragment.
The object holds parsed uri information. It is owning. It uses 8-bit descriptors.
The functionality provided by this API allows the uri components to be set or removed
from this parsed uri. Also, it provides a reference to TUriC8 object so that the non-modifying
functionality can be used.
@publishedAll
@released
@since 6.0
*/
{
public: // Methods
IMPORT_C static CUri8* CreateFileUriL(const TDesC& aFullFileName, TUint aFlags = 0);
IMPORT_C static CUri8* CreatePrivateFileUriL(const TDesC& aRelativeFileName, TDriveNumber aDrive, TInt aFlags = 0);
IMPORT_C static CUri8* NewL(const TUriC8& aUri);
IMPORT_C static CUri8* NewLC(const TUriC8& aUri);
IMPORT_C static CUri8* NewL();
IMPORT_C static CUri8* NewLC();
IMPORT_C static CUri8* ResolveL(const TUriC8& aBaseUri, const TUriC8& aRefUri);
IMPORT_C ~CUri8();
IMPORT_C const TUriC8& Uri() const;
IMPORT_C void SetComponentL(const TDesC8& aData, TUriComponent aComponent);
IMPORT_C void RemoveComponentL(TUriComponent aComponent);
private: // Methods
CUri8(const TUriC8& aNewUri);
void ConstructL();
void FormUriL();
void InitializeFileUriComponentsL(const TDesC& aFileName, TDriveNumber aDrive, TUint aFlags);
private: // Attributes
/** The descriptor buffer that contains the uri.
*/
HBufC8* iUriBuf;
/** The parsed uri object.
*/
TUriC8 iUri;
/**
A friend class used for testing.
@see TUri8StateAccessor
@since 6.0
@cat Friend class
@internal
*/
friend class TUri8StateAccessor;
};
#endif // __URI8_H__
// ExampleInetProtUtil.CPP
//
// Copyright (c) Symbian Software Ltd 2005. All rights reserved.
//
/**
ExampleInetProtUtil is a sample code for understanding the applicability of InetProtUtil.
It is intended as an example and introduction to the INETPROTUTIL API's.
Users should have a brief understanding of URIs and the different concepts
associated with it, like, URLs and URI components.
*/
// System includes
#include <e32base.h>
#include <e32cons.h>
// Local include
#include "ExampleInetProtUtil.h"
_LIT ( KTest, "InetProtUtil Example" );
_LIT (KInetProtUtilExamplePanic, "InetProtUtil example");
_LIT ( KDisplay, "\n%S" );
_LIT ( KDisplayAll, "\n%d %S %d %S " );
_LIT ( KLeaveALine, "\n" );
CExampleInetProtUtil::CExampleInetProtUtil()
{
}
CExampleInetProtUtil::~CExampleInetProtUtil()
{
delete iConsole;
}
void CExampleInetProtUtil::NewL()
{
CExampleInetProtUtil *self = new (ELeave) CExampleInetProtUtil;
CleanupStack::PushL(self);
self->ConstructL();
CleanupStack::PopAndDestroy(self);
}
void CExampleInetProtUtil::ConstructL()
{
iConsole = Console::NewL(KTest,TSize(KConsFullScreen,KConsFullScreen));
iConsole->Printf ( KInetProtUtilExamplePanic );
_LIT(KTextStart, "\nPress any key to step through the example");
iConsole->Printf ( KTextStart );
iConsole->Getch ();
//Create an URI
CreateUri();
//Modify URI components
ModifyUriComponents();
//Resolve
ResolveUri();
//Parse the URI
ParseUri();
//Validate URI components
ValidateUriComponents();
//Extract URI components
ExtractUriComponents();
//Retrieve Filename from a given Uri
RetrieveFileName();
//Add and Trim delimiters
ModifyDelimiter();
//Text Utilities
WhiteSpaceRemover();
//Escape encode and decode
EscapeEncodeDecode();
}
//Create an URI
void CExampleInetProtUtil::CreateUri()
{
//Set the physical path of the file
_LIT(KText1, "\n\n\nThe Physical location of the file is....");
iConsole->Printf ( KText1 );
_LIT(KFullUriName, "K:\\ws\\direct\\direct.mmp");
//display it
TBuf<40> desFullUriName(KFullUriName);
iConsole->Printf ( KLeaveALine );
iConsole->Printf ( KFullUriName );
//create the Uri for the path
CUri8* uri8 = CUri8::CreateFileUriL(desFullUriName);
const TDesC8& desUriDisplay = uri8->Uri().UriDes();
TBuf16<100> desCreateUri;
desCreateUri.Copy (desUriDisplay);
//display it
_LIT(KText2, "And its Uri is....");
iConsole->Printf ( KLeaveALine );
iConsole->Printf ( KText2 );
iConsole->Printf ( KLeaveALine );
iConsole->Printf ( desCreateUri );
delete uri8;
iConsole->Getch ();
}
//Modify URI components
void CExampleInetProtUtil::ModifyUriComponents()
{
TUriParser8 parser1;
CUri8* aUri = CUri8::NewL(parser1);
_LIT(KText3, "\n\n\nAdding Uri components one by one....");
iConsole->Printf ( KText3 );
// Adding components to the Uri
//Setting and displaying SCHEME
_LIT8(KScheme, "http");
_LIT(KScheme1, "\nSCHEME : http");
iConsole->Printf ( KScheme1 );
aUri->SetComponentL(KScheme, EUriScheme);
//Setting and displaying HOST
_LIT8(KHost, "www.symbian.com");
_LIT(KHost1, "\nHOST : www.symbian.com");
iConsole->Printf ( KHost1 );
aUri->SetComponentL(KHost, EUriHost);
//Setting and displaying PORT
_LIT8(KPort, "80");
_LIT(KPort1, "\nPORT : 80");
iConsole->Printf ( KPort1 );
aUri->SetComponentL(KPort, EUriPort);
//Setting and displaying PATH
_LIT8(KPath, "/developer/techlib/turic8class.html");
_LIT(KPath1, "\nPATH : /developer/techlib/turic8class.html");
iConsole->Printf ( KPath1 );
aUri->SetComponentL(KPath, EUriPath);
//Display the constucted Uri
_LIT(KText4, "\nThe fully constructed Uri....");
iConsole->Printf ( KText4 );
const TDesC8& desUriDisplay = aUri->Uri().UriDes();
TBuf16<100> desFullUri;
desFullUri.Copy (desUriDisplay);
iConsole->Printf( KLeaveALine );
iConsole->Printf ( desFullUri );
// Removal of component from the Uri
iConsole->Getch ();
_LIT(KText5, "\n\nUri with the Port number removed....\n");
iConsole->Printf ( KText5 );
aUri->RemoveComponentL(EUriPort);
//Display the modified Uri
const TDesC8& desRemovedComponentDisplay =aUri->Uri().UriDes();
TBuf16<100> desRemovedComponent;
desRemovedComponent.Copy (desRemovedComponentDisplay);
iConsole->Printf ( desRemovedComponent );
delete aUri;
iConsole->Getch ();
}
//Parse the URI
void CExampleInetProtUtil::ParseUri()
{
//Create a Uri
_LIT(KText6, "\n\n\nParsing the Uri for....\n");
iConsole->Printf ( KText6 );
_LIT(KFullUriName,"K:\\ws\\direct\\direct.mmp");
TBuf<40> desFullUriName(KFullUriName);
iConsole->Printf ( desFullUriName );
//Convert from Unicode format to UTF-8 format
HBufC8* convert8 = EscapeUtils::ConvertFromUnicodeToUtf8L(desFullUriName);
TUriParser8 parser;
//Parse the Uri
TInt errResult = parser.Parse(*convert8);
if (errResult==KErrNone)
{
_LIT(KTextParsing, "\nThis Uri has been parsed successfully");
iConsole->Printf ( KTextParsing );
}
delete convert8;
iConsole->Getch();
}
//Validate URI components
void CExampleInetProtUtil::ValidateUriComponents()
{
TUriParser8 parser1;
CUri8* aUri = CUri8::NewL(parser1);
_LIT(KTextf, "\n\n\nValidating the Uri....\n");
iConsole->Printf ( KTextf );
// Adding components to the Uri
//Adding Scheme
_LIT8(KScheme, "http");
aUri->SetComponentL(KScheme,EUriScheme);
//Adding Host
_LIT8(KHost, "waterlang.org");
aUri->SetComponentL(KHost,EUriHost);
//Adding Port
_LIT8(KPort, "90");
aUri->SetComponentL(KPort,EUriPort);
//Adding Path
_LIT8(KPath, "/turic8class.html");
aUri->SetComponentL(KPath,EUriPath);
//Adding Query
_LIT8(KQuery, "bar=2&x=3");
aUri->SetComponentL(KQuery,EUriQuery);
//Adding Fragment
_LIT8(KFragment, "fragment");
aUri->SetComponentL(KFragment,EUriFragment);
//Display the constructed Uri
const TDesC8& desUriDisplays =aUri->Uri().UriDes();
TBuf16<100> desValidate;
desValidate.Copy (desUriDisplays);
iConsole->Printf ( desValidate );
// Validate() is not supported for HTTP, but only SIP and SIPS.
//The Parse() function itself validates the components and returns the
//appropriate result.
TInt res = parser1.Parse(desUriDisplays);
if (res==KErrNone)
{
_LIT(KText8, "\nThis Uri is VALID");
iConsole->Printf ( KText8 );
}
delete aUri;
iConsole->Getch();
}
//Extract URI components
void CExampleInetProtUtil::ExtractUriComponents()
{
_LIT(KTextExtract, "\n\n\nExtracting from....\n");
iConsole->Printf ( KTextExtract );
//Create a Uri
_LIT(KUriName, "K:\\ws\\direct\\direct.mmp");
TBuf<40> desUriName(KUriName);
CUri8* uriName = CUri8::CreateFileUriL(desUriName);
//Display the Uri
const TDesC8& uriDisplay = uriName->Uri().UriDes();
TBuf16<100> desExtract;
desExtract.Copy (uriDisplay);
iConsole->Printf ( desExtract );
//Parse the Uri
TUriParser8* uriComponent = new(ELeave) TUriParser8();
uriComponent->Parse(uriDisplay);
//Extract the Scheme component from this Uri
const TDesC8& host = uriComponent->Extract(EUriScheme);
TBuf16<100> desEx;
desEx.Copy (host);
//Display the Component extracted
_LIT(KTextEx, "\nThe extracted Scheme component is....\n");
iConsole->Printf ( KTextEx );
iConsole->Printf ( desEx );
//delete fileName;
delete uriComponent;
delete uriName;
iConsole->Getch();
}
//Extract URI components
void CExampleInetProtUtil::RetrieveFileName()
{
_LIT(KTextRet, "\n\n\nRetrieving filename from....\n");
iConsole->Printf ( KTextRet );
//Create a Uri
_LIT(KUriRetName, "K:\\ws\\direct\\direct.mmp");
TBuf<40> desUriRetName(KUriRetName);
CUri8* uriRetName = CUri8::CreateFileUriL(desUriRetName);
//Display the Uri
const TDesC8& uriDisp = uriRetName->Uri().UriDes();
TBuf16<100> desRetrieve;
desRetrieve.Copy (uriDisp);
iConsole->Printf ( desRetrieve );
//Parse the Uri
TUriParser8* uriComp = new(ELeave) TUriParser8();
uriComp->Parse(uriDisp);
//Get or Extract the Filename from the Uri
_LIT(KTextGetFilename, "\nGetting the filename....\n");
iConsole->Printf ( KTextGetFilename );
HBufC* fileName = uriComp->GetFileNameL();
TPtr uriFileNameDisplay = fileName->Des();
TBuf16<100> desFileName;
desFileName.Copy (uriFileNameDisplay);
iConsole->Printf ( desFileName );
delete fileName;
delete uriComp;
delete uriRetName;
iConsole->Getch();
}
//Modify the Uri w.r.t Delimiters
void CExampleInetProtUtil::ModifyDelimiter()
{
// First set the delimiter before performing any operation
_LIT(KTextDelimit1, "\n\n\nThe Delimiter is...\n");
iConsole->Printf ( KTextDelimit1 );
CExampleDelimiterModifier* delimiterModifyingObj = new(ELeave) CExampleDelimiterModifier;
delimiterModifyingObj->SetDelimiter(TChar(';'));
//Display the delimiter
_LIT(KTextDelimit2, ";\n");
iConsole->Printf ( KTextDelimit2 );
_LIT(KTextDelimit, "to be checked in...\n");
iConsole->Printf ( KTextDelimit );
_LIT(KFullUriName,"K:\\ws\\direct\\direct.mmp;");
TBuf<40> desFullUriName(KFullUriName);
iConsole->Printf ( desFullUriName );
//Then parse the Uri
HBufC8* convert8 = EscapeUtils::ConvertFromUnicodeToUtf8L(desFullUriName);
delimiterModifyingObj->Parse(*convert8);
//Check if the delimiter is present in the front
TBool checkFrontDelimiter = delimiterModifyingObj->CheckFrontDelimiter();
//Check if the delimiter is present at the back
TBool checkBackDelimiter = delimiterModifyingObj->CheckBackDelimiter();
//Display the result
if (!checkFrontDelimiter)
{
_LIT(KTextDelimit3, "\nNo delimiter in the front");
iConsole->Printf ( KTextDelimit3 );
}
else
{
_LIT(KTextDelimit4, "\nDelimiter is present in the front");
iConsole->Printf ( KTextDelimit4 );
}
if (!checkBackDelimiter)
{
_LIT(KTextDelimit5, "\nNo delimiter at the back");
iConsole->Printf ( KTextDelimit5 );
}
else
{
_LIT(KTextDelimit6, "\nDelimiter is present at the back");
iConsole->Printf ( KTextDelimit6 );
}
delete convert8;
delete delimiterModifyingObj;
iConsole->Getch();
}
//Check for white spaces in the Uri
void CExampleInetProtUtil::WhiteSpaceRemover()
{
//Take an eg file and insert white spaces in the front and rear
_LIT(KTextWhiteSpace, "\n\n\nThe Uri containing white spaces....\n");
iConsole->Printf ( KTextWhiteSpace );
_LIT(KFullUriPath," K:\\ws\\direct\\direct.mmp ");
TBuf<40> desFullUriPath(KFullUriPath);
iConsole->Printf ( desFullUriPath );
//Gets the Whitespaces on the right and left of the Uri
TPtrC desFullUriName(KFullUriPath);
//Check for white spaces in the front or on the left of the Uri
TInt consumedWhiteSpacesLeft = InetProtTextUtils::RemoveWhiteSpace(desFullUriName,InetProtTextUtils::ERemoveLeft);
//Check for white spaces at the back or on the right of the Uri
TInt consumedWhiteSpacesRight = InetProtTextUtils::RemoveWhiteSpace(desFullUriName,InetProtTextUtils::ERemoveRight);
_LIT(KTextAnd, " and ");
_LIT(KTextInfo, " white spaces have been removed from the Uri");
//Display the number of white spaces removed from Uri
iConsole->Printf ( KDisplayAll,consumedWhiteSpacesLeft,&KTextAnd,consumedWhiteSpacesRight, &KTextInfo);
iConsole->Getch();
}
//Encode and Decode the Uri
void CExampleInetProtUtil::EscapeEncodeDecode()
{
//Take an eg file to encode it and then decode it....
_LIT(KFullUriName,"K:\\ws\\direct\\direct.mmp");
TBuf<40> desFullUriName(KFullUriName);
//UTF-8 defines a mapping from sequences of octets to sequences of chars
HBufC8* convert = EscapeUtils::ConvertFromUnicodeToUtf8L(desFullUriName);
//Encode the eg Uri and display it
_LIT(KTextEncode, "\n\n\nThe Encoded Uri is....\n");
iConsole->Printf ( KTextEncode );
HBufC16* encode = EscapeUtils::EscapeEncodeL(desFullUriName,EscapeUtils::EEscapeNormal);
TPtr uriEncoded = encode->Des();
TBuf16<100> desEncodedUri;
desEncodedUri.Copy (uriEncoded);
iConsole->Printf ( _L("%S"), &desEncodedUri );
//Decode the eg Uri and display it
_LIT(KTextDecode, "\nThe Decoded Uri is....\n");
iConsole->Printf ( KTextDecode );
HBufC16* decode = EscapeUtils::EscapeDecodeL(desFullUriName);
TPtr uriDecoded = decode->Des();
TBuf16<100> desDecodedUri;
desDecodedUri.Copy (uriDecoded);
iConsole->Printf ( _L("%S"), &desDecodedUri );
delete decode;
delete encode;
delete convert;
iConsole->Getch();
iConsole->Printf ( KLeaveALine );
}
//Resolve the Uri w.r.t a Base and a refernce Uri
void CExampleInetProtUtil::ResolveUri()
{
_LIT(KTextResolve1, "\n\n\nThe Base and reference Uris are\n");
iConsole->Printf ( KTextResolve1 );
TUriParser8 parserResolve1;
CUri8* aUriBase = CUri8::NewL(parserResolve1);
//Adding Scheme
_LIT8(KScheme, "http");
aUriBase->SetComponentL(KScheme,EUriScheme);
//Adding Host
_LIT8(KHost, "symbian.com");
aUriBase->SetComponentL(KHost,EUriHost);
//Adding Port
_LIT8(KPort, "90");
aUriBase->SetComponentL(KPort,EUriPort);
//Adding Path
_LIT8(KPath, "/resolve.aspx");
aUriBase->SetComponentL(KPath,EUriPath);
const TDesC8& desBaseUri =aUriBase->Uri().UriDes();
TBuf16<100> desBase;
desBase.Copy (desBaseUri);
iConsole->Printf ( desBase );
iConsole->Printf( KLeaveALine );
CUri8* aUriRef = CUri8::NewL(parserResolve1);
//Adding Path
_LIT8(KPath1, "/uris/base/reference/resolve.aspx");
aUriRef->SetComponentL(KPath1,EUriPath);
//Adding Query
_LIT8(KQuery1, "bar=2&x=3");
aUriRef->SetComponentL(KQuery1,EUriQuery);
const TDesC8& desRefUri =aUriRef->Uri().UriDes();
TBuf16<100> desRef;
desRef.Copy (desRefUri);
iConsole->Printf ( desRef );
_LIT(KTextResolve, "\nThe Resolved Uri is....\n");
iConsole->Printf ( KTextResolve );
//Resolve the 2 Uri's to get a resultant uri
CUri8* Uri8 = CUri8::ResolveL(aUriBase->Uri(),aUriRef->Uri());
// Display the resultant Uri
const TDesC8& desDisplayReslovedUri = Uri8->Uri().UriDes();
TBuf16<100> desResolve;
desResolve.Copy (desDisplayReslovedUri);
iConsole->Printf ( desResolve );
delete Uri8;
delete aUriRef;
delete aUriBase;
iConsole->Getch ();
}
////////////////////////////////////////////
// Main //
////////////////////////////////////////////
GLDEF_C TInt E32Main()
{
__UHEAP_MARK;
CTrapCleanup* tc = CTrapCleanup::New();
TRAPD(err, CExampleInetProtUtil::NewL());
if (err != KErrNone)
User::Panic(_L("Failed to complete"),err);
delete tc;
__UHEAP_MARKEND;
return KErrNone;
}
// HTTPEXAMPLEUTILS.CPP
//
// Copyright (c) 2001 Symbian Ltd. All rights reserved.
//
// for StartC32()
#include <c32comm.h>
#include "httpexampleutils.h"
// PDD names for the physical device drivers that are loaded in wins or arm
#if defined (__WINS__)
#define PDD_NAME _L("ECDRV")
#else
#define PDD_NAME _L("EUART1")
#define PDD2_NAME _L("EUART2")
#define PDD3_NAME _L("EUART3")
#define PDD4_NAME _L("EUART4")
#endif
#define LDD_NAME _L("ECOMM")
void CHttpExampleUtils::InitCommsL()
{
TInt ret = User::LoadPhysicalDevice(PDD_NAME);
User::LeaveIfError(ret == KErrAlreadyExists?KErrNone:ret);
#ifndef __WINS__
ret = User::LoadPhysicalDevice(PDD2_NAME);
ret = User::LoadPhysicalDevice(PDD3_NAME);
ret = User::LoadPhysicalDevice(PDD4_NAME);
#endif
ret = User::LoadLogicalDevice(LDD_NAME);
User::LeaveIfError(ret == KErrAlreadyExists?KErrNone:ret);
ret = StartC32();
User::LeaveIfError(ret == KErrAlreadyExists?KErrNone:ret);
}
CHttpExampleUtils* CHttpExampleUtils::NewL(const TDesC& aTestName)
{
CHttpExampleUtils* me = new (ELeave) CHttpExampleUtils(aTestName);
return me;
}
CHttpExampleUtils::CHttpExampleUtils(const TDesC& aTestName) : iTest(aTestName)
{
iTest.Start(KNullDesC);
}
CHttpExampleUtils::~CHttpExampleUtils()
{
iTest.End();
iTest.Close();
}
RTest& CHttpExampleUtils::Test()
{
return iTest;
}
void CHttpExampleUtils::PressAnyKey()
{
iTest.Printf(TRefByValue<const TDesC>_L("\nPress a key"));
iTest.Getch();
}
TInt CHttpExampleUtils::GetSelection(const TDesC& aPrompt, const TDesC& aValidChoices)
//
// Present the user with a list of options, and get their selection
{
TKeyCode key = EKeyNull;
iTest.Console()->SetPos (0, iTest.Console()->WhereY ());
iTest.Console()->Printf(_L("%S "), &aPrompt);
iTest.Console()->Printf(_L("[%S] :"), &aValidChoices);
TInt retVal = KErrNotFound;
while (retVal == KErrNotFound)
{
key = iTest.Getch();
// Check that key is in the list of valid choices
retVal = aValidChoices.Locate((TChar)key);
}
iTest.Console()->Printf(_L("%c\n\n"), key);
return retVal;
}
void CHttpExampleUtils::LogIt(TRefByValue<const TDesC> aFmt, ...)
{
VA_LIST list;
VA_START(list,aFmt);
TBuf<KMaxFileName + 4> buf; // 4 for the log prompt
buf.Zero();
buf.Append(_L("> "));
buf.AppendFormatList(aFmt,list);
VA_END(list);
iTest.Printf(_L("%S\n"), &buf);
}
void CHttpExampleUtils::GetAnEntry(const TDesC& ourPrompt, TDes& currentstring)
{
TBuf16<KMaxUserEntrySize> ourLine;
TBuf<KMaxUserEntrySize> tempstring; //tempstring is a unicode descriptor
//create a temporary buffer where the
//unicode strings are stored in order to
//be displayed
ourLine.Zero ();
tempstring.Copy(currentstring); //Copy current string to Unicode buffer
TKeyCode key = EKeyNull; //current string buffer is 8 bits wide.
//Unicode string bufffer (tempstring) is 16 bits wide.
FOREVER
{
if (ourLine.Length () == 0)
{
iTest.Console()->SetPos (0, iTest.Console()->WhereY ());
iTest.Console()->Printf (_L ("%S"), &ourPrompt);
if (tempstring.Length () != 0) //get tempstring's number of items
iTest.Console()->Printf (_L (" = %S"), &tempstring); //if not zero print them to iTest.Console()
iTest.Console()->Printf (_L (" : "));
iTest.Console()->ClearToEndOfLine ();
}
key = iTest.Getch();
if (key == EKeyBackspace)
{
if (ourLine.Length() !=0)
{
ourLine.SetLength(ourLine.Length()-1);
iTest.Console()->Printf (_L ("%c"), key);
iTest.Console()->SetPos(iTest.Console()->WhereX(),iTest.Console()->WhereY());
iTest.Console()->ClearToEndOfLine();
} // end if (ourLine.Length() !=0)
} // end if (key == KeyBackSpace)
if (key == EKeyDelete)
{
ourLine.Zero();
iTest.Console()->SetPos (0, iTest.Console()->WhereY ());
iTest.Console()->ClearToEndOfLine ();
tempstring.Copy(ourLine);
break;
}
if (key == EKeyEnter)
break;
if (key < ' ') // ascii code thats not a printable character
{
continue;
}
ourLine.Append (key);
iTest.Console()->Printf (_L ("%c"), key);
iTest.Console()->SetPos(iTest.Console()->WhereX(),iTest.Console()->WhereY());
iTest.Console()->ClearToEndOfLine();
if (ourLine.Length () == ourLine.MaxLength ())
break;
} // end of for statement
if ((key == EKeyEnter) && (ourLine.Length () == 0))
tempstring.Copy (currentstring); //copy contents of 8 bit "ourLine" descriptor
iTest.Console()->SetPos (0, iTest.Console()->WhereY ());
iTest.Console()->ClearToEndOfLine ();
if ((key == EKeyEnter) && (ourLine.Length() !=0))
tempstring.Copy(ourLine);
if (tempstring.Length () != 0) //if temstring length is not zero
{
iTest.Console()->Printf (_L (" Entered = %S\n"), &tempstring); //print the contents to iTest.Console()
LogIt(_L ("%S = %S\n"), &ourPrompt, &tempstring);
}
iTest.Console()->Printf (_L ("\n"));
currentstring.Copy(tempstring); //copy 16 bit tempstring descriptor back
}
// InetProtUtil.mmp
//
// Copyright (c) Symbian Software Ltd 2005. All rights reserved.
//
TARGET ExampleInetProtUtil.exe
TARGETTYPE exe
CAPABILITY ALL -TCB
//TrustedUI ProtServ
SOURCEPATH .
SOURCE ExampleInetProtUtil.cpp Httpexampleutils.cpp
USERINCLUDE .
SYSTEMINCLUDE \epoc32\include
LIBRARY euser.lib efsrv.lib inetprotutil.lib
VENDORID 0x70000001
This example code demonstrates the usage of utilities provided by the InetProtUtil API. The users should have a prior knowledge of concepts associated with it, such as URLs and URI components.
The central class is CExampleInetProtUtil
, which
demonstrates the following functionality:
void CExampleInetProtUtil::CreateUri();
Creates a URI with respect to the physical path of a given file.
For example, the physical path of the file:
K:/ws/direct/direct.mmp
gives the following URI file:
///k/ws/direct/direct.mmp
The screen output from this example is:
void CExampleInetProtUtil::ModifyUriComponents();
Modifies URI components, which involves:
Adding URI components, where it constructs the URI component by component. For example, you can add the following components:
scheme: http
host: waterlang.org
path: main_page.html
port: 8080
to get the complete URI:
http://waterlang.org:8080/main_page.html
The screen output from this example is:
Removing the specific URI component(s) from a constructed URI. For example, the above URI with the port number removed:
http://waterlang.org/main_page.html
The screen output from this example is:
void CExampleInetProtUtil::ResolveUri();
Resolves the URI, which involves creation of an absolute
CUri
object from a given reference URI.
The screen output from this example is:
void CExampleInetProtUtil::ParseUri();
Parses the URI into its components (as given in RFC2396). The five URI components are:
scheme
authority
path
query
fragment.
The screen output from this example is:
void CExampleInetProtUtil::ValidateUriComponents();
Validates a given URI. This function is usually used for URIs with SIP as the scheme.
The screen output from this example is:
void CExampleInetProtUtil::ExtractUriComponents();
Extracts URI components from the given URI.
The screen output from this example is:
void CExampleInetProtUtil::RetrieveFileName();
Extracts the actual physical location of the file from its URI.
The screen output from this example is:
void CExampleInetProtUtil::ModifyDelimiter();
Adds the delimiters to and removes the delimiters from a URI. Before doing this ensure that:
the delimiter is set using SetDelimiter()
the URI has already been parsed.
The screen output from this example is:
void CExampleInetProtUtil::WhiteSpaceRemover();
Removes the whitespace from the given URI and returns the number of white spaces that were removed.
The screen output from this example is:
void CExampleInetProtUtil::EscapeEncodeDecode();
Escape encodes the characters in a given URI as escape triplets and decodes it to the original one.
The screen output from this example is:
CUri8
: Create, modify and resolve URI
TUriParser8
: Parse, validate and extract URI
components
EscapeUtils
: Escape encode and decode
TDelimitedParserBase8
: Provides the parser
InetProtTextUtils
: Text utilities
CExampleDelimiterModifier
: inherits from
TDelimitedParserBase8