NS_IMETHODIMP nsAppleMailImportModule::GetImportInterface(const char *aImportType, nsISupports **aInterface) { NS_ENSURE_ARG_POINTER(aImportType); NS_ENSURE_ARG_POINTER(aInterface); *aInterface = nsnull; nsresult rv = NS_ERROR_NOT_AVAILABLE; if (!strcmp(aImportType, "mail")) { nsCOMPtr<nsIImportMail> mail(do_CreateInstance(NS_APPLEMAILIMPL_CONTRACTID, &rv)); if (NS_SUCCEEDED(rv)) { nsCOMPtr<nsIImportService> impSvc(do_GetService(NS_IMPORTSERVICE_CONTRACTID, &rv)); if (NS_SUCCEEDED(rv)) { nsCOMPtr<nsIImportGeneric> generic; rv = impSvc->CreateNewGenericMail(getter_AddRefs(generic)); if (NS_SUCCEEDED(rv)) { nsAutoString name; rv = mBundle->GetStringFromID(APPLEMAILIMPORT_NAME, getter_Copies(name)); NS_ENSURE_SUCCESS(rv, rv); nsCOMPtr<nsISupportsString> nameString(do_CreateInstance(NS_SUPPORTS_STRING_CONTRACTID, &rv)); NS_ENSURE_SUCCESS(rv, rv); nameString->SetData(name); generic->SetData("name", nameString); generic->SetData("mailInterface", mail); rv = CallQueryInterface(generic, aInterface); } } } } return rv; }
static jobjectArray getNames(JNIEnv* env, UResourceBundle* namesBundle, bool months, NameType type, NameWidth width) { const char* typeKey = (type == REGULAR) ? "format" : "stand-alone"; const char* widthKey = (width == LONG) ? "wide" : "abbreviated"; UErrorCode status = U_ZERO_ERROR; ScopedResourceBundle formatBundle(ures_getByKey(namesBundle, typeKey, NULL, &status)); ScopedResourceBundle valuesBundle(ures_getByKey(formatBundle.get(), widthKey, NULL, &status)); if (U_FAILURE(status)) { return NULL; } // The months array has a trailing empty string. The days array has a leading empty string. int count = ures_getSize(valuesBundle.get()); jobjectArray result = env->NewObjectArray(count + 1, JniConstants::stringClass, NULL); env->SetObjectArrayElement(result, months ? count : 0, env->NewStringUTF("")); int arrayOffset = months ? 0 : 1; for (int i = 0; i < count; ++i) { int nameLength; const jchar* name = ures_getStringByIndex(valuesBundle.get(), i, &nameLength, &status); if (U_FAILURE(status)) { return NULL; } ScopedLocalRef<jstring> nameString(env, env->NewString(name, nameLength)); env->SetObjectArrayElement(result, arrayOffset++, nameString.get()); } return result; }
void ThatStar::setAttribute(const StringPimpl &name, const StringPimpl &value) throw(InternalProgrammerErrorException &) { LOG_BOT_METHOD("void ThatStar::setAttribute(const StringPimpl &name, const StringPimpl &value)"); String nameString(name.c_str()); String valueString(value.c_str()); logging("<Input> name:" + nameString); logging("<Input> value:" + valueString); try { if(nameString == "index" && (!valueString.empty())) { m_pimpl->m_index = lexical_cast<int>(valueString); } } catch(bad_lexical_cast &) { String msg("Index string is not numeric"); msg += valueString; m_pimpl->m_builder.getCallBacks().thatStarTagNumericConversionError(msg.c_str()); logging("Error, the cast to a numeric value failed"); } }
void RegistrySettingsManager::extractValueName(const TCHAR *key, StringStorage *keyName) { std::vector<TCHAR> nameString(_tcslen(key) + 1); memcpy(&nameString.front(), key, nameString.size()); TCHAR *token = _tcsrchr(&nameString.front(), _T('\\')); if (token != NULL) { keyName->setString(++token); } else { keyName->setString((TCHAR *)key); } }
void TestCasesHandler::TestCase::setAttribute(const StringPimpl &name, const StringPimpl &value) throw(InternalProgrammerErrorException &) { string nameString(name.c_str()); string valueString(value.c_str()); if(nameString == "name") { m_handler.outputln("Test Case name: " + valueString); } else { cout << "Error, wrong attribute" << endl; } }
void Bot::setAttribute(const StringPimpl &name, const StringPimpl &value) throw(InternalProgrammerErrorException &) { LOG_BOT_METHOD("void Bot::setAttribute(const StringPimpl &name, const StringPimpl &value)"); String nameString(name.c_str()); String valueString(value.c_str()); logging("<Input> name:" + nameString); logging("<Input> value:" + valueString); if(nameString == "name" && (!valueString.empty())) { m_pimpl->m_botPredicateName = valueString; } }
/** * \brief Get the name of the animation * Note: altered 24/09/07 to solve a D3DX memory leak caused because I was not releasing the set after getting it * \param index - the animation set index * \return the name * \author Keith Ditchburn \date 18 July 2005 */ std::string CXFileEntity::GetAnimationSetName(unsigned int index) { if (index>=m_numAnimationSets) return "Error: No set exists"; // Get the animation set LPD3DXANIMATIONSET set; m_animController->GetAnimationSet(m_currentAnimationSet, &set ); std::string nameString(set->GetName()); set->Release(); return nameString; }
void AIML::setAttribute(const StringPimpl &name, const StringPimpl &value) throw(InternalProgrammerErrorException &) { LOG_BOT_METHOD("void AIML::setAttribute(const StringPimpl &name, const StringPimpl &value)"); String nameString(name.c_str()); String valueString(value.c_str()); logging("<Input> name: " + nameString + "value: " + valueString); if(nameString == "version") { ///@todo use something else instead of this or just leave it out. // m_parser.setAIMLVersion(valueString); } else { //Ignore all the rest for right now. I don't care about any other attributes. } }
NS_IMETHODIMP nsDogbertProfileMigrator::GetSourceProfiles(nsISupportsArray** aResult) { nsresult rv; const char* profileDir = PR_GetEnv(PROFILE_HOME_ENVIRONMENT_VARIABLE); if (!profileDir) { profileDir = PR_GetEnv(HOME_ENVIRONMENT_VARIABLE); } if (!profileDir) return NS_ERROR_FAILURE; nsCAutoString profilePath(profileDir); profilePath += "/.netscape"; nsCOMPtr<nsILocalFile> profileFile; rv = NS_NewNativeLocalFile(profilePath, PR_TRUE, getter_AddRefs(profileFile)); NS_ENSURE_SUCCESS(rv, rv); nsCOMPtr<nsIFile> prefFile; rv = profileFile->Clone(getter_AddRefs(prefFile)); NS_ENSURE_SUCCESS(rv, rv); prefFile->AppendNative(NS_LITERAL_CSTRING("preferences.js")); PRBool exists; rv = prefFile->Exists(&exists); if (NS_FAILED(rv) || !exists) { return NS_ERROR_FAILURE; } mSourceProfile = profileFile; mProfiles = do_CreateInstance(NS_SUPPORTSARRAY_CONTRACTID, &rv); NS_ENSURE_SUCCESS(rv, rv); nsCOMPtr<nsISupportsString> nameString (do_CreateInstance("@mozilla.org/supports-string;1")); if (!nameString) return NS_ERROR_FAILURE; nameString->SetData(NS_LITERAL_STRING("Netscape 4.x")); mProfiles->AppendElement(nameString); NS_ADDREF(*aResult = mProfiles); return NS_OK; }
NS_IMETHODIMP nsDogbertProfileMigrator::GetSourceProfiles(nsISupportsArray** aResult) { if (!mProfiles) { nsresult rv; mProfiles = do_CreateInstance(NS_SUPPORTSARRAY_CONTRACTID, &rv); NS_ENSURE_SUCCESS(rv, rv); nsCOMPtr<nsIFile> regFile; rv = NS_GetSpecialDirectory(OLDREG_DIR, getter_AddRefs(regFile)); NS_ENSURE_SUCCESS(rv, rv); regFile->AppendNative(NS_LITERAL_CSTRING(OLDREG_NAME)); nsCAutoString path; rv = regFile->GetNativePath(path); NS_ENSURE_SUCCESS(rv, rv); if (NR_StartupRegistry()) return NS_ERROR_FAILURE; HREG reg = nsnull; REGENUM enumstate = 0; if (NR_RegOpen(path.get(), ®)) { NR_ShutdownRegistry(); return NS_ERROR_FAILURE; } char profileName[MAXREGNAMELEN]; while (!NR_RegEnumSubkeys(reg, ROOTKEY_USERS, &enumstate, profileName, MAXREGNAMELEN, REGENUM_CHILDREN)) { nsCOMPtr<nsISupportsString> nameString (do_CreateInstance("@mozilla.org/supports-string;1")); if (nameString) { nameString->SetData(NS_ConvertUTF8toUTF16(profileName)); mProfiles->AppendElement(nameString); } } } NS_IF_ADDREF(*aResult = mProfiles); return NS_OK; }
void Condition::setAttribute(const StringPimpl &name, const StringPimpl &value) throw(InternalProgrammerErrorException &) { LOG_BOT_METHOD("void Condition::setAttribute(const StringPimpl &name, const StringPimpl &value)"); String nameString(name.c_str()); String valueString(value.c_str()); if(nameString == "name") { m_pimpl->m_name = true; logging("Setting the m_predicateName to:" + nameString); m_pimpl->m_predicateName = valueString; } else if(nameString == "value") { m_pimpl->m_value = true; logging("Setting the m_aimlPattern to:" + valueString); m_pimpl->m_aimlPattern = valueString; } else { logging("Warning, empty name and/or empty value given or invalid values given"); } }
NS_IMETHODIMP nsOutlookImport::GetImportInterface(const char *pImportType, nsISupports **ppInterface) { NS_PRECONDITION(pImportType != nsnull, "null ptr"); if (! pImportType) return NS_ERROR_NULL_POINTER; NS_PRECONDITION(ppInterface != nsnull, "null ptr"); if (! ppInterface) return NS_ERROR_NULL_POINTER; *ppInterface = nsnull; nsresult rv; if (!strcmp(pImportType, "mail")) { // create the nsIImportMail interface and return it! nsIImportMail * pMail = nsnull; nsIImportGeneric *pGeneric = nsnull; rv = ImportOutlookMailImpl::Create(&pMail); if (NS_SUCCEEDED(rv)) { nsCOMPtr<nsIImportService> impSvc(do_GetService(NS_IMPORTSERVICE_CONTRACTID, &rv)); if (NS_SUCCEEDED(rv)) { rv = impSvc->CreateNewGenericMail(&pGeneric); if (NS_SUCCEEDED(rv)) { pGeneric->SetData("mailInterface", pMail); nsString name; nsOutlookStringBundle::GetStringByID(OUTLOOKIMPORT_NAME, name); nsCOMPtr<nsISupportsString> nameString (do_CreateInstance(NS_SUPPORTS_STRING_CONTRACTID, &rv)); if (NS_SUCCEEDED(rv)) { nameString->SetData(name); pGeneric->SetData("name", nameString); rv = pGeneric->QueryInterface(kISupportsIID, (void **)ppInterface); } } } } NS_IF_RELEASE(pMail); NS_IF_RELEASE(pGeneric); return rv; } if (!strcmp(pImportType, "addressbook")) { // create the nsIImportAddressBook interface and return it! nsIImportAddressBooks * pAddress = nsnull; nsIImportGeneric * pGeneric = nsnull; rv = ImportOutlookAddressImpl::Create(&pAddress); if (NS_SUCCEEDED(rv)) { nsCOMPtr<nsIImportService> impSvc(do_GetService(NS_IMPORTSERVICE_CONTRACTID, &rv)); if (NS_SUCCEEDED(rv)) { rv = impSvc->CreateNewGenericAddressBooks(&pGeneric); if (NS_SUCCEEDED(rv)) { pGeneric->SetData("addressInterface", pAddress); rv = pGeneric->QueryInterface(kISupportsIID, (void **)ppInterface); } } } NS_IF_RELEASE(pAddress); NS_IF_RELEASE(pGeneric); return rv; } if (!strcmp(pImportType, "settings")) { nsIImportSettings *pSettings = nsnull; rv = nsOutlookSettings::Create(&pSettings); if (NS_SUCCEEDED(rv)) pSettings->QueryInterface(kISupportsIID, (void **)ppInterface); NS_IF_RELEASE(pSettings); return rv; } return NS_ERROR_NOT_AVAILABLE; }
const SkRefPtr<SkPDFDict>& SkPDFDevice::getResourceDict() { if (fResourceDict.get() == NULL) { fResourceDict = new SkPDFDict; fResourceDict->unref(); // SkRefPtr and new both took a reference. if (fGraphicStateResources.count()) { SkRefPtr<SkPDFDict> extGState = new SkPDFDict(); extGState->unref(); // SkRefPtr and new both took a reference. for (int i = 0; i < fGraphicStateResources.count(); i++) { SkString nameString("G"); nameString.appendS32(i); extGState->insert( nameString.c_str(), new SkPDFObjRef(fGraphicStateResources[i]))->unref(); } fResourceDict->insert("ExtGState", extGState.get()); } if (fXObjectResources.count()) { SkRefPtr<SkPDFDict> xObjects = new SkPDFDict(); xObjects->unref(); // SkRefPtr and new both took a reference. for (int i = 0; i < fXObjectResources.count(); i++) { SkString nameString("X"); nameString.appendS32(i); xObjects->insert( nameString.c_str(), new SkPDFObjRef(fXObjectResources[i]))->unref(); } fResourceDict->insert("XObject", xObjects.get()); } if (fFontResources.count()) { SkRefPtr<SkPDFDict> fonts = new SkPDFDict(); fonts->unref(); // SkRefPtr and new both took a reference. for (int i = 0; i < fFontResources.count(); i++) { SkString nameString("F"); nameString.appendS32(i); fonts->insert(nameString.c_str(), new SkPDFObjRef(fFontResources[i]))->unref(); } fResourceDict->insert("Font", fonts.get()); } if (fShaderResources.count()) { SkRefPtr<SkPDFDict> patterns = new SkPDFDict(); patterns->unref(); // SkRefPtr and new both took a reference. for (int i = 0; i < fShaderResources.count(); i++) { SkString nameString("P"); nameString.appendS32(i); patterns->insert(nameString.c_str(), new SkPDFObjRef(fShaderResources[i]))->unref(); } fResourceDict->insert("Pattern", patterns.get()); } // For compatibility, add all proc sets (only used for output to PS // devices). const char procs[][7] = {"PDF", "Text", "ImageB", "ImageC", "ImageI"}; SkRefPtr<SkPDFArray> procSets = new SkPDFArray(); procSets->unref(); // SkRefPtr and new both took a reference. procSets->reserve(SK_ARRAY_COUNT(procs)); for (size_t i = 0; i < SK_ARRAY_COUNT(procs); i++) procSets->append(new SkPDFName(procs[i]))->unref(); fResourceDict->insert("ProcSet", procSets.get()); } return fResourceDict; }
//------------------------------------------------------------------------------ void UserInformation::insertName(std::wstring &str, MCONTACT user) const { // insert the user's name into the string str.replace(str.find(L"%u"), 2, nameString(user)); }
GeoDataDocument* MapQuestRunner::parse( const QByteArray &content ) const { QDomDocument xml; if ( !xml.setContent( content ) ) { mDebug() << "Cannot parse xml file with routing instructions."; return 0; } // mDebug() << xml.toString(2); QDomElement root = xml.documentElement(); GeoDataDocument* result = new GeoDataDocument(); result->setName( "MapQuest" ); GeoDataPlacemark* routePlacemark = new GeoDataPlacemark; routePlacemark->setName( "Route" ); GeoDataLineString* routeWaypoints = new GeoDataLineString; QDomNodeList shapePoints = root.elementsByTagName( "shapePoints" ); if ( shapePoints.size() == 1 ) { QDomNodeList geometry = shapePoints.at( 0 ).toElement().elementsByTagName( "latLng" ); for ( int i=0; i<geometry.size(); ++i ) { double const lat = geometry.item( i ).namedItem( "lat" ).toElement().text().toDouble(); double const lon = geometry.item( i ).namedItem( "lng" ).toElement().text().toDouble(); GeoDataCoordinates const position( lon, lat, 0.0, GeoDataCoordinates::Degree ); routeWaypoints->append( position ); } } routePlacemark->setGeometry( routeWaypoints ); QTime time; time = time.addSecs( root.elementsByTagName( "time" ).at( 0 ).toElement().text().toInt() ); qreal length = routeWaypoints->length( EARTH_RADIUS ); const QString name = nameString( "MQ", length, time ); const GeoDataExtendedData data = routeData( length, time ); routePlacemark->setExtendedData( data ); result->setName( name ); result->append( routePlacemark ); QMap<int,int> mapping; QDomNodeList maneuvers = root.elementsByTagName( "maneuverIndexes" ); if ( maneuvers.size() == 1 ) { maneuvers = maneuvers.at( 0 ).childNodes(); for ( int i=0; i<maneuvers.size(); ++i ) { mapping[i] = maneuvers.at( i ).toElement().text().toInt(); if ( mapping[i] == routeWaypoints->size() ) { --mapping[i]; } } } QDomNodeList instructions = root.elementsByTagName( "maneuver" ); unsigned int const lastInstruction = qMax<int>( 0, instructions.length()-1 ); // ignore the last 'Welcome to xy' instruction for ( unsigned int i = 0; i < lastInstruction; ++i ) { QDomElement node = instructions.item( i ).toElement(); QDomNodeList maneuver = node.elementsByTagName( "turnType" ); QDomNodeList textNodes = node.elementsByTagName( "narrative" ); QDomNodeList points = node.elementsByTagName( "startPoint" ); QDomNodeList streets = node.elementsByTagName( "streets" ); Q_ASSERT( mapping.contains( i ) ); if ( textNodes.size() == 1 && maneuver.size() == 1 && points.size() == 1 && mapping.contains( i ) ) { GeoDataPlacemark* instruction = new GeoDataPlacemark; instruction->setName( textNodes.at( 0 ).toElement().text() ); GeoDataExtendedData extendedData; GeoDataData turnType; turnType.setName( "turnType" ); turnType.setValue( maneuverType( maneuver.at( 0 ).toElement().text().toInt() ) ); extendedData.addValue( turnType ); if ( streets.size() == 1 ) { GeoDataData roadName; roadName.setName( "roadName" ); roadName.setValue( streets.at( 0 ).toElement().text() ); extendedData.addValue( roadName ); } instruction->setExtendedData( extendedData ); int const start = mapping[i]; int const end = mapping.contains(i+1) ? mapping[i+1] : routeWaypoints->size()-1; if ( start >= 0 && start < routeWaypoints->size() && end < routeWaypoints->size() ) { instruction->setName( textNodes.item( 0 ).toElement().text() ); GeoDataLineString *lineString = new GeoDataLineString; for ( int j=start; j<=end; ++j ) { *lineString << GeoDataCoordinates( routeWaypoints->at( j ).longitude(), routeWaypoints->at( j ).latitude() ); } if ( !lineString->isEmpty() ) { instruction->setGeometry( lineString ); result->append( instruction ); } } } } if ( routeWaypoints->size() < 1 ) { delete result; result = 0; } return result; }
// Method to store load ocean tide harmonics data in this class' // data map void BLQDataReader::loadData(void) throw( FFStreamError, gpstk::StringUtils::StringException ) { // Counter of valid data lines int row(0); // We will store here the station name std::string nameString(""); // Declare structure to store tide harmonics data BLQDataReader::tideData data; // Do this until end-of-file reached or something else happens while(1) { try { if(row>6) { // If row>6, all station harmonics are already read, // so let's store tide data in data map setData(nameString, data); // Clear harmonics data data.harmonics.resize(6,11,0.0); // Reset counter to get data from an additional station row = 0; } std::string line; formattedGetLine(line, true); // If line is too long, we throw an exception if (line.size()>255) { FFStreamError e("Line too long"); GPSTK_THROW(e); } // Let's find and strip comments, wherever they are if( StringUtils::firstWord(line)[0] == '$' ) { formattedGetLine(line, true); } std::string::size_type idx = line.find('$'); if( !(idx == std::string::npos) ) { line = line.substr(0, idx); } // Remove trailing and leading blanks line = StringUtils::strip(line); // Skip blank lines if (line.size()==0) { continue; } // Let's start to get data out of file // If this is the first valid line, it contains station name if (row==0) { nameString = StringUtils::upperCase(StringUtils::stripFirstWord(line)); ++row; continue; } else { // 2nd to 7th valid lines contains tide harmonics if ( (row>0) && (row<=6) ) { for(int col=0; col<11; col++) { std::string value(StringUtils::stripFirstWord(line)); data.harmonics((row-1),col) = StringUtils::asDouble(value); } ++row; continue; } } } // End of try block catch (EndOfFile& e) { // We should close this data stream before returning (*this).close(); return; } catch (...) { // We should close this data stream before returning (*this).close(); return; } } // End of 'while(1)...' } // End of method 'BLQDataReader::loadData()'
TrackSupplier* FilePlaylistItem::CreateTrackSupplier() const { MediaFileTrackSupplier* supplier = new(std::nothrow) MediaFileTrackSupplier(); if (supplier == NULL) return NULL; for (vector<entry_ref>::size_type i = 0; i < fRefs.size(); i++) { BMediaFile* mediaFile = new(std::nothrow) BMediaFile(&fRefs[i]); if (mediaFile == NULL) { delete supplier; return NULL; } if (supplier->AddMediaFile(mediaFile) != B_OK) delete mediaFile; } for (vector<entry_ref>::size_type i = 0; i < fImageRefs.size(); i++) { BBitmap* bitmap = BTranslationUtils::GetBitmap(&fImageRefs[i]); if (bitmap == NULL) continue; if (supplier->AddBitmap(bitmap) != B_OK) delete bitmap; } // Search for subtitle files in the same folder // TODO: Error checking BEntry entry(&fRefs[0], true); char originalName[B_FILE_NAME_LENGTH]; entry.GetName(originalName); BString nameWithoutExtension(originalName); int32 extension = nameWithoutExtension.FindLast('.'); if (extension > 0) nameWithoutExtension.Truncate(extension); BPath path; entry.GetPath(&path); path.GetParent(&path); BDirectory directory(path.Path()); while (directory.GetNextEntry(&entry) == B_OK) { char name[B_FILE_NAME_LENGTH]; if (entry.GetName(name) != B_OK) continue; BString nameString(name); if (nameString == originalName) continue; if (nameString.IFindFirst(nameWithoutExtension) < 0) continue; BFile file(&entry, B_READ_ONLY); if (file.InitCheck() != B_OK) continue; int32 pos = nameString.FindLast('.'); if (pos < 0) continue; BString extensionString(nameString.String() + pos + 1); extensionString.ToLower(); BString language = "default"; if (pos > 1) { int32 end = pos; while (pos > 0 && *(nameString.String() + pos - 1) != '.') pos--; language.SetTo(nameString.String() + pos, end - pos); } if (extensionString == "srt") { SubTitles* subTitles = new(std::nothrow) SubTitlesSRT(&file, language.String()); if (subTitles != NULL && !supplier->AddSubTitles(subTitles)) delete subTitles; } } return supplier; }
GeoDataDocument *CycleStreetsRunner::parse( const QByteArray &content ) const { QDomDocument xml; if ( !xml.setContent( content ) ) { mDebug() << "Cannot parse xml file with routing instructions."; return 0; } GeoDataDocument *result = new GeoDataDocument(); result->setName( "CycleStreets" ); GeoDataPlacemark *routePlacemark = new GeoDataPlacemark; routePlacemark->setName( "Route" ); GeoDataLineString *routeWaypoints = new GeoDataLineString; QDomNodeList features = xml.elementsByTagName( "gml:featureMember" ); if ( features.isEmpty() ) { return 0; } QDomElement route = features.at( 0 ).toElement().firstChild().toElement(); QDomElement lineString = route.elementsByTagName( "gml:LineString" ).at( 0 ).toElement(); QDomElement coordinates = lineString.toElement().elementsByTagName( "gml:coordinates" ).at( 0 ).toElement(); QStringList coordinatesList = coordinates.text().split( ' ' ); QStringList::iterator iter = coordinatesList.begin(); QStringList::iterator end = coordinatesList.end(); for( ; iter != end; ++iter) { QStringList coordinate = iter->split(','); if ( coordinate.size() == 2 ) { double const lon = coordinate.at( 0 ).toDouble(); double const lat = coordinate.at( 1 ).toDouble(); GeoDataCoordinates const position( lon, lat, 0.0, GeoDataCoordinates::Degree ); routeWaypoints->append( position ); } } routePlacemark->setGeometry( routeWaypoints ); QDomElement durationElement = route.elementsByTagName( "cs:time" ).at(0).toElement(); QTime duration; duration = duration.addSecs( durationElement.text().toInt() ); qreal length = routeWaypoints->length( EARTH_RADIUS ); const QString name = nameString( "CS", length, duration ); const GeoDataExtendedData data = routeData( length, duration ); routePlacemark->setExtendedData( data ); result->setName( name ); result->append( routePlacemark ); int i; for ( i = 1; i < features.count() && features.at( i ).firstChildElement().tagName() != "cs:segment"; ++i ); for ( ; i < features.count(); ++i) { QDomElement segment = features.at( i ).toElement(); QString name = segment.elementsByTagName( "cs:name" ).at( 0 ).toElement().text(); QString maneuver = segment.elementsByTagName( "cs:turn" ).at( 0 ).toElement().text(); QStringList points = segment.elementsByTagName( "cs:points" ).at( 0 ).toElement().text().split( ' ' ); QStringList const elevation = segment.elementsByTagName( "cs:elevations" ).at( 0 ).toElement().text().split( ',' ); GeoDataPlacemark *instructions = new GeoDataPlacemark; QString instructionName; if ( !maneuver.isEmpty() ) { instructionName = maneuver.left( 1 ).toUpper() + maneuver.mid( 1 ); } else { instructionName = "Straight"; } if ( name != "Short un-named link" && name != "Un-named link" ){ instructionName.append( " into " + name ); } instructions->setName( instructionName ); GeoDataExtendedData extendedData; GeoDataData turnType; turnType.setName( "turnType" ); turnType.setValue( maneuverType( maneuver ) ); extendedData.addValue( turnType ); instructions->setExtendedData( extendedData ); GeoDataLineString *lineString = new GeoDataLineString; QStringList::iterator iter = points.begin(); QStringList::iterator end = points.end(); for ( int j=0; iter != end; ++iter, ++j ) { QStringList coordinate = iter->split( ',' ); if ( coordinate.size() == 2 ) { double const lon = coordinate.at( 0 ).toDouble(); double const lat = coordinate.at( 1 ).toDouble(); double const alt = j < elevation.size() ? elevation[j].toDouble() : 0.0; lineString->append( GeoDataCoordinates( lon, lat, alt, GeoDataCoordinates::Degree ) ); } } instructions->setGeometry( lineString ); result->append( instructions ); } return result; }
GeoDataDocument* OpenRouteServiceRunner::parse( const QByteArray &content ) const { QDomDocument xml; if ( !xml.setContent( content ) ) { mDebug() << "Cannot parse xml file with routing instructions."; return nullptr; } QDomElement root = xml.documentElement(); GeoDataDocument* result = new GeoDataDocument(); result->setName(QStringLiteral("OpenRouteService")); QDomNodeList errors = root.elementsByTagName(QStringLiteral("xls:Error")); if ( errors.size() > 0 ) { return nullptr; // Returning early because fallback routing providers are used now // The code below can be used to parse OpenGis errors reported by ORS // and may be useful in the future for (int i=0 ; i < errors.length(); ++i ) { QDomNode node = errors.item( i ); QString errorMessage = node.attributes().namedItem(QStringLiteral("message")).nodeValue(); QRegExp regexp = QRegExp( "^(.*) Please Check your Position: (-?[0-9]+.[0-9]+) (-?[0-9]+.[0-9]+) !" ); if ( regexp.indexIn( errorMessage ) == 0 ) { if ( regexp.capturedTexts().size() == 4 ) { GeoDataPlacemark* placemark = new GeoDataPlacemark; placemark->setName( regexp.capturedTexts().at( 1 ) ); GeoDataCoordinates position; position.setLongitude( regexp.capturedTexts().at( 2 ).toDouble(), GeoDataCoordinates::Degree ); position.setLatitude( regexp.capturedTexts().at( 3 ).toDouble(), GeoDataCoordinates::Degree ); placemark->setCoordinate( position ); result->append( placemark ); } } else { mDebug() << "Error message " << errorMessage << " not parsable."; /** @todo: How to handle this now with plugins? */ // QString message = tr( "Sorry, a problem occurred when calculating the route. Try adjusting start and destination points." ); // QPointer<QMessageBox> messageBox = new QMessageBox( QMessageBox::Warning, "Route Error", message ); // messageBox->setDetailedText( errorMessage ); // messageBox->exec(); // delete messageBox; } } } GeoDataPlacemark* routePlacemark = new GeoDataPlacemark; routePlacemark->setName(QStringLiteral("Route")); QTime time; QDomNodeList summary = root.elementsByTagName(QStringLiteral("xls:RouteSummary")); if ( summary.size() > 0 ) { QDomNodeList timeNodeList = summary.item(0).toElement().elementsByTagName(QStringLiteral("xls:TotalTime")); if ( timeNodeList.size() == 1 ) { QRegExp regexp = QRegExp( "^P(?:(\\d+)D)?T(?:(\\d+)H)?(?:(\\d+)M)?(\\d+)S" ); if ( regexp.indexIn( timeNodeList.item( 0 ).toElement().text() ) == 0 ) { QStringList matches = regexp.capturedTexts(); unsigned int hours( 0 ), minutes( 0 ), seconds( 0 ); switch ( matches.size() ) { case 5: // days = regexp.cap( matches.size() - 4 ).toInt(); // Intentionally no break case 4: hours = regexp.cap( matches.size() - 3 ).toInt(); // Intentionally no break case 3: minutes = regexp.cap( matches.size() - 2 ).toInt(); // Intentionally no break case 2: seconds = regexp.cap( matches.size() - 1 ).toInt(); break; default: mDebug() << "Unable to parse time string " << timeNodeList.item( 0 ).toElement().text(); } time = QTime( hours, minutes, seconds, 0 ); } } } GeoDataLineString* routeWaypoints = new GeoDataLineString; QDomNodeList geometry = root.elementsByTagName(QStringLiteral("xls:RouteGeometry")); if ( geometry.size() > 0 ) { QDomNodeList waypoints = geometry.item( 0 ).toElement().elementsByTagName( "gml:pos" ); for (int i=0 ; i < waypoints.length(); ++i ) { QDomNode node = waypoints.item( i ); const QStringList content = node.toElement().text().split(QLatin1Char(' ')); if ( content.length() == 2 ) { GeoDataCoordinates position; position.setLongitude( content.at( 0 ).toDouble(), GeoDataCoordinates::Degree ); position.setLatitude( content.at( 1 ).toDouble(), GeoDataCoordinates::Degree ); routeWaypoints->append( position ); } } } routePlacemark->setGeometry( routeWaypoints ); qreal length = routeWaypoints->length( EARTH_RADIUS ); const QString name = nameString( "ORS", length, time ); const GeoDataExtendedData data = routeData( length, time ); routePlacemark->setExtendedData( data ); result->setName( name ); result->append( routePlacemark ); QDomNodeList instructionList = root.elementsByTagName(QStringLiteral("xls:RouteInstructionsList")); if ( instructionList.size() > 0 ) { QDomNodeList instructions = instructionList.item(0).toElement().elementsByTagName(QStringLiteral("xls:RouteInstruction")); for (int i=0 ; i < instructions.length(); ++i ) { QDomElement node = instructions.item( i ).toElement(); QDomNodeList textNodes = node.elementsByTagName(QStringLiteral("xls:Instruction")); QDomNodeList positions = node.elementsByTagName(QStringLiteral("gml:pos")); if ( textNodes.size() > 0 && positions.size() > 0 ) { const QStringList content = positions.at(0).toElement().text().split(QLatin1Char(' ')); if ( content.length() == 2 ) { GeoDataLineString *lineString = new GeoDataLineString; for( int i = 0; i < positions.count(); ++i ) { const QStringList pointList = positions.at(i).toElement().text().split(QLatin1Char(' ')); GeoDataCoordinates position; position.setLongitude( pointList.at( 0 ).toDouble(), GeoDataCoordinates::Degree ); position.setLatitude( pointList.at( 1 ).toDouble(), GeoDataCoordinates::Degree ); lineString->append( position ); } GeoDataPlacemark* instruction = new GeoDataPlacemark; QString const text = textNodes.item( 0 ).toElement().text().remove(QRegExp("<[^>]*>")); GeoDataExtendedData extendedData; GeoDataData turnTypeData; turnTypeData.setName(QStringLiteral("turnType")); QString road; RoutingInstruction::TurnType turnType = parseTurnType( text, &road ); turnTypeData.setValue( turnType ); extendedData.addValue( turnTypeData ); if ( !road.isEmpty() ) { GeoDataData roadName; roadName.setName(QStringLiteral("roadName")); roadName.setValue( road ); extendedData.addValue( roadName ); } QString const instructionText = turnType == RoutingInstruction::Unknown ? text : RoutingInstruction::generateRoadInstruction( turnType, road ); instruction->setName( instructionText ); instruction->setExtendedData( extendedData ); instruction->setGeometry( lineString ); result->append( instruction ); } } } } return result; }
void PeerInformationSocket::processPacket(const QHostAddress &address, const QByteArray &packetArray) { const char *data = packetArray.constData(); CITP_PINF_PLoc *packet = (CITP_PINF_PLoc*)data; // CITP header if (packet->CITPPINFHeader.CITPHeader.Cookie != COOKIE_CITP) { return; } if (packet->CITPPINFHeader.CITPHeader.VersionMajor != 0x01) { qDebug() << "Invalid VersionMajor value:" << packet->CITPPINFHeader.CITPHeader.VersionMajor; return; } if (packet->CITPPINFHeader.CITPHeader.VersionMinor != 0x00) { qDebug() << "Invalid VersionMinor value:" << packet->CITPPINFHeader.CITPHeader.VersionMinor; return; } //packet->CITPPINFHeader.CITPHeader.Reserved[0] = 0x00; //packet->CITPPINFHeader.CITPHeader.Reserved[1] = 0x00; //packet->CITPPINFHeader.CITPHeader.MessageSize = bufferLen; //packet->CITPPINFHeader.CITPHeader.MessagePartCount = 0x01; //packet->CITPPINFHeader.CITPHeader.MessagePart = 0x01; // XXX - doc says 0-based? if (packet->CITPPINFHeader.CITPHeader.ContentType != COOKIE_PINF) { return; } // PINF header if (packet->CITPPINFHeader.ContentType != COOKIE_PINF_PLOC) { return; } // PLoc data quint16 listeningPort = packet->ListeningTCPPort; if (0 == listeningPort) { // XXX - uncomment if we don't want non-listeners //return; } // type int offset = sizeof(struct CITP_PINF_PLoc); QString typeString(packetArray.constData()+offset); //memcpy(buffer + offset, typeString.toAscii().constData(), typeString.size()); // name offset += typeString.size() + 1; QString nameString(packetArray.constData()+offset); //memcpy(buffer + offset, name.toAscii().constData(), name.size()); // state offset += nameString.size() + 1; QString stateString(packetArray.constData()+offset); //memcpy(buffer + offset, state.toAscii().constData(), state.size()); // XXX - these strings are going out of scope because they are implicitly shared // from the original buffer addPeer(address, listeningPort, typeString, nameString, stateString); }