Esempio n. 1
0
        public IEnumerable <WeatherInfo> PastWeather(double lat, double log, DateTime from, DateTime to)
        {
            string latStr  = lat.ToString("0.000", CultureInfo.InvariantCulture);
            string logStr  = log.ToString("0.000", CultureInfo.InvariantCulture);
            string fromStr = from.ToString("dd-MM-yyyy");
            string toStr   = to.ToString("dd-MM-yyyy");

            String url = String.Format(PATH_WEATHER, latStr, logStr, fromStr, toStr, WEATHER_KEY);

            string body = req.GetBody(url);

            pastWeather
            .CtorArg("date", 0)
            .CtorArg("tempC", 2)
            .PropArg("PrecipMM", 11)
            .PropArg("Desc", 10);

            IEnumerable <WeatherInfo> items = pastWeather
                                              .Load(body)
                                              .RemoveWith("#")
                                              .Remove(1)
                                              .RemoveEvenIndexes()
                                              .Parse();

            return(items);
        }
Esempio n. 2
0
        public WeatherInfo[] PastWeather(double lat, double log, DateTime from, DateTime to)
        {
            string latStr = lat.ToString("0.000", CultureInfo.InvariantCulture);
            string logStr = log.ToString("0.000", CultureInfo.InvariantCulture);

            string dateFrom = FormatDates(from);
            string dateTo   = FormatDates(to);

            string path = PATH_WEATHER
                          .Replace("{0}", latStr)
                          .Replace("{1}", logStr)
                          .Replace("{2}", dateFrom)
                          .Replace("{3}", dateTo);

            string body = req.GetBody(path);

            CsvParser <WeatherInfo> weather =
                new CsvParser <WeatherInfo>()
                .CtorArg("date", 0)
                .CtorArg("tempC", 2)
                .PropArg("PrecipMM", 11)
                .PropArg("Desc", 10);

            IEnumerable <WeatherInfo> items = weather
                                              .Load(body)
                                              .RemoveWith("#")
                                              .Remove(1)
                                              .RemoveEmpties()
                                              .RemoveOddIndexes()
                                              .Parse();

            return(items.Select(x => (WeatherInfo)x).ToArray());
        }
Esempio n. 3
0
        private void NewFileAgentInventoryUploadHandler(NewFileAgentInventoryMessage message, Capability cap,
                                                        IHttpClientContext context, IHttpRequest request, IHttpResponse response)
        {
            byte[] assetData = request.GetBody();
            UUID   assetID   = UUID.Zero;
            UUID   itemID    = UUID.Zero;

            m_log.Debug("Received inventory asset upload from " + cap.OwnerID + " (" + assetData.Length + " bytes)");

            if (assetData != null && assetData.Length > 0)
            {
                string contentType = LLUtil.LLAssetTypeToContentType((int)message.AssetType);

                // Create the asset
                if (m_assetClient.StoreAsset(contentType, false, false, assetData, cap.OwnerID, out assetID))
                {
                    // Create the inventory item
                    LLInventoryItem item = new LLInventoryItem();
                    item.AssetID      = assetID;
                    item.ContentType  = contentType;
                    item.CreationDate = DateTime.UtcNow;
                    item.CreatorID    = cap.OwnerID;
                    item.Description  = message.Description;
                    item.ID           = UUID.Random();
                    item.Name         = message.Name;
                    item.OwnerID      = cap.OwnerID;
                    item.ParentID     = message.FolderID;
                    item.Permissions  = (m_permissions != null) ? m_permissions.GetDefaultPermissions() : Permissions.FullPermissions;
                    item.SalePrice    = 10;
                    item.SaleType     = SaleType.Not;

                    if (m_inventoryClient.TryCreateItem(cap.OwnerID, item))
                    {
                        itemID = item.ID;
                    }
                    else
                    {
                        m_log.Warn("Failed to create inventory item for uploaded asset " + assetID);
                    }
                }
                else
                {
                    m_log.WarnFormat("Failed to store uploaded inventory asset ({0} bytes)", assetData.Length);
                }
            }
            else
            {
                m_log.Warn("Inventory asset upload contained no data");
            }

            // Build the response message
            OSDMap reply = new OSDMap
            {
                { "state", OSD.FromString("complete") },
                { "new_asset", OSD.FromUUID(assetID) },
                { "new_inventory_item", OSD.FromUUID(itemID) }
            };

            LLUtil.SendLLSDXMLResponse(response, reply);
        }
Esempio n. 4
0
        /// <summary>
        ///     Create an <see cref="HttpWebRequest" /> from the given <see cref="IHttpRequest" /> instance
        /// </summary>
        /// <param name="request">The instance of <see cref="IHttpRequest" /></param>
        /// <param name="progress">The progress reporter</param>
        /// <returns>An instance of <see cref="HttpWebRequest" /></returns>
        protected virtual HttpWebRequest CreateRequest(IHttpRequest request, Interfaces.Infrastructure.IProgress <double> progress)
        {
            var            uri = request.GetUri();
            HttpWebRequest realRequest;

            if (uri.Scheme == Uri.UriSchemeHttps)
            {
                realRequest = (HttpWebRequest)WebRequest.Create(uri);
                realRequest.ProtocolVersion = HttpVersion.Version11;
            }
            else
            {
                realRequest = (HttpWebRequest)WebRequest.Create(request.GetUri());
            }

            realRequest.Method = request.GetMethod();
            var headers = request.GetHeaders();

            headers.Keys.ToList().ForEach(key =>
            {
                var handler = HeaderHandlers.FirstOrDefault(h => h.CanSetHeader(realRequest, key));
                if (null != handler)
                {
                    handler.SetHeader(realRequest, key, headers[key]);
                }
                else
                {
                    realRequest.Headers.Add(key, headers[key]);
                }
            });
            return(SetBody(realRequest, request.GetBody(), progress));
        }
Esempio n. 5
0
        private void UploadBakedTextureDataHandler(Capability cap, IHttpClientContext context, IHttpRequest request, IHttpResponse response)
        {
            byte[] textureData = request.GetBody();
            UUID   assetID     = UUID.Zero;

            m_log.Debug("Received baked texture upload from " + cap.OwnerID + " (" + textureData.Length + " bytes)");

            if (textureData != null && textureData.Length > 0)
            {
                if (!m_assetClient.StoreAsset("image/x-j2c", true, true, textureData, cap.OwnerID, out assetID))
                {
                    m_log.WarnFormat("Failed to store uploaded texture bake ({0} bytes)", textureData.Length);
                }
            }
            else
            {
                m_log.Warn("Texture bake upload contained no data");
            }

            UploadBakedTextureMessage reply      = new UploadBakedTextureMessage();
            UploaderRequestComplete   replyBlock = new UploaderRequestComplete();

            replyBlock.AssetID = assetID;
            reply.Request      = replyBlock;

            LLUtil.SendLLSDXMLResponse(response, reply.Serialize());
        }
Esempio n. 6
0
        public ClimateValues[] GetClimateValues(VALUES options, int dateFrom, int dateTo)
        {
            string dataType = (options == VALUES.PR ? "pr" : (options == VALUES.TAS ? "tas" : null));

            if (dataType == null)
            {
                throw new Exception("illegal argument on GetClimateValues, choose between VALUES.PT for precepitation and VALUES.TAS for temperature");
            }

            string request = PATH
                             .Replace("{0}", dataType)
                             .Replace("{1}", dateFrom.ToString())
                             .Replace("{2}", dateTo.ToString());

            string body = req.GetBody(request);

            CsvParser <ClimateValues> values =
                new CsvParser <ClimateValues>()
                .CtorArg("gCM", 0)
                .CtorArg("variableType", 1)
                .CtorArg("jan", 4)
                .CtorArg("feb", 5)
                .CtorArg("mar", 6);

            IEnumerable <ClimateValues> items = values
                                                .Load(body)
                                                .Remove(1)
                                                .RemoveEmpties()
                                                .Parse();

            return(items.Select(x => (ClimateValues)x).ToArray());
        }
Esempio n. 7
0
        public bool CanGetResponse(IHttpRequest request)
        {
            if (request.GetMethod() == HttpMethods.Get)
            {
                return(request.GetBody() == null);
            }

            return(true);
        }
Esempio n. 8
0
        private static string getText(IHttpRequest request)
        {
            var bytes = request.GetBody();

            if (bytes == null)
            {
                return(string.Empty);
            }
            return(Encoding.UTF8.GetString(bytes));
        }
Esempio n. 9
0
        public void TestLoadSearchOportoOnRequestMock()
        {
            Mocker mocker = new Mocker(typeof(IHttpRequest));

            mocker
            .When("GetBody")
            .With("www.somerequest.com")
            .Return("response");

            mocker
            .When("GetBody")
            .With("www.anotherrequest.com")
            .Return("anotherresponse");

            IHttpRequest req = (IHttpRequest)mocker.Create();

            Assert.AreEqual(req.GetBody("www.somerequest.com"), "response");
            Assert.AreEqual(req.GetBody("www.anotherrequest.com"), "anotherresponse");
            Assert.AreEqual(req.GetBody("www.notDifinedRequest.com"), 0);;
        }
Esempio n. 10
0
        public IEnumerable <AnnualAverage> PastAnnualAverage(string var, string start, string end, string countryCode)
        {
            string url = GetAnnualAvgUrl(var, start, end, countryCode);

            string body = req.GetBody(url);

            annualAvg
            .CtorArg("gcm", 0)
            .CtorArg("measure", 1)
            .CtorArg("average", 4)
            .PropArg("Beginning", 2)
            .PropArg("End", 3);

            IEnumerable <AnnualAverage> items = annualAvg
                                                .Load(body)
                                                .Remove(1)
                                                .RemoveEmpties()
                                                .Parse();

            return(items);
        }
Esempio n. 11
0
        public void ShouldGetBodyWithDelegate()
        {
            string oportoSearchUrl = "http://api.worldweatheronline.com/premium/v1/search.ashx?query=oporto&format=tab&key=ccb0b4929d574c7cb5f183401191305";

            Mocker mockReq = new Mocker(typeof(IHttpRequest));

            mockReq.When("GetBody").Then <string, string>(url => new WebClient().DownloadString(url)).With(oportoSearchUrl);
            IHttpRequest req = (IHttpRequest)mockReq.Create();

            string expected = "#The Search API\r\n#Data returned is laid out in the following order:-\r\n#AreaName    Country     Region(If available)    Latitude    Longitude   Population(if available)    Weather Forecast URL\r\n#\r\nOporto\tSpain\tGalicia\t42.383\t-7.100\t0\thttp://api-cdn.worldweatheronline.com/v2/weather.aspx?q=42.3833,-7.1\nOporto\tPortugal\tPorto\t41.150\t-8.617\t0\thttp://api-cdn.worldweatheronline.com/v2/weather.aspx?q=41.15,-8.6167\nOporto\tSouth Africa\tLimpopo\t-22.667\t29.633\t0\thttp://api-cdn.worldweatheronline.com/v2/weather.aspx?q=-22.6667,29.6333\nEl Oporto\tMexico\tTamaulipas\t23.266\t-98.768\t0\thttp://api-cdn.worldweatheronline.com/v2/weather.aspx?q=23.2658,-98.7675\nPuerto Oporto\tBolivia\tPando\t-9.933\t-66.417\t0\thttp://api-cdn.worldweatheronline.com/v2/weather.aspx?q=-9.9333,-66.4167\nOporto\tCuba\tSantiago de Cuba\t20.233\t-76.167\t0\thttp://api-cdn.worldweatheronline.com/v2/weather.aspx?q=20.2333,-76.1667\n";

            string actual = req.GetBody(oportoSearchUrl);

            Assert.AreEqual(expected, actual);
        }
Esempio n. 12
0
        /// <summary>
        ///     Create an <see cref="HttpWebRequest" /> from the given <see cref="IHttpRequest" /> instance
        /// </summary>
        /// <param name="request">The instance of <see cref="IHttpRequest" /></param>
        /// <param name="progress">The progress reporter</param>
        /// <returns>An instance of <see cref="HttpWebRequest" /></returns>
        protected virtual HttpWebRequest CreateRequest(IHttpRequest request, IProgress <double> progress)
        {
            var            uri = request.GetUri();
            HttpWebRequest realRequest;

            if (uri.Scheme == Uri.UriSchemeHttps)
            {
                realRequest = WebRequest.CreateHttp(uri);
                realRequest.ProtocolVersion = HttpVersion.Version10;
            }
            else
            {
                realRequest = WebRequest.CreateHttp(request.GetUri());
            }

            realRequest.Method = request.GetMethod();
            var headers = request.GetHeaders();

            headers.Keys.ToList().ForEach(key => { realRequest.Headers.Add(key, headers[key]); });
            return(SetBody(realRequest, request.GetBody(), progress));
        }
Esempio n. 13
0
        public AppUsageData[] PastAppUsage(string timeGrain, string table, string[] metric, DateTime from, DateTime to)
        {
            string dateRange = String.Format(from.ToString("dd-MM-yyyy"), "/", to.ToString("dd-MM-yyyy"));
            String url       = String.Format(PATH_APP_USAGE, timeGrain, metric, dateRange, FLURRY_TOKEN);

            string body = req.GetBody(url);

            //Configuration
            appUsage
            .Load(body)
            .CtorArg("xxx", 0);
            //Utilization
            object[] items = appUsage
                             .Load(body)
                             .RemoveWith("#")
                             .Remove(1)
                             .RemoveEvenIndexes()
                             .Parse();

            return((AppUsageData[])items);
        }
 public IHttpResponse GetResponse(IHttpRequest request, Interfaces.Infrastructure.IProgress <double> progress = null)
 {
     #if DEBUG
     var time1 = DateTime.Now;
     #endif
     var requestMessage = new HttpRequestMessage(HttpMethod.Get, request.GetUri())
     {
         Content = new StreamContent(request.GetBody())
     };
     requestMessage.Headers.Clear();
     requestMessage.Content.Headers.Clear();
     request.GetHeaders().Where(header => !header.Key.StartsWith("Content")).ToList()
     .ForEach(header => requestMessage.Headers.Add(header.Key, header.Value));
     request.GetHeaders().Where(header => header.Key.StartsWith("Content")).ToList()
     .ForEach(header => requestMessage.Content.Headers.Add(header.Key, header.Value));
     var responseMessage = Client.SendAsync(requestMessage).Result;
     var response        = new GetWithPayloadHttpResponse(responseMessage);
     #if DEBUG
     var time2 = DateTime.Now;
     Debug(
         $"[{(time2 - time1).TotalMilliseconds} ms]-[{request.GetMethod()}] {request.GetUri()} {Environment.NewLine} {response.GetResponseStream().AsString()}");
     #endif
     return(response);
 }
Esempio n. 15
0
        public void LocationInfoCustomAttribute()
        {
            const string WEATHER_KEY  = "1368ef2d6f8a41d19a4171602191205";
            const string WEATHER_HOST = "http://api.worldweatheronline.com/premium/v1/";
            const string SEARCH       = WEATHER_HOST + "search.ashx?query={0}&format=tab&key=" + WEATHER_KEY;

            req = new HttpRequest();

            string path = SEARCH.Replace("{0}", "oporto");

            string body = req.GetBody(path);

            CsvParser <LocationInfo> location = new CsvParser <LocationInfo>('\t');

            CsvCorrespondenceAttr <LocationInfo> .MakeAttributeCorrespondence(location, typeof(LocationInfo)); // this makes the correspondence between ctorArgs, fieldArgs and paramArgs

            IEnumerable <LocationInfo> locationInfo = location
                                                      .Load(body)
                                                      .Remove(4)
                                                      .RemoveEmpties()
                                                      .Parse();

            Assert.AreEqual(6, locationInfo.Count());
        }
Esempio n. 16
0
        private void NewFileAgentInventoryVariablePriceUploadHandler(NewFileAgentInventoryVariablePriceMessage message, Capability cap,
            IHttpClientContext context, IHttpRequest request, IHttpResponse response)
        {
            byte[] assetData = request.GetBody();
            UUID assetID = UUID.Zero;
            LLInventoryItem item = null;

            m_log.Debug("Received inventory asset upload from " + cap.OwnerID + " (" + assetData.Length + " bytes)");

            if (assetData != null && assetData.Length > 0)
            {
                string contentType = LLUtil.LLAssetTypeToContentType((int)message.AssetType);

                // Create the asset
                if (m_assetClient.StoreAsset(contentType, false, false, assetData, cap.OwnerID, out assetID))
                {
                    // Create the inventory item
                    item = new LLInventoryItem();
                    item.AssetID = assetID;
                    item.ContentType = contentType;
                    item.CreationDate = DateTime.UtcNow;
                    item.CreatorID = cap.OwnerID;
                    item.Description = message.Description;
                    item.ID = UUID.Random();
                    item.Name = message.Name;
                    item.OwnerID = cap.OwnerID;
                    item.ParentID = message.FolderID;

                    Permissions perms = (m_permissions != null) ? m_permissions.GetDefaultPermissions() : Permissions.FullPermissions;
                    perms.EveryoneMask = message.EveryoneMask;
                    perms.GroupMask = message.GroupMask;
                    perms.NextOwnerMask = message.NextOwnerMask;
                    item.Permissions = perms;

                    item.SalePrice = 10;
                    item.SaleType = SaleType.Not;

                    if (!m_inventoryClient.TryCreateItem(cap.OwnerID, item))
                        m_log.Warn("Failed to create inventory item for uploaded asset " + assetID);
                }
                else
                {
                    m_log.WarnFormat("Failed to store uploaded inventory asset ({0} bytes)", assetData.Length);
                }
            }
            else
            {
                m_log.Warn("Inventory asset upload contained no data");
            }

            // Build the response message
            NewFileAgentInventoryUploadReplyMessage reply = new NewFileAgentInventoryUploadReplyMessage();
            reply.NewAsset = assetID;
            if (item != null)
            {
                reply.NewInventoryItem = item.ID;
                reply.NewBaseMask = item.Permissions.BaseMask;
                reply.NewEveryoneMask = item.Permissions.EveryoneMask;
                reply.NewNextOwnerMask = item.Permissions.NextOwnerMask;
                reply.NewOwnerMask = item.Permissions.OwnerMask;
            }

            LLUtil.SendLLSDXMLResponse(response, reply.Serialize());
        }
Esempio n. 17
0
        private void NewFileAgentInventoryUploadHandler(NewFileAgentInventoryMessage message, Capability cap,
            IHttpClientContext context, IHttpRequest request, IHttpResponse response)
        {
            byte[] assetData = request.GetBody();
            UUID assetID = UUID.Zero;
            UUID itemID = UUID.Zero;

            m_log.Debug("Received inventory asset upload from " + cap.OwnerID + " (" + assetData.Length + " bytes)");

            if (assetData != null && assetData.Length > 0)
            {
                string contentType = LLUtil.LLAssetTypeToContentType((int)message.AssetType);

                // Create the asset
                if (m_assetClient.StoreAsset(contentType, false, false, assetData, cap.OwnerID, out assetID))
                {
                    // Create the inventory item
                    LLInventoryItem item = new LLInventoryItem();
                    item.AssetID = assetID;
                    item.ContentType = contentType;
                    item.CreationDate = DateTime.UtcNow;
                    item.CreatorID = cap.OwnerID;
                    item.Description = message.Description;
                    item.ID = UUID.Random();
                    item.Name = message.Name;
                    item.OwnerID = cap.OwnerID;
                    item.ParentID = message.FolderID;
                    item.Permissions = (m_permissions != null) ? m_permissions.GetDefaultPermissions() : Permissions.FullPermissions;
                    item.SalePrice = 10;
                    item.SaleType = SaleType.Not;

                    if (m_inventoryClient.TryCreateItem(cap.OwnerID, item))
                        itemID = item.ID;
                    else
                        m_log.Warn("Failed to create inventory item for uploaded asset " + assetID);
                }
                else
                {
                    m_log.WarnFormat("Failed to store uploaded inventory asset ({0} bytes)", assetData.Length);
                }
            }
            else
            {
                m_log.Warn("Inventory asset upload contained no data");
            }

            // Build the response message
            OSDMap reply = new OSDMap
            {
                { "state", OSD.FromString("complete") },
                { "new_asset", OSD.FromUUID(assetID) },
                { "new_inventory_item", OSD.FromUUID(itemID) }
            };

            LLUtil.SendLLSDXMLResponse(response, reply);
        }
Esempio n. 18
0
        private bool Register(IHttpRequest request, IHttpResponse response)
        {
            try
            {
                var postBody = Encoding.UTF8.GetString(request.GetBody());
                var r = JsonConvert.DeserializeObject<RegisterInfo>(postBody);

                if (r == null)
                    throw new Exception("Null data");

                var slave = OBBContext.Current.SlaveInfo.Where(s => s.ip == request.RemoteEndPoint.Address.ToString()).FirstOrDefault();
                if (slave == null)
                {
                    slave = new SlaveOBBInfo();
                    slave.ip = request.RemoteEndPoint.Address.ToString();
                    slave.servicePort = r.servicePort;

                    OBBContext.Current.SlaveInfo.Add(slave);
                }
                slave.GameInfo = r.game;

                Write(response, Utility.GetJsonResult(JsonStatus.OK));
                return true;
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex);
                Write(response, Utility.GetJsonResult(JsonStatus.FAIL, ex.Message));
                return false;
            }
        }
Esempio n. 19
0
 public void TestRequestGetBodyNotImplemented()
 {
     req.GetBody("");
 }
Esempio n. 20
0
        private void UploadBakedTextureDataHandler(Capability cap, IHttpClientContext context, IHttpRequest request, IHttpResponse response)
        {
            byte[] textureData = request.GetBody();
            UUID assetID = UUID.Zero;

            m_log.Debug("Received baked texture upload from " + cap.OwnerID + " (" + textureData.Length + " bytes)");

            if (textureData != null && textureData.Length > 0)
            {
                if (!m_assetClient.StoreAsset("image/x-j2c", true, true, textureData, cap.OwnerID, out assetID))
                    m_log.WarnFormat("Failed to store uploaded texture bake ({0} bytes)", textureData.Length);
            }
            else
            {
                m_log.Warn("Texture bake upload contained no data");
            }

            UploadBakedTextureMessage reply = new UploadBakedTextureMessage();
            UploaderRequestComplete replyBlock = new UploaderRequestComplete();
            replyBlock.AssetID = assetID;
            reply.Request = replyBlock;

            LLUtil.SendLLSDXMLResponse(response, reply.Serialize());
        }
 public void TestHttpRequestSuccessfully()
 {
     Assert.AreEqual(req.GetBody("www.somerequest.com"), "response");
     Assert.AreEqual(req.GetBody("www.anotherrequest.com"), "anotherresponse");
     Assert.AreEqual(req.GetBody("www.notDifinedRequest.com"), 0); //when returns 0 the cast throws an exception
 }
Esempio n. 22
0
        HttpStatusCode PutHandler(IHttpRequest request, string path, string username)
        {
            try
            {
                byte[] assetData = request.GetBody();

                string[] pathParts = path.Split('/');
                string parentPath = String.Empty;
                for (int i = 0; i < pathParts.Length - 1; i++)
                {
                    parentPath += pathParts[i];
                    parentPath += "/";
                }

                string contentType = request.Headers["Content-type"];
                int assetType = -1; //unknown
                if (contentType != null && contentType != String.Empty)
                {
                    m_log.DebugFormat("[WORLDINVENTORY]: Found content-type {0} for put request to {1}", contentType, path);
                    assetType = MimeTypeConverter.GetAssetTypeFromMimeType(contentType);
                }
                else
                {
                    //missing content type
                    m_log.WarnFormat("[WORLDINVENTORY]: Could not find content-type from request {0} headers. Trying to parse from file extension", path);
                    string[] fileParts = pathParts[pathParts.Length - 1].Split('.');
                    if (fileParts.Length > 1)
                    {
                        string fileExtension = fileParts[fileParts.Length - 1];
                        assetType = MimeTypeConverter.GetAssetTypeFromFileExtension(fileExtension);
                    }
                    contentType = MimeTypeConverter.GetContentType(assetType);
                }

                AssetBase asset = new AssetBase(UUID.Random(), pathParts[pathParts.Length - 1], (sbyte)assetType, m_scenes[0].RegionInfo.EstateSettings.EstateOwner.ToString());
                asset.Local = false;

                if (m_autoconvertJpgToJ2k && assetType == (int)AssetType.ImageJPEG)
                {
                    System.IO.MemoryStream ms = new System.IO.MemoryStream(assetData);
                    System.Drawing.Bitmap bitmap = (System.Drawing.Bitmap)System.Drawing.Image.FromStream(ms);
                    assetData = OpenMetaverse.Imaging.OpenJPEG.EncodeFromImage(bitmap, false);
                    asset.Type = (int)AssetType.Texture;
                    asset.Name = ReplaceFileExtension(asset.Name, "jp2");
                }

                asset.Data = assetData;
                m_scenes[0].AssetService.Store(asset);

                AssetFolder oldAsset = m_assetFolderStrg.GetItem(parentPath, asset.Name);
                if (oldAsset != null)
                {
                    m_log.InfoFormat("[WORLDINVENTORY]: Replacing old asset {0} with new", oldAsset.Name);
                    if (!m_assetFolderStrg.RemoveItem(oldAsset))
                    {
                        return HttpStatusCode.Conflict;
                    }
                }
                m_assetFolderStrg.Save(new AssetFolderItem(parentPath, asset.Name, asset.FullID));

                IWebDAVResource oldProp = m_propertyMngr.GetResource(path);
                if (oldProp == null)
                {
                    WebDAVFile prop = new WebDAVFile(path, contentType, asset.Data.Length, asset.Metadata.CreationDate, asset.Metadata.CreationDate, DateTime.Now, false, false);
                    prop.AddProperty(new WebDAVProperty("AssetID", "http://www.realxtend.org/", asset.FullID.ToString()));
                    m_propertyMngr.SaveResource(prop);
                }
                else
                {
                    WebDAVProperty assetIdProp = null;
                    foreach (WebDAVProperty prop in oldProp.CustomProperties)
                    {
                        if (prop.Name == "AssetID" && prop.Namespace == "http://www.realxtend.org/")
                            assetIdProp = prop;
                    }
                    if (assetIdProp != null)
                        oldProp.CustomProperties.Remove(assetIdProp);
                    oldProp.AddProperty(new WebDAVProperty("AssetID", "http://www.realxtend.org/", asset.FullID.ToString()));
                    m_propertyMngr.SaveResource(oldProp);
                }

                return HttpStatusCode.Created;
            }
            catch (Exception e)
            {
                m_log.ErrorFormat("[WORLDINVENTORY]: Failed to put resource to {0}. Exception {1} occurred.", path, e.ToString());
                return HttpStatusCode.InternalServerError;
            }
        }
Esempio n. 23
0
        private static string getText(IHttpRequest request)
        {
            var bytes = request.GetBody();

            return(bytes == null ? string.Empty : Encoding.UTF8.GetString(bytes));
        }
 public bool CanGetResponse(IHttpRequest request)
 {
     return(request.GetMethod() == HttpMethods.Get && request.GetBody() != null);
 }
 public void TestRequestSuccessfully()
 {
     Assert.AreEqual(pastWeatherForLisbon, req.GetBody(pastWeatherForLisbonUrl));
 }
Esempio n. 26
0
        private void NewFileAgentInventoryVariablePriceUploadHandler(NewFileAgentInventoryVariablePriceMessage message, Capability cap,
                                                                     IHttpClientContext context, IHttpRequest request, IHttpResponse response)
        {
            byte[]          assetData = request.GetBody();
            UUID            assetID   = UUID.Zero;
            LLInventoryItem item      = null;

            m_log.Debug("Received inventory asset upload from " + cap.OwnerID + " (" + assetData.Length + " bytes)");

            if (assetData != null && assetData.Length > 0)
            {
                string contentType = LLUtil.LLAssetTypeToContentType((int)message.AssetType);

                // Create the asset
                if (m_assetClient.StoreAsset(contentType, false, false, assetData, cap.OwnerID, out assetID))
                {
                    // Create the inventory item
                    item              = new LLInventoryItem();
                    item.AssetID      = assetID;
                    item.ContentType  = contentType;
                    item.CreationDate = DateTime.UtcNow;
                    item.CreatorID    = cap.OwnerID;
                    item.Description  = message.Description;
                    item.ID           = UUID.Random();
                    item.Name         = message.Name;
                    item.OwnerID      = cap.OwnerID;
                    item.ParentID     = message.FolderID;

                    Permissions perms = (m_permissions != null) ? m_permissions.GetDefaultPermissions() : Permissions.FullPermissions;
                    perms.EveryoneMask  = message.EveryoneMask;
                    perms.GroupMask     = message.GroupMask;
                    perms.NextOwnerMask = message.NextOwnerMask;
                    item.Permissions    = perms;

                    item.SalePrice = 10;
                    item.SaleType  = SaleType.Not;

                    if (!m_inventoryClient.TryCreateItem(cap.OwnerID, item))
                    {
                        m_log.Warn("Failed to create inventory item for uploaded asset " + assetID);
                    }
                }
                else
                {
                    m_log.WarnFormat("Failed to store uploaded inventory asset ({0} bytes)", assetData.Length);
                }
            }
            else
            {
                m_log.Warn("Inventory asset upload contained no data");
            }

            // Build the response message
            NewFileAgentInventoryUploadReplyMessage reply = new NewFileAgentInventoryUploadReplyMessage();

            reply.NewAsset = assetID;
            if (item != null)
            {
                reply.NewInventoryItem = item.ID;
                reply.NewBaseMask      = item.Permissions.BaseMask;
                reply.NewEveryoneMask  = item.Permissions.EveryoneMask;
                reply.NewNextOwnerMask = item.Permissions.NextOwnerMask;
                reply.NewOwnerMask     = item.Permissions.OwnerMask;
            }

            LLUtil.SendLLSDXMLResponse(response, reply.Serialize());
        }