TVerdict CMacIncrementalWithReplicateStep::doTestStepL() { //Assume faliure, unless all is successful SetTestStepResult(EFail); INFO_PRINTF1(_L("*** Mac - Incremental with Replicate ***")); INFO_PRINTF2(_L("HEAP CELLS: %d"), User::CountAllocCells()); TVariantPtrC algorithmUid; TPtrC sourcePath; TPtrC expectedMac; TPtrC encryptKey; TVariantPtrC keyType; //Extract the Test Case ID parameter from the specified INI file if(!GetStringFromConfig(ConfigSection(),KConfigAlgorithmUid,algorithmUid) || !GetStringFromConfig(ConfigSection(),KConfigSourcePath,sourcePath) || !GetStringFromConfig(ConfigSection(),KConfigExMacValue,expectedMac) || !GetStringFromConfig(ConfigSection(),KConfigEncryptKey,encryptKey) || !GetStringFromConfig(ConfigSection(),KConfigEncryptKeyType,keyType)) { ERR_PRINTF1(_L("** Error: Failed to Load Configuration Parameters **")); return EFail; } //Create a pointer for the Mac Implementation Object CMac* macImpl= NULL; //Convert encryption key to an 8 Bit Descriptor HBufC8* keyStr = HBufC8::NewLC(encryptKey.Length()); TPtr8 keyStrPtr = keyStr->Des(); keyStrPtr.Copy(encryptKey); //Create an new CryptoParams object to encapsulate the key type and secret key string CCryptoParams* keyParams = CCryptoParams::NewL(); CleanupStack::PushL(keyParams); keyParams->AddL(*keyStr,keyType); //Create Key Object TKeyProperty keyProperty; CKey* key=CKey::NewL(keyProperty,*keyParams); CleanupStack::PushL(key); //Retrieve a Mac Factory Object TRAPD(err,CMacFactory::CreateMacL(macImpl, algorithmUid, *key, NULL)); if (err != KErrNone) { CleanupStack::PopAndDestroy(3, keyStr); // keyStr, keyParams, key delete macImpl; ERR_PRINTF2(_L("*** FAIL: Failed to Create Mac Object - %d ***"), err); return EFail; } //Push the Mac Implementation Object onto the Cleanup Stack CleanupStack::PushL(macImpl); RFs fsSession; User::LeaveIfError(fsSession.Connect()); CleanupClosePushL(fsSession); RFile sourceFile; CleanupClosePushL(sourceFile); //Open the specified source file User::LeaveIfError(sourceFile.Open(fsSession,sourcePath, EFileRead)); TInt sourceLength = 0; TInt readPosition = 0; TInt readIncrement = 0; TBool macComplete = EFalse; TBool macReplicated = EFalse; TPtrC8 macStr; CMac* macReplicateImpl = NULL; User::LeaveIfError(sourceFile.Size(sourceLength)); //Divide the total size of the source file up into individual equal sized blocks to read //over several increments readIncrement = sourceLength/KDataReadBlocks; if (readIncrement == 0) { ERR_PRINTF2(_L("*** Error: Source File must be larger than %d bytes ***"), KDataReadBlocks); User::LeaveIfError(KErrNotSupported); } do { //Create a heap based descriptor to store the data HBufC8* sourceData = HBufC8::NewL(readIncrement); CleanupStack::PushL(sourceData); TPtr8 sourcePtr = sourceData->Des(); //Read in a block of data from the source file from the current position err = sourceFile.Read(readPosition,sourcePtr,readIncrement); //Update the read position by adding the number of bytes read readPosition += readIncrement; if(readPosition == readIncrement) { //Read in the first block from the data file into the Mac implementation object if(macReplicated == EFalse) { macImpl->MacL(*sourceData); INFO_PRINTF2(_L("Intial Mac - Bytes Read: %d"), readPosition); } else { macReplicateImpl->MacL(*sourceData); INFO_PRINTF2(_L("Intial Mac (Replicate) - Bytes Read: %d"), readPosition); } CleanupStack::PopAndDestroy(sourceData); } else if(readPosition >= sourceLength) { //Reading in the final block, constructs the complete hash value and returns it within a TPtrC8 macStr.Set(macReplicateImpl->FinalL(*sourceData)); CleanupStack::PopAndDestroy(sourceData); //Sets the Complete Flag to ETrue in order to drop out of the loop macComplete = ETrue; TInt totalRead = (readPosition - readIncrement) + (*sourceData).Length(); INFO_PRINTF2(_L("Final Mac - Bytes Read: %d"),totalRead); } //If the read position is half the source length and the implementation //object hasn't already been replicated else if((readPosition >= sourceLength/2) && (macReplicated == EFalse)) { INFO_PRINTF1(_L("Replicating Mac Object...")); macImpl->UpdateL(*sourceData); CleanupStack::PopAndDestroy(sourceData); //Create a Copy of the existing Mac Object with NO internal message state macReplicateImpl = macImpl->ReplicateL(); macReplicated = ETrue; //Sets the read position back to 0 inorder to restart the file read from the beginning readPosition =0; CleanupStack::PushL(macReplicateImpl); INFO_PRINTF2(_L("*** Mac REPLICATE - Bytes Read: %d ***"), readPosition); } else { //Update the message data within the Mac object with the new block if(macReplicated == EFalse) { macImpl->UpdateL(*sourceData); INFO_PRINTF2(_L("Mac Update - Bytes Read: %d"), readPosition); } else { macReplicateImpl->UpdateL(*sourceData); INFO_PRINTF2(_L("Mac Update (Replicate) - Bytes Read: %d"), readPosition); } CleanupStack::PopAndDestroy(sourceData); } }while(macComplete == EFalse); //Create a NULL TCharacteristics pointer const TCharacteristics* charsPtr(NULL); //Retrieve the characteristics for the mac implementation object TRAP_LOG(err, macImpl->GetCharacteristicsL(charsPtr)); //Static cast the characteristics to type TMacCharacteristics const TMacCharacteristics* macCharsPtr = static_cast<const TMacCharacteristics*>(charsPtr); //The mac output size is returned in Bits, divide by 8 to get the Byte size TInt macSize = macCharsPtr->iHashAlgorithmChar->iOutputSize/8; //Retrieve the final 8 bit Mac and convert to 16bit HBufC* macData = HBufC::NewLC(macSize); TPtr macPtr = macData->Des(); macPtr.Copy(macStr); //Take the 16 bit descriptor and convert the string to hexadecimal TVariantPtrC convertMac; convertMac.Set(macPtr); HBufC* macResult = convertMac.HexStringLC(); INFO_PRINTF2(_L("*** Mac: %S ***"), &*macResult); INFO_PRINTF2(_L("*** Expected Mac: %S ***"), &expectedMac); //If the returned mac value matches the expected mac, Pass the test if (*macResult == expectedMac) { INFO_PRINTF1(_L("*** Mac - Incremental with Replicate : PASS ***")); SetTestStepResult(EPass); } else { ERR_PRINTF2(_L("*** FAIL: Mac Mismatch ***"), err); } CleanupStack::PopAndDestroy(9, keyStr); // keyStr, keyParams, key, macImpl, &fsSession, &sourceFile, macReplicateImpl, macData, macResult INFO_PRINTF2(_L("HEAP CELLS: %d"), User::CountAllocCells()); return TestStepResult(); }
CSenElement* CPolicyNormalizer::ProcessAssertionTermL(CSenElement* aAssertion, CSenElement* aNormalAssertion) { TPtrC8 assertionName = aAssertion->LocalName(); TPtrC8 assertionNsUri = aAssertion->NamespaceURI(); TPtrC8 nsPrefix = aAssertion->NsPrefix(); TBuf8<255> qname(nsPrefix); qname.Append(':'); qname.Append(assertionName); CSenElement& newNormalForm = aNormalAssertion->AddElementL(assertionNsUri,assertionName, qname); if(IsOptionalL(aAssertion)) { if (CopySenElementWithoutOptionL(aAssertion, &newNormalForm)) { CSenElement* parent = aNormalAssertion->Parent(); AddAndElementL(parent); } } else { CopySenElementL(aAssertion, &newNormalForm); } RPointerArray<CSenElement>& children = aAssertion->ElementsL(); TInt childCount = children.Count(); if (childCount > 0) { CSenElement* pNextChild; TInt i =0; while (i < childCount) { pNextChild = children[i]; TPtrC8 localName = pNextChild->LocalName(); if(localName.Compare(KXorCompositeAssertion) == 0) { } else if (localName.Compare(KAndCompositeAssertion) == 0) { } else if (localName.Compare(KWsPolicy) == 0 ) { CSenElement* aNewElement = AddPolicyElementL(&newNormalForm); aNewElement = ProcessPolicyTermL(pNextChild,aNewElement); } else {//if asserion is not well defined and dont have apolicy object here //then it should add one and then add XOR and AND // CSenElement* aNewElement = AddPolicyElementL(&newNormalForm); // CSenElement* pChildXor = AddXorElementL(aNewElement); // CSenElement* pChildAnd = AddAndElementL(pChildXor); aNormalAssertion = ProcessAssertionTermL(pNextChild, &newNormalForm); } i++; } } return aNormalAssertion; }
CSenElement* CPolicyNormalizer::ProcessLogicL(CSenElement* aTerm) { //if sibling names are same as <ExactlyOne> RPointerArray<CSenElement> matchingSiblings; TInt matchingSiblingCount = 0; if(aTerm->ElementsL(matchingSiblings, WSPolicy::KXorCompositeAssertion) == KErrNone) matchingSiblingCount= matchingSiblings.Count(); if(matchingSiblingCount>1) { //XOR elements should have AND elements in them else normalization error //Find elements CSenElement* firstSibling = matchingSiblings[0]; TInt i = 1; while ( i < matchingSiblingCount) { CSenElement* nextSibling = matchingSiblings[i]; firstSibling = ProcessAndAndLogicL(firstSibling, nextSibling); i++; } TInt j = 0; while ( j < matchingSiblingCount) { CSenElement* removed = aTerm->RemoveElement(*matchingSiblings[j]); if(removed) delete removed; j++; } /**** aTerm->AddElementL(*firstSibling); */ } RPointerArray<CSenElement>& children = aTerm->ElementsL(); TInt childCount = children.Count(); TInt i=0; while (i < childCount) { CSenElement* pChild = children[i]; if(childCount == 1) ProcessLogicL(pChild); TPtrC8 childName = pChild->LocalName(); TPtrC8 parentName = aTerm->LocalName(); //if parent name and child name are same if(childName.Compare(parentName) == 0) { if(childName.Compare(WSPolicy::KWsPolicy) == 0) { } else if(childName.Compare(WSPolicy::KAndCompositeAssertion) == 0) { } else if(childName.Compare(WSPolicy::KXorCompositeAssertion) == 0) { ProcessXorCollapseLogicL(aTerm,pChild); continue; } } i++; } matchingSiblings.Close(); return aTerm; }
static void PerformanceTest3L() { test.Printf(_L("\n8 byte performance with existing parser comparison \n")); TTime startTime, stopTime; //legacy startTime.UniversalTime(); TPtrC value; for (TInt i=0;i<1000;i++) { CIniFile* ini=CIniFile::NewL(_L("z:\\resource\\legacy8.ini")); test(ini->FindVar(_L("test_section"),_L("key1"),value)); test(value.Compare(_L("value1"))==0); test(ini->FindVar(_L("test_section"),_L("key2"),value)); test(value.Compare(_L("value2"))==0); test(ini->FindVar(_L("test_section"),_L("key3"),value)); test(value.Compare(_L("value3"))==0); test(ini->FindVar(_L("test_section"),_L("key4"),value)); test(value.Compare(_L("value4"))==0); test(ini->FindVar(_L("test_section"),_L("key5"),value)); test(value.Compare(_L("value value value"))==0); test(ini->FindVar(_L("1"),_L("timestamps"),value)); test(value.Compare(_L("0"))==0); test(ini->FindVar(_L("1"),_L("setting"),value)); test(value.Compare(_L("value"))==0); delete ini; } stopTime.UniversalTime(); TTimeIntervalMicroSeconds timeTaken = stopTime.MicroSecondsFrom(startTime); test.Printf(_L("Time taken for 8 bit Legacy= %d microseconds\n"), timeTaken.Int64() ); //light weight startTime.UniversalTime(); for (TInt i=0;i<1000;i++) { TPtrC8 value; //it is not necessarily to reopen a new file server session but just //for fair performance comparison RFs myFs; User::LeaveIfError(myFs.Connect()) ; CIniFile8* ini=CIniFile8::NewL(myFs,_L("z:\\resource\\legacy8.ini")); test(ini->FindVar(_L8("test_section"),_L8("key1"),value)==KErrNone); test(value.Compare(_L8("value1"))==0); test(ini->FindVar(_L8("test_section"),_L8("key2"),value)==KErrNone); test(value.Compare(_L8("value2"))==0); test(ini->FindVar(_L8("test_section"),_L8("key3"),value)==KErrNone); test(value.Compare(_L8("value3"))==0); test(ini->FindVar(_L8("test_section"),_L8("key4"),value)==KErrNone); test(value.Compare(_L8("value4"))==0); test(ini->FindVar(_L8("test_section"),_L8("key5"),value)==KErrNone); test(value.Compare(_L8("value value value"))==0); test(ini->FindVar(_L8("1"),_L8("timestamps"),value)==KErrNone); test(value.Compare(_L8("0"))==0); test(ini->FindVar(_L8("1"),_L8("setting"),value)==KErrNone); test(value.Compare(_L8("value"))==0); delete ini; myFs.Close(); } stopTime.UniversalTime(); timeTaken = stopTime.MicroSecondsFrom(startTime); test.Printf(_L("Time taken for 8 bit Light= %d microseconds\n"), timeTaken.Int64() ); //heavy weight startTime.UniversalTime(); for (TInt i=0;i<1000;i++) { TPtrC8 value; //it is not necessarily to reopen a new file server session but just //for fair performance comparison RFs myFs; User::LeaveIfError(myFs.Connect()) ; CIniDocument8* ini=CIniDocument8::NewL(myFs,_L("z:\\resource\\legacy8.ini")); test(ini->GetKeyValue(_L8("test_section"),_L8("key1"),value)==KErrNone); test(value.Compare(_L8("value1"))==0); test(ini->GetKeyValue(_L8("test_section"),_L8("key2"),value)==KErrNone); test(value.Compare(_L8("value2"))==0); test(ini->GetKeyValue(_L8("test_section"),_L8("key3"),value)==KErrNone); test(value.Compare(_L8("value3"))==0); test(ini->GetKeyValue(_L8("test_section"),_L8("key4"),value)==KErrNone); test(value.Compare(_L8("value4"))==0); test(ini->GetKeyValue(_L8("test_section"),_L8("key5"),value)==KErrNone); test(value.Compare(_L8("value value value"))==0); test(ini->GetKeyValue(_L8("1"),_L8("timestamps"),value)==KErrNone); test(value.Compare(_L8("0"))==0); test(ini->GetKeyValue(_L8("1"),_L8("setting"),value)==KErrNone); test(value.Compare(_L8("value"))==0); delete ini; myFs.Close(); } stopTime.UniversalTime(); timeTaken = stopTime.MicroSecondsFrom(startTime); test.Printf(_L("Time taken for 8 bit Heavy= %d microseconds\n"), timeTaken.Int64() ); }
void CPjAudioOutputEngine::MaoscOpenComplete(TInt aError) { if (startAsw_.IsStarted()) { startAsw_.AsyncStop(); } lastError_ = aError; if (aError==KErrNone) { // set stream properties, 16bit 8KHz mono TMdaAudioDataSettings iSettings; iSettings.iChannels = get_channel_cap(parentStrm_->param.channel_count); iSettings.iSampleRate = get_clock_rate_cap(parentStrm_->param.clock_rate); iOutputStream_->SetAudioPropertiesL(iSettings.iSampleRate, iSettings.iChannels); /* Apply output volume setting if specified */ if (parentStrm_->param.flags & PJMEDIA_AUD_DEV_CAP_OUTPUT_VOLUME_SETTING) { stream_set_cap(&parentStrm_->base, PJMEDIA_AUD_DEV_CAP_OUTPUT_VOLUME_SETTING, &parentStrm_->param.output_vol); } else { // set volume to 1/2th of stream max volume iOutputStream_->SetVolume(iOutputStream_->MaxVolume()/2); } // set stream priority to normal and time sensitive iOutputStream_->SetPriority(EPriorityNormal, EMdaPriorityPreferenceTime); // Call callback to retrieve frame from upstream. pjmedia_frame f; pj_status_t status; f.type = PJMEDIA_FRAME_TYPE_AUDIO; f.buf = frameBuf_; f.size = frameBufSize_; f.timestamp.u32.lo = timestamp_; f.bit_info = 0; status = playCb_(this->userData_, &f); if (status != PJ_SUCCESS) { this->Stop(); return; } if (f.type != PJMEDIA_FRAME_TYPE_AUDIO) pj_bzero(frameBuf_, frameBufSize_); // Increment timestamp. timestamp_ += (frameBufSize_ / BYTES_PER_SAMPLE); // issue WriteL() to write the first audio data block, // subsequent calls to WriteL() will be issued in // MMdaAudioOutputStreamCallback::MaoscBufferCopied() // until whole data buffer is written. frame_.Set(frameBuf_, frameBufSize_); iOutputStream_->WriteL(frame_); // output stream opened succesfully, set status to Active state_ = STATE_ACTIVE; } else { snd_perror("Error in MaoscOpenComplete()", aError); } }
// ----------------------------------------------------------------------------- // CWPPushMessage::ParseContentType // ----------------------------------------------------------------------------- // void CWPPushMessage::ParseContentType( TLex8& aPointer ) { // Go through the whole content type header. while( !aPointer.Eos() ) { // Each parameter might be well-known (integer) or unknown (text) if( IsIntegerValue( aPointer ) ) { // For well-known parameters, the token is an integer value TUint paramToken( I64LOW( GetIntegerValue( aPointer ) ) ); // These are filled with results from parsing. TInt resultInteger( 0 ); TPtrC8 resultString; // Make sure paramToken fits into KParameterTypes table if( paramToken < sizeof(KParameterTypes)/sizeof(TParameterCodingType)) { // Get the coding and use it to determine how we should decode // the next parameter value. We actually ignore all results // except short integer (SEC) and text-value (MAC), but the // rest of the parameters have to be parsed anyway. TParameterCodingType coding( KParameterTypes[paramToken] ); switch( coding ) { case EQValue: GetQValue( aPointer ); break; case EWellKnownCharset: GetWellKnownCharset( aPointer ); break; case EVersionValue: GetVersionValue( aPointer ); break; case EIntegerValue: GetIntegerValue( aPointer ); break; case ETextString: GetTextString( aPointer ); break; case EFieldName: GetFieldName( aPointer ); break; case EShortInteger: resultInteger = GetShortInteger( aPointer ); break; case EConstrainedEncoding: GetConstrainedEncoding( aPointer ); break; case EDeltaSecondsValue: GetDeltaSecondsValue( aPointer ); break; case ENoValue: GetNoValue( aPointer ); break; case ETextValue: resultString.Set( GetTextValue( aPointer ) ); break; case EDateValue: GetDateValue( aPointer ); break; default: break; } // We have a result. We're actually only interested in // SEC and MAC parameters, so we save them here. switch( paramToken ) { case KWSPHeaderSEC: iSEC = resultInteger; break; case KWSPHeaderMAC: iMAC.Set( resultString ); break; default: break; } } } else { // Unknown parameter. Its name is in text, and the value // might be an integer or text. GetTokenText( aPointer ); if( IsIntegerValue( aPointer ) ) { GetIntegerValue( aPointer ); } else { GetTextValue( aPointer ); } } } }
// ----------------------------------------------------------------------------- // CHttpCacheDataSupplier::GetNextDataPart // Return the next chunk of response body from the Cache // ----------------------------------------------------------------------------- // TBool CHttpCacheDataSupplier::GetNextDataPart( TPtrC8 &aDataChunk ) { aDataChunk.Set( *m_body ); return ETrue; }
void CSenLayeredXmlProperties::WriteToL(RWriteStream& aWriteStream) { // Find out whether we should declare the namespace TPtrC8 nsPrefix = ipFragment->NsPrefix(); // Element name aWriteStream.WriteL(KSenLessThan); if ( nsPrefix.Length() > 0 ) { aWriteStream.WriteL(nsPrefix); aWriteStream.WriteL(KSenColon); } aWriteStream.WriteL(ipFragment->AsElement().LocalName()); RPointerArray<CSenBaseAttribute>& attrs = ipFragment->AsElement().AttributesL(); RPointerArray<CSenNamespace>& namespaces = ipFragment->AsElement().NamespacesL(); if ( ( attrs.Count() > 0 ) || ( namespaces.Count() > 0 ) ) { CSenNamespace* ns = NULL; TInt count = namespaces.Count(); for (TInt i=0; i < count; i++) { ns = (namespaces)[i]; if (ns) { aWriteStream.WriteL(KSenSpaceXmlns); if (ns->Prefix().Length() > 0) { aWriteStream.WriteL(KSenColon); aWriteStream.WriteL(ns->Prefix()); } aWriteStream.WriteL(KSenEqualsDblQuot); aWriteStream.WriteL(ns->URI()); aWriteStream.WriteL(KSenDblQuot); } } count = attrs.Count(); for (TInt j = 0; j < count; j++) { aWriteStream.WriteL(KSenSpace); aWriteStream.WriteL((attrs)[j]->Name()); aWriteStream.WriteL(KSenEqualsDblQuot); aWriteStream.WriteL((attrs)[j]->Value()); aWriteStream.WriteL(KSenDblQuot); } } // Elements and content RPointerArray<CSenElement> elements; ElementsL(elements); if ( (elements.Count() > 0) || ipFragment->AsElement().HasContent() ) { aWriteStream.WriteL(KSenGreaterThan); // Body TInt elementCount(elements.Count()); for (TInt k=0; k<elementCount; k++) { elements[k]->WriteAsXMLToL(aWriteStream); } aWriteStream.WriteL(ipFragment->AsElement().Content()); // Closing element aWriteStream.WriteL(KSenLessThanSlash); if (nsPrefix.Length() > 0) { aWriteStream.WriteL(nsPrefix); aWriteStream.WriteL(KSenColon); } aWriteStream.WriteL(ipFragment->AsElement().LocalName()); aWriteStream.WriteL(KSenGreaterThan); } else { aWriteStream.WriteL(KSenSlashGreaterThan); } elements.Close(); }
TInt CSenLayeredXmlProperties::PropertyL(const TDesC8& aName, TPtrC8& aValue, TPtrC8& aType) { if ( ipChildProperties ) { TInt retVal = ipChildProperties->PropertyL(aName, aValue); if ( retVal == KErrNotFound ) { CSenElement* pElement = ipFragment->AsElement().Element(aName); if ( pElement ) { /* CSenPropertiesElement* pPropertyElement = (CSenPropertiesElement*) pElement; aValue.Set(pPropertyElement->Value()); aType.Set(pPropertyElement->Type()); */ const TDesC8* pAttrValue = pElement->AttrValue(KSenOmittedAttributeName); if ( pAttrValue ) { if ( *pAttrValue == KSenOmittedTrueNoValue) { return KErrSenOmitted; } else if ( *pAttrValue == KSenPropertyTrue) { return KErrSenOmitted; } } aValue.Set(pElement->Content()); aType.Set(*pElement->AttrValue(KSenTypeAttributeName)); return KErrNone; } else { return KErrNotFound; } } return retVal; } else { CSenElement* pElement = ipFragment->AsElement().Element(aName); if ( pElement ) { /* CSenPropertiesElement* pPropertyElement = (CSenPropertiesElement*) pElement; aValue.Set(pPropertyElement->Value()); aType.Set(pPropertyElement->Type()); */ const TDesC8* pAttrValue = pElement->AttrValue(KSenOmittedAttributeName); if ( pAttrValue ) { if ( *pAttrValue == KSenOmittedTrueNoValue) { return KErrSenOmitted; } else if ( *pAttrValue == KSenPropertyTrue) { return KErrSenOmitted; } } aValue.Set(pElement->Content()); aType.Set(*pElement->AttrValue(KSenTypeAttributeName)); return KErrNone; } else { return KErrNotFound; } } }
TBool CExampleResolver::Match(const TDesC8& aImplementationType, const TDesC8& aMatchType, TBool aUseWildcards) const { TInt matchPos = KErrNotFound; _LIT8(dataSeparator, "||"); const TInt separatorLength = dataSeparator().Length(); // Look for the section separator marker '||' TInt separatorPos = aImplementationType.Find(dataSeparator); if(separatorPos == KErrNotFound) { // Match against the whole string if(aUseWildcards) matchPos = aImplementationType.Match(aMatchType); else matchPos = aImplementationType.Compare(aMatchType); } else { // Find the first section, up to the separator TPtrC8 dataSection = aImplementationType.Left(separatorPos); TPtrC8 remainingData = aImplementationType.Mid(separatorPos + separatorLength); // Match against each section in turn while(separatorPos != KErrNotFound) { // Search this section if(aUseWildcards) matchPos = dataSection.Match(aMatchType); else matchPos = dataSection.Compare(aMatchType); // If we found it then no need to continue, so return if(matchPos != KErrNotFound) return ETrue; // Move on to the next section separatorPos = remainingData.Find(dataSeparator); if(separatorPos != KErrNotFound) { dataSection.Set(remainingData.Left(separatorPos)); remainingData.Set(remainingData.Mid(separatorPos + separatorLength)); } else dataSection.Set(remainingData); } // Check the final part if(aUseWildcards) matchPos = dataSection.Match(aMatchType); else matchPos = dataSection.Compare(aMatchType); } return matchPos != KErrNotFound; }
void CSTTrackerConnection::MHFRunL(RHTTPTransaction aTransaction, const THTTPEvent& aEvent) { switch (aEvent.iStatus) { case THTTPEvent::EGotResponseHeaders: { // HTTP response headers have been received. Use // aTransaction.Response() to get the response. However, it's not // necessary to do anything with the response when this event occurs. LWRITELN(iLog, _L("[Trackerconnection] Got HTTP headers")); // Get HTTP status code from header (e.g. 200) RHTTPResponse resp = aTransaction.Response(); TInt status = resp.StatusCode(); if (status != 200) // ERROR, hiba esetén mi legyen? 404-et lekezelni! { LWRITE(iLog, _L("[Trackerconnection] Error, status = ")); TBuf<20> numBuf; numBuf.Num(status); LWRITELN(iLog, numBuf); Cancel(); if (iObserver) iObserver->TrackerConnectionFailedL(); break; } // Get status text (e.g. "OK") HLWRITE(iLog, _L("[Trackerconnection] Status text = ")); TBuf<32> statusText; statusText.Copy(resp.StatusText().DesC()); HLWRITELN(iLog, statusText); #ifdef LOG_TO_FILE RHTTPHeaders headers = aTransaction.Response().GetHeaderCollection(); THTTPHdrFieldIter i = headers.Fields(); for (i.First(); !(i.AtEnd()); ++i) { RStringF header = iSession.StringPool().StringF(i()); if ((header.DesC() == _L8("Content-Type"))) { HLWRITE(iLog, header.DesC()); HLWRITE(iLog, _L(": ")); THTTPHdrVal val; headers.GetField(header, 0, val); RStringF value = val.StrF(); HLWRITELN(iLog, value.DesC()); } else HLWRITELN(iLog, header.DesC()); } #endif } break; case THTTPEvent::EGotResponseBodyData: { // Part (or all) of response's body data received. Use // aTransaction.Response().Body()->GetNextDataPart() to get the actual // body data. // Get the body data supplier MHTTPDataSupplier* body = aTransaction.Response().Body(); TPtrC8 dataChunk; // GetNextDataPart() returns ETrue, if the received part is the last // one. TBool isLast = body->GetNextDataPart(dataChunk); //iDownloadedSize += dataChunk.Size(); HLWRITELN(iLog, _L8("[TrackerConnection] HTTP response body chunk received: ")); HLWRITELN(iLog, dataChunk); if (iReceiveBuffer) { HBufC8* temp = HBufC8::NewL( iReceiveBuffer->Length() + dataChunk.Length()); TPtr8 tempPtr(temp->Des()); tempPtr.Copy(*iReceiveBuffer); tempPtr.Append(dataChunk); delete iReceiveBuffer; iReceiveBuffer = temp; } else iReceiveBuffer = dataChunk.AllocL(); // Always remember to release the body data. body->ReleaseData(); // NOTE: isLast may not be ETrue even if last data part received. // (e.g. multipart response without content length field) // Use EResponseComplete to reliably determine when body is completely // received. if (isLast) { #ifdef LOG_TO_FILE _LIT(KBodyReceived,"Body received"); HLWRITELN(iLog, KBodyReceived); #endif //CSTBencode* bencodedResponse = CSTBencode::ParseL(*iReceiveBuffer); //iLog->WriteLineL(*iReceiveBuffer); // //if (bencodedResponse) //{ // CleanupStack::PushL(bencodedResponse); // iTorrent.ProcessTrackerResponseL(bencodedResponse); // CleanupStack::PopAndDestroy(); // bencodedResponse //} } } break; case THTTPEvent::EResponseComplete: { // Indicates that header & body of response is completely received. // No further action here needed. //_LIT(KTransactionComplete, "Transaction Complete"); //iLog->WriteLineL(KTransactionComplete); //iResult = ESucceeded; } break; case THTTPEvent::ESucceeded: { LWRITELN(iLog, _L("[Trackerconnection] HTTP transaction succeded")); CSTBencode* bencodedResponse = CSTBencode::ParseL(*iReceiveBuffer); //iLog->WriteLineL(*iReceiveBuffer); if (bencodedResponse && iObserver) { CleanupStack::PushL(bencodedResponse); iObserver->TrackerResponseReceivedL(*bencodedResponse); CleanupStack::PopAndDestroy(); // bencodedResponse } iRunning = EFalse; if (iObserver) iObserver->TrackerConnectionSucceededL(); } break; case THTTPEvent::EFailed: { LWRITELN(iLog, _L("[Trackerconnection] HTTP transaction failed")); iRunning = EFalse; if (iObserver) iObserver->TrackerConnectionFailedL(); } break; default: // There are more events in THTTPEvent, but they are not usually // needed. However, event status smaller than zero should be handled // correctly since it's error. { TBuf<64> text; if (aEvent.iStatus < 0) { LWRITE(iLog, _L("[Trackerconnection] HTTP transaction failed, ")); _LIT(KErrorStr, "Error: %d"); text.Format(KErrorStr, aEvent.iStatus); LWRITELN(iLog, text); // Just close the transaction on errors aTransaction.Close(); iRunning = EFalse; if (iObserver) iObserver->TrackerConnectionFailedL(); } else { // Other events are not errors (e.g. permanent and temporary // redirections) _LIT(KUnrecognisedEvent, "[Trackerconnection] Unrecognised event: %d"); text.Format(KUnrecognisedEvent, aEvent.iStatus); LWRITELN(iLog, text); } } break; } }
// MHTTPTransactionCallback interface functions void CXmlHandler::MHFRunL(RHTTPTransaction aTransaction, const THTTPEvent& aEvent) { switch (aEvent.iStatus) { case THTTPEvent::EGotResponseHeaders: { iObserver.GIEStateChanged(eStateFoundServer); iModel.iState = eStateFoundServer; /* Not interested in the received header */ } break; case THTTPEvent::EGotResponseBodyData: { #ifdef _INCREMENTAL_H #else /* The non incremental version of the parser will just build up a string of the data until the EReponseComplete code is received. Then the string is sent to parser in one go */ RHTTPResponse response = aTransaction.Response(); MHTTPDataSupplier* bodyPtr = response.Body(); /* Received data is appended to the existing block (if there is a block), otherwise a new block is created */ TPtrC8 bodypart; bodyPtr->GetNextDataPart(bodypart); if (iQueryResponse == NULL) { iQueryResponse = HBufC8::NewL( bodypart.Length() ); } else { const TInt newSize = iQueryResponse->Length() + bodypart.Length(); iQueryResponse = iQueryResponse->ReAllocL( newSize ); } TPtr8 tmp = iQueryResponse->Des(); tmp.Append(bodypart); bodyPtr->ReleaseData(); #endif } break; case THTTPEvent::EResponseComplete: { iObserver.GIEStateChanged(eStateReceivedResponse); iModel.iState = eStateReceivedResponse; #ifdef _INCREMENTAL_H #else #ifdef LOG_RESONSE LogMessage(iFs, KResponseFilename, *iQueryResponse); #endif /* Data block ready. Parse and fill data model */ OneTripParse(iQueryResponse->Des(), iModel.iError, iModel.iResult, iModel.iItems); #endif CleanupQueryText(); iObserver.GIEStateChanged(eStateComplete); iModel.iState = eStateComplete; } break; case THTTPEvent::ESucceeded: { // transaction successful // we do not do this in the response complete phase or error // phase as it is nicer to break it up because if the parser // is working non incrementally we have potientionally done // a lot of work in the ReponseComplete phase iObserver.GIEStateChanged(eStateComplete); iModel.iState = eStateComplete; } break; case THTTPEvent::EFailed: { // Transaction failed MHFRunError(aEvent.iStatus, aTransaction, aEvent); } break; default: { /* All errors will fall through to the generic event handler The only exceptional error handling is done when the soap request itself fails and it reports an error */ MHFRunError(aEvent.iStatus, aTransaction, aEvent); } break; } }
/** Finds Implementation UID. @param aCodec Codec names. @param aNext Pointer to 8-bit data that is to recieve the delegate name. @return always returns a valid UID of the codec plugin. @leave KErrNotFound Specified Codec. @internalComponent */ TUid CHeaderCodecPlugin::FindImplementationUidL(const TDesC8& aCodec, TPtrC8& aNext) { TEComResolverParams resolverParams; TPtrC8 codec(aCodec); // The codec to look for (may be changed so we need our own pointer) TUid id = KNullUid; while(id == KNullUid) // while there is no match { // if the string we need to match can't be made by a TPtrC, we will create it in resolve HBufC8* resolve = NULL; resolverParams.SetWildcardMatch(ETrue); // find the first slash of text in the form: "protocol/type/name/etc" or "protocol/type" or "protocol" // This will be the name of the protocol TInt firstSlash = codec.Locate('/'); if( firstSlash < 0 ) // no slashes -- this is just the protocol name ("protocol") { resolverParams.SetDataType(codec); // look for a match for "protocol" aNext.Set(KNullDesC8); // no next codec in chain. } else if( firstSlash == codec.Length() - 1) // just "protocol/" // it's easier to use this than to pass around with the *, since this // way aNext always points to the original descriptor { resolve = HBufC8::NewL(codec.Length()+1); TPtr8 res = resolve->Des(); res.Copy(codec); res.Append('*'); resolverParams.SetDataType(res); // the string "protocol/*" aNext.Set( codec.Left(firstSlash) ); // next codec is "protocol" (no slash) } else // there is at least one slash with subsequent content ("protocol/name") { TInt lastSlash = codec.LocateReverse('/'); // find the last slash // must match exactly otherwise we'd always resolve "protocol/*" resolverParams.SetWildcardMatch(EFalse); if (lastSlash > firstSlash) {// has at least 2 slashes ("protocol/name1/name2") // resolve = up to and including first slash, and everything after last slash ("protocol/name2") resolve = HBufC8::NewL(firstSlash+1 + codec.Length()-lastSlash); TPtr8 res = resolve->Des(); res.Copy(codec.Left(firstSlash+1)); // up to and including first slash res.Append(codec.Mid(lastSlash+1)); // everything after last slash aNext.Set( codec.Left(lastSlash) ); // up to,but not including the last slash resolverParams.SetDataType(res); } else // just the one slash ("protocol/name") { resolverParams.SetDataType(codec); // look for "protocol/name" aNext.Set(codec.Left(firstSlash+1)); // next codec is "protocol" } } CleanupStack::PushL(resolve); // resolve might be NULL, but that's ok RImplInfoPtrArray implArray; // the list of plugins will be put here. REComSession::ListImplementationsL(KUidHeaderCodecPlugin, resolverParams, implArray); TInt count = implArray.Count();; // number of matches CleanupStack::PopAndDestroy(resolve); // don't need this anymore if(count != 0) // we found the match. save it in id { id = implArray[0]->ImplementationUid(); } implArray.ResetAndDestroy(); if(count == 0 && aNext.Length() == 0) // no more codecs to try { User::Leave(KErrNotFound); // No suitable implementation is present } codec.Set(aNext); } return id; }
//*************************************************************************** //Helpers //*************************************************************************** static void CopyAddr(const TBTSockAddr& aAddr, void* dst) { const TBTDevAddr& devAddr(aAddr.BTAddr()); const TPtrC8 devPtrC8(devAddr.Des()); DEBUG_ASSERT(devPtrC8.Length() == BTADDR_LEN); memcpy(dst, devPtrC8.Ptr(), BTADDR_LEN); }
// ----------------------------------------------------------------------------- // CEcmtPanPlugin::HandleNotifyL // // ----------------------------------------------------------------------------- // void CEcmtPanPlugin::HandleNotifyL( const CEcmtMessageEvent& aEvent ) { const TPtrC8 m = iMessaging->Message( aEvent ); TLex8 lexer( m ); TPtrC8 btCom = lexer.NextToken(); TPtrC8 btComVal = lexer.NextToken(); TPtrC8 hci = lexer.NextToken(); TPtrC8 hciVal = lexer.NextToken(); TPtrC8 irdaCom = lexer.NextToken(); TPtrC8 irdaComVal = lexer.NextToken(); if ( btCom != KBtCom || hci != KHci || irdaCom != KIrdaCom ) { ErrorReply( R_INTERNAL_ERROR, KNullDesC ); return; } _LIT8( KMinusOne, "-1" ); if ( btComVal != KMinusOne && btComVal == irdaComVal ) { ErrorReply( R_IRDA_BT_ERROR, KNullDesC ); return; } TBuf<KMaxWin32Path> buff; TPtrC8 line; /* * Handle bt.esk */ GetBtEskFilename( buff ); REcmtFile btFile( buff ); btFile.Read(); if ( !btFile.IsGood() ) { ErrorReply( R_FILE_NOT_FOUND, buff ); return; } // Set port number line.Set( btFile.FindLine( KBtPort ) ); if ( line.Length() == 0 ) { ErrorReply( R_FILE_CORRUPTED, buff ); return; } TBuf8< 64 > newLine; newLine.Append( KBtPort ); newLine.Append( _L(" ") ); newLine.Append( btComVal ); newLine.Append( _L("\r\n") ); if ( !btFile.ReplaceLine( line, newLine ) ) { ErrorReply( R_INTERNAL_ERROR, KNullDesC ); return; } // Set hci dll line.Set( btFile.FindLine( KHciDll ) ); if ( line.Length() == 0 ) { ErrorReply( R_FILE_CORRUPTED, buff ); return; } newLine.Zero(); newLine.Append( KHciDll ); newLine.Append( _L(" ") ); if ( hciVal[0] == '0' ) { newLine.Append( KHciDllBcsp ); } else if ( hciVal[0] == '1' ) { newLine.Append( KHciDllH4 ); } else if ( hciVal[0] == '2' ) { newLine.Append( KHciDllUsb ); } else { newLine.Append( KHciDllH4 ); } newLine.Append( _L("\r\n") ); if ( !btFile.ReplaceLine( line, newLine ) ) { ErrorReply( R_INTERNAL_ERROR, KNullDesC ); return; } if ( !btFile.Write() ) { ErrorReply( R_FILE_WRITE_ERROR, buff ); return; } /* * Handle irda.esk */ GetIrdaEskFilename( buff ); REcmtFile irdaFile( buff ); irdaFile.Read(); if ( !irdaFile.IsGood() ) { ErrorReply( R_FILE_NOT_FOUND, buff ); return; } // Set port number line.Set( irdaFile.FindLine( KIrdaPort ) ); if ( line.Length() == 0 ) { ErrorReply( R_FILE_CORRUPTED, buff ); return; } newLine.Zero(); newLine.Append( KIrdaPort ); newLine.Append( _L(" ") ); newLine.Append( irdaComVal ); newLine.Append( _L("\r\n") ); if ( !irdaFile.ReplaceLine( line, newLine ) ) { ErrorReply( R_INTERNAL_ERROR, KNullDesC ); return; } if ( !irdaFile.Write() ) { ErrorReply( R_FILE_WRITE_ERROR, buff ); return; } SuccessReply(); }
EXPORT_C TInt TMTPTypeNull::FirstReadChunk(TPtrC8& aChunk) const { aChunk.Set(KNullDesC8); return KMTPChunkSequenceCompletion; }
// ----------------------------------------------------------------------------- // CEcmtPanPlugin::SendCurrentValues // // ----------------------------------------------------------------------------- // void CEcmtPanPlugin::SendCurrentValuesL( ) { #ifdef ECMT_RDEBUG RDebug::Print( _L( "EcmtPanPlugin::SendCurrentValuesL" ) ); #endif TBuf<KMaxWin32Path> buf; TBuf8<KMaxPanMsgLen> msg; TPtrC8 line; TLex8 lexer; /* * Handle bt.esk */ GetBtEskFilename( buf ); REcmtFile btFile( buf ); btFile.Read(); if ( !btFile.IsGood() ) { return; } line.Set( btFile.FindLine( KBtPort ) ); if ( line.Length() == 0 ) { return; } msg.Append( KBtCom ); msg.Append( ' ' ); lexer.Assign( line ); lexer.SkipCharacters(); msg.Append( lexer.NextToken() ); msg.Append( ' ' ); line.Set( btFile.FindLine( KHciDll ) ); if ( line.Length() == 0 ) { return; } msg.Append( KHci ); msg.Append( ' ' ); lexer.Assign( line ); lexer.SkipCharacters(); TPtrC8 dll( lexer.NextToken() ); if ( dll.CompareF( KHciDllBcsp ) == 0 ) { msg.Append( '0' ); } else if ( dll.CompareF( KHciDllH4 ) == 0 ) { msg.Append( '1' ); } else if ( dll.CompareF( KHciDllUsb ) == 0 ) { msg.Append( '2' ); } else { msg.Append( '-1' ); } /* * Handle irda.esk */ GetIrdaEskFilename( buf ); REcmtFile irdaFile( buf ); irdaFile.Read(); if ( !irdaFile.IsGood() ) { return; } line.Set( irdaFile.FindLine( KIrdaPort ) ); if ( line.Length() == 0 ) { return; } msg.Append( ' ' ); msg.Append( KIrdaCom ); msg.Append( ' ' ); lexer.Assign( line ); lexer.SkipCharacters(); msg.Append( lexer.NextToken() ); /* * Send values */ CEcmtMessageEvent* m = iMessaging->NewMessageEvent( iTargetUid, msg ); if ( m ) { #ifdef ECMT_RDEBUG RDebug::Print( _L( "EcmtPanPlugin::SendCurrentValuesL: Sending a message" ) ); #endif iMessageSender->SendMessage( m ); } }
EXPORT_C TInt TMTPTypeNull::NextReadChunk(TPtrC8& aChunk) const { aChunk.Set(KNullDesC8); return KErrNotReady; }
void CHttpEventHandler::MHFRunL(RHTTPTransaction aTransaction, const THTTPEvent& aEvent) { switch (aEvent.iStatus) { case THTTPEvent::EGotResponseHeaders: { // HTTP response headers have been received. We can determine now if there is // going to be a response body to save. RHTTPResponse resp = aTransaction.Response(); TInt status = resp.StatusCode(); if (iVerbose) { RStringF statusStr = resp.StatusText(); TBuf<32> statusStr16; statusStr16.Copy(statusStr.DesC()); iTest->Console()->Printf(_L("Status: %d (%S)\n"), status, &statusStr16); // Dump the headers if we're being verbose DumpRespHeadersL(aTransaction); } // Determine if the body will be saved to disk iSavingResponseBody = EFalse; if (resp.HasBody() && (status >= 200) && (status < 300) && (status != 204)) { if (iVerbose) { TInt dataSize = resp.Body()->OverallDataSize(); if (dataSize >= 0) iTest->Console()->Printf(_L("Response body size is %d\n"), dataSize); else iTest->Console()->Printf(_L("Response body size is unknown\n")); } iSavingResponseBody = ETrue; } else { if (iVerbose) iTest->Console()->Printf(_L("Response status is bad\n")); } if ((status >= 200) && (status < 300) && (status != 204)) { ParseCookieL(aTransaction); } if (iSavingResponseBody) // If we're saving, then open a file handle for the new file { if ( iUsingFile ) { iHttpFileManager->GetNewFile(iRespBodyFilePath, iRespBodyFileName, EFalse); // Check it exists and open a file handle TInt valid = iFileServ.IsValidName(iRespBodyFilePath); if (!valid) { if (iVerbose) iTest->Console()->Printf(_L("The specified filename is not valid!.\n")); iSavingResponseBody = EFalse; } else { TInt err = iRespBodyFile.Create(iFileServ, iRespBodyFilePath, EFileWrite|EFileShareExclusive); if (err) { iSavingResponseBody = EFalse; User::Leave(err); } } } else { TInt dataSize = resp.Body()->OverallDataSize(); if ( iResBodyBuffer ) delete iResBodyBuffer; iResBodyBuffer = NULL; if ( dataSize > 50 * 1024) //skip large chunks of data { iSavingResponseBody = false; //try to stop current connection if (iVerbose) iTest->Console()->Printf(_L("Transaction Failed\n")); aTransaction.Close(); CActiveScheduler::Stop(); } else { iResBodyBuffer = HBufC8::NewMaxL(dataSize); iResBodyBufferPtr.Set(iResBodyBuffer->Des()); } iCurPos = 0; } } } break; case THTTPEvent::EGotResponseBodyData: { // Get the body data supplier iRespBody = aTransaction.Response().Body(); // Some (more) body data has been received (in the HTTP response) if (iVerbose) DumpRespBody(aTransaction); // Append to the output file if we're saving responses if (iSavingResponseBody) { TPtrC8 bodyData; TBool lastChunk = iRespBody->GetNextDataPart(bodyData); if ( iUsingFile ) { iRespBodyFile.Write(bodyData); if (lastChunk) { iRespBodyFile.Flush(); iRespBodyFile.Rename(iRespBodyFileName); iRespBodyFile.Close(); } } else { Mem::Copy((void*)(iResBodyBuffer->Ptr()+iCurPos), (void*)bodyData.Ptr(), bodyData.Size()); iCurPos += bodyData.Size(); } } // Done with that bit of body data iRespBody->ReleaseData(); } break; case THTTPEvent::EResponseComplete: { // The transaction's response is complete if (iVerbose) iTest->Console()->Printf(_L("\nTransaction Complete\n")); } break; case THTTPEvent::ESucceeded: { if (iVerbose) iTest->Console()->Printf(_L("Transaction Successful\n")); aTransaction.Close(); CActiveScheduler::Stop(); } break; case THTTPEvent::EFailed: { if (iVerbose) iTest->Console()->Printf(_L("Transaction Failed\n")); aTransaction.Close(); CActiveScheduler::Stop(); } break; case THTTPEvent::ERedirectedPermanently: { if (iVerbose) iTest->Console()->Printf(_L("Permanent Redirection\n")); } break; case THTTPEvent::ERedirectedTemporarily: { if (iVerbose) iTest->Console()->Printf(_L("Temporary Redirection\n")); } break; default: { if (iVerbose) iTest->Console()->Printf(_L("<unrecognised event: %d>\n"), aEvent.iStatus); // close off the transaction if it's an error if (aEvent.iStatus < 0) { aTransaction.Close(); CActiveScheduler::Stop(); } } break; } }
TVerdict CHashIncrementalHashWithCopyStep::doTestStepL() { if (TestStepResult()==EPass) { //Assume faliure, unless all is successful SetTestStepResult(EFail); INFO_PRINTF1(_L("*** Hash - Incremental Hash with Copy ***")); INFO_PRINTF2(_L("HEAP CELLS: %d"), User::CountAllocCells()); TVariantPtrC algorithmUid; TVariantPtrC operationModeUid; TPtrC sourcePath; TPtrC expectedHash; //Extract the Test Case ID parameter from the specified INI file if(!GetStringFromConfig(ConfigSection(),KConfigAlgorithmUid,algorithmUid) || !GetStringFromConfig(ConfigSection(),KConfigOperationMode,operationModeUid) || !GetStringFromConfig(ConfigSection(),KConfigSourcePath,sourcePath) || !GetStringFromConfig(ConfigSection(),KConfigExHashHmacValue,expectedHash)) { ERR_PRINTF1(_L("** Error: Failed to Load Configuration Parameters **")); SetTestStepResult(EFail); } else { //Create a pointer for the Hash Implementation Object CHash* hashImpl = NULL; //Retrieve a Hash Factory Object TRAPD(err,CHashFactory::CreateHashL(hashImpl, algorithmUid, operationModeUid, NULL, NULL)); if(hashImpl && (err == KErrNone)) { //Push the Hash Implementation Object onto the Cleanup Stack CleanupStack::PushL(hashImpl); RFs fsSession; //Create a connection to the file server err = fsSession.Connect(); if(err != KErrNone) { ERR_PRINTF2(_L("*** Error: File Server Connection - %d ***"), err); SetTestStepResult(EFail); } else { RFile sourceFile; CleanupClosePushL(sourceFile); //Open the specified source file err = sourceFile.Open(fsSession,sourcePath, EFileRead); if(err != KErrNone) { ERR_PRINTF2(_L("*** Error: Opening Source File - %d ***"), err); SetTestStepResult(EFail); } else { TInt sourceLength = 0; TInt readPosition = 0; TInt readIncrement = 0; TBool hashComplete = EFalse; TBool hashCopied = EFalse; TPtrC8 hashStr; CHash* hashCopyImpl = NULL; User::LeaveIfError(sourceFile.Size(sourceLength)); //Divide the total size of the source file up into individual equal sized blocks to read //over several increments readIncrement = sourceLength/KDataReadBlocks; do { //Create a heap based descriptor to store the data HBufC8* sourceData = HBufC8::NewL(readIncrement); CleanupStack::PushL(sourceData); TPtr8 sourcePtr = sourceData->Des(); //Read in a block of data from the source file from the current position err = sourceFile.Read(readPosition,sourcePtr,readIncrement); //Update the read position by adding the number of bytes read readPosition += readIncrement; if(readPosition == readIncrement) { //Read in the first block from the data file into the Hash implementation object hashImpl->Hash(*sourceData); INFO_PRINTF2(_L("Intial Hash - Bytes Read: %d"), readPosition); } else if(readPosition >= sourceLength) { //Reading in the final block, constructs the complete hash value and returns it within a TPtrC8 hashStr.Set(hashCopyImpl->Final(*sourceData)); //Sets the Complete Flag to ETrue in order to drop out of the loop hashComplete = ETrue; TInt totalRead = (readPosition - readIncrement) + (*sourceData).Length(); INFO_PRINTF2(_L("Final Hash - Bytes Read: %d"),totalRead); } //If the read position is half the source length and the implementation //object hasn't already been copied else if((readPosition >= sourceLength/2) && (hashCopied == EFalse)) { //Update the hash message before copying hashImpl->Update(*sourceData); INFO_PRINTF1(_L("Copying Hash Object...")); //Create a Copy of the existing Hash Object and all internal state of the message digest hashCopyImpl = hashImpl->CopyL(); hashCopied = ETrue; INFO_PRINTF2(_L("*** HASH COPY - Bytes Read: %d ***"), readPosition); } else { //Update the message data within the Hash object with the new block if(hashCopied == EFalse) { hashImpl->Update(*sourceData); INFO_PRINTF2(_L("Hash Update - Bytes Read: %d"), readPosition); } else { hashCopyImpl->Update(*sourceData); INFO_PRINTF2(_L("Hash Update (Copy) - Bytes Read: %d"), readPosition); } } CleanupStack::PopAndDestroy(sourceData); }while(hashComplete == EFalse); //Create a NULL TCharacteristics pointer const TCharacteristics* charsPtr(NULL); //Retrieve the characteristics for the hash implementation object TRAP_LOG(err, hashImpl->GetCharacteristicsL(charsPtr)); //Static cast the characteristics to type THashCharacteristics const THashCharacteristics* hashCharsPtr = static_cast<const THashCharacteristics*>(charsPtr); //The hash output size is returned in Bits, divide by 8 to get the Byte size TInt hashSize = hashCharsPtr->iOutputSize/8; //Retrieve the final 8bit hash value and convert to 16bit HBufC* hashData = HBufC::NewLC(hashSize); TPtr hashPtr = hashData->Des(); //Copy the hashed content into the heap based descriptor hashPtr.Copy(hashStr); //Take the 16bit descriptor and convert the string to hexadecimal TVariantPtrC convertHash; convertHash.Set(hashPtr); HBufC* hashResult = convertHash.HexStringLC(); INFO_PRINTF2(_L("*** Hashed Data: %S ***"),&*hashResult); INFO_PRINTF2(_L("*** Expected Hash: %S ***"),&expectedHash); //If the returned hash value matches the expected hash, Pass the test if(*hashResult == expectedHash) { INFO_PRINTF1(_L("*** Hash - Incremental Hash with Copy : PASS ***")); SetTestStepResult(EPass); } else { ERR_PRINTF2(_L("*** FAIL: Hashed and Expected Value Mismatch ***"), err); SetTestStepResult(EFail); } CleanupStack::PopAndDestroy(hashResult); CleanupStack::PopAndDestroy(hashData); delete hashCopyImpl; } //Cleanup the Source RFile CleanupStack::PopAndDestroy(); } fsSession.Close(); CleanupStack::PopAndDestroy(hashImpl); } else { ERR_PRINTF2(_L("*** FAIL: Failed to Create Hash Object - %d ***"), err); SetTestStepResult(EFail); } } } INFO_PRINTF2(_L("HEAP CELLS: %d"), User::CountAllocCells()); return TestStepResult(); }
TPtrC8 CSocketEngine::GetHttpHeaderInfo(const TDesC8 &aHeaderData,const TDesC8 &aHeaderInfo){ _LIT8(KEnter,"\r\n"); TBuf8<256> bufInfo(aHeaderInfo); bufInfo.Append(_L8(": ")); TPtrC8 ret; TPtrC8 ptr; ptr.Set(aHeaderData); TInt pos=ptr.FindF(bufInfo); if(pos>0){ TInt start=pos+bufInfo.Length(); ptr.Set(ptr.Mid(start)); pos=ptr.FindF(KEnter); if(pos>0){ ptr.Set(ptr.Left(pos)); ret.Set(ptr); }else if(-1==pos){ pos=ptr.FindF(_L8("\n")); if(pos>0){ ptr.Set(ptr.Left(pos)); ret.Set(ptr); } } } return ret; }
// ----------------------------------------------------------------------------- // CSTSCredentialManager::AddCredentialL // Adds a certificate or certificate URI to certificate store // ----------------------------------------------------------------------------- // TBool CSTSCredentialManager::AddCredentialL( TInt/*const TDesC&*/ aCertDisplayName, TInt/*const TDesC&*/ aPkiPath) { if (iState != EReady) { User::Leave(KErrNotReady); } iWritableCertStoreIndex = CheckWriteCertStoreSEIDL(NULL, NULL); const TDesC8* path = reinterpret_cast< const TDesC8* >(aPkiPath); TASN1DecGeneric genericDecoder(*path); genericDecoder.InitL(); TPtrC8 certificates = genericDecoder.GetContentDER(); TInt certificatesLength = certificates.Length(); TInt pos = 0; iSubject.Set(certificates.Right(certificatesLength)); TPtrC8 issuer(iSubject); // go through the certificate chain, leaving the last certificate as subject // and second last as issuer while (pos < certificatesLength) { issuer.Set(iSubject); TASN1DecGeneric certDecoder(certificates.Right(certificatesLength - pos)); certDecoder.InitL(); TInt certLength = certDecoder.LengthDER(); TPtrC8 singleCert(certificates.Mid(pos, certLength)); iSubject.Set(singleCert); pos+=certLength; } CX509Certificate* cert = CX509Certificate::NewLC(iSubject); CX509Certificate* issuerCert = CX509Certificate::NewLC(issuer); iSubjectKeyId = cert->KeyIdentifierL(); iIssuerKeyId = issuerCert->KeyIdentifierL(); iCertDisplayName = reinterpret_cast<TDesC*>(aCertDisplayName); // now we have to check that this certificate does not exist in the // database yet CCertAttributeFilter* filter = CCertAttributeFilter::NewLC(); filter->SetFormat(EX509Certificate); filter->SetSubjectKeyId(iSubjectKeyId); filter->SetIssuerKeyId(iIssuerKeyId); RMPointerArray< CCTCertInfo >* certInfoArray = new(ELeave) RMPointerArray< CCTCertInfo >(); if (iCertInfoArray) { iCertInfoArray->Close(); delete iCertInfoArray; } iCertInfoArray = certInfoArray; iState = EAddListing; iStore->WritableCertStore(iWritableCertStoreIndex) .List(*iCertInfoArray, *filter, iStatus); WaitForCompletionL(); CleanupStack::PopAndDestroy(3); // filter, cert, issuerCert iCertInfoArray->Close(); delete iCertInfoArray; iCertInfoArray = NULL; return ETrue; }
//comparing light weight and heavy weight on a small ini file static void PerformanceTest1L() { test.Printf(_L("\nSmall Ini file comparison \n")); TTime startTime, stopTime; TPtrC8 value; startTime.UniversalTime(); for (TInt i=0;i<1000;i++) { CIniFile8* ini=CIniFile8::NewL(TheRFs,_L("z:\\resource\\testconfig8.ini")); test(ini->FindVar(_L8("test_section"),_L8("key1"),value)==KErrNone); test(value.Compare(_L8("value1"))==0); test(ini->FindVar(_L8("test_section"),_L8("key2"),value)==KErrNone); test(value.Compare(_L8("value2"))==0); test(ini->FindVar(_L8("test_section"),_L8("key3"),value)==KErrNone); test(value.Compare(_L8("value3"))==0); test(ini->FindVar(_L8("test_section"),_L8("key4"),value)==KErrNone); test(value.Compare(_L8("value4"))==0); test(ini->FindVar(_L8("test_section"),_L8("key5"),value)==KErrNone); test(value.Compare(_L8("value value value"))==0); test(ini->FindVar(_L8("SERVERS"),_L8("SWTRACER"),value)==KErrNone); test(value.Compare(_L8(""))==0); test(ini->FindVar(_L8("1"),_L8("timestamps"),value)==KErrNone); test(value.Compare(_L8("0"))==0); test(ini->FindVar(_L8("1"),_L8("setting"),value)==KErrNone); test(value.Compare(_L8("value"))==0); delete ini; } stopTime.UniversalTime(); TTimeIntervalMicroSeconds timeTaken = stopTime.MicroSecondsFrom(startTime); test.Printf(_L("Time taken for Light= %d microseconds\n"), timeTaken.Int64() ); //heavy weight testing startTime.UniversalTime(); for (TInt j=0;j<1000;j++) { CIniDocument8* dom=CIniDocument8::NewL(TheRFs,_L("z:\\resource\\testconfig8.ini")); test(dom->GetKeyValue(_L8("test_section"),_L8("key1"),value)==KErrNone); test(value.Compare(_L8("value1"))==0); test(dom->GetKeyValue(_L8("test_section"),_L8("key2"),value)==KErrNone); test(value.Compare(_L8("value2"))==0); test(dom->GetKeyValue(_L8("test_section"),_L8("key3"),value)==KErrNone); test(value.Compare(_L8("value3"))==0); test(dom->GetKeyValue(_L8("test_section"),_L8("key4"),value)==KErrNone); test(value.Compare(_L8("value4"))==0); test(dom->GetKeyValue(_L8("test_section"),_L8("key5"),value)==KErrNone); test(value.Compare(_L8("value value value"))==0); test(dom->GetKeyValue(_L8("SERVERS"),_L8("SWTRACER"),value)==KErrNone); test(value.Compare(_L8(""))==0); test(dom->GetKeyValue(_L8("1"),_L8("timestamps"),value)==KErrNone); test(value.Compare(_L8("0"))==0); test(dom->GetKeyValue(_L8("1"),_L8("setting"),value)==KErrNone); test(value.Compare(_L8("value"))==0); delete dom; } stopTime.UniversalTime(); timeTaken = stopTime.MicroSecondsFrom(startTime); test.Printf(_L("Time taken for Heavy= %d microseconds\n"), timeTaken.Int64() ); }
void CVJDecompressTypeErrorTest::ProcessPacketL() /** This is a virtual function. This function feeds precompressed IP/TCP packets into both the VJDeCompressor (unit under test) and the Referece Decompressor (provided in RFC 1144). The output of the VJDeCompressor is compared against the output of the Reference Decompressor to verify its corectness */ { TUint packetType = TrimPacketBeforeDecompression(); if (packetType == 911) { // Packet type is unsupported. Abort test. SetTestStepResult(EFail); return; } // Create packet buffer to be sent to reference decompressor // This is to prevent compromising the test results if the compressor/decompressor alters the original data HBufC8* refPacketBuffer = HBufC8::NewMaxLC(TPcapRecord::KMaxPacketSize+KRefPacketHeaderSpace); // Reserve some space at the head of the HBufC8 for the uncompressed header // The reference decompressor expects the packet has enough space to prepend 120 byes of resconstructed header TPtr8 refInputPtr(const_cast<TUint8*>(refPacketBuffer->Ptr())+KRefPacketHeaderSpace, refPacketBuffer->Length()-KRefPacketHeaderSpace); refInputPtr = iRec->Data(); TUint8 *refdecompOutput = NULL; TInt refPacketLen = refInputPtr.Length(); // Create packet buffer to be sent to VJDecompressor // This is to prevent compromising the test results if the compressor/decompressor alters the original data // The size of the HBuf object must have a maximum length that is big enough to hold the decompressed data HBufC8* vjPacketBuffer = HBufC8::NewLC(TPcapRecord::KMaxPacketSize); TPtr8 vjOutputPtr (vjPacketBuffer->Des()); vjOutputPtr = iRec->Data(); iPacket.CopyIn(*vjPacketBuffer, 0); iPacket.TrimEnd(vjPacketBuffer->Length()); // Create info packet RMBufPacket pkt; RMBufPktInfo* info = 0; info = pkt.NewInfoL(); info->iLength = vjPacketBuffer->Length(); pkt.Pack(); iPacket.Prepend(pkt); // Put info packet in front of this packet TUint vjdecompRet; //-------------- substep 7 -------------------- // decompress the packet using VJDeCompressor and Reference decompressor INFO_PRINTF1(_L(" 07, 08 Decompress the packet using VJDeCompressor and Reference Decompressor:")); switch (packetType) { case KPppIdIp: // the packet is TYPE_IP // decompress TYPE_IP packet using our reference decompressor INFO_PRINTF1(_L(" 07 Decompress TYPE_IP packet using reference decompressor:")); refdecompOutput = sl_uncompress_tcp(const_cast<TUint8*>(refInputPtr.Ptr()), &refPacketLen, (TUint)TYPE_IP, iComp); // VJ Decompressor function is not called because the packet is TYPE_IP INFO_PRINTF1(_L(" 08 TYPE_IP packet is not modified by VJDecompressor.")); vjdecompRet = ETrue; break; case KPppIdVjCompTcp: // the packet is COMPRESSED_TCP // decompress using our reference decompressor INFO_PRINTF1(_L(" 07 Decompress COMPRESSED_TCP packet using reference decompressor:")); refdecompOutput = sl_uncompress_tcp(const_cast<TUint8*>(refInputPtr.Ptr()), &refPacketLen, (TUint)TYPE_COMPRESSED_TCP, iComp); //decompress using our VJ Decompressor INFO_PRINTF1(_L(" 08 Decompress COMPRESSED_TCP packet using VJDeCompressor:")); vjdecompRet = iVJDeCompressor->DecompVJComp(iPacket); INFO_PRINTF2(_L(" 08 COMPRESSED_TCP packet is decompressed: %d"), vjdecompRet); break; case KPppIdVjUncompTcp: // the packet is UNCOMPRESSED_TCP // decompress using our reference Compressor INFO_PRINTF1(_L(" 07 Decompress UNCOMPRESSED_TCP packet using reference decompressor:")); refdecompOutput = sl_uncompress_tcp(const_cast<TUint8*>(refInputPtr.Ptr()), &refPacketLen, (TUint)TYPE_UNCOMPRESSED_TCP, iComp); //decompress using our VJ Decompressor INFO_PRINTF1(_L(" 08 Decompress UNCOMPRESSED_TCP packet using VJDeCompressor:")); vjdecompRet = iVJDeCompressor->DecompVJUncomp(iPacket); INFO_PRINTF2(_L(" 08 UNCOMPRESSED_TCP packet is decompressed: %d"), vjdecompRet); break; default: //the packet is TYPE_ERROR // set 'toss' flag and discard COMPRESSED_TCP packet until one with C bit set // or an UNCOMPRESSED_TCP packet arrives // decompress using our reference decompressor INFO_PRINTF1(_L(" 07 Decompress TYPE_ERROR packet using reference decompressor:")); refdecompOutput = sl_uncompress_tcp(const_cast<TUint8*>(refInputPtr.Ptr()), &refPacketLen, (TUint)TYPE_ERROR, iComp); //decompress using our VJ Decompressor INFO_PRINTF1(_L(" 08 Handle TYPE_ERROR packet using VJDeCompressor:")); iVJDeCompressor->CRCError(); vjdecompRet = EFalse; break; } if ((vjdecompRet) && refdecompOutput != 0) { //--------------substep 09---------------------- // Display VJ decompressed packet INFO_PRINTF1(_L(" 09 The VJ decompressed packet:")); // The decompressed data should be larger than the compressed data // So we need to expand the size of the pointer in order to hold the decompressed data vjOutputPtr.SetMax(); // Remove info packet iPacket.Remove(); iPacket.CopyOut(vjOutputPtr); INFO_PRINTF2(_L("VJ decompressed packet len: %d"), vjPacketBuffer->Length()); // TPtrC8 object is created because DumpIp() takes a TPtrC8 object as a parameter TPtrC8 vjOutputPtrC (vjOutputPtr); DumpIp(vjOutputPtrC); //--------------substep 10---------------------- // Display REF decompressed packet INFO_PRINTF1(_L("10 The REF decompressed packet is:")); TPtrC8 refOutputPtrC(refdecompOutput, refPacketLen); DumpIp(refOutputPtrC); //--------------substep 11---------------------- //Compare the results of the reference compressor output and our VJ compressor output INFO_PRINTF1(_L(" 11 Compare the result of the compression by VJCompressor to Reference compressor:")); INFO_PRINTF2(_L(" Size of VJ comp output: %d"), vjOutputPtrC.Length()); INFO_PRINTF2(_L(" Size of Reference comp output: %d"), refOutputPtrC.Length()); if (!CompareOutput(vjOutputPtrC, refOutputPtrC)) { INFO_PRINTF1(_L("The results are not equal")); SetTestStepResult(EFail); } } else { IsItATossPacket(vjdecompRet, refdecompOutput); } CleanupStack::PopAndDestroy(vjPacketBuffer); CleanupStack::PopAndDestroy(refPacketBuffer); vjPacketBuffer = NULL; refPacketBuffer = NULL; } // VJDecompressTypeErrorTest
void CContentWindowContainer::DataReceived(class MBrCtlLinkContent* aLinkContent, const isab::DataGuiMess* aMess, const char *aUrl) { HBufC8* data = NULL; HBufC* contentType = NULL; HBufC* url = WFTextUtil::AllocLC(aUrl); TPtr8 ptr(const_cast<unsigned char*>(aMess->getData()), aMess->getSize(), aMess->getSize()); TInt neck = ptr.Find(KNeck()); if (neck == KErrNotFound) { data = HBufC8::NewLC( ptr.Length()); data->Des().Copy(ptr); contentType = WFTextUtil::AllocLC("text/html"); } else { TPtrC8 header = ptr.Left(neck); TPtrC8 body = ptr.Mid(neck+4); data = HBufC8::NewLC( body.Length()); data->Des().Copy(body); TInt pos = header.Find(KLineEnd); TPtrC8 rest = header; while (pos != KErrNotFound) { TPtrC8 tmp = rest.Left(pos); rest.Set(rest.Mid(pos+2)); pos = rest.Find(KLineEnd); TInt ctpos = tmp.FindF(KContentTypeMarker); if (ctpos != KErrNotFound) { TPtrC8 tmp2 = tmp.Mid(ctpos+KContentTypeMarker().Length()); TInt scpos = tmp2.Find(KSemiColon); if (scpos == KErrNotFound) { contentType = HBufC::NewLC(tmp2.Length()); contentType->Des().Copy(tmp2); } else { contentType = HBufC::NewLC(tmp2.Left(scpos).Length()); contentType->Des().Copy(tmp2.Left(scpos)); } break; } } if (!contentType) { contentType = WFTextUtil::AllocLC("text/html"); } } /* contentType = RecognizeLC(*url, ptr); */ /* contentType = WFTextUtil::AllocLC("text/html"); */ aLinkContent->HandleResolveComplete(*contentType, KCharSet, data); CleanupStack::PopAndDestroy(contentType); CleanupStack::PopAndDestroy(data); CleanupStack::PopAndDestroy(url); }
TBool CTestRandTerm::CheckRead() { TPtrC8 ref; ref.Set(iWriter->iDes.Ptr()+iOffset, iReader->iDes.Length()); return ref.Compare(iReader->iDes)==0; }
CSenElement* CPolicyNormalizer::ProcessPolicyTermL(CSenElement* aAssertion, CSenElement* aNormalAssertion) { RPointerArray<CSenElement>& children = aAssertion->ElementsL(); TInt childCount = children.Count(); CSenElement* pNextChild; if(childCount == 0) { CSenElement* pXor = AddXorElementL(aNormalAssertion); CSenElement* pAnd = AddAndElementL(pXor); return aNormalAssertion; } TInt i=0; CSenElement* assertionParent = aNormalAssertion; while (i < childCount) { pNextChild = children[i]; TPtrC8 localName = pNextChild->LocalName(); if(localName.Compare(WSPolicy::KXorCompositeAssertion) == 0) { TPtrC8 nt = aNormalAssertion->LocalName(); if(nt.Compare(WSPolicy::KWsPolicy)== 0) //PERFECT we need it { // aNormalAssertion = ProcessXORTermL(pNextChild,aNormalAssertion); } else if(nt.Compare(WSPolicy::KXorCompositeAssertion)== 0) { CSenElement* NewXorParent = aNormalAssertion->Parent(); ProcessXORTermL(pNextChild,NewXorParent); } else if(nt.Compare(WSPolicy::KAndCompositeAssertion)== 0) { CSenElement* NewXorParent = aNormalAssertion->Parent()->Parent(); ProcessXORTermL(pNextChild,NewXorParent); } else { //SHOULDNT BE A CASE CAZ then we have XOR in some assertion //It should always be in a POLICY tag } } else if (localName.Compare(WSPolicy::KAndCompositeAssertion) == 0) { CSenElement* pNormChild = AddXorElementL(aNormalAssertion); // aNormalAssertion = ProcessANDTermL(pNextChild, pNormChild); } else if (localName.Compare(WSPolicy::KWsPolicy) == 0 ) { TPtrC8 parentName = aNormalAssertion->LocalName(); if(parentName.Compare(WSPolicy::KXorCompositeAssertion) == 0) { CSenElement* pChildXor = AddXorElementL(aNormalAssertion); CSenElement* pChildAnd = AddAndElementL(pChildXor); } else if(parentName.Compare(WSPolicy::KAndCompositeAssertion) == 0) { } else if(parentName.Compare(WSPolicy::KWsPolicy) == 0) { CSenElement* pChildXor = AddXorElementL(aNormalAssertion); CSenElement* pChildAnd = AddAndElementL(pChildXor); } else { CSenElement* pChildXor = AddXorElementL(aNormalAssertion); CSenElement* pChildAnd = AddAndElementL(pChildXor); } } else //its an Assertion { TPtrC8 parentName = assertionParent->LocalName(); //if parent is Policy -> add XOR and AND and then process //assertion- >new parent for same level is AND //if parent is XOR -> Add AND and then process assertion. at this level the parent will be AND //if parent is AND just process assertion if(IsOptionalL(pNextChild)) { if(parentName.Compare(WSPolicy::KWsPolicy) == 0) { CSenElement* pXor = AddXorElementL(assertionParent); CSenElement* pAnd = AddAndElementL(pXor); // aNormalAssertion = ProcessAssertionTermL(pNextChild, pAnd); } else if(parentName.Compare(WSPolicy::KAndCompositeAssertion) == 0) { CSenElement* parentNow = assertionParent; assertionParent = assertionParent->Parent(); CSenElement* policyParent= assertionParent->Parent(); CSenElement* pXor = AddXorElementL(policyParent); CSenElement* pAnd = AddAndElementL(pXor); // aNormalAssertion = ProcessAssertionTermL(pNextChild, pAnd); assertionParent = parentNow; } else if(parentName.Compare(WSPolicy::KXorCompositeAssertion) == 0) { } else { //probably error } } else { if(parentName.Compare(WSPolicy::KWsPolicy) == 0) { CSenElement* pXor = AddXorElementL(assertionParent); CSenElement* pAnd = AddAndElementL(pXor); assertionParent = pAnd; // assertionParent = ProcessAssertionTermL(pNextChild, pAnd); } else if(parentName.Compare(WSPolicy::KXorCompositeAssertion) == 0) { CSenElement* pXor = AddXorElementL(assertionParent); CSenElement* pAnd = AddAndElementL(pXor); // aNormalAssertion = ProcessAssertionTermL(pNextChild, pAnd); } else if(parentName.Compare(WSPolicy::KAndCompositeAssertion) == 0) { // aNormalAssertion = ProcessAssertionTermL(pNextChild, assertionParent); } else { CSenElement* pXor = AddXorElementL(assertionParent); CSenElement* pAnd = AddAndElementL(pXor); assertionParent = pAnd; // aNormalAssertion = ProcessAssertionTermL(pNextChild, pAnd); } ProcessAssertionTermL(pNextChild, assertionParent); } } i++; } return assertionParent; }
TInt CISO2022KRImplementation::ConvertToUnicode( CCnvCharacterSetConverter::TEndianness aDefaultEndiannessOfForeignCharacters, TDes16& aUnicode, const TDesC8& aForeign, TInt& aState, TInt& aNumberOfUnconvertibleCharacters, TInt& aIndexOfFirstByteOfFirstUnconvertibleCharacter) { TInt err; TInt ret = 0; TInt currPos = 0; TInt convPos = 0; TInt shiftInPos = KErrNotFound; TInt shiftOutPos = KErrNotFound; TInt shiftPos = KErrNotFound; TInt escPos = KErrNotFound; TPtrC8 currSegment; TPtrC8 convSegment; TBool changeState = EFalse; TUint outputConversionFlags = 0; TUint inputConversionFlags = CCnvCharacterSetConverter::EInputConversionFlagAppend; TInt numberOfUnconvertibleCharacters = 0; TInt indexOfFirstByteOfFirstUnconvertibleCharacter = 0; aNumberOfUnconvertibleCharacters = 0; while( currPos < aForeign.Length() ) { currSegment.Set( aForeign.Mid( currPos ) ); /* First change state if needed */ if( changeState ) { changeState = EFalse; if( (aState & KBitsForNonStandardStates) == KShiftedToKSCState ) { /* Switch back to default ASCII */ aState &= ~(KShiftedToKSCState); } else { /* Switch to KSC */ aState |= KShiftedToKSCState; } } /* Search for escape which should be skipped */ escPos = currSegment.Find( KLit8EscapeSequence ); /* Search for shift in byte */ shiftInPos = currSegment.Locate( SHIFT_IN_BYTE ); /* Search for shift out byte */ shiftOutPos = currSegment.Locate( SHIFT_OUT_BYTE ); /* Set shift pos according to found shift bytes */ if( shiftInPos == KErrNotFound && shiftOutPos == KErrNotFound ) { /* Neither found */ shiftPos = KErrNotFound; } else { if( (shiftInPos != KErrNotFound) && ((shiftInPos < shiftOutPos) || (shiftOutPos == KErrNotFound)) ) { /* shift in is nearer or shift out not found */ shiftPos = shiftInPos; /* Set state change if needed */ if( (aState & KBitsForNonStandardStates) == KShiftedToKSCState ) { changeState = ETrue; } } else { /* shift out must be nearer or shift in not fouind */ shiftPos = shiftOutPos; /* Set state change if needed */ if( (aState & KBitsForNonStandardStates) != KShiftedToKSCState ) { changeState = ETrue; } } } if( shiftPos == KErrNotFound ) { /* Shift byte not found, same coding for the rest of the data */ if( escPos == KErrNotFound ) { /* No escape sequence either, just convert the rest */ convSegment.Set( currSegment ); } } else if( ((escPos != KErrNotFound) && (shiftPos < escPos)) || (escPos == KErrNotFound) ) { /* Shift byte found and it comes before escape sequence or no escape sequence was found, convert data preceeding the shift byte if shift byte isn't the first character */ if( shiftPos == 0 ) { /* No data to convert preceeds the shift byte, just skip it and continue */ currPos += 1; continue; } convSegment.Set( currSegment.Left( shiftPos ) ); /* Clear to prevent convert to escape sequence */ escPos = KErrNotFound; } if( escPos != KErrNotFound ) { /* Escape sequence found before any shift bytes, clear possible state change and convert data preceeding the escape sequence if escape sequence is not at the beginning */ changeState = EFalse; if( escPos == 0 ) { /* No data to convert preceeds the escape sequence, just skip it continue */ currPos += KLit8EscapeSequence().Length(); continue; } convSegment.Set( currSegment.Left( escPos ) ); } if( (aState & KBitsForNonStandardStates) == KShiftedToKSCState ) { /* Convert KSC encoded */ HBufC8 *tmpForeign = NULL; if( (convSegment.Length() & 0x1) ) { /* KSC should have even amount of bytes */ ret = CCnvCharacterSetConverter::EErrorIllFormedInput; } else { convPos = 0; while( convPos < convSegment.Length() ) { TRAP( err, tmpForeign = HBufC8::NewL( KMaxSizeOfTmpBuffer ) ); if( err != KErrNone ) { User::Panic( _L("ISO-2022-KR"), err ); } if( convSegment.Length() < KMaxSizeOfTmpBuffer ) { /* Convert whole segment */ tmpForeign->Des().Copy( convSegment ); } else { /* Convert in chunks */ if( (convPos + KMaxSizeOfTmpBuffer) >= convSegment.Length() ) { /* Last chunk */ tmpForeign->Des().Copy( convSegment.Mid( convPos ) ); } else { tmpForeign->Des().Copy( convSegment.Mid( convPos, KMaxSizeOfTmpBuffer ) ); } } TUint8 *chars = (TUint8 *)tmpForeign->Des().Ptr(); for( TInt i = 0 ; i < tmpForeign->Length() ; i++ ) { /* Set highest bit in characters */ chars[i] |= 0x80; } numberOfUnconvertibleCharacters = 0; ret = CCnvCharacterSetConverter::DoConvertToUnicode( CnvCp949Table::ConversionData(), aDefaultEndiannessOfForeignCharacters, aUnicode, *tmpForeign, numberOfUnconvertibleCharacters, indexOfFirstByteOfFirstUnconvertibleCharacter, outputConversionFlags, inputConversionFlags ); if( numberOfUnconvertibleCharacters != 0 && aNumberOfUnconvertibleCharacters == 0 ) { /* First uncovertible found, set index relative to actual input buffer*/ aIndexOfFirstByteOfFirstUnconvertibleCharacter = (currPos + convPos + indexOfFirstByteOfFirstUnconvertibleCharacter); } aNumberOfUnconvertibleCharacters += numberOfUnconvertibleCharacters; if( ret < 0 ) { /* Some error, break the loop, errors are handled later */ delete tmpForeign; break; } if( ret > 0 ) { /* Not all were converted, fix return value to be relative to convSegment and break the loop */ ret = (convSegment.Length() - convPos - tmpForeign->Length() + ret); delete tmpForeign; break; } convPos += tmpForeign->Length(); delete tmpForeign; } } } else { /* Convert ASCII encoded by default, KSC can be used without setting highest bit */ numberOfUnconvertibleCharacters = 0; ret = CCnvCharacterSetConverter::DoConvertToUnicode( CnvCp949Table::ConversionData(), aDefaultEndiannessOfForeignCharacters, aUnicode, convSegment, numberOfUnconvertibleCharacters, indexOfFirstByteOfFirstUnconvertibleCharacter, outputConversionFlags, inputConversionFlags ); if( numberOfUnconvertibleCharacters != 0 && aNumberOfUnconvertibleCharacters == 0 ) { /* First uncovertible found, set index relative to actual input buffer*/ aIndexOfFirstByteOfFirstUnconvertibleCharacter = currPos + indexOfFirstByteOfFirstUnconvertibleCharacter; } aNumberOfUnconvertibleCharacters += numberOfUnconvertibleCharacters; } if( ret < 0 ) { /* Error during conversion */ return ret; } else if( ret > 0 ) { /* Not all characters where converted, return value indicating how many bytes in total are left unconverted */ return (aForeign.Length() - currPos - convSegment.Length() + ret); } /* Increase to skip converted data */ currPos += convSegment.Length(); if( escPos != KErrNotFound ) { /* Increase to skip escape sequence */ currPos += KLit8EscapeSequence().Length(); } else if( shiftPos != KErrNotFound ) { /* Increase to skip shift byte */ currPos += 1; } } return 0; }
CSenElement* CPolicyNormalizer::DuplicateAssertionBranchL(CSenElement* /*aParent*/, CSenElement* aDuplicatingPolicy) { //aDuplicatingPolicy is always an assertion //check if aDuplicatingPolicy have two assertions, if yes then divide the assertion in // T W O separate assertions //first check that if any of the two assertion themselve have // if XOR have multiple ANDs then check if XOR parent is an Assertion. // if yes then divide them in Two assertions. TPtrC8 asseryName = aDuplicatingPolicy->LocalName(); TInt childCount = HasChildL(aDuplicatingPolicy); if( childCount== 0) //There is NO CHILD NESTING in assertion return aDuplicatingPolicy; else if (childCount == 1) ////Assertion should always have only one <wsp:policy> element. { TBool deleted = EFalse; CSenElement* assertionPolicyElement = aDuplicatingPolicy->Child(0); //policy element TPtrC8 policyName = assertionPolicyElement->LocalName(); if(policyName.Compare(WSPolicy::KWsPolicy)== 0) { //now we should have XOR and AND elements CSenElement* assertionXORElement = assertionPolicyElement->Child(0); //XOR element //there should be only one XOR element (in normalize mode) TPtrC8 name1 = assertionXORElement->LocalName(); TInt AndElementCount = HasChildL(assertionXORElement); //If it has only one AND child element then nuthing to do here but if more then one element // then it means that assertion have nesting and should have a different branch. if(AndElementCount == 0) return aDuplicatingPolicy; else if(AndElementCount == 1) { ProcessAssertionBranchingL(assertionXORElement->Child(0)); } else if(AndElementCount > 1) { RPointerArray<CSenElement>& assertionXorChildren = assertionXORElement->ElementsL(); //AND elements TInt i = 0; while (i < AndElementCount) { //copy the root assertion to new tag // Take out the replacing tag // create two separate tag and replace them in the original and root copy tag CSenXmlElement* AND = (CSenXmlElement*)assertionXorChildren[i]; // ProcessAssertionBranchingL(AND); CSenXmlElement* rootAssertion = (CSenXmlElement*)FindRootAssertionL(AND); if (!IsChildOfElement(rootAssertion, AND)) { i++; continue; } //create a duplicate tag, //duplicating assertion TPtrC8 assertionCopyName = rootAssertion->LocalName(); TPtrC8 assertionCopyNsUri = rootAssertion->NamespaceURI(); CSenXmlElement* XORParent = (CSenXmlElement*)rootAssertion->Parent(); CSenElement* parentsBrandNewRootAssertion =AddAndElementL(XORParent->Parent()); CSenElement& newDuplicateAssertion = parentsBrandNewRootAssertion->AddElementL(assertionCopyNsUri,assertionCopyName); //cut and paste the second AND to duplicate newDuplicateAssertion.CopyFromL(*rootAssertion); DeleteAsertionIndexL(aDuplicatingPolicy, &newDuplicateAssertion, i); deleted = ETrue; // newDuplicateAssertion.SetParent(parentsBrandNewRootAssertion); //parentsBrandNewRootAssertion->ReplaceElementL(newDuplicateAssertion); //find from this new element the required assertion and then delete // all of the optins from it except the current i+1 ALL element i++; } if(deleted) { CSenElement* rootAssertion = FindRootAssertionL(aDuplicatingPolicy); CSenElement* AND = rootAssertion->Parent(); CSenElement* XOR = AND->Parent(); CSenElement* thisOne = XOR->RemoveElement(*AND); if(thisOne) iOrphanElements.Append(thisOne); // delete thisOne; //P DuplicateAssertionBranch A T H E T I C H A C K //now we have solved the first level nesting //our original policy is changed so now use the original policy and solve it again CSenElement* documentRoot = (CSenElement*)&XOR->Root(); ProcessAssertionBranchingL(documentRoot); } } } } else if(childCount > 1) { //this count is always one because its a child wsp:policy element, policy element //could have multiple XOR elements . If it comes here something is W R O N G } //here is the nesting problem. the assertion policy should have only one // Alternative = <XOR><AND>< --assertion-- ></AND></XOR> // NO TWO XORs are allowed here return aDuplicatingPolicy; }
TInt TTestActionSpec::TEFInit(RFs& aFs, const TDesC8& aInput, const TDesC8& aTestCaseID, TDesC8& aPrevTestCaseID, TBool& tefFile, TBool& runtest, TBool& inifile, TDes8& aScriptResult, TDes8& aActionType, const TDesC& aScriptPath, CConsoleBase& /*aConsole*/, Output& aOut) { TInt err = KErrNone; TInt actionTypePos=3; TBool scriptactionResultSet = EFalse; // TBool iniactionResultSet = EFalse; TBuf8<512> prevTestCaseID; TBuf8<512> prevTestDescription; // Checks if the first word from the script file is an error code // if(error code) // sets 'actionResult' to the relevent error code with the <return></return> tags TPtrC8 firstWord = Tefinput::ParseNthElement(aInput,1, err); if(err == KErrNone) { TInt tmpno; TLex8 lex8(firstWord); err = lex8.Val(tmpno); if(err != KErrNone) { actionTypePos = 4; err = Tefinput::ParseActionResult(firstWord, aScriptResult); scriptactionResultSet = ETrue; } } //1. Extracts the .ini file name from the .script file //2. Reads in the [section] name from the .script file //3. Generates .ini path from .script file path and .ini file name //4. Sets iActionBody with the info from .ini file TBuf<KMaxPath + KMaxFileName> iniFilePath; TBuf<512> iniFileData; TPtrC8 iniSectionData; TPtrC8 iniFileName = Tefinput::ParseNthElement(aInput,actionTypePos+1,err); if(err == KErrNone) { TPtrC8 iniSectionName = Tefinput::ParseNthElement(aInput,actionTypePos+2,err); if(err == KErrNone) { err = Tefinput::ParseiniPath(iniFileName, aScriptPath, iniFilePath); if(err == KErrNone) { aTestIniFilePtr.Assign(Tefinput::GetiniFile(aFs, iniFilePath, err)); // Load up our local RBuf ptr to takeover the management of the inifile data in Heap if(err == KErrNone) { TPtrC8 iniFile = aTestIniFilePtr.Ptr(); inifile = ETrue; err = Tefinput::ParseActionbody(iniFile, iniSectionName, iniSectionData); if(err == KErrNone) { TInt pos = 0; iActionBody.Set(Input::ParseElement(iniSectionData, KActionBodyStart, KActionBodyEnd, pos, err)); if (err == KErrNotFound) { aOut.writeString(_L("Error couldn't find actionbody in test case spec")); aOut.writeNewLine(); return err; } } } else { inifile = EFalse; } } } } else { inifile = EFalse; } TInt pos = 0; // Extracts info b/w <actionresult> </actionresult> tags // Sets iActionResult with info both from .script and .ini file TPtrC8 tempResult; TPtrC8 scriptResult; TInt resultlen ; if(scriptactionResultSet) { scriptResult.Set(aScriptResult); tempResult.Set(Input::ParseElement(iniSectionData, KActionResultStart, KActionResultEnd, pos, err)); if (err == KErrNone) { resultlen = scriptResult.Length() + tempResult.Length(); iniSectionResultBody.Create(tempResult,resultlen); iniSectionResultBody.Insert(0,scriptResult); iActionResult.Set(iniSectionResultBody); // iniactionResultSet = ETrue; } else { iniSectionResultBody.Create(scriptResult); iActionResult.Set(iniSectionResultBody); } } else { tempResult.Set(Input::ParseElement(iniSectionData, KActionResultStart, KActionResultEnd, pos, err)); err = Tefinput::GetActionResult(KErrNone, aScriptResult); if(err == KErrNone) { scriptResult.Set(aScriptResult); resultlen = tempResult.Length() + scriptResult.Length(); iniSectionResultBody.Create(tempResult, resultlen); iniSectionResultBody.Insert(0,aScriptResult); iActionResult.Set(iniSectionResultBody); } else { iniSectionResultBody.Create(tempResult); iActionResult.Set(iniSectionResultBody); } } // aPrevTestCaseID = aTestCaseID; //Sets iActionName with the @SYMTestCaseID if(!runtest) { iActionName.Set(aPrevTestCaseID); } else { iActionName.Set(aTestCaseID); } //Sets iActionType from .script file TBuf8<512> modifiedType; TBuf8<512> modifiedTypeTemp; TPtrC8 actionTypeTemp; TPtrC8 actionType; TPtrC8 TempType; iActionType.Set(Tefinput::ParseNthElement(aInput,actionTypePos,err)); if (err == KErrNone) { modifiedType.Copy(iActionType); modifiedType.Copy(Tefinput::TrimActionType(modifiedType, aActionType)); iActionType.Set(aActionType); } else { aOut.writeString(_L("Error couldn't find actiontype in test case spec")); aOut.writeNewLine(); return err; } iTefScript = tefFile; return KErrNone; }