public void RestSessionRequestHeaderValueNullTest()
        {
            var h = new RestSession(null, new SessionContext(), null);

            Assert.IsTrue(string.IsNullOrEmpty(h.RequestHeaderValue(null)));
            Assert.IsTrue(string.IsNullOrEmpty(h.ResponseHeaderValue(null)));
        }
        private static T wrapExceptions <T>(RestSession session, Wrapped <T> wrapped)
        {
            T result = wrapped();

            session.logout();
            return(result);
        }
        private static RestSession createSessionAndLogin(BambooServer server)
        {
            RestSession s = new RestSession(server);

            s.login(server.UserName, server.Password);
            return(s);
        }
        public async Task <GetWifiEventsResult> GetEvents(RestSession session, string objectId)
        {
            var headers = SessionToHeaders(session);

            var parameters = new Dictionary <string, string>
            {
                { "where", $"{{\"device\":{{\"__type\":\"Pointer\",\"className\":\"Device\",\"objectId\":\"{objectId}\"}}}}" }
            };

            var result = await _restService.SendRestGetRequest(GetWifiEventsLink, headers, parameters);

            if (result.Status == RestResponseStatus.Ok)
            {
                var message    = JsonSerializer.Deserialize <WifiEventMessage>(result.Data);
                var wifiEvents = message.WifiEvents.Select(row => new WifiEvent(EnumerationExtensions.GetEnumValueFromDescription <WifiEventType>(row.EventType), row.CreatedAt));

                return(new GetWifiEventsResult {
                    ResponseStatus = RestResponseStatus.Ok, WifiEvents = wifiEvents
                });
            }

            return(new GetWifiEventsResult {
                ResponseStatus = RestResponseStatus.Error
            });
        }
        protected Dictionary <string, string> SessionToHeaders(RestSession session)
        {
            var headers = LoginConfigurationToHeaders(session.Configuration);

            headers.Add("X-Parse-Session-Token", session.SessionToken);

            return(headers);
        }
Exemple #6
0
        public async Task <RestResponseStatus> DeleteDevice(RestSession session, string objectId)
        {
            var url     = string.Format(DeleteDeviceLink, objectId);
            var headers = SessionToHeaders(session);

            var result = await _restService.SendRestDeleteRequest(url, headers);

            return(result.Status);
        }
        public ConnectionHandler()
        {
            _session      = new RestSession();
            _loginService = new LoginService();

            var configurationReader = new ConfigurationReader();

            _session.Configuration = configurationReader.GetRestConfiguration();
        }
Exemple #8
0
        public async Task <RestResponseStatus> UpdateDeviceName(RestSession session, string deviceName)
        {
            var url     = string.Format(UpdateDeviceLink, session.ObjectId);
            var headers = SessionToHeaders(session);
            var content = $"{{deviceName:{deviceName}}}";

            var result = await _restService.SendRestPutRequest(url, headers, content);

            return(result.Status);
        }
        public void RestSessionNullValueTest()
        {
            var session = new RestSession(null, null, null)
            {
                Body = null
            };

            Assert.IsNull(session.ResponseText);
            Assert.IsNull(session.Body);
        }
Exemple #10
0
        public async Task <RestResponseStatus> CreateDeviceRecord(RestSession session, Device record)
        {
            var headers = SessionToHeaders(session);

            var content = JsonSerializer.Serialize(record);

            var result = await _restService.SendRestPostRequest(CreateDeviceUrl, headers, content);

            return(result.Status);
        }
        public async Task <LoginStatus> Connect(string username, string password)
        {
            var result = await _loginService.Login(_session.Configuration, username, password);

            if (result.ResultStatus == LoginStatus.Successful)
            {
                _session = result.Session;
            }

            _lastLoginStatus = result.ResultStatus;
            return(result.ResultStatus);
        }
        public void RestSessionMakeRequestTest()
        {
            const string textBody = "random text";
            var          h        = new RestSession(null, new SessionContext(), new RestRequestMockFactory())
            {
                Body     = textBody,
                EndPoint = new Uri("http://localhost")
            };

            Assert.IsTrue(h.MakeRequest("Get", "api"), "MakeRequest succeeds");
            Assert.AreEqual("http://localhost/api", h.Request.RequestUri.AbsoluteUri, "RequestUri OK");
            var m = (RestRequestMock)h.Request;

            Assert.IsTrue(m.ExecuteWasCalled, "Execute was called");
        }
        public void AppendSessionIdCookie(RestSession session)
        {
            Cookie cookie = m_response.Cookies[RestSessionManager.SESSION_KEY];

            if (cookie != null)
            {
                cookie.Value = session.SessionID;
            }
            else
            {
                cookie         = new Cookie(RestSessionManager.SESSION_KEY, session.SessionID, "/");
                cookie.Expires = DateTime.Now.AddMinutes(RestSessionManager.SESSION_EXPIRATION_MINUTES);
                m_response.Cookies.Add(cookie);
            }
        }
        public void RestSessionSetBodyTest()
        {
            const string textBody = "Text Line 1\r\nTextLine2\r\n";
            var          h        = new RestSession(null, null, null)
            {
                Body = textBody
            };

            Assert.AreEqual(h.Body, textBody);

            const string jsonBodyIn  = "{\"title\": \"Test Data\",\r\n \"body\": \"Test Body\",\r\n \"userId\":96\r\n }";
            const string jsonBodyOut = "{\"title\": \"Test Data\", \"body\": \"Test Body\", \"userId\":96 }";

            h.Body = jsonBodyIn;
            Assert.AreEqual(h.Body, jsonBodyOut);
        }
        public async Task <GetAllDevicesResult> GetAllDevices(RestSession session)
        {
            var headers = SessionToHeaders(session);

            var result = await _restService.SendRestGetRequest(GetAllDevicesLink, headers);

            if (result.Status == RestResponseStatus.Ok)
            {
                var devices = JsonSerializer.Deserialize <List <DeviceRecord> >(result.Data);

                return(new GetAllDevicesResult {
                    Devices = devices, ResponseStatus = RestResponseStatus.Ok
                });
            }

            return(new GetAllDevicesResult {
                ResponseStatus = result.Status
            });
        }
Exemple #16
0
        public async Task <GetDeviceRecordResult> GetDeviceRecord(RestSession session, string objectId)
        {
            var url     = string.Format(GetDeviceRecordLink, objectId);
            var headers = SessionToHeaders(session);

            var result = await _restService.SendRestGetRequest(url, headers);

            if (result.Status == RestResponseStatus.Ok)
            {
                var deviceRecord = JsonSerializer.Deserialize <DeviceRecord>(result.Data);

                return(new GetDeviceRecordResult {
                    Record = deviceRecord, ResponseStatus = RestResponseStatus.Ok
                });
            }

            return(new GetDeviceRecordResult {
                ResponseStatus = result.Status
            });
        }
        public async Task <RestResponseStatus> PostDeviceStatusUpdate(RestSession session, DeviceStatusUpdate statusUpdate)
        {
            var headers = SessionToHeaders(session);
            var message = new StatusUpdateMessage
            {
                Country = statusUpdate.Country.ToString(),
                Traffic = statusUpdate.Traffic,
                Device  = new Device
                {
                    ClassName = "Device",
                    Type      = "Pointer",
                    ObjectId  = session.ObjectId
                }
            };

            var content = JsonSerializer.Serialize(message);

            var result = await _restService.SendRestPostRequest(PostDeviceStatusLink, headers, content);

            return(result.Status);
        }
        public ICollection <BambooPlan> getPlanList(BambooServer server)
        {
            RestSession session = createSessionAndLogin(server);

            return(wrapExceptions(session, () => session.getAllPlans()));
        }
        public BambooBuild getBuildByKey(BambooServer server, string buildKey)
        {
            RestSession session = createSessionAndLogin(server);

            return(wrapExceptions(session, () => session.getBuildByKey(buildKey)));
        }
//        public string getBuildLog(BambooBuild build) {
//            RestSession session = createSessionAndLogin(build.Server);
//            return wrapExceptions(session, () => session.getBuildLog(build));
//        }

        public string getBuildLog(BambooServer server, string logUrl)
        {
            RestSession session = createSessionAndLogin(server);

            return(wrapExceptions(session, () => session.getBuildLog(logUrl)));
        }
 /// <summary>Instantiate REST tester with endpoint URL</summary>
 /// <param name="endPoint">URL of the end point (base URL) of the REST server</param>
 /// <remarks>
 ///     Taking a dependency on the injector since this is an entry point for FitNesse,
 ///     so we don't want the dependencies to be injected via the constructor here
 /// </remarks>
 public RestTester(string endPoint)
 {
     _session = Injector.InjectRestSession(endPoint);
     _contentObjectFactory = Injector.InjectContentObjectFactory();
 }
        public ICollection <BuildArtifact> getArtifacts(BambooBuild build)
        {
            RestSession session = createSessionAndLogin(build.Server);

            return(wrapExceptions(session, () => session.getArtifacts(build.Key)));
        }
 private static void wrapExceptionsVoid(RestSession session, WrappedVoid wrapped)
 {
     wrapped();
     session.logout();
 }
        public void runBuild(BambooServer server, string planKey)
        {
            RestSession session = createSessionAndLogin(server);

            wrapExceptionsVoid(session, () => session.runBuild(planKey));
        }
        public void addLabel(BambooServer server, string planKey, int buildNumber, string label)
        {
            RestSession session = createSessionAndLogin(server);

            wrapExceptionsVoid(session, () => session.addLabel(planKey, buildNumber, label));
        }
    //---------------------------------------------------------------------
    //-------------------------  PUBLIC METHODS  --------------------------
    //---------------------------------------------------------------------

    // Use this to do a POST and create a session
    public IEnumerator LOGINUser(string email, string password)
    {
        bool allProper = false;
        int retryCount = NumberOfRetries;

        // First thing first - I need to do some cleanup of the email string
        // And I need to store those informations for other calls
        login_email = CleanInput(email);
        login_password = password;

        JSONObject nested_fields = new JSONObject(JSONObject.Type.OBJECT);
        nested_fields.AddField("email", login_email);
        nested_fields.AddField("password", login_password);
        JSONObject root_field = new JSONObject(JSONObject.Type.OBJECT);
        root_field.AddField("user", nested_fields);

        string encodedString = root_field.ToString();

        string result = "";

        while (!allProper && retryCount > 0)
        {
            // the actual call, in a try catch
            try
            {
                using (var client = new WebClient())
                {
                    client.Headers[HttpRequestHeader.ContentType] = "application/json";
                    result = client.UploadString(login_url, "POST", encodedString);
                }
                allProper = true;
            }
            catch (WebException ex)
            {
                retryCount--;

                if (retryCount == 0)
                {
                    Debug.Log("TESTexception: " + ex);
                    var response = ex.Response as HttpWebResponse;
                    errorHandler = RestError.GenericLoginError;

                    if (response != null)
                    {
                        Debug.Log("HTTP Status Code: " + (int)response.StatusCode);
                        switch ((int)response.StatusCode)
                        {

                            case 400:
                                errorHandler = RestError.WrongMail;
                                break;
                            case 401:
                                errorHandler = RestError.WrongPassword;
                                break;
                            case 500:
                                errorHandler = RestError.ServerError;
                                break;
                            default:
                                break;
                        }
                        break;
                    }
                }
            }
        }

        yield return result;

        if (allProper)
        {
            errorHandler = RestError.AllGood;

            Debug.Log(result);
            JSONObject j = new JSONObject(result);
            // this won't work everytime
            Dictionary<string, string> decoded_response = j.ToDictionary();
            token = decoded_response["token"];
            logged_user_complete_name = decoded_response["complete_name"];
            logged_user_id = decoded_response["id"];


            int sessionCounter = int.Parse(decoded_response["sessions_counter"]);

            if (sessionCounter > 0)
            {
                sessionsHandler = RestSession.MultipleActive;
            }
        }
    }
        public ICollection <BambooBuild> getLastNBuildsForPlan(BambooServer server, string planKey, int howMany)
        {
            RestSession session = createSessionAndLogin(server);

            return(wrapExceptions(session, () => session.getLastNBuildsForPlan(planKey, howMany)));
        }
        public ICollection <BambooBuild> getLatestBuildsForPlanKeys(BambooServer server, ICollection <string> keys)
        {
            RestSession session = createSessionAndLogin(server);

            return(wrapExceptions(session, () => session.getLatestBuildsForPlanKeys(keys)));
        }
        public ICollection <BambooBuild> getLatestBuildsForFavouritePlans(BambooServer server)
        {
            RestSession session = createSessionAndLogin(server);

            return(wrapExceptions(session, () => session.getLatestBuildsForFavouritePlans()));
        }
        void ListenerCallback(IAsyncResult asyncRequest)
        {
            HttpListenerContext context  = m_httpListener.EndGetContext(asyncRequest);
            RestRequest         request  = new RestRequest(context.Request);
            RestResponse        response = new RestResponse(context.Response);
            Type   restModuleType        = null;
            string result = "";

            bool        isNewSession = false;
            RestSession session      = m_sessionManager.GetSession(request, out isNewSession);

            m_logger.LogInfo("Server received: " + request.ToString());

            if (m_restModuleTypes.TryGetValue(request.RESTModuleName, out restModuleType))
            {
                // Find the method on the module by name
                MethodInfo method = restModuleType.GetMethod(request.RESTMethodName);

                if (method != null)
                {
                    // Attempt to convert convert all string arguments over to the corresponding native types
                    try
                    {
                        ParameterInfo[] methodParameters = method.GetParameters();
                        object[]        parameters       = new object[methodParameters.Length];

                        for (int parameterIndex = 0; parameterIndex < parameters.Length; parameterIndex++)
                        {
                            Type   parameterType   = methodParameters[parameterIndex].ParameterType;
                            string parameterName   = methodParameters[parameterIndex].Name;
                            string stringParameter = request.RESTMethodParameters[parameterName];

                            parameters[parameterIndex] = Convert.ChangeType(stringParameter, parameterType);
                        }

                        // Attempt to call the REST method
                        try
                        {
                            ICacheAdapter    applicationCacheAdapter = new DictionaryCacheAdapter(m_applicationCache);
                            ISessionAdapter  sessionAdapter          = session;
                            IResponseAdapter responseAdapter         = response;

                            RestModule restModule =
                                (RestModule)Activator.CreateInstance(
                                    restModuleType,
                                    applicationCacheAdapter,
                                    sessionAdapter,
                                    responseAdapter);

                            object methodResult = method.Invoke(restModule, parameters);

                            result = methodResult.ToString();
                        }
                        catch (System.Exception ex)
                        {
                            result = "Failed to invoke REST Method: " + ex.Message;
                            m_logger.LogError(result);
                        }
                    }
                    catch (System.Exception ex)
                    {
                        result = "Malformed REST Parameters: " + ex.Message;
                        m_logger.LogError(result);
                    }
                }
                else
                {
                    result = "Unknown REST Method: " + request.RESTMethodName;
                    m_logger.LogError(result);
                }
            }
            else
            {
                result = "Unknown REST Module: " + request.RESTModuleName;
                m_logger.LogError(result);
            }

            // If the module wants the session to be abandoned free it from the session manager
            if (session.IsAbandoned)
            {
                m_sessionManager.FreeSession(session);
            }
            // If this is a new session, give the client the session cookie
            else if (isNewSession)
            {
                response.AppendSessionIdCookie(session);
            }

            // If there was any result string from the rest method, assign it to the result
            if (result.Length > 0)
            {
                response.SetBody(result);
            }

            response.Close();
        }
        public void addComment(BambooServer server, string planKey, int buildNumber, string comment)
        {
            RestSession session = createSessionAndLogin(server);

            wrapExceptionsVoid(session, () => session.addComment(planKey, buildNumber, comment));
        }