std::istream* HTTPStreamFactory::open(const URI& uri) { poco_assert (uri.getScheme() == "http"); URI resolvedURI(uri); URI proxyUri; HTTPClientSession* pSession = 0; HTTPResponse res; bool retry = false; bool authorize = false; std::string username; std::string password; try { do { if (!pSession) { pSession = new HTTPClientSession(resolvedURI.getHost(), resolvedURI.getPort()); if (proxyUri.empty()) pSession->setProxy(_proxyHost, _proxyPort); else pSession->setProxy(proxyUri.getHost(), proxyUri.getPort()); pSession->setProxyCredentials(_proxyUsername, _proxyPassword); } std::string path = resolvedURI.getPathAndQuery(); if (path.empty()) path = "/"; HTTPRequest req(HTTPRequest::HTTP_GET, path, HTTPMessage::HTTP_1_1); if (authorize) { HTTPCredentials::extractCredentials(uri, username, password); HTTPCredentials cred(username, password); cred.authenticate(req, res); } pSession->sendRequest(req); std::istream& rs = pSession->receiveResponse(res); bool moved = (res.getStatus() == HTTPResponse::HTTP_MOVED_PERMANENTLY || res.getStatus() == HTTPResponse::HTTP_FOUND || res.getStatus() == HTTPResponse::HTTP_SEE_OTHER || res.getStatus() == HTTPResponse::HTTP_TEMPORARY_REDIRECT); if (moved) { resolvedURI.resolve(res.get("Location")); if (!username.empty()) { resolvedURI.setUserInfo(username + ":" + password); } throw URIRedirection(resolvedURI.toString()); } else if (res.getStatus() == HTTPResponse::HTTP_OK) { return new HTTPResponseStream(rs, pSession); } else if (res.getStatus() == HTTPResponse::HTTP_USEPROXY && !retry) { // The requested resource MUST be accessed through the proxy // given by the Location field. The Location field gives the // URI of the proxy. The recipient is expected to repeat this // single request via the proxy. 305 responses MUST only be generated by origin servers. // only use for one single request! proxyUri.resolve(res.get("Location")); delete pSession; pSession = 0; retry = true; // only allow useproxy once } else if (res.getStatus() == HTTPResponse::HTTP_UNAUTHORIZED && !authorize) { authorize = true; retry = true; Poco::NullOutputStream null; Poco::StreamCopier::copyStream(rs, null); } else throw HTTPException(res.getReason(), uri.toString()); } while (retry); throw HTTPException("Too many redirects", uri.toString()); } catch (...) { delete pSession; throw; } }
void KML_Placemark::build( const Config& conf, KMLContext& cx ) { Style style; if ( conf.hasValue("styleurl") ) { // process a "stylesheet" style const Style* ref_style = cx._sheet->getStyle( conf.value("styleurl"), false ); if ( ref_style ) style = *ref_style; } else if ( conf.hasChild("style") ) { // process an "inline" style KML_Style kmlStyle; kmlStyle.scan( conf.child("style"), cx ); style = cx._activeStyle; } // parse the geometry. the placemark must have geometry to be valid. The // geometry parse may optionally specify an altitude mode as well. KML_Geometry geometry; geometry.build(conf, cx, style); // KML's default altitude mode is clampToGround. AltitudeMode altMode = ALTMODE_RELATIVE; AltitudeSymbol* altSym = style.get<AltitudeSymbol>(); if ( !altSym ) { altSym = style.getOrCreate<AltitudeSymbol>(); altSym->clamping() = AltitudeSymbol::CLAMP_RELATIVE_TO_TERRAIN; } else if ( !altSym->clamping().isSetTo(AltitudeSymbol::CLAMP_RELATIVE_TO_TERRAIN) ) { altMode = ALTMODE_ABSOLUTE; } if ( geometry._geom.valid() && geometry._geom->getTotalPointCount() > 0 ) { Geometry* geom = geometry._geom.get(); GeoPoint position(cx._srs.get(), geom->getBounds().center(), altMode); bool isPoly = geom->getComponentType() == Geometry::TYPE_POLYGON; bool isPoint = geom->getComponentType() == Geometry::TYPE_POINTSET; // read in the Marker if there is one. URI markerURI; osg::ref_ptr<osg::Image> markerImage; osg::ref_ptr<osg::Node> markerModel; MarkerSymbol* marker = style.get<MarkerSymbol>(); if ( marker && marker->url().isSet() ) { if ( marker->isModel() == false ) { markerImage = marker->getImage( *cx._options->iconMaxSize() ); } else { markerURI = URI( marker->url()->eval(), marker->url()->uriContext() ); markerModel = markerURI.getNode(); // We can't leave the marker symbol in the style, or the GeometryCompiler will // think we want to do Point-model substitution. So remove it. A bit of a hack if ( marker ) style.removeSymbol(marker); } } std::string text = conf.hasValue("name") ? conf.value("name") : ""; AnnotationNode* fNode = 0L; AnnotationNode* pNode = 0L; // place a 3D model: if ( markerModel.valid() ) { LocalGeometryNode* lg = new LocalGeometryNode(cx._mapNode, markerModel.get(), style, false); lg->setPosition( position ); if ( marker ) { if ( marker->scale().isSet() ) { float scale = marker->scale()->eval(); lg->setScale( osg::Vec3f(scale,scale,scale) ); } if ( marker->orientation().isSet() ) { // lg->setRotation( ); } } fNode = lg; //Feature* feature = new Feature(geometry._geom.get(), cx._srs.get(), style); //fNode = new FeatureNode( cx._mapNode, feature, false ); } // Place node (icon + text) or Label node (text only) else if ( marker || geometry._geom->getTotalPointCount() == 1 ) { if ( !markerImage.valid() ) { markerImage = cx._options->defaultIconImage().get(); if ( !markerImage.valid() ) { markerImage = cx._options->defaultIconURI()->getImage(); } } if ( !style.get<TextSymbol>() && cx._options->defaultTextSymbol().valid() ) { style.addSymbol( cx._options->defaultTextSymbol().get() ); } if ( markerImage.valid() ) pNode = new PlaceNode( cx._mapNode, position, markerImage.get(), text, style ); else pNode = new LabelNode( cx._mapNode, position, text, style ); } if ( geometry._geom->getTotalPointCount() > 1 ) { const ExtrusionSymbol* ex = style.get<ExtrusionSymbol>(); const AltitudeSymbol* alt = style.get<AltitudeSymbol>(); if ( style.get<MarkerSymbol>() ) style.removeSymbol(style.get<MarkerSymbol>()); bool draped = isPoly && ex == 0L && (alt == 0L || alt->clamping() == AltitudeSymbol::CLAMP_TO_TERRAIN); // Make a feature node; drape if we're not extruding. GeometryCompilerOptions options; options.clustering() = false; Feature* feature = new Feature(geometry._geom.get(), cx._srs.get(), style); fNode = new FeatureNode( cx._mapNode, feature, draped, options ); if ( !ex ) { fNode->getOrCreateStateSet()->setMode(GL_LIGHTING, 0); } } if ( pNode && fNode ) { osg::Group* group = new osg::Group(); group->addChild( fNode ); group->addChild( pNode ); cx._groupStack.top()->addChild( group ); if ( cx._options->declutter() == true ) Decluttering::setEnabled( pNode->getOrCreateStateSet(), true ); KML_Feature::build( conf, cx, pNode ); KML_Feature::build( conf, cx, fNode ); } else if ( pNode ) { if ( cx._options->iconAndLabelGroup().valid() ) { cx._options->iconAndLabelGroup()->addChild( pNode ); } else { cx._groupStack.top()->addChild( pNode ); if ( cx._options->declutter() == true ) Decluttering::setEnabled( pNode->getOrCreateStateSet(), true ); } KML_Feature::build( conf, cx, pNode ); } else if ( fNode ) { cx._groupStack.top()->addChild( fNode ); KML_Feature::build( conf, cx, fNode ); } } }
// This function will take a resolved URI and create a version of it that is relative to // another existing URI. The new URI is stored in the "originalURI" bool URI::makeRelativeTo ( const URI& relativeToURI, bool ignoreCase) { // Can only do this function if both URIs have the same scheme and authority if (mScheme != relativeToURI.mScheme || mAuthority != relativeToURI.mAuthority) return false; // advance till we find a segment that doesn't match WideString thisPathWideSring = StringUtils::utf8String2WideString(getPath()); WideString relativeToPathWideSring = StringUtils::utf8String2WideString(relativeToURI.getPath()); const wchar_t *this_path = thisPathWideSring.c_str(); const wchar_t *relativeTo_path = relativeToPathWideSring.c_str(); const wchar_t *this_slash = this_path; const wchar_t *relativeTo_slash = relativeTo_path; /* const char *this_path = getPath().c_str(); const char *relativeTo_path = relativeToURI.getPath().c_str(); const char *this_slash = this_path; const char *relativeTo_slash = relativeTo_path; */ while( *this_path ) { if ( ignoreCase ) { wchar_t characters[3]; characters[0] = *this_path; characters[1] = *relativeTo_path; characters[2] = 0; boost::to_lower(characters); if ( characters[0] != characters[1] ) break; } else { if (*this_path != *relativeTo_path) break; } if(*this_path == '/') { this_slash = this_path; relativeTo_slash = relativeTo_path; } this_path++; relativeTo_path++; } // Decide how many ../ segments are needed (Filepath should always end in a /) int segment_count = 0; relativeTo_slash++; while(*relativeTo_slash != 0) { if(*relativeTo_slash == '/') segment_count ++; relativeTo_slash++; } this_slash++; String newPath; if ( segment_count == 0 ) { newPath = "./"; } else { for (int i = 0; i < segment_count; i++) newPath += "../"; } WideString thisSlashWideString(this_slash); newPath += StringUtils::wideString2utf8String(thisSlashWideString); set("", "", newPath, mQuery, mFragment, 0/*relativeToURI*/); return true; }
bool OAuth2SessionLogin::handlePage(HTTP::WebContext &ctx, ostream &stream, const URI &uri) { HTTP::Connection &con = ctx.getConnection(); HTTP::Request &request = con.getRequest(); HTTP::Response &response = con.getResponse(); ctx.setDynamic(); // Don't cache // Force secure if (!con.isSecure()) THROWCS("Cannot logon via insecure port", HTTP::StatusCode::HTTP_UNAUTHORIZED); // Get session ID string sid = request.findCookie(sessionManager->getSessionCookie()); if (sid.empty() && uri.has("state")) sid = uri.get("state"); HTTP::SessionPtr session = sessionManager->findSession(ctx, sid); try { if (session.isNull() || (uri.has("state") && uri.get("state") != session->getID()) || (!uri.has("state") && session->getUser().empty())) { session = sessionManager->openSession(ctx); sid = session->getID(); URI redirectURL = auth->getRedirectURL(uri.getPath(), sid); response.redirect(redirectURL); } else if (session->getUser().empty()) { // TODO Make sure session is not very old URI postURI = auth->getVerifyURL(uri, sid); LOG_DEBUG(5, "Token URI: " << postURI); // Extract query data string data = postURI.getQuery(); postURI.setQuery(""); // Verify authorization with OAuth2 server HTTP::Transaction tran(sslCtx); tran.post(postURI, data.data(), data.length(), "application/x-www-form-urlencoded", 1.0); // Read response tran.receiveHeader(); JSON::ValuePtr token = JSON::Reader(tran).parse(); LOG_DEBUG(5, "Token Response: \n" << tran.getResponse() << *token); // Verify token string accessToken = auth->verifyToken(token); // Get profile URI profileURL = auth->getProfileURL(accessToken); HTTP::Transaction tran2(sslCtx); tran2.get(profileURL); // Read response tran2.receiveHeader(); JSON::ValuePtr profile = JSON::Reader(tran2).parse(); // Process profile string email = profile->getString("email"); if (!profile->getBoolean("email_verified")) THROWCS("Email not verified", HTTP::StatusCode::HTTP_UNAUTHORIZED); session->setUser(email); LOG_INFO(1, "Authorized: " << email); // Final redirect to remove auth parameters response.redirect(uri.getPath()); } else return false; // Already authorized // Make sure session cookie is set sessionManager->setSessionCookie(ctx); } catch (...) { // Close session on error if (!sid.empty()) sessionManager->closeSession(ctx, sid); throw; } return true; }
/** override */ Status initialize( const osgDB::Options* dbOptions ) { osg::ref_ptr<const Profile> result; char sep = _options.url()->full().find_first_of('?') == std::string::npos? '?' : '&'; URI capUrl = _options.capabilitiesUrl().value(); if ( capUrl.empty() ) { capUrl = URI( _options.url()->full() + sep + std::string("SERVICE=WMS") + std::string("&VERSION=") + _options.wmsVersion().value() + std::string("&REQUEST=GetCapabilities") ); } //Try to read the WMS capabilities osg::ref_ptr<WMSCapabilities> capabilities = WMSCapabilitiesReader::read( capUrl.full(), dbOptions ); if ( !capabilities.valid() ) { return Status::Error( "Unable to read WMS GetCapabilities." ); } else { OE_INFO << LC << "Got capabilities from " << capUrl.full() << std::endl; } if ( _formatToUse.empty() && capabilities.valid() ) { _formatToUse = capabilities->suggestExtension(); OE_INFO << LC << "No format specified, capabilities suggested extension " << _formatToUse << std::endl; } if ( _formatToUse.empty() ) _formatToUse = "png"; if ( _srsToUse.empty() ) _srsToUse = "EPSG:4326"; std::string wmsFormatToUse = _options.wmsFormat().value(); //Initialize the WMS request prototype std::stringstream buf; // first the mandatory keys: buf << std::fixed << _options.url()->full() << sep << "SERVICE=WMS" << "&VERSION=" << _options.wmsVersion().value() << "&REQUEST=GetMap" << "&LAYERS=" << _options.layers().value() << "&FORMAT=" << ( wmsFormatToUse.empty() ? std::string("image/") + _formatToUse : wmsFormatToUse ) << "&STYLES=" << _options.style().value() << (_options.wmsVersion().value() == "1.3.0" ? "&CRS=" : "&SRS=") << _srsToUse << "&WIDTH="<< _options.tileSize().value() << "&HEIGHT="<< _options.tileSize().value() << "&BBOX=%lf,%lf,%lf,%lf"; // then the optional keys: if ( _options.transparent().isSet() ) buf << "&TRANSPARENT=" << (_options.transparent() == true ? "TRUE" : "FALSE"); _prototype = ""; _prototype = buf.str(); //OE_NOTICE << "Prototype " << _prototype << std::endl; osg::ref_ptr<SpatialReference> wms_srs = SpatialReference::create( _srsToUse ); // check for spherical mercator: if ( wms_srs.valid() && wms_srs->isEquivalentTo( osgEarth::Registry::instance()->getGlobalMercatorProfile()->getSRS() ) ) { result = osgEarth::Registry::instance()->getGlobalMercatorProfile(); } else if (wms_srs.valid() && wms_srs->isEquivalentTo( osgEarth::Registry::instance()->getGlobalGeodeticProfile()->getSRS())) { result = osgEarth::Registry::instance()->getGlobalGeodeticProfile(); } // Next, try to glean the extents from the layer list if ( capabilities.valid() ) { //TODO: "layers" mights be a comma-separated list. need to loop through and //combine the extents?? yes WMSLayer* layer = capabilities->getLayerByName( _options.layers().value() ); if ( layer ) { double minx, miny, maxx, maxy; minx = miny = maxx = maxy = 0; //Check to see if the profile is equivalent to global-geodetic if (wms_srs->isGeographic()) { //Try to get the lat lon extents if they are provided layer->getLatLonExtents(minx, miny, maxx, maxy); //If we still don't have any extents, just default to global geodetic. if (!result.valid() && minx == 0 && miny == 0 && maxx == 0 && maxy == 0) { result = osgEarth::Registry::instance()->getGlobalGeodeticProfile(); } } if (minx == 0 && miny == 0 && maxx == 0 && maxy == 0) { layer->getExtents(minx, miny, maxx, maxy); } if (!result.valid()) { result = Profile::create( _srsToUse, minx, miny, maxx, maxy ); } //Add the layer extents to the list of valid areas if (minx != 0 || maxx != 0 || miny != 0 || maxy != 0) { GeoExtent extent( result->getSRS(), minx, miny, maxx, maxy); getDataExtents().push_back( DataExtent(extent, 0) ); } } } // Last resort: create a global extent profile (only valid for global maps) if ( !result.valid() && wms_srs->isGeographic()) { result = osgEarth::Registry::instance()->getGlobalGeodeticProfile(); } // JPL uses an experimental interface called TileService -- ping to see if that's what // we are trying to read: URI tsUrl = _options.tileServiceUrl().value(); if ( tsUrl.empty() ) { tsUrl = URI(_options.url()->full() + sep + std::string("request=GetTileService") ); } OE_INFO << LC << "Testing for JPL/TileService at " << tsUrl.full() << std::endl; _tileService = TileServiceReader::read(tsUrl.full(), dbOptions); if (_tileService.valid()) { OE_INFO << LC << "Found JPL/TileService spec" << std::endl; TileService::TilePatternList patterns; _tileService->getMatchingPatterns( _options.layers().value(), _formatToUse, _options.style().value(), _srsToUse, _options.tileSize().value(), _options.tileSize().value(), patterns ); if (patterns.size() > 0) { result = _tileService->createProfile( patterns ); _prototype = _options.url()->full() + sep + patterns[0].getPrototype(); } } else { OE_INFO << LC << "No JPL/TileService spec found; assuming standard WMS" << std::endl; } // Use the override profile if one is passed in. if ( getProfile() == 0L ) { setProfile( result.get() ); } if ( getProfile() ) { OE_INFO << LC << "Profile=" << getProfile()->toString() << std::endl; // set up the cache options properly for a TileSource. _dbOptions = Registry::instance()->cloneOrCreateOptions( dbOptions ); return STATUS_OK; } else { return Status::Error( "Unable to establish profile" ); } }
/** override */ Status initialize( const osgDB::Options* dbOptions ) { osg::ref_ptr<const Profile> result; char sep = _options.url()->full().find_first_of('?') == std::string::npos? '?' : '&'; URI capUrl = _options.capabilitiesUrl().value(); if ( capUrl.empty() ) { capUrl = URI( _options.url()->full() + sep + std::string("SERVICE=WMS") + std::string("&VERSION=") + _options.wmsVersion().value() + std::string("&REQUEST=GetCapabilities") ); } //Try to read the WMS capabilities osg::ref_ptr<WMSCapabilities> capabilities = WMSCapabilitiesReader::read( capUrl, dbOptions ); if ( !capabilities.valid() ) { return Status::Error( Status::ResourceUnavailable, "Unable to read WMS GetCapabilities." ); } else { OE_INFO << LC << "Got capabilities from " << capUrl.full() << std::endl; } if ( _formatToUse.empty() && capabilities.valid() ) { _formatToUse = capabilities->suggestExtension(); OE_INFO << LC << "No format specified, capabilities suggested extension " << _formatToUse << std::endl; } if ( _formatToUse.empty() ) _formatToUse = "png"; if ( _srsToUse.empty() ) _srsToUse = "EPSG:4326"; std::string wmsFormatToUse = _options.wmsFormat().value(); //Initialize the WMS request prototype std::stringstream buf; // first the mandatory keys: buf << std::fixed << _options.url()->full() << sep << "SERVICE=WMS" << "&VERSION=" << _options.wmsVersion().value() << "&REQUEST=GetMap" << "&LAYERS=" << _options.layers().value() << "&FORMAT=" << ( wmsFormatToUse.empty() ? std::string("image/") + _formatToUse : wmsFormatToUse ) << "&STYLES=" << _options.style().value() << (_options.wmsVersion().value() == "1.3.0" ? "&CRS=" : "&SRS=") << _srsToUse << "&WIDTH="<< getPixelsPerTile() << "&HEIGHT=" << getPixelsPerTile() << "&BBOX=%lf,%lf,%lf,%lf"; // then the optional keys: if ( _options.transparent().isSet() ) buf << "&TRANSPARENT=" << (_options.transparent() == true ? "TRUE" : "FALSE"); _prototype = ""; _prototype = buf.str(); //OE_NOTICE << "Prototype " << _prototype << std::endl; osg::ref_ptr<SpatialReference> wms_srs = SpatialReference::create( _srsToUse ); // check for spherical mercator: if ( wms_srs.valid() && wms_srs->isEquivalentTo( osgEarth::Registry::instance()->getSphericalMercatorProfile()->getSRS() ) ) { result = osgEarth::Registry::instance()->getSphericalMercatorProfile(); } else if (wms_srs.valid() && wms_srs->isEquivalentTo( osgEarth::Registry::instance()->getGlobalGeodeticProfile()->getSRS())) { result = osgEarth::Registry::instance()->getGlobalGeodeticProfile(); } // Next, try to glean the extents from the layer list if ( capabilities.valid() ) { StringTokenizer tok(","); StringVector tized; tok.tokenize(_options.layers().value(), tized); for (StringVector::const_iterator itr = tized.begin(); itr != tized.end(); ++itr) { std::string layerName = *itr; WMSLayer* layer = capabilities->getLayerByName(layerName); if (layer) { // Get the lat/lon extents double minLon, minLat, maxLon, maxLat; layer->getLatLonExtents(minLon, minLat, maxLon, maxLat); GeoExtent wgs84Extent(SpatialReference::create("wgs84"), minLon, minLat, maxLon, maxLat); getDataExtents().push_back(DataExtent(wgs84Extent, 0)); } } // If we don't have a profile yet, transform the lat/lon extents to the requested srs and use it as the extents of the profile. if (!result.valid()) { const SpatialReference* srs = SpatialReference::create(_srsToUse); GeoExtent totalExtent(srs); for (DataExtentList::const_iterator itr = getDataExtents().begin(); itr != getDataExtents().end(); ++itr) { GeoExtent dataExtent = *itr; GeoExtent nativeExtent; dataExtent.transform(srs, nativeExtent); totalExtent.expandToInclude(nativeExtent); } result = Profile::create(srs, totalExtent.xMin(), totalExtent.yMin(), totalExtent.xMax(), totalExtent.yMax()); } } // Last resort: create a global extent profile (only valid for global maps) if ( !result.valid() && wms_srs->isGeographic()) { result = osgEarth::Registry::instance()->getGlobalGeodeticProfile(); } #ifdef SUPPORT_JPL_TILESERVICE // JPL uses an experimental interface called TileService -- ping to see if that's what // we are trying to read: URI tsUrl = _options.tileServiceUrl().value(); if ( tsUrl.empty() ) { tsUrl = URI(_options.url()->full() + sep + std::string("request=GetTileService"), tsUrl.context()); } OE_INFO << LC << "Testing for JPL/TileService at " << tsUrl.full() << std::endl; osg::ref_ptr<TileService> tileService = TileServiceReader::read(tsUrl.full(), dbOptions); if (tileService.valid()) { OE_INFO << LC << "Found JPL/TileService spec" << std::endl; TileService::TilePatternList patterns; tileService->getMatchingPatterns( _options.layers().value(), _formatToUse, _options.style().value(), _srsToUse, getPixelsPerTile(), getPixelsPerTile(), patterns ); if (patterns.size() > 0) { result = tileService->createProfile( patterns ); _prototype = _options.url()->full() + sep + patterns[0].getPrototype(); } } else { OE_INFO << LC << "No JPL/TileService spec found; assuming standard WMS" << std::endl; } #endif // Use the override profile if one is passed in. if ( getProfile() == 0L ) { setProfile( result.get() ); } if ( getProfile() ) { OE_INFO << LC << "Profile=" << getProfile()->toString() << std::endl; // set up the cache options properly for a TileSource. _dbOptions = Registry::instance()->cloneOrCreateOptions( dbOptions ); return Status::OK(); } else { return Status::Error( "Unable to establish profile" ); } }
void PlaceNode::init() { Decluttering::setEnabled( this->getOrCreateStateSet(), true ); //reset. //this->clearDecoration(); getPositionAttitudeTransform()->removeChildren(0, getPositionAttitudeTransform()->getNumChildren()); _geode = new osg::Geode(); // ensure that (0,0,0) is the bounding sphere control/center point. // useful for things like horizon culling. _geode->setComputeBoundingSphereCallback(new ControlPointCallback()); osg::Drawable* text = 0L; // If there's no explicit text, look to the text symbol for content. if ( _text.empty() && _style.has<TextSymbol>() ) { _text = _style.get<TextSymbol>()->content()->eval(); } osg::ref_ptr<const InstanceSymbol> instance = _style.get<InstanceSymbol>(); // backwards compability, support for deprecated MarkerSymbol if ( !instance.valid() && _style.has<MarkerSymbol>() ) { instance = _style.get<MarkerSymbol>()->convertToInstanceSymbol(); } const IconSymbol* icon = instance->asIcon(); if ( !_image.valid() ) { URI imageURI; if ( icon ) { if ( icon->url().isSet() ) { imageURI = icon->url()->evalURI(); } else if (icon->getImage()) { _image = icon->getImage(); } } if ( !imageURI.empty() ) { _image = imageURI.getImage( _dbOptions.get() ); } } osg::BoundingBox imageBox(0,0,0,0,0,0); // found an image; now format it: if ( _image.get() ) { // Scale the icon if necessary double scale = 1.0; if ( icon && icon->scale().isSet() ) { scale = icon->scale()->eval(); } double s = scale * _image->s(); double t = scale * _image->t(); // this offset anchors the image at the bottom osg::Vec2s offset; if ( !icon || !icon->alignment().isSet() ) { // default to bottom center offset.set(0.0, t / 2.0); } else { // default to bottom center switch (icon->alignment().value()) { case IconSymbol::ALIGN_LEFT_TOP: offset.set((s / 2.0), -(t / 2.0)); break; case IconSymbol::ALIGN_LEFT_CENTER: offset.set((s / 2.0), 0.0); break; case IconSymbol::ALIGN_LEFT_BOTTOM: offset.set((s / 2.0), (t / 2.0)); break; case IconSymbol::ALIGN_CENTER_TOP: offset.set(0.0, -(t / 2.0)); break; case IconSymbol::ALIGN_CENTER_CENTER: offset.set(0.0, 0.0); break; case IconSymbol::ALIGN_CENTER_BOTTOM: default: offset.set(0.0, (t / 2.0)); break; case IconSymbol::ALIGN_RIGHT_TOP: offset.set(-(s / 2.0), -(t / 2.0)); break; case IconSymbol::ALIGN_RIGHT_CENTER: offset.set(-(s / 2.0), 0.0); break; case IconSymbol::ALIGN_RIGHT_BOTTOM: offset.set(-(s / 2.0), (t / 2.0)); break; } } // Apply a rotation to the marker if requested: double heading = 0.0; if ( icon && icon->heading().isSet() ) { heading = osg::DegreesToRadians( icon->heading()->eval() ); } //We must actually rotate the geometry itself and not use a MatrixTransform b/c the //decluttering doesn't respect Transforms above the drawable. osg::Geometry* imageGeom = AnnotationUtils::createImageGeometry( _image.get(), offset, 0, heading, scale ); if ( imageGeom ) { _geode->addDrawable( imageGeom ); imageBox = imageGeom->getBoundingBox(); } } if ( _image.valid() ) { TextSymbol* textSymbol = _style.getOrCreate<TextSymbol>(); if ( !textSymbol->alignment().isSet() ) textSymbol->alignment() = textSymbol->ALIGN_LEFT_CENTER; } text = AnnotationUtils::createTextDrawable( _text, _style.get<TextSymbol>(), imageBox ); if ( text ) _geode->addDrawable( text ); osg::StateSet* stateSet = _geode->getOrCreateStateSet(); stateSet->setAttributeAndModes( new osg::Depth(osg::Depth::ALWAYS, 0, 1, false), 1 ); getPositionAttitudeTransform()->addChild( _geode ); // for clamping and occlusion culling //OE_WARN << LC << "PlaceNode::applyStyle: " << _style.getConfig().toJSON(true) << std::endl; applyStyle( _style ); setLightingIfNotSet( false ); // generate shaders: Registry::shaderGenerator().run( this, "osgEarth.PlaceNode", Registry::stateSetCache() ); setPriority(getPriority()); if ( _dynamic ) setDynamic( _dynamic ); }
void CookieJar::cookiesForRequest( const URI &request, std::string &headers, time_t now) { loadDomainCookies(request.server()); loadDomainCookies(topLevel(request.server())); // printf("cookiesForRequest: %s \n",request.asString().c_str()); string domain(request.server()); // find a cookie in the jar that corresponds to the requested domain... string tmp("Cookie: "); bool needSep(false); const static string sep("; "); bool haveExpired(false); std::vector<Cookie *>::const_iterator it(m_cookies.begin()); for (; it != m_cookies.end(); ++it) { Cookie *c(*it); if (c->name() == DOMAIN_STR) continue; if (c->matchesDomain(domain)) { if (c->expired(now)) { haveExpired = true; continue; } if (not c->path().empty()) { // check to see if the requested path is a sub dir of path string value = c->path(); string file = request.fileName(); size_t pos = file.find(value); if (pos != 0) { continue; } } // do not send secure cookies to unsecure domains if (c->secure() and request.protocol() != URI::HTTPS_PROTOCOL) { continue; } if (needSep) { tmp += sep; } string value(c->value()); bool needQuotes = value.find_first_of(" ")!=string::npos; tmp += c->name(); tmp += "="; if (needQuotes) { tmp += "\""; } tmp += c->value(); if (needQuotes) { tmp += "\""; } needSep = true; } } if (needSep) { tmp += "\r\n"; headers = tmp; } if (haveExpired) { gcExpiredCookies(now); } }
bool VFSFile::readStats( const URI& uri, FileStat &s ) { return Sys::fal_stats( uri.path(), s ); }
void SearchRequest::AddQueryStringParameters(URI& uri) const { Aws::StringStream ss; if(m_cursorHasBeenSet) { ss << m_cursor; uri.AddQueryStringParameter("cursor", ss.str()); ss.str(""); } if(m_exprHasBeenSet) { ss << m_expr; uri.AddQueryStringParameter("expr", ss.str()); ss.str(""); } if(m_facetHasBeenSet) { ss << m_facet; uri.AddQueryStringParameter("facet", ss.str()); ss.str(""); } if(m_filterQueryHasBeenSet) { ss << m_filterQuery; uri.AddQueryStringParameter("fq", ss.str()); ss.str(""); } if(m_highlightHasBeenSet) { ss << m_highlight; uri.AddQueryStringParameter("highlight", ss.str()); ss.str(""); } if(m_partialHasBeenSet) { ss << m_partial; uri.AddQueryStringParameter("partial", ss.str()); ss.str(""); } if(m_queryHasBeenSet) { ss << m_query; uri.AddQueryStringParameter("q", ss.str()); ss.str(""); } if(m_queryOptionsHasBeenSet) { ss << m_queryOptions; uri.AddQueryStringParameter("q.options", ss.str()); ss.str(""); } if(m_queryParserHasBeenSet) { ss << QueryParserMapper::GetNameForQueryParser(m_queryParser); uri.AddQueryStringParameter("q.parser", ss.str()); ss.str(""); } if(m_returnHasBeenSet) { ss << m_return; uri.AddQueryStringParameter("return", ss.str()); ss.str(""); } if(m_sizeHasBeenSet) { ss << m_size; uri.AddQueryStringParameter("size", ss.str()); ss.str(""); } if(m_sortHasBeenSet) { ss << m_sort; uri.AddQueryStringParameter("sort", ss.str()); ss.str(""); } if(m_startHasBeenSet) { ss << m_start; uri.AddQueryStringParameter("start", ss.str()); ss.str(""); } if(m_statsHasBeenSet) { ss << m_stats; uri.AddQueryStringParameter("stats", ss.str()); ss.str(""); } }
///Extract the hostname, port and attributes void URIPrivate::parseHostname() { if (!m_Parsed) parse(); const QByteArray extHn = q_ptr->hostname().toLatin1(); int length(extHn.size()), start(0); bool inAttributes = false; URI::Section section = URI::Section::HOSTNAME; // in case no port, attributes, etc are provided m_Hostname2 = q_ptr->hostname(); for (int i = 0; i < length; i++) { const char c = extHn[i]; switch (c) { case ':': //Begin port switch(section) { case URI::Section::HOSTNAME: m_Hostname2 = extHn.mid(start,i); start = i; section = URI::Section::PORT; break; case URI::Section::USER_INFO: case URI::Section::CHEVRONS : case URI::Section::SCHEME : case URI::Section::TRANSPORT: case URI::Section::TAG : case URI::Section::PORT : break; } break; case ';': //Begin attributes if (inAttributes) { parseAttribute(extHn, start, i); } else { switch(section) { case URI::Section::HOSTNAME: m_Hostname2 = extHn.mid(start+1,i-start); break; case URI::Section::PORT: m_Port = extHn.mid(start+1,i-start-1).toInt(); break; case URI::Section::USER_INFO: case URI::Section::CHEVRONS : case URI::Section::SCHEME : case URI::Section::TRANSPORT: case URI::Section::TAG : break; } inAttributes = true; } start = i; break; case '#': //Begin fragments //TODO handle fragments to comply to the RFC break; default: break; } } ///Get the remaining attribute parseAttribute(extHn, start, length-1); m_IsHNParsed = true; }
Circuit::Circuit( const URI& source ) : _impl( newImpl( brion::BlueConfig( source.getPath( )))) { }
bool operator == (const URI& lhs, const URI& rhs) noexcept { return icase_equal(lhs.scheme(), rhs.scheme()) and (lhs.userinfo() == rhs.userinfo()) and icase_equal(lhs.host(), rhs.host()) and lhs.port() == rhs.port() and lhs.path() == rhs.path() and lhs.query() == rhs.query() and lhs.fragment() == rhs.fragment(); }
bool operator < (const URI& lhs, const URI& rhs) noexcept { return lhs.to_string() < rhs.to_string(); }
URIBuilderImpl(const URI& uri) { uri_stream.fill('0'); uri_stream << uri.toString(); }
bool VFSFile::unlink( const URI &uri ) { int32 err = 0; return Sys::fal_unlink( uri.path(), err ); }
std::shared_ptr<HttpResponse> CurlHttpClient::MakeRequest(HttpRequest& request, Aws::Utils::RateLimits::RateLimiterInterface* readLimiter, Aws::Utils::RateLimits::RateLimiterInterface* writeLimiter) const { //handle uri encoding at last second. Otherwise, the signer and the http layer will mismatch. URI uri = request.GetUri(); uri.SetPath(URI::URLEncodePath(uri.GetPath())); Aws::String url = uri.GetURIString(); AWS_LOGSTREAM_TRACE(CURL_HTTP_CLIENT_TAG, "Making request to " << url); struct curl_slist* headers = NULL; if (writeLimiter != nullptr) { writeLimiter->ApplyAndPayForCost(request.GetSize()); } Aws::StringStream headerStream; HeaderValueCollection requestHeaders = request.GetHeaders(); AWS_LOG_TRACE(CURL_HTTP_CLIENT_TAG, "Including headers:"); for (auto& requestHeader : requestHeaders) { headerStream.str(""); headerStream << requestHeader.first << ": " << requestHeader.second; Aws::String headerString = headerStream.str(); AWS_LOGSTREAM_TRACE(CURL_HTTP_CLIENT_TAG, headerString); headers = curl_slist_append(headers, headerString.c_str()); } headers = curl_slist_append(headers, "transfer-encoding:"); if (!request.HasHeader(Http::CONTENT_LENGTH_HEADER)) { headers = curl_slist_append(headers, "content-length:"); } if (!request.HasHeader(Http::CONTENT_TYPE_HEADER)) { headers = curl_slist_append(headers, "content-type:"); } std::shared_ptr<HttpResponse> response(nullptr); CURL* connectionHandle = m_curlHandleContainer.AcquireCurlHandle(); if (connectionHandle) { AWS_LOGSTREAM_DEBUG(CURL_HTTP_CLIENT_TAG, "Obtained connection handle " << connectionHandle); if (headers) { curl_easy_setopt(connectionHandle, CURLOPT_HTTPHEADER, headers); } response = Aws::MakeShared<StandardHttpResponse>(CURL_HTTP_CLIENT_TAG, request); CurlWriteCallbackContext writeContext(this, &request, response.get(), readLimiter); CurlReadCallbackContext readContext(this, &request, writeLimiter); SetOptCodeForHttpMethod(connectionHandle, request); curl_easy_setopt(connectionHandle, CURLOPT_URL, url.c_str()); curl_easy_setopt(connectionHandle, CURLOPT_WRITEFUNCTION, &CurlHttpClient::WriteData); curl_easy_setopt(connectionHandle, CURLOPT_WRITEDATA, &writeContext); curl_easy_setopt(connectionHandle, CURLOPT_HEADERFUNCTION, &CurlHttpClient::WriteHeader); curl_easy_setopt(connectionHandle, CURLOPT_HEADERDATA, response.get()); //we only want to override the default path if someone has explicitly told us to. if(!m_caPath.empty()) { curl_easy_setopt(connectionHandle, CURLOPT_CAPATH, m_caPath.c_str()); } if(!m_caFile.empty()) { curl_easy_setopt(connectionHandle, CURLOPT_CAINFO, m_caFile.c_str()); } // only set by android test builds because the emulator is missing a cert needed for aws services #ifdef TEST_CERT_PATH curl_easy_setopt(connectionHandle, CURLOPT_CAPATH, TEST_CERT_PATH); #endif // TEST_CERT_PATH if (m_verifySSL) { curl_easy_setopt(connectionHandle, CURLOPT_SSL_VERIFYPEER, 1L); curl_easy_setopt(connectionHandle, CURLOPT_SSL_VERIFYHOST, 2L); #if LIBCURL_VERSION_MAJOR >= 7 #if LIBCURL_VERSION_MINOR >= 34 curl_easy_setopt(connectionHandle, CURLOPT_SSLVERSION, CURL_SSLVERSION_TLSv1); #endif //LIBCURL_VERSION_MINOR #endif //LIBCURL_VERSION_MAJOR } else { curl_easy_setopt(connectionHandle, CURLOPT_SSL_VERIFYPEER, 0L); curl_easy_setopt(connectionHandle, CURLOPT_SSL_VERIFYHOST, 0L); } if (m_allowRedirects) { curl_easy_setopt(connectionHandle, CURLOPT_FOLLOWLOCATION, 1L); } else { curl_easy_setopt(connectionHandle, CURLOPT_FOLLOWLOCATION, 0L); } //curl_easy_setopt(connectionHandle, CURLOPT_VERBOSE, 1); //curl_easy_setopt(connectionHandle, CURLOPT_DEBUGFUNCTION, CurlDebugCallback); if (m_isUsingProxy) { curl_easy_setopt(connectionHandle, CURLOPT_PROXY, m_proxyHost.c_str()); curl_easy_setopt(connectionHandle, CURLOPT_PROXYPORT, (long) m_proxyPort); curl_easy_setopt(connectionHandle, CURLOPT_PROXYUSERNAME, m_proxyUserName.c_str()); curl_easy_setopt(connectionHandle, CURLOPT_PROXYPASSWORD, m_proxyPassword.c_str()); } else { curl_easy_setopt(connectionHandle, CURLOPT_PROXY, ""); } if (request.GetContentBody()) { curl_easy_setopt(connectionHandle, CURLOPT_READFUNCTION, &CurlHttpClient::ReadBody); curl_easy_setopt(connectionHandle, CURLOPT_READDATA, &readContext); } CURLcode curlResponseCode = curl_easy_perform(connectionHandle); bool shouldContinueRequest = ContinueRequest(request); if (curlResponseCode != CURLE_OK && shouldContinueRequest) { response = nullptr; AWS_LOGSTREAM_ERROR(CURL_HTTP_CLIENT_TAG, "Curl returned error code " << curlResponseCode); } else if(!shouldContinueRequest) { response->SetResponseCode(HttpResponseCode::REQUEST_NOT_MADE); } else { long responseCode; curl_easy_getinfo(connectionHandle, CURLINFO_RESPONSE_CODE, &responseCode); response->SetResponseCode(static_cast<HttpResponseCode>(responseCode)); AWS_LOGSTREAM_DEBUG(CURL_HTTP_CLIENT_TAG, "Returned http response code " << responseCode); char* contentType = nullptr; curl_easy_getinfo(connectionHandle, CURLINFO_CONTENT_TYPE, &contentType); if (contentType) { response->SetContentType(contentType); AWS_LOGSTREAM_DEBUG(CURL_HTTP_CLIENT_TAG, "Returned content type " << contentType); } if (request.GetMethod() != HttpMethod::HTTP_HEAD && writeContext.m_client->IsRequestProcessingEnabled() && response->HasHeader(Aws::Http::CONTENT_LENGTH_HEADER)) { const Aws::String& contentLength = response->GetHeader(Aws::Http::CONTENT_LENGTH_HEADER); int64_t numBytesResponseReceived = writeContext.m_numBytesResponseReceived; AWS_LOGSTREAM_TRACE(CURL_HTTP_CLIENT_TAG, "Response content-length header: " << contentLength); AWS_LOGSTREAM_TRACE(CURL_HTTP_CLIENT_TAG, "Response body length: " << numBytesResponseReceived); if (StringUtils::ConvertToInt64(contentLength.c_str()) != numBytesResponseReceived) { response = nullptr; AWS_LOG_ERROR(CURL_HTTP_CLIENT_TAG, "Response body length doesn't match the content-length header."); } } AWS_LOGSTREAM_DEBUG(CURL_HTTP_CLIENT_TAG, "Releasing curl handle " << connectionHandle); } m_curlHandleContainer.ReleaseCurlHandle(connectionHandle); //go ahead and flush the response body stream if(response) { response->GetResponseBody().flush(); } } if (headers) { curl_slist_free_all(headers); } return response; }
bool VFSFile::move( const URI &suri, const URI &duri ) { int32 err = 0; return Sys::fal_move( suri.path(), duri.path(), err ); }
void URITest::testConstruction() { URI uri; assert (uri.getScheme().empty()); assert (uri.getAuthority().empty()); assert (uri.getUserInfo().empty()); assert (uri.getHost().empty()); assert (uri.getPort() == 0); assert (uri.getPath().empty()); assert (uri.getQuery().empty()); assert (uri.getFragment().empty()); uri.setScheme("ftp"); assert (uri.getScheme() == "ftp"); assert (uri.getPort() == 21); uri.setScheme("HTTP"); assert (uri.getScheme() == "http"); uri.setAuthority("www.appinf.com"); assert (uri.getAuthority() == "www.appinf.com"); assert (uri.getPort() == 80); uri.setAuthority("[email protected]:8000"); assert (uri.getUserInfo() == "user"); assert (uri.getHost() == "services.appinf.com"); assert (uri.getPort() == 8000); uri.setPath("/index.html"); assert (uri.getPath() == "/index.html"); uri.setPath("/file%20with%20spaces.html"); assert (uri.getPath() == "/file with spaces.html"); uri.setPathEtc("/query.cgi?query=foo"); assert (uri.getPath() == "/query.cgi"); assert (uri.getQuery() == "query=foo"); assert (uri.getFragment().empty()); assert (uri.getPathEtc() == "/query.cgi?query=foo"); assert (uri.getPathAndQuery() == "/query.cgi?query=foo"); uri.setPathEtc("/query.cgi?query=bar#frag"); assert (uri.getPath() == "/query.cgi"); assert (uri.getQuery() == "query=bar"); assert (uri.getFragment() == "frag"); assert (uri.getPathEtc() == "/query.cgi?query=bar#frag"); assert (uri.getPathAndQuery() == "/query.cgi?query=bar"); uri.setQuery("query=test"); assert (uri.getQuery() == "query=test"); uri.setFragment("result"); assert (uri.getFragment() == "result"); URI uri2("file", "/home/guenter/foo.bar"); assert (uri2.getScheme() == "file"); assert (uri2.getPath() == "/home/guenter/foo.bar"); URI uri3("http", "www.appinf.com", "/index.html"); assert (uri3.getScheme() == "http"); assert (uri3.getAuthority() == "www.appinf.com"); assert (uri3.getPath() == "/index.html"); URI uri4("http", "www.appinf.com:8000", "/index.html"); assert (uri4.getScheme() == "http"); assert (uri4.getAuthority() == "www.appinf.com:8000"); assert (uri4.getPath() == "/index.html"); URI uri5("http", "[email protected]:8000", "/index.html"); assert (uri5.getScheme() == "http"); assert (uri5.getUserInfo() == "user"); assert (uri5.getHost() == "www.appinf.com"); assert (uri5.getPort() == 8000); assert (uri5.getAuthority() == "[email protected]:8000"); assert (uri5.getPath() == "/index.html"); URI uri6("http", "[email protected]:80", "/index.html"); assert (uri6.getScheme() == "http"); assert (uri6.getUserInfo() == "user"); assert (uri6.getHost() == "www.appinf.com"); assert (uri6.getPort() == 80); assert (uri6.getAuthority() == "*****@*****.**"); assert (uri6.getPath() == "/index.html"); URI uri7("http", "[email protected]:", "/index.html"); assert (uri7.getScheme() == "http"); assert (uri7.getUserInfo() == "user"); assert (uri7.getHost() == "www.appinf.com"); assert (uri7.getPort() == 80); assert (uri7.getAuthority() == "*****@*****.**"); assert (uri7.getPath() == "/index.html"); URI uri8("http", "www.appinf.com", "/index.html", "query=test"); assert (uri8.getScheme() == "http"); assert (uri8.getAuthority() == "www.appinf.com"); assert (uri8.getPath() == "/index.html"); assert (uri8.getQuery() == "query=test"); URI uri9("http", "www.appinf.com", "/index.html", "query=test", "fragment"); assert (uri9.getScheme() == "http"); assert (uri9.getAuthority() == "www.appinf.com"); assert (uri9.getPath() == "/index.html"); assert (uri9.getPathEtc() == "/index.html?query=test#fragment"); assert (uri9.getQuery() == "query=test"); assert (uri9.getFragment() == "fragment"); uri9.clear(); assert (uri9.getScheme().empty()); assert (uri9.getAuthority().empty()); assert (uri9.getUserInfo().empty()); assert (uri9.getHost().empty()); assert (uri9.getPort() == 0); assert (uri9.getPath().empty()); assert (uri9.getQuery().empty()); assert (uri9.getFragment().empty()); URI uri10("ldap", "[2001:db8::7]", "/c=GB?objectClass?one"); assert (uri10.getScheme() == "ldap"); assert (uri10.getUserInfo().empty()); assert (uri10.getHost() == "2001:db8::7"); assert (uri10.getPort() == 389); assert (uri10.getAuthority() == "[2001:db8::7]"); assert (uri10.getPathEtc() == "/c=GB?objectClass?one"); URI uri11("http", "www.appinf.com", "/index.html?query=test#fragment"); assert (uri11.getScheme() == "http"); assert (uri11.getAuthority() == "www.appinf.com"); assert (uri11.getPath() == "/index.html"); assert (uri11.getPathEtc() == "/index.html?query=test#fragment"); assert (uri11.getQuery() == "query=test"); assert (uri11.getFragment() == "fragment"); }
bool VFSFile::mkdir( const URI &uri, uint32 mode ) { int32 err = 0; return Sys::fal_mkdir( uri.path(), err ); }
void PlaceNode::init(const osgDB::Options* dbOptions) { _geode = new osg::Geode(); osg::Drawable* text = 0L; // If there's no explicit text, look to the text symbol for content. if ( _text.empty() && _style.has<TextSymbol>() ) _text = _style.get<TextSymbol>()->content()->eval(); osg::ref_ptr<const InstanceSymbol> instance = _style.get<InstanceSymbol>(); // backwards compability, support for deprecated MarkerSymbol if ( !instance.valid() && _style.has<MarkerSymbol>() ) instance = _style.get<MarkerSymbol>()->convertToInstanceSymbol(); const IconSymbol* icon = instance->asIcon(); if ( !_image.valid() ) { URI imageURI; if ( icon ) { if ( icon->url().isSet() ) { imageURI = URI( icon->url()->eval(), icon->url()->uriContext() ); } } if ( !imageURI.empty() ) { _image = imageURI.getImage( dbOptions ); } } // found an image; now format it: if ( _image.get() ) { // this offset anchors the image at the bottom osg::Vec2s offset; if ( !icon || !icon->alignment().isSet() ) { // default to bottom center offset.set(0.0, (_image->t() / 2.0)); } else { // default to bottom center switch (icon->alignment().value()) { case IconSymbol::ALIGN_LEFT_TOP: offset.set((_image->s() / 2.0), -(_image->t() / 2.0)); break; case IconSymbol::ALIGN_LEFT_CENTER: offset.set((_image->s() / 2.0), 0.0); break; case IconSymbol::ALIGN_LEFT_BOTTOM: offset.set((_image->s() / 2.0), (_image->t() / 2.0)); break; case IconSymbol::ALIGN_CENTER_TOP: offset.set(0.0, -(_image->t() / 2.0)); break; case IconSymbol::ALIGN_CENTER_CENTER: offset.set(0.0, 0.0); break; case IconSymbol::ALIGN_CENTER_BOTTOM: default: offset.set(0.0, (_image->t() / 2.0)); break; case IconSymbol::ALIGN_RIGHT_TOP: offset.set(-(_image->s() / 2.0), -(_image->t() / 2.0)); break; case IconSymbol::ALIGN_RIGHT_CENTER: offset.set(-(_image->s() / 2.0), 0.0); break; case IconSymbol::ALIGN_RIGHT_BOTTOM: offset.set(-(_image->s() / 2.0), (_image->t() / 2.0)); break; } } // Apply a rotation to the marker if requested: double heading = 0.0; if ( icon && icon->heading().isSet() ) { heading = osg::DegreesToRadians( icon->heading()->eval() ); } //We must actually rotate the geometry itself and not use a MatrixTransform b/c the //decluttering doesn't respect Transforms above the drawable. osg::Geometry* imageGeom = AnnotationUtils::createImageGeometry( _image.get(), offset, 0, heading ); if ( imageGeom ) _geode->addDrawable( imageGeom ); text = AnnotationUtils::createTextDrawable( _text, _style.get<TextSymbol>(), osg::Vec3( (offset.x() + (_image->s() / 2.0) + 2), offset.y(), 0 ) ); } else { text = AnnotationUtils::createTextDrawable( _text, _style.get<TextSymbol>(), osg::Vec3( 0, 0, 0 ) ); } if ( text ) _geode->addDrawable( text ); osg::StateSet* stateSet = _geode->getOrCreateStateSet(); stateSet->setAttributeAndModes( new osg::Depth(osg::Depth::ALWAYS, 0, 1, false), 1 ); getAttachPoint()->addChild( _geode ); // for clamping applyStyle( _style ); setLightingIfNotSet( false ); ShaderGenerator gen( Registry::stateSetCache() ); this->accept( gen ); }
bool VFSFile::rmdir( const URI &uri ) { int32 err = 0; return Sys::fal_rmdir( uri.path(), err ); }
void URIReference::attach(const URI &uri) throw(BadURIException) { SPDocument *document = NULL; // Attempt to get the document that contains the URI if (_owner) { document = _owner->document; } else if (_owner_document) { document = _owner_document; } // createChildDoc() assumes that the referenced file is an SVG. // PNG and JPG files are allowed (in the case of feImage). gchar *filename = uri.toString(); bool skip = false; if( g_str_has_suffix( filename, ".jpg" ) || g_str_has_suffix( filename, ".JPG" ) || g_str_has_suffix( filename, ".png" ) || g_str_has_suffix( filename, ".PNG" ) ) { skip = true; } // The path contains references to separate document files to load. if(document && uri.getPath() && !skip ) { std::string base = document->getBase() ? document->getBase() : ""; std::string path = uri.getFullPath(base); if(!path.empty()) { document = document->createChildDoc(path); } else { document = NULL; } } if(!document) { g_warning("Can't get document for referenced URI: %s", filename); g_free( filename ); return; } g_free( filename ); gchar const *fragment = uri.getFragment(); if ( !uri.isRelative() || uri.getQuery() || !fragment ) { throw UnsupportedURIException(); } /* FIXME !!! real xpointer support should be delegated to document */ /* for now this handles the minimal xpointer form that SVG 1.0 * requires of us */ gchar *id = NULL; if (!strncmp(fragment, "xpointer(", 9)) { /* FIXME !!! this is wasteful */ /* FIXME: It looks as though this is including "))" in the id. I suggest moving the strlen calculation and validity testing to before strdup, and copying just the id without the "))". -- pjrm */ if (!strncmp(fragment, "xpointer(id(", 12)) { id = g_strdup(fragment+12); size_t const len = strlen(id); if ( len < 3 || strcmp(id+len-2, "))") ) { g_free(id); throw MalformedURIException(); } } else { throw UnsupportedURIException(); } } else { id = g_strdup(fragment); } /* FIXME !!! validate id as an NCName somewhere */ _connection.disconnect(); delete _uri; _uri = new URI(uri); _setObject(document->getObjectById(id)); _connection = document->connectIdChanged(id, sigc::mem_fun(*this, &URIReference::_setObject)); g_free(id); }
void CEigenLSS::solve() { #ifdef CF_HAVE_TRILINOS Timer timer; const Uint nb_rows = size(); cf_assert(nb_rows == m_system_matrix.outerSize()); Epetra_SerialComm comm; Epetra_Map map(nb_rows, 0, comm); Epetra_Vector ep_rhs(View, map, m_rhs.data()); Epetra_Vector ep_sol(View, map, m_solution.data()); // Count non-zeros std::vector<int> nnz(nb_rows, 0); for(int row=0; row < nb_rows; ++row) { for(MatrixT::InnerIterator it(m_system_matrix, row); it; ++it) { ++nnz[row]; } cf_assert(nnz[row]); } Epetra_CrsMatrix ep_A(Copy, map, &nnz[0]); time_matrix_construction = timer.elapsed(); timer.restart(); // Fill the matrix for(int row=0; row < nb_rows; ++row) { std::vector<int> indices; indices.reserve(nnz[row]); std::vector<Real> values; values.reserve(nnz[row]); for(MatrixT::InnerIterator it(m_system_matrix, row); it; ++it) { indices.push_back(it.col()); values.push_back(it.value()); } ep_A.InsertGlobalValues(row, nnz[row], &values[0], &indices[0]); } ep_A.FillComplete(); time_matrix_fill = timer.elapsed(); timer.restart(); /////////////////////////////////////////////////////////////////////////////////////////////// //BEGIN//////////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////////////// Teuchos::RCP<Epetra_CrsMatrix> epetra_A=Teuchos::rcpFromRef(ep_A); Teuchos::RCP<Epetra_Vector> epetra_x=Teuchos::rcpFromRef(ep_sol); Teuchos::RCP<Epetra_Vector> epetra_b=Teuchos::rcpFromRef(ep_rhs); const URI config_uri = option("config_file").value<URI>(); const std::string config_path = config_uri.path(); Stratimikos::DefaultLinearSolverBuilder linearSolverBuilder(config_path); // the most important in general setup Teuchos::RCP<Teuchos::FancyOStream> out = Teuchos::VerboseObjectBase::getDefaultOStream(); // TODO: decouple from fancyostream to ostream or to C stdout when possible typedef Teuchos::ParameterList::PrintOptions PLPrintOptions; Teuchos::CommandLineProcessor clp(false); // false: don't throw exceptions Teuchos::RCP<const Thyra::LinearOpBase<double> > A = Thyra::epetraLinearOp( epetra_A ); Teuchos::RCP<Thyra::VectorBase<double> > x = Thyra::create_Vector( epetra_x, A->domain() ); Teuchos::RCP<const Thyra::VectorBase<double> > b = Thyra::create_Vector( epetra_b, A->range() ); // r = b - A*x, initial L2 norm double nrm_r=0.; Real systemResidual=-1.; { Epetra_Vector epetra_r(*epetra_b); Epetra_Vector epetra_A_x(epetra_A->OperatorRangeMap()); epetra_A->Apply(*epetra_x,epetra_A_x); epetra_r.Update(-1.0,epetra_A_x,1.0); epetra_r.Norm2(&nrm_r); } // Reading in the solver parameters from the parameters file and/or from // the command line. This was setup by the command-line options // set by the setupCLP(...) function above. linearSolverBuilder.readParameters(0); // out.get() if want confirmation about the xml file within trilinos Teuchos::RCP<Thyra::LinearOpWithSolveFactoryBase<double> > lowsFactory = linearSolverBuilder.createLinearSolveStrategy(""); // create linear solver strategy lowsFactory->setVerbLevel(Teuchos::VERB_NONE); // set verbosity // // print back default and current settings // if (opts->trilinos.dumpDefault!=0) { // fflush(stdout); cout << flush; // _MMESSAGE_(0,1,"Dumping Trilinos/Stratimikos solver defaults to files: 'trilinos_default.txt' and 'trilinos_default.xml'...\n"); // fflush(stdout); cout << flush; // std::ofstream ofs("./trilinos_default.txt"); // linearSolverBuilder.getValidParameters()->print(ofs,PLPrintOptions().indent(2).showTypes(true).showDoc(true)); // the last true-false is the deciding about whether printing documentation to option or not // ofs.flush();ofs.close(); // ofs.open("./trilinos_default.xml"); // Teuchos::writeParameterListToXmlOStream(*linearSolverBuilder.getValidParameters(),ofs); // ofs.flush();ofs.close(); // } // if (opts->trilinos.dumpCurrXML!=0) { // fflush(stdout); cout << flush; // _MMESSAGE_(0,1,"Dumping Trilinos/Stratimikos current settings to file: 'trilinos_current.xml'...\n"); // fflush(stdout); cout << flush; // linearSolverBuilder.writeParamsFile(*lowsFactory,"./trilinos_current.xml"); // } time_solver_setup = timer.elapsed(); timer.restart(); // solve the matrix Teuchos::RCP<Thyra::LinearOpWithSolveBase<double> > lows = Thyra::linearOpWithSolve(*lowsFactory, A); // create solver Thyra::solve(*lows, Thyra::NOTRANS, *b, &*x); // solve time_solve = timer.elapsed(); timer.restart(); // r = b - A*x, final L2 norm { Epetra_Vector epetra_r(*epetra_b); Epetra_Vector epetra_A_x(epetra_A->OperatorRangeMap()); epetra_A->Apply(*epetra_x,epetra_A_x); epetra_r.Update(-1.0,epetra_A_x,1.0); systemResidual=1./nrm_r; nrm_r=0.; epetra_r.Norm2(&nrm_r); systemResidual*=nrm_r; } time_residual = timer.elapsed(); /////////////////////////////////////////////////////////////////////////////////////////////// //END////////////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////////////// #else // no trilinos #ifdef CF_HAVE_SUPERLU Eigen::SparseMatrix<Real> A(m_system_matrix); Eigen::SparseLU<Eigen::SparseMatrix<Real>,Eigen::SuperLU> lu_of_A(A); if(!lu_of_A.solve(rhs(), &m_solution)) throw Common::FailedToConverge(FromHere(), "Solution failed."); #else // no trilinos and no superlu RealMatrix A(m_system_matrix); Eigen::FullPivLU<RealMatrix> lu_of_A(A); m_solution = lu_of_A.solve(m_rhs); #endif // end ifdef superlu #endif // end ifdef trilinos }
Future<Nothing> CurlFetcherPlugin::fetch( const URI& uri, const string& directory) { // TODO(jieyu): Validate the given URI. if (!uri.has_path()) { return Failure("URI path is not specified"); } Try<Nothing> mkdir = os::mkdir(directory); if (mkdir.isError()) { return Failure( "Failed to create directory '" + directory + "': " + mkdir.error()); } // TODO(jieyu): Allow user to specify the name of the output file. const string output = path::join(directory, Path(uri.path()).basename()); const vector<string> argv = { "curl", "-s", // Don’t show progress meter or error messages. "-S", // Makes curl show an error message if it fails. "-L", // Follow HTTP 3xx redirects. "-w", "%{http_code}", // Display HTTP response code on stdout. "-o", output, // Write output to the file. strings::trim(stringify(uri)) }; Try<Subprocess> s = subprocess( "curl", argv, Subprocess::PATH("/dev/null"), Subprocess::PIPE(), Subprocess::PIPE()); if (s.isError()) { return Failure("Failed to exec the curl subprocess: " + s.error()); } return await( s.get().status(), io::read(s.get().out().get()), io::read(s.get().err().get())) .then([](const tuple< Future<Option<int>>, Future<string>, Future<string>>& t) -> Future<Nothing> { Future<Option<int>> status = std::get<0>(t); if (!status.isReady()) { return Failure( "Failed to get the exit status of the curl subprocess: " + (status.isFailed() ? status.failure() : "discarded")); } if (status->isNone()) { return Failure("Failed to reap the curl subprocess"); } if (status->get() != 0) { Future<string> error = std::get<2>(t); if (!error.isReady()) { return Failure( "Failed to perform 'curl'. Reading stderr failed: " + (error.isFailed() ? error.failure() : "discarded")); } return Failure("Failed to perform 'curl': " + error.get()); } Future<string> output = std::get<1>(t); if (!output.isReady()) { return Failure( "Failed to read stdout from 'curl': " + (output.isFailed() ? output.failure() : "discarded")); } // Parse the output and get the HTTP response code. Try<int> code = numify<int>(output.get()); if (code.isError()) { return Failure("Unexpected output from 'curl': " + output.get()); } if (code.get() != http::Status::OK) { return Failure( "Unexpected HTTP response code: " + http::Status::string(code.get())); } return Nothing(); }); }
bool parseURI(string stringUri, URI &uri) { /* * schema://[username[:password]@]host[:port][/[path[?parameters]]] */ LOG_URI("------------------------"); LOG_URI("stringUri: `%s`", STR(stringUri)); string fullUri; string fullUriWithAuth = stringUri; string scheme; string authentication; string username; string password; string hostPort; string host; string portString; uint16_t port = 0; bool portSpecified = false; string fullDocumentPathWithParameters; string fullDocumentPath; string fullParameters; string documentPath; string document; string documentWithFullParameters; Variant parameters; string::size_type cursor = 0; string::size_type pos = 0; //1. Reset uri.Reset(); //2. trim trim(stringUri); if (stringUri == "") { FATAL("Empty uri"); return false; } //2. Get the scheme and the default port pos = stringUri.find("://", cursor); if (pos == string::npos) { FATAL("Unable to determine scheme"); return false; } scheme = lowerCase(stringUri.substr(cursor, pos - cursor)); cursor = pos + 3; if (_schemeToPort.size() == 0) { _schemeToPort["http"] = 80; _schemeToPort["rtmpt"] = 80; _schemeToPort["rtmpte"] = 80; _schemeToPort["https"] = 443; _schemeToPort["rtmps"] = 443; _schemeToPort["rtsp"] = 554; _schemeToPort["rtmp"] = 1935; _schemeToPort["rtmpe"] = 1935; _schemeToPort["mms"] = 1755; } if (MAP_HAS1(_schemeToPort, scheme)) { port = _schemeToPort[scheme]; } // else { // FATAL("Scheme `%s` not supported", STR(scheme)); // return false; // } LOG_URI("scheme: %s; default port: %"PRIu16, STR(scheme), port); //3. get the authentication portion. the search starts from //where the scheme detection left and up to the first / character string::size_type limit = stringUri.find("/", cursor); bool hasAuthentication = false; pos = stringUri.find("@", cursor); if (pos != string::npos) { if (limit != string::npos) { hasAuthentication = pos<limit; } else { hasAuthentication = true; } } if (hasAuthentication) { authentication = stringUri.substr(cursor, pos - cursor); fullUri = stringUri.substr(0, cursor); fullUri += stringUri.substr(pos + 1); cursor = pos + 1; } else { fullUri = fullUriWithAuth; } if (authentication != "") { pos = authentication.find(":"); if (pos != string::npos) { username = authentication.substr(0, pos); password = authentication.substr(pos + 1); } else { username = authentication; password = ""; } } LOG_URI("fullUri: `%s`; fullUriWithAuth: `%s`", STR(fullUri), STR(fullUriWithAuth)); LOG_URI("username: `%s`; password: `%s`", STR(username), STR(password)); //4. Get the host:port pos = stringUri.find("/", cursor); if (pos == string::npos) { hostPort = stringUri.substr(cursor); cursor = stringUri.size() - 1; fullDocumentPathWithParameters = "/"; } else { hostPort = stringUri.substr(cursor, pos - cursor); cursor = pos + 1; fullDocumentPathWithParameters = "/" + stringUri.substr(cursor); } trim(hostPort); if (hostPort == "") { FATAL("Invalid host:port specified"); return false; } pos = hostPort.find(":"); if (pos == string::npos) { host = hostPort; portSpecified = false; } else { host = hostPort.substr(0, pos); trim(host); portString = hostPort.substr(pos + 1); portSpecified = true; port = (uint16_t) atoi(STR(portString)); if (format("%"PRIu16, port) != portString) { FATAL("Invalid port number specified: `%s`", STR(portString)); return false; } } LOG_URI("host: %s; port: %"PRIu16"; portSpecified: %d", STR(host), port, portSpecified); //5. fullDocumentPathWithParameters fullDocumentPath = "/"; fullParameters = ""; documentPath = "/"; document = ""; documentWithFullParameters = ""; parameters.Reset(); parameters.IsArray(false); if (fullDocumentPathWithParameters != "/") { pos = fullDocumentPathWithParameters.find("?"); if (pos == string::npos) { fullDocumentPath = fullDocumentPathWithParameters; fullParameters = ""; } else { fullDocumentPath = fullDocumentPathWithParameters.substr(0, pos); fullParameters = fullDocumentPathWithParameters.substr(pos + 1); } trim(fullParameters); if (fullParameters != "") { vector<string> elements; split(fullParameters, "&", elements); for (uint32_t i = 0; i < elements.size(); i++) { string kvp = elements[i]; if (kvp == "") continue; string k = ""; string v = ""; pos = kvp.find("="); if (pos == string::npos) { k = kvp; v = ""; } else { k = kvp.substr(0, pos); v = kvp.substr(pos + 1); } if (k == "") continue; parameters[k] = v; } } bool rtmpDocument = false; if (scheme.find("rtmp") == 0) { pos = fullDocumentPath.find(':'); if (pos == string::npos) { rtmpDocument = false; } else { pos = fullDocumentPath.rfind('/', pos); if (pos == string::npos) { rtmpDocument = false; } else { rtmpDocument = true; } } } else { rtmpDocument = false; } if (rtmpDocument) { pos = fullDocumentPath.find(':'); pos = fullDocumentPath.rfind('/', pos); documentPath = fullDocumentPath.substr(0, pos + 1); document = fullDocumentPath.substr(pos + 1); } else { for (string::size_type i = fullDocumentPath.size() - 1; i != 0; i--) { if (fullDocumentPath[i] == '/') break; document = fullDocumentPath[i] + document; } documentPath = fullDocumentPath.substr(0, fullDocumentPath.size() - document.size()); } documentWithFullParameters = document; if (fullParameters != "") documentWithFullParameters += "?" + fullParameters; } LOG_URI("fullDocumentPathWithParameters: `%s`", STR(fullDocumentPathWithParameters)); LOG_URI("fullDocumentPath: `%s`", STR(fullDocumentPath)); LOG_URI("fullParameters: `%s`", STR(fullParameters)); LOG_URI("documentPath: `%s`", STR(documentPath)); LOG_URI("document: `%s`", STR(document)); LOG_URI("documentWithFullParameters: `%s`", STR(documentWithFullParameters)); LOG_URI("parameters:"); #ifdef DEBUG_URI FOR_MAP(parameters, string, Variant, i) { LOG_URI("\t`%s`: `%s`", STR(MAP_KEY(i)), STR(MAP_VAL(i))); }
void URI::copyFrom(const URI& copyFrom) { set(copyFrom.originalStr()); }
Status TMSTileSource::initialize(const osgDB::Options* dbOptions) { // local copy of options we can modify if necessary. _dbOptions = Registry::instance()->cloneOrCreateOptions(dbOptions); // see if the use passed in a profile const Profile* profile = getProfile(); // URI is mandatory. URI tmsURI = _options.url().value(); if ( tmsURI.empty() ) { return Status::Error( Status::ConfigurationError, "Fail: TMS driver requires a valid \"url\" property" ); } // A repo is writable only if it's local. if ( tmsURI.isRemote() ) { OE_DEBUG << LC << "Repo is remote; opening in read-only mode" << std::endl; } // Is this a new repo? (You can only create a new repo at a local non-archive URI.) bool isNewRepo = false; if (!tmsURI.isRemote() && !osgEarth::isPathToArchivedFile(tmsURI.full()) && !osgDB::fileExists(tmsURI.full()) ) { isNewRepo = true; // new repo REQUIRES a profile: if ( !profile ) { return Status::Error(Status::ConfigurationError, "Fail: profile required to create new TMS repo"); } } // Take the override profile if one is given if ( profile ) { OE_INFO << LC << "Using express profile \"" << getProfile()->toString() << "\" for URI \"" << tmsURI.base() << "\"" << std::endl; DataExtentList extents; _tileMap = TMS::TileMap::create( _options.url()->full(), profile, extents, _options.format().value(), 256, 256); //getPixelsPerTile(), //getPixelsPerTile() ); // If this is a new repo, write the tilemap file to disk now. if ( isNewRepo ) { if ( !_options.format().isSet() ) { return Status::Error(Status::ConfigurationError, "Missing required \"format\" property: e.g. png, jpg"); } TMS::TileMapReaderWriter::write( _tileMap.get(), tmsURI.full() ); OE_INFO << LC << "Created new TMS repo at " << tmsURI.full() << std::endl; } } else { // Attempt to read the tile map parameters from a TMS TileMap XML tile on the server: _tileMap = TMS::TileMapReaderWriter::read( tmsURI.full(), _dbOptions.get() ); if (!_tileMap.valid()) { return Status::Error( Status::ResourceUnavailable, Stringify() << "Failed to read configuration from " << tmsURI.full() ); } OE_INFO << LC << "TMS tile map datestamp = " << DateTime(_tileMap->getTimeStamp()).asRFC1123() << std::endl; profile = _tileMap->createProfile(); if ( profile ) setProfile( profile ); } // Make sure we've established a profile by this point: if ( !profile ) { return Status::Error( Stringify() << "Failed to establish a profile for " << tmsURI.full() ); } // resolve the writer if ( !tmsURI.isRemote() && !resolveWriter() ) { OE_WARN << LC << "Cannot create writer; writing disabled" << std::endl; } // TileMap and profile are valid at this point. Build the tile sets. // Automatically set the min and max level of the TileMap if ( _tileMap->getTileSets().size() > 0 ) { OE_DEBUG << LC << "TileMap min/max " << _tileMap->getMinLevel() << ", " << _tileMap->getMaxLevel() << std::endl; if (_tileMap->getDataExtents().size() > 0) { for (DataExtentList::iterator itr = _tileMap->getDataExtents().begin(); itr != _tileMap->getDataExtents().end(); ++itr) { this->getDataExtents().push_back(*itr); } } } return STATUS_OK; }
bool URI::operator<( const URI& rhs ) const { if ( getURIString() < rhs.getURIString() ) return true; return false; }
inline std::string toString() const { return mURI.toString(); }