Example #1
0
    protected override void OnStartRunning()
    {
        batches = new RequestBatch[MAX_QUERIES];
        for (var i = 0; i < MAX_QUERIES; ++i)
        {
            batches[i] = new RequestBatch(2000);
        }
        waitingEntities = new NativeQueue <Entity>(Allocator.Persistent);
        counter         = new NativeCounter(Allocator.Persistent);

        endFence = new JobHandle();
    }
        //---------------------------------------------------------------------
        private bool ModifyRequestGroup(RequestBatch batch, string group, object[] data)
        {
            RequestGroup requestGroup = GetRequestGroup(batch, group);

            if (requestGroup == null)
            {
                return(false);
            }

            requestGroup.datas = data;

            return(true);
        }
        //---------------------------------------------------------------------
        private RequestBatch GetRequestBatch(RequestType type)
        {
            for (int i = 0; i < m_RequestBatchs.Count; ++i)
            {
                RequestBatch batch = m_RequestBatchs[i];
                if (batch.type == type)
                {
                    return(batch);
                }
            }

            return(null);
        }
Example #4
0
 private void UpdateEditorCount(RequestBatch batch)
 {
     foreach (Request request in batch.Requests)
     {
         if (request is JoinCoauthoringRequest)
         {
             this.editorCount++;
         }
         else if (request is ExitCoauthoringRequest)
         {
             this.Saver.SaveAndThrowExceptions();
             this.editorCount--;
         }
     }
 }
Example #5
0
        /// <summary>
        /// Serialize <see cref="RequestBatch"/>.
        /// </summary>
        /// <param name="request">Request to serialize</param>
        private void SerializeRequestBatch(RequestBatch request)
        {
            if (this.versionToUse < SerializationFormatVersions.Version15)
            {
                throw new ArgumentException("This session doesn't support Batch Requests");
            }

            this.binaryWriter.Write((ushort)request.Requests.Count);
            foreach (IRingMasterRequest req in request.Requests)
            {
                this.SerializeRingmasterRequest(req);
            }

            this.binaryWriter.Write((bool)request.CompleteSynchronously);
        }
Example #6
0
        /// <summary>
        /// Verify that ringmaster correctly handles a batch sent to the Transaction Manager execution queue with just book keeping requests.
        /// </summary>
        /// <returns>A <see cref="Task"/> that tracks completion of this test</returns>
        /// <remarks>
        /// RDBug 6351033: When a batch with just book keeping requests was sent to RingMaster,
        /// it did not update an internal variable that tracked last applied batch id and refused
        /// the subsequent batches.  This verifies the fix for that issue.
        /// </remarks>
        public async Task TestTransactionManagerExecutionQueue_EmptyBatch()
        {
            using (var ringMaster = this.ConnectToRingMaster())
            {
                IRingMasterRequestHandler ringMasterRequestHandler = (IRingMasterRequestHandler)ringMaster;
                ulong lastAppliedBatchId = await QueryRingMasterLastAppliedBatchId(ringMaster);

                ulong batchId = lastAppliedBatchId + 1;

                // First send a regular batch to initialize the lastAppliedBatchId tracker in RM
                RequestBatch    initializationBatch = CreateBatch(batchId, CreateTransaction(1));
                RequestResponse batchResponse       = await ringMasterRequestHandler.Request(initializationBatch);

                Assert.AreEqual((int)RingMasterException.Code.Ok, batchResponse.ResultCode);

                lastAppliedBatchId = await QueryRingMasterLastAppliedBatchId(ringMaster);

                batchId = lastAppliedBatchId + 1;

                // Create a batch with only book keeping requests.
                RequestBatch firstBatch = CreateBatch(batchId);

                Trace.TraceInformation("Sending first batch. batchId={0}, executionQueueId={1}", batchId, firstBatch.ExecutionQueueId);
                batchResponse = await ringMasterRequestHandler.Request(firstBatch);

                Assert.AreEqual((int)RingMasterException.Code.Ok, batchResponse.ResultCode);

                // The last applied batch id value must have been updated.
                lastAppliedBatchId = await QueryRingMasterLastAppliedBatchId(ringMaster);

                Trace.TraceInformation("After first batch. lastAppliedBatchId={0}", lastAppliedBatchId);
                Assert.AreEqual(batchId, lastAppliedBatchId);

                // Verify that the internal last applied batch id variable has been updated and subsequent
                // batches will be accepted.
                batchId = lastAppliedBatchId + 1;
                RequestBatch secondBatch = CreateBatch(batchId);
                Trace.TraceInformation("Sending second batch. batchId={0} executionQueueId={1}", batchId, secondBatch.ExecutionQueueId);
                batchResponse = await ringMasterRequestHandler.Request(secondBatch);

                Assert.AreEqual((int)RingMasterException.Code.Ok, batchResponse.ResultCode);

                lastAppliedBatchId = await QueryRingMasterLastAppliedBatchId(ringMaster);

                Trace.TraceInformation("After second batch. lastAppliedBatchId={0}", lastAppliedBatchId);
                Assert.AreEqual(batchId, lastAppliedBatchId);
            }
        }
Example #7
0
        /// <summary>
        /// Create a batch request which contains the given requests and book keeping requests.
        /// </summary>
        /// <param name="batchId">Id of the batch</param>
        /// <param name="requests">Requests to include in the batch</param>
        /// <returns>A <see cref="RequestBatch"/> that contains the given requests and book keeping requests</returns>
        private static RequestBatch CreateBatch(ulong batchId, params IRingMasterRequest[] requests)
        {
            var requestArray = new IRingMasterRequest[2 + requests.Length];

            requestArray[0] = new RequestSetData(TestExecutionQueue.LastAppliedBatchIdPath, data: BitConverter.GetBytes(batchId), version: -1);
            requests.CopyTo(requestArray, 1);
            requestArray[requestArray.Length - 1] = new RequestGetData(TestExecutionQueue.TransactionCrcPath, options: RequestGetData.GetDataOptions.None, watcher: null);

            var batchRequest = new RequestBatch(requestArray, completeSynchronously: true);

            batchRequest.Uid = batchId;
            batchRequest.ExecutionQueueId            = TransactionManagerExecutionQueueId;
            batchRequest.ExecutionQueueTimeoutMillis = 10000;

            return(batchRequest);
        }
        public void GetBatchRequestAtPositionTest()
        {
            Guid         respId  = Guid.NewGuid();
            RequestBatch rqBatch = new RequestBatch();

            rqBatch.BatchId = respId;
            List <BatchItemOrganizationRequest> batchItems = new List <BatchItemOrganizationRequest>();
            BatchItemOrganizationRequest        itmOrgRqs  = new BatchItemOrganizationRequest();

            itmOrgRqs.Request = new OrganizationRequest();
            batchItems.Add(itmOrgRqs);
            rqBatch.BatchItems = batchItems;
            MCrmServiceClient.AllInstances.GetBatchByIdGuid = (objsvcAction, guid) => { return(rqBatch); };
            OrganizationRequest result = crmaction.GetBatchRequestAtPosition(respId, 0);

            Assert.IsNotNull(result);
        }
        //---------------------------------------------------------------------
        private RequestGroup GetRequestGroup(RequestBatch batch, string group)
        {
            if (batch == null)
            {
                return(null);
            }

            for (int i = 0; i < batch.groups.Count; ++i)
            {
                RequestGroup reqeustGroup = batch.groups[i];
                if (reqeustGroup.group == group)
                {
                    return(reqeustGroup);
                }
            }

            return(null);
        }
Example #10
0
        public Atom ProcessRequest(int accessTokenId, Stream requestStream)
        {
            var token = _tokenManager.GetToken(accessTokenId);

            var atomRequest = new AtomFromStream(requestStream);

            var requestBatch = new RequestBatch();

            try
            {
                var cobaltFile = _fileManager.Get(token.FilePath) ?? _fileManager.Create(accessTokenId);

                Object ctx;
                ProtocolVersion protocolVersion;

                requestBatch.DeserializeInputFromProtocol(atomRequest, out ctx, out protocolVersion);
                cobaltFile.CobaltEndpoint.ExecuteRequestBatch(requestBatch);


                foreach (var request in requestBatch.Requests)
                {

                    if (request.GetType() == typeof (PutChangesRequest) &&
                        request.PartitionId == FilePartitionId.Content && request.CompletedSuccessfully)
                    {
                        using (var saveStream = new MemoryStream())
                        {
                            CopyStream(cobaltFile, saveStream);
                            _webDavManager.UploadFile(token.FilePath, saveStream.ToArray());
                        }
                    }
                }


                return requestBatch.SerializeOutputToProtocol(protocolVersion);
            }

            catch (Exception e)
            {
                Log.Error("Cobalt manager Process request", e);

                throw;
            }
        }
Example #11
0
        public static PhotoModerationStatus GetPhotoModerationStatus(PluckConfigElement pluckConfig, string photoKey)
        {
            var pluckService = new PluckService(pluckConfig.apiUrl);
            var authToken    = new UserAuthenticationToken(pluckConfig.userKey, pluckConfig.userNickname, pluckConfig.userEmail, pluckConfig.sharedSecret);

            var requests     = new RequestBatch();
            var photorequest = new PhotoRequest {
                PhotoKey = new PhotoKey {
                    Key = photoKey
                }
            };

            requests.AddRequest(photorequest);

            ResponseBatch responseBatch = pluckService.SendRequest(requests, authToken);
            var           photo         = (PhotoResponse)responseBatch.Envelopes[0].GetResponse();

            return(DetermineModerationStatus(photo));
        }
Example #12
0
        public Atom ProcessRequest(int accessTokenId, Stream requestStream)
        {
            var token = _tokenManager.GetToken(accessTokenId);

            var atomRequest = new AtomFromStream(requestStream);

            var requestBatch = new RequestBatch();

            try
            {
                var cobaltFile = _fileManager.Get(token.FilePath) ?? _fileManager.Create(accessTokenId);

                Object          ctx;
                ProtocolVersion protocolVersion;

                requestBatch.DeserializeInputFromProtocol(atomRequest, out ctx, out protocolVersion);
                cobaltFile.CobaltEndpoint.ExecuteRequestBatch(requestBatch);


                foreach (var request in requestBatch.Requests)
                {
                    if (request.GetType() == typeof(PutChangesRequest) &&
                        request.PartitionId == FilePartitionId.Content && request.CompletedSuccessfully)
                    {
                        using (var saveStream = new MemoryStream())
                        {
                            CopyStream(cobaltFile, saveStream);
                            _webDavManager.UploadFile(token.FilePath, saveStream.ToArray());
                        }
                    }
                }


                return(requestBatch.SerializeOutputToProtocol(protocolVersion));
            }

            catch (Exception e)
            {
                Server.Utils.Log.WriteError("Cobalt manager Process request", e);

                throw;
            }
        }
        //---------------------------------------------------------------------
        private RequestGroup PopRequestGroup()
        {
            RequestBatch batch = LastRequestBatch();

            if (batch == null)
            {
                return(null);
            }

            RequestGroup group = LastRequestGroup(batch);

            batch.groups.Remove(group);
            if (batch.groups.Count == 0)
            {
                m_RequestBatchs.Remove(batch);
            }

            return(group);
        }
        //---------------------------------------------------------------------
        private RequestBatch LastRequestBatch()
        {
            RequestBatch batch = null;
            int          index = m_RequestBatchs.Count;

            for (int i = index; i > 0; --i)
            {
                batch = m_RequestBatchs[i - 1];
                if (batch.groups.Count != 0)
                {
                    return(batch);
                }
                else
                {
                    m_RequestBatchs.Remove(batch);
                }
            }

            return(null);
        }
        //---------------------------------------------------------------------
        private bool ModifyMutexRequest(RequestType type, string group, object[] datas)
        {
            RequestBatch batch = GetRequestBatch(type);

            if (batch == null)
            {
                return(false);
            }

            RequestGroup requestGroup = GetRequestGroup(batch, group);

            if (requestGroup == null)
            {
                return(false);
            }

            requestGroup.datas = datas;

            return(true);
        }
Example #16
0
        public override Action <Stream> SetFileContent(byte[] newContent)
        {
            // Refactoring tip: there are more ways of initializing Atom
            AtomFromByteArray atomRequest  = new AtomFromByteArray(newContent);
            RequestBatch      requestBatch = new RequestBatch();

            object          ctx;
            ProtocolVersion protocolVersion;

            requestBatch.DeserializeInputFromProtocol(atomRequest, out ctx, out protocolVersion);
            ExecuteRequestBatch(requestBatch);

            if (requestBatch.Requests.Any(request => request.GetType() == typeof(PutChangesRequest) && request.PartitionId == FilePartitionId.Content))
            {
                Save();
            }
            var             response     = requestBatch.SerializeOutputToProtocol(protocolVersion);
            Action <Stream> copyToAction = s => { response.CopyTo(s); };

            return(copyToAction);
        }
        public void ExecuteBatchTest()
        {
            ExecuteMultipleRequest orgReq = null;
            Guid respId = Guid.NewGuid();

            BCrmServiceClient.MockCrmCommandExecute();
            RequestBatch rqBatch = new RequestBatch();

            rqBatch.BatchId = respId;
            List <BatchItemOrganizationRequest> batchItems = new List <BatchItemOrganizationRequest>();
            BatchItemOrganizationRequest        itmOrgRqs  = new BatchItemOrganizationRequest();

            itmOrgRqs.Request = new OrganizationRequest();
            batchItems.Add(itmOrgRqs);
            rqBatch.BatchItems = batchItems;
            MBatchManager.AllInstances.GetRequestBatchByIdGuid = (objbatchmgr, guid) => { return(rqBatch); };
            ExecuteMultipleResponse rsp = crmaction.ExecuteBatch(respId);

            Assert.AreEqual(rsp, BCrmServiceClient.GetResponse(typeof(ExecuteMultipleRequest)));
            orgReq = (ExecuteMultipleRequest)BCrmServiceClient.GetRequest(typeof(ExecuteMultipleRequest));
            Assert.IsNotNull(((ExecuteMultipleRequest)orgReq).Requests);
        }
Example #18
0
        /// <inheritdoc/>
        public Action <Stream> ProcessCobalt(IWopiFile file, ClaimsPrincipal principal, byte[] newContent)
        {
            // Refactoring tip: there are more ways of initializing Atom
            var atomRequest  = new AtomFromByteArray(newContent);
            var requestBatch = new RequestBatch();


            requestBatch.DeserializeInputFromProtocol(atomRequest, out var ctx, out var protocolVersion);
            var cobaltFile = GetCobaltFile(file, principal);

            cobaltFile.CobaltEndpoint.ExecuteRequestBatch(requestBatch);

            if (requestBatch.Requests.Any(request => request is PutChangesRequest && request.PartitionId == FilePartitionId.Content))
            {
                using var stream = file.GetWriteStream();
                new GenericFda(cobaltFile.CobaltEndpoint).GetContentStream().CopyTo(stream);
            }
            var             response     = requestBatch.SerializeOutputToProtocol(protocolVersion);
            Action <Stream> copyToAction = s => { response.CopyTo(s); };

            return(copyToAction);
        }
Example #19
0
        public static void GetPhotoModerationStatus(PluckConfigElement pluckConfig, List <string> photoKeys)
        {
            if (photoKeys.Count == 0)
            {
                return;
            }

            var          pluckService = new PluckService(pluckConfig.apiUrl);
            var          authToken    = new UserAuthenticationToken(pluckConfig.userKey, pluckConfig.userNickname, pluckConfig.userEmail, pluckConfig.sharedSecret);
            RequestBatch requests     = null;

            int numBatches = photoKeys.Count / PLUCK_BATCH_SIZE;

            if (photoKeys.Count % PLUCK_BATCH_SIZE > 0)
            {
                numBatches++;
            }

            int photoKeyIndex = 0;

            for (int batchNumber = 1; batchNumber <= numBatches; batchNumber++)
            {
                requests = new RequestBatch();
                #region build requests batch
                for (int i = 0; i < PLUCK_BATCH_SIZE; i++)
                {
                    photoKeyIndex = (batchNumber * PLUCK_BATCH_SIZE) - PLUCK_BATCH_SIZE + i;

                    if (photoKeyIndex == photoKeys.Count)
                    {
                        break;
                    }

                    var photorequest = new PhotoRequest()
                    {
                        PhotoKey = new PhotoKey {
                            Key = photoKeys[photoKeyIndex]
                        }
                    };

                    requests.AddRequest(photorequest);
                }
                #endregion

                ResponseBatch             responseBatch = pluckService.SendRequest(requests, authToken);
                Dictionary <string, bool> photoStatus   = new Dictionary <string, bool>();

                #region build responses batch
                if (responseBatch != null)
                {
                    foreach (var envelope in responseBatch.Envelopes)
                    {
                        var photo  = (PhotoResponse)envelope.GetResponse();
                        var status = DetermineModerationStatus(photo);

                        if (status == PhotoModerationStatus.Pending || status == PhotoModerationStatus.Unknown)
                        {
                            continue;
                        }

                        try
                        {
                            //var photokey = photoKeys[photoKeyIndex];
                            //UserSubmitDB.SetModerationStatus(photo.Photo.PhotoKey.Key, (status == PhotoModerationStatus.Approved));
                            if (status == PhotoModerationStatus.Approved)
                            {
                                photoStatus.Add(photo.Photo.PhotoKey.Key, true);
                            }
                            else
                            {
                                string photokey = photo.ResponseStatus.Exceptions.Where(e => e.Name == "PhotoKey").Select(e => e.Value).FirstOrDefault();
                                photoStatus.Add(photokey, false);
                            }
                        }
                        catch
                        {
                            continue;
                        }
                    }
                }
                #endregion
            }
        }
Example #20
0
 public void ExecuteRequestBatch(RequestBatch requestBatch)
 {
     _cobaltFile.CobaltEndpoint.ExecuteRequestBatch(requestBatch);
     _lastUpdated = DateTime.Now;
 }
Example #21
0
        public override Action<Stream> SetFileContent(byte[] newContent)
        {
            // Refactoring tip: there are more ways of initializing Atom
            AtomFromByteArray atomRequest = new AtomFromByteArray(newContent);
            RequestBatch requestBatch = new RequestBatch();

            object ctx;
            ProtocolVersion protocolVersion;

            requestBatch.DeserializeInputFromProtocol(atomRequest, out ctx, out protocolVersion);
            ExecuteRequestBatch(requestBatch);

            if (requestBatch.Requests.Any(request => request.GetType() == typeof(PutChangesRequest) && request.PartitionId == FilePartitionId.Content))
            {
                Save();
            }
            var response = requestBatch.SerializeOutputToProtocol(protocolVersion);
            Action<Stream> copyToAction = s => { response.CopyTo(s); };
            return copyToAction;
        }
Example #22
0
        public static Dictionary<string, string> UpdatePluckPhotoDetails(string appName, Pluck.Config.PluckConfigElement pluckConfig, string description, string title, string tags, string photoKey)
        {
            var requests = new RequestBatch();

            #region Add UpdatePhotoActionRequest to batch
            var updateRequest = new UpdatePhotoActionRequest
            {
                Description = description,
                Title = title,
                Tags = tags,
                PhotoKey = new PhotoKey { Key = photoKey }
            };

            requests.AddRequest(updateRequest);
            #endregion

            #region Add UpdateDiscoveryFilterFlagActionRequest to batch
            ////Make the photo not discoverable
            UpdateDiscoveryFilterFlagActionRequest discAction = new UpdateDiscoveryFilterFlagActionRequest();
            discAction.BaseKey = updateRequest.PhotoKey;
            discAction.ExcludeFromDiscovery = true;
            requests.AddRequest(discAction);
            #endregion

            #region Add PhotoRequest to batch
            requests.AddRequest(new PhotoRequest { PhotoKey = updateRequest.PhotoKey });
            #endregion

            var pluckService = new PluckService(pluckConfig.apiUrl);
            var authToken = new UserAuthenticationToken(pluckConfig.userKey, pluckConfig.userNickname, pluckConfig.userEmail, pluckConfig.sharedSecret);

            ResponseBatch responseBatch = pluckService.SendRequest(requests, authToken);

            Dictionary<string, string> resultURI = new Dictionary<string, string>();
            if (responseBatch != null)
            {
                if (responseBatch.Envelopes[0].Payload.ResponseStatus.Exceptions != null && responseBatch.Envelopes[0].Payload.ResponseStatus.Exceptions.Length > 0)
                {
                    throw new ApplicationException(responseBatch.Envelopes[0].Payload.ResponseStatus.Exceptions[0].ExceptionMessage);
                }

                IResponse photoObject = responseBatch.Envelopes[2].GetResponse();
                PhotoResponse photoDetails = (PhotoResponse)photoObject;

                resultURI.Add("tiny", photoDetails.Photo.Image.Tiny);
                resultURI.Add("full", photoDetails.Photo.Image.Full);
                resultURI.Add("small", photoDetails.Photo.Image.Small);//60x60
                resultURI.Add("medium", photoDetails.Photo.Image.Medium);//h=200
            }
            return resultURI;
        }
Example #23
0
 virtual public void ExecuteRequestBatch(RequestBatch requestBatch) { }
Example #24
0
 override public void ExecuteRequestBatch(RequestBatch requestBatch)
 {
     m_cobaltFile.CobaltEndpoint.ExecuteRequestBatch(requestBatch);
     m_lastUpdated = DateTime.Now;
 }
Example #25
0
        public static PhotoModerationStatus GetPhotoModerationStatus(PluckConfigElement pluckConfig, string photoKey)
        {
            var pluckService = new PluckService(pluckConfig.apiUrl);
            var authToken = new UserAuthenticationToken(pluckConfig.userKey, pluckConfig.userNickname, pluckConfig.userEmail, pluckConfig.sharedSecret);

            var requests = new RequestBatch();
            var photorequest = new PhotoRequest{PhotoKey = new PhotoKey { Key = photoKey }};
            requests.AddRequest(photorequest);

            ResponseBatch responseBatch = pluckService.SendRequest(requests, authToken);
            var photo = (PhotoResponse)responseBatch.Envelopes[0].GetResponse();

            return DetermineModerationStatus(photo);
        }
        //---------------------------------------------------------------------
        private void PushRequest(RequestType type, object[] datas)
        {
            if (type == RequestType.None)
            {
                return;
            }

            RequestBatch batch = GetRequestBatch(type);

            if (batch == null)
            {
                batch = new RequestBatch(type);
                m_RequestBatchs.Add(batch);
                m_RequestBatchs.Sort(delegate(RequestBatch a, RequestBatch b) {
                    return(-a.type.CompareTo(b.type));
                });
            }

            string group = defaultGroup;

            if (datas != null && datas.Length != 0)
            {
                List <IUIRequestOption> options = ExtractRequestOption(ref datas);
                string groupOption = GetRequestGroup(options);
                if (!string.IsNullOrEmpty(groupOption))
                {
                    group = groupOption;
                }
            }

            if (ContainsRequestGroup(batch, group))
            {
                ModifyRequestGroup(batch, group, datas);
                return;
            }

            // modify mutex request first
            if (type == RequestType.HideBegin)
            {
                if (ModifyMutexRequest(RequestType.HideEnd, group, datas) ||
                    ModifyMutexRequest(RequestType.HideAnimation, group, datas))
                {
                    return;
                }

                OnRequestHide();
                UIManager.TouchWindowRequestHide(this);
            }
            else if (type == RequestType.ShowBegin)
            {
                if (ModifyMutexRequest(RequestType.ShowEnd, group, datas) ||
                    ModifyMutexRequest(RequestType.ShowAnimation, group, datas))
                {
                    return;
                }

                OnRequestShow();
                UIManager.TouchWindowRequestShow(this);
            }

            batch.groups.Add(new RequestGroup(group, datas));
        }
Example #27
0
        public void QueueBatches(IRingMasterRequestHandler ringMaster, int batchLength)
        {
            if (ringMaster == null)
            {
                throw new ArgumentNullException(nameof(ringMaster));
            }

            ulong batchId = 0;
            var   random  = new RandomGenerator();

            Trace.TraceInformation($"Queue Exists Batches");

            while (!this.cancellationToken.IsCancellationRequested)
            {
                var operations = new Op[batchLength];
                for (int i = 0; i < batchLength; i++)
                {
                    var index    = random.GetRandomInt(0, this.nodeList.Count);
                    var nodePath = this.nodeList[index];

                    operations[i] = Op.Check(nodePath, -1);
                }

                var batchRequest = new RequestBatch(operations, completeSynchronously: false, uid: batchId++);
                this.semaphore.Wait();
                var timer = Stopwatch.StartNew();

                ringMaster.Request(batchRequest).ContinueWith(responseTask =>
                {
                    try
                    {
                        this.semaphore.Release();
                        timer.Stop();
                        int successCount         = 0;
                        int failureCount         = 0;
                        RequestResponse response = responseTask.Result;
                        if (response.ResultCode == (int)RingMasterException.Code.Ok)
                        {
                            var results = (IReadOnlyList <OpResult>)response.Content;
                            if (results != null)
                            {
                                foreach (var result in results)
                                {
                                    if (result.ErrCode == RingMasterException.Code.Ok)
                                    {
                                        successCount++;
                                    }
                                    else
                                    {
                                        failureCount++;
                                    }
                                }
                            }

                            this.instrumentation?.BatchProcessed(timer.Elapsed, batchRequest.Requests.Count, successCount, failureCount);
                        }
                        else
                        {
                            this.instrumentation?.BatchFailed(batchRequest.Requests.Count);
                        }
                    }
                    catch (Exception)
                    {
                        this.instrumentation?.BatchFailed(batchRequest.Requests.Count);
                    }
                });
            }
        }
Example #28
0
        private void ProcessRequest(IAsyncResult result)
        {
            try
            {
                logger.Info($"监听中......");
                var listener = (HttpListener)result.AsyncState;
                var context  = listener.EndGetContext(result);
                try
                {
                    var listStr = new List <string>();
                    foreach (var item in context.Request.Headers.AllKeys)
                    {
                        listStr.Add(context.Request.Headers[item]);
                    }
                    logger.Info($"监听内容:HTTP请求方法为【{context.Request.HttpMethod}】,HTTP请求绝对路径为【{context.Request.Url.AbsolutePath}】,HTTP请求头为【{JsonConvert.SerializeObject(context.Request.Headers.AllKeys)}】值为【{JsonConvert.SerializeObject(listStr)}】");
                    var stringarr    = context.Request.Url.AbsolutePath.Split('/');
                    var access_token = context.Request.QueryString["access_token"];

                    if (stringarr.Length < 3 || access_token == null)
                    {
                        logger.Info($"请求参数无效,参数为:{stringarr},token参数为:{access_token}");
                        ErrorResponse(context, @"无效的请求参数");
                        m_listener.BeginGetContext(new AsyncCallback(ProcessRequest), m_listener);
                        return;
                    }

                    documentUtil = new DocumentUtil();
                    //string fileId = stringarr[3];
                    var docInfo = documentUtil.GetInfo(stringarr[3]);
                    logger.Info($"文件信息为:{JsonConvert.SerializeObject(docInfo)}");
                    var filename = docInfo.fileName;

                    EditSession editSession = CobaltSessionManager.Instance.GetSession(docInfo.uuid);
                    if (editSession == null)
                    {
                        var fileExt = filename.Substring(filename.LastIndexOf('.') + 1);
                        if (fileExt.ToLower().Contains("xlsx"))
                        {
                            editSession = new FileSession(docInfo.uuid, docInfo.filePath, docInfo.loginUser, docInfo.author, false);
                        }
                        else
                        {
                            editSession = new CobaltSession(docInfo.uuid, docInfo.filePath, docInfo.loginUser, docInfo.author, false);
                        }
                        CobaltSessionManager.Instance.AddSession(editSession);
                    }

                    if (stringarr.Length == 4 && context.Request.HttpMethod.Equals(@"GET"))
                    {
                        using (var memoryStream = new MemoryStream())
                        {
                            var json = new DataContractJsonSerializer(typeof(WopiCheckFileInfo));
                            json.WriteObject(memoryStream, editSession.GetCheckFileInfo(access_token));
                            memoryStream.Flush();
                            memoryStream.Position = 0;
                            StreamReader streamReader = new StreamReader(memoryStream);
                            var          jsonResponse = Encoding.UTF8.GetBytes(streamReader.ReadToEnd());

                            context.Response.AddHeader("Cache-Control", "no-cache");
                            context.Response.AddHeader("Pragma", "no-cache");
                            context.Response.AddHeader("Expires", "-1");
                            context.Response.ContentType     = @"application/json";
                            context.Response.ContentLength64 = jsonResponse.Length;
                            context.Response.OutputStream.Write(jsonResponse, 0, jsonResponse.Length);
                            context.Response.OutputStream.Flush();
                            context.Response.StatusCode = (int)HttpStatusCode.OK;

                            context.Response.Close();
                        }
                    }
                    else if (stringarr.Length == 5 && stringarr[4].Equals(@"contents"))
                    {
                        if (context.Request.HttpMethod.Equals(@"POST"))
                        {
                            logger.Info($"进入contents方法,调用了保存。");

                            var ms = new MemoryStream();
                            context.Request.InputStream.CopyTo(ms);
                            editSession.Save(ms.ToArray());
                            context.Response.ContentLength64 = 0;
                            context.Response.ContentType     = @"text/html";
                            context.Response.StatusCode      = (int)HttpStatusCode.OK;
                        }
                        else
                        {
                            var content = editSession.GetFileContent();
                            context.Response.ContentType     = @"application/octet-stream";
                            context.Response.ContentLength64 = content.Length;
                            context.Response.OutputStream.Write(content, 0, content.Length);
                            context.Response.OutputStream.Flush();
                        }
                        //context.Response.StatusCode = (int)HttpStatusCode.OK;
                        context.Response.Close();
                    }
                    else if (context.Request.HttpMethod.Equals(@"POST") &&
                             context.Request.Headers["X-WOPI-Override"].Equals("COBALT"))
                    {
                        var ms = new MemoryStream();
                        context.Request.InputStream.CopyTo(ms);
                        AtomFromByteArray atomRequest  = new AtomFromByteArray(ms.ToArray());
                        RequestBatch      requestBatch = new RequestBatch();

                        Object          ctx;
                        ProtocolVersion protocolVersion;

                        requestBatch.DeserializeInputFromProtocol(atomRequest, out ctx, out protocolVersion);
                        editSession.ExecuteRequestBatch(requestBatch);

                        foreach (Request request in requestBatch.Requests)
                        {
                            if (request.GetType() == typeof(PutChangesRequest) &&
                                request.PartitionId == FilePartitionId.Content)
                            {
                                editSession.Save();
                                editSession.fileinfo = new FileInfo(docInfo.filePath);
                            }
                        }
                        var response = requestBatch.SerializeOutputToProtocol(protocolVersion);

                        context.Response.Headers.Add("X-WOPI-CorellationID", context.Request.Headers["X-WOPI-CorrelationID"]);
                        context.Response.Headers.Add("request-id", context.Request.Headers["X-WOPI-CorrelationID"]);
                        context.Response.ContentType     = @"application/octet-stream";
                        context.Response.ContentLength64 = response.Length;
                        context.Response.StatusCode      = (int)HttpStatusCode.OK;
                        response.CopyTo(context.Response.OutputStream);
                        context.Response.Close();
                    }
                    else if (context.Request.HttpMethod.Equals(@"POST") &&
                             (context.Request.Headers["X-WOPI-Override"].Equals("LOCK") ||
                              context.Request.Headers["X-WOPI-Override"].Equals("UNLOCK") ||
                              context.Request.Headers["X-WOPI-Override"].Equals("REFRESH_LOCK"))
                             )
                    {
                        context.Response.ContentLength64 = 0;
                        context.Response.ContentType     = @"text/html";
                        context.Response.StatusCode      = (int)HttpStatusCode.OK;
                        context.Response.Close();
                    }
                    else
                    {
                        logger.Info($"请求参数无效,参数为:{stringarr},token参数为:{access_token}");
                        ErrorResponse(context, @"无效的请求参数");
                    }
                    logger.Info($"当前请求处理完成...");
                }
                catch (Exception ex)
                {
                    logger.Error($"请求处理发生异常:{ex.Message}");
                }
                m_listener.BeginGetContext(new AsyncCallback(ProcessRequest), m_listener);
            }
            catch (Exception ex)
            {
                logger.Error($"获取请求时发生异常:{ex.Message}");
                return;
            }
        }
Example #29
0
        public void BatchTest()
        {
            Mock <IOrganizationService> orgSvc = null;
            Mock <MoqHttpMessagehander> fakHttpMethodHander = null;
            ServiceClient cli = null;

            testSupport.SetupMockAndSupport(out orgSvc, out fakHttpMethodHander, out cli);


            CreateResponse createResponse = new CreateResponse();

            createResponse.Results = new ParameterCollection();
            createResponse.Results.Add("annotationid", testSupport._DefaultId);

            ExecuteMultipleResponseItem responseItem = new ExecuteMultipleResponseItem();

            responseItem.Response     = createResponse;
            responseItem.RequestIndex = 0;

            ExecuteMultipleResponseItemCollection responseItems = new ExecuteMultipleResponseItemCollection();

            responseItems.Add(responseItem);

            ExecuteMultipleResponse executeMultipleResponse = new ExecuteMultipleResponse();

            executeMultipleResponse.Results = new ParameterCollection();
            executeMultipleResponse.Results.Add("Responses", responseItems);

            orgSvc.Setup(req1 => req1.Execute(It.IsAny <ExecuteMultipleRequest>())).Returns(executeMultipleResponse);


            // Setup a batch
            string BatchRequestName = "TestBatch";
            Guid   batchid          = cli.CreateBatchOperationRequest(BatchRequestName);

            // use create operation to setup request
            Dictionary <string, DataverseDataTypeWrapper> newFields = new Dictionary <string, DataverseDataTypeWrapper>();

            newFields.Add("name", new DataverseDataTypeWrapper("CrudTestAccount", DataverseFieldType.String));
            newFields.Add("accountnumber", new DataverseDataTypeWrapper("12345", DataverseFieldType.String));
            newFields.Add("telephone1", new DataverseDataTypeWrapper("555-555-5555", DataverseFieldType.String));
            newFields.Add("donotpostalmail", new DataverseDataTypeWrapper(true, DataverseFieldType.Boolean));

            // issue request as a batch:
            Guid result = cli.CreateAnnotation("account", testSupport._DefaultId, newFields, batchid);

            Assert.Equal <Guid>(Guid.Empty, result);

            OrganizationRequest req = cli.GetBatchRequestAtPosition(batchid, 0);

            // Executes the batch request.
            cli.ExecuteBatch(batchid);

            // Request Batch by name
            Guid OperationId = cli.GetBatchOperationIdRequestByName(BatchRequestName);

            // Request batch back
            RequestBatch reqBatch = cli.GetBatchById(batchid);

            Assert.NotNull(reqBatch);
            Assert.Equal(BatchRequestName, reqBatch.BatchName);
            Assert.True(reqBatch.BatchItems.Count == 1);

            // Release batch request
            cli.ReleaseBatchInfoById(batchid);
        }
Example #30
0
        private void ProcessRequest(IAsyncResult result)
        {
            try
            {
                Console.WriteLine("start...");
                HttpListener listener = (HttpListener)result.AsyncState;
                HttpListenerContext context = listener.EndGetContext(result);
                try
                {
                    Console.WriteLine("1111...");
                    Console.WriteLine(context.Request.HttpMethod + @" " + context.Request.Url.AbsolutePath);
                    var stringarr = context.Request.Url.AbsolutePath.Split('/');
                    var access_token = context.Request.QueryString["access_token"];

                    if (stringarr.Length < 3 || access_token == null)
                    {
                        Console.WriteLine(@"Invalid request");
                        ErrorResponse(context, @"Invalid request parameter");
                        m_listener.BeginGetContext(ProcessRequest, m_listener);
                        return;
                    }

                    //todo:
                    
                    
                    //string fileId = stringarr[3];
                    var filename = stringarr[3];
                    //Stream gridfsStream = GetFileById(fileId);
                    //StreamToFile(gridfsStream, filename);


                    //use filename as session id just test, recommend use file id and lock id as session id
                    EditSession editSession = CobaltSessionManager.Instance.GetSession(filename);
                    if (editSession == null)
                    {
                        Console.WriteLine("2222...");
                        var fileExt = filename.Substring(filename.LastIndexOf('.') + 1);
                        if (fileExt.ToLower().Equals(@"xlsx"))
                            editSession = new FileSession(filename, m_docsPath + "/" + filename, @"yonggui.yu", @"yuyg", @"*****@*****.**", false);
                        else
                            editSession = new CobaltSession(filename, m_docsPath + "/" + filename, @"yonggui.yu", @"yuyg", @"*****@*****.**", false);
                        CobaltSessionManager.Instance.AddSession(editSession);
                    }
            
                    if (stringarr.Length == 4 && context.Request.HttpMethod.Equals(@"GET"))
                    {
                        Console.WriteLine("4444...");
                        //request of checkfileinfo, will be called first
                        var memoryStream = new MemoryStream();
                        var json = new DataContractJsonSerializer(typeof(WopiCheckFileInfo));
                        json.WriteObject(memoryStream, editSession.GetCheckFileInfo());
                        memoryStream.Flush();
                        memoryStream.Position = 0;
                        StreamReader streamReader = new StreamReader(memoryStream);
                        var jsonResponse = Encoding.UTF8.GetBytes(streamReader.ReadToEnd());

                        context.Response.ContentType = @"application/json";
                        context.Response.ContentLength64 = jsonResponse.Length;
                        context.Response.OutputStream.Write(jsonResponse, 0, jsonResponse.Length);
                        context.Response.Close();
                    }
                    else if (stringarr.Length == 5 && stringarr[4].Equals(@"contents"))
                    {
                        Console.WriteLine("5555...");
                        // get and put file's content, only for xlsx and pptx
                        if (context.Request.HttpMethod.Equals(@"POST"))
                        {
                            var ms = new MemoryStream();
                            context.Request.InputStream.CopyTo(ms);
                            editSession.Save(ms.ToArray());
                            context.Response.ContentLength64 = 0;
                            context.Response.ContentType = @"text/html";
                            context.Response.StatusCode = (int)HttpStatusCode.OK;
                        }
                        else
                        {
                            var content = editSession.GetFileContent();
                            context.Response.ContentType = @"application/octet-stream";
                            context.Response.ContentLength64 = content.Length;
                            context.Response.OutputStream.Write(content, 0, content.Length);
                        }
                        context.Response.Close();
                    }
                    else if (context.Request.HttpMethod.Equals(@"POST") && 
                        context.Request.Headers["X-WOPI-Override"].Equals("COBALT"))
                    {
                        Console.WriteLine("6666...");
                        //cobalt, for docx and pptx
                        var ms = new MemoryStream();
                        context.Request.InputStream.CopyTo(ms);
                        AtomFromByteArray atomRequest = new AtomFromByteArray(ms.ToArray());
                        RequestBatch requestBatch = new RequestBatch();

                        Object ctx;
                        ProtocolVersion protocolVersion;

                        requestBatch.DeserializeInputFromProtocol(atomRequest, out ctx, out protocolVersion);
                        editSession.ExecuteRequestBatch(requestBatch);

                        foreach (Request request in requestBatch.Requests)
                        {
                            if (request.GetType() == typeof(PutChangesRequest) && 
                                request.PartitionId == FilePartitionId.Content)
                            {
                               
                                editSession.Save();
                             
                            }
                        }
                        var response = requestBatch.SerializeOutputToProtocol(protocolVersion);

                        context.Response.Headers.Add("X-WOPI-CorellationID", context.Request.Headers["X-WOPI-CorrelationID"]);
                        context.Response.Headers.Add("request-id", context.Request.Headers["X-WOPI-CorrelationID"]);
                        context.Response.ContentType = @"application/octet-stream";
                        context.Response.ContentLength64 = response.Length;
                        response.CopyTo(context.Response.OutputStream);
                        context.Response.Close();
                    }
                    else if (context.Request.HttpMethod.Equals(@"POST") &&
                        (context.Request.Headers["X-WOPI-Override"].Equals("LOCK") ||
                        context.Request.Headers["X-WOPI-Override"].Equals("UNLOCK") ||
                        context.Request.Headers["X-WOPI-Override"].Equals("REFRESH_LOCK"))
                        )
                    {
                        Console.WriteLine("7777...");
                        //lock, for xlsx and pptx
                        context.Response.ContentLength64 = 0;
                        context.Response.ContentType = @"text/html";
                        context.Response.StatusCode = (int)HttpStatusCode.OK;
                        context.Response.Close();
                    }
                    else
                    {
                        Console.WriteLine(@"Invalid request parameters");
                        ErrorResponse(context, @"Invalid request cobalt parameter");
                    }

                    Console.WriteLine("ok...");
                }
                catch (Exception ex)
                {
                    Console.WriteLine(@"process request exception:" + ex.Message);
                }
                m_listener.BeginGetContext(ProcessRequest, m_listener);
            }
            catch (Exception ex)
            {
                Console.WriteLine(@"get request context:" + ex.Message);
                return;
            }
        }
Example #31
0
        private void ProcessRequest(IAsyncResult result)
        {
            HttpListener        listener = (HttpListener)result.AsyncState;
            HttpListenerContext context  = listener.EndGetContext(result);

            var stringarr    = context.Request.Url.AbsolutePath.Split('/');
            var access_token = context.Request.QueryString["access_token"];

            if (stringarr.Length < 3 || access_token == null)
            {
                Console.WriteLine(@"Invalid request");
                SendError(context);
                return;
            }

            var filename = stringarr[3];
            //filename = "test2.docx"; //overrride

            WopiSession cf = WopiSessionManager.Instance.GetSession(access_token);

            if (cf == null)
            {
                cf = new WopiSession(access_token, _docs + "/" + filename);
                WopiSessionManager.Instance.AddSession(cf);
            }

            if (stringarr.Length == 5 && context.Request.HttpMethod.Equals(@"GET"))
            {
                // get file's content
                var content = cf.GetFileContent();
                context.Response.ContentType     = @"application/octet-stream";
                context.Response.ContentLength64 = content.Length;
                content.CopyTo(context.Response.OutputStream);
                context.Response.Close();
            }
            else if (context.Request.HttpMethod.Equals(@"POST") && context.Request.Headers["X-WOPI-Override"].Equals("COBALT"))
            {
                var ms = new MemoryStream();
                context.Request.InputStream.CopyTo(ms);
                AtomFromByteArray atomRequest  = new AtomFromByteArray(ms.ToArray());
                RequestBatch      requestBatch = new RequestBatch();

                Object          ctx;
                ProtocolVersion protocolVersion;

                requestBatch.DeserializeInputFromProtocol(atomRequest, out ctx, out protocolVersion);
                cf.ExecuteRequestBatch(requestBatch);

                foreach (Request request in requestBatch.Requests)
                {
                    if (request.GetType() == typeof(PutChangesRequest) && request.PartitionId == FilePartitionId.Content)
                    {
                        cf.Save();
                    }
                }
                var response = requestBatch.SerializeOutputToProtocol(protocolVersion);

                context.Response.Headers.Add("X-WOPI-CorellationID", context.Request.Headers["X-WOPI-CorrelationID"]);
                context.Response.Headers.Add("request-id", context.Request.Headers["X-WOPI-CorrelationID"]);
                context.Response.ContentType     = @"application/octet-stream";
                context.Response.ContentLength64 = response.Length;
                response.CopyTo(context.Response.OutputStream);
                context.Response.Close();
            }
            else if (stringarr.Length == 4 && context.Request.HttpMethod.Equals(@"GET"))
            {
                // encode json
                var memoryStream = new MemoryStream();
                var json         = new DataContractJsonSerializer(typeof(WopiCheckFileInfo));
                json.WriteObject(memoryStream, cf.GetCheckFileInfo());
                memoryStream.Flush();
                memoryStream.Position = 0;
                StreamReader streamReader = new StreamReader(memoryStream);
                var          jsonResponse = Encoding.UTF8.GetBytes(streamReader.ReadToEnd());

                context.Response.ContentType     = @"application/json";
                context.Response.ContentLength64 = jsonResponse.Length;
                context.Response.OutputStream.Write(jsonResponse, 0, jsonResponse.Length);
                context.Response.Close();
            }
            else
            {
                Console.WriteLine(@"Invalid request parameters");
                SendError(context);
            }

            _listener.BeginGetContext(ProcessRequest, _listener);
        }
Example #32
0
        private void ProcessRequest(IAsyncResult result)
        {
            try
            {
                Console.WriteLine("start...");
                HttpListener        listener = (HttpListener)result.AsyncState;
                HttpListenerContext context  = listener.EndGetContext(result);
                try
                {
                    //Console.WriteLine("1111...");
                    Console.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.ffff") + " " + context.Request.HttpMethod + @" " + context.Request.Url.AbsolutePath);
                    var stringarr    = context.Request.Url.AbsolutePath.Split('/');
                    var access_token = context.Request.QueryString["access_token"];

                    if (stringarr.Length < 3 || access_token == null)
                    {
                        Console.WriteLine(@"Invalid request");
                        ErrorResponse(context, @"Invalid request parameter");
                        m_listener.BeginGetContext(ProcessRequest, m_listener);
                        return;
                    }

                    //todo:


                    documentUtil = new DocumentUtil();
                    //string fileId = stringarr[3];
                    var docInfo  = documentUtil.GetInfo(stringarr[3]);
                    var filename = docInfo.fileName;
                    //Stream gridfsStream = GetFileById(fileId);
                    //StreamToFile(gridfsStream, filename);


                    //use filename as session id just test, recommend use file id and lock id as session id
                    EditSession editSession = CobaltSessionManager.Instance.GetSession(filename);
                    if (editSession == null)
                    {
                        //Console.WriteLine("2222...");
                        var fileExt = filename.Substring(filename.LastIndexOf('.') + 1);
                        if (fileExt.ToLower().Contains("xlsx"))
                        {
                            editSession = new FileSession(filename, docInfo.filePath, docInfo.author, docInfo.loginUser,
                                                          docInfo.mail, false);
                        }
                        else
                        {
                            editSession = new CobaltSession(filename, docInfo.filePath,
                                                            docInfo.author, docInfo.loginUser, docInfo.mail, false);
                        }
                        CobaltSessionManager.Instance.AddSession(editSession);
                    }

                    if (stringarr.Length == 4 && context.Request.HttpMethod.Equals(@"GET"))
                    {
                        //Console.WriteLine("4444...");
                        //request of checkfileinfo, will be called first
                        using (var memoryStream = new MemoryStream())
                        {
                            var json = new DataContractJsonSerializer(typeof(WopiCheckFileInfo));
                            json.WriteObject(memoryStream, editSession.GetCheckFileInfo(access_token));
                            memoryStream.Flush();
                            memoryStream.Position = 0;
                            StreamReader streamReader = new StreamReader(memoryStream);
                            var          jsonResponse = Encoding.UTF8.GetBytes(streamReader.ReadToEnd());

                            context.Response.AddHeader("Cache-Control", "no-cache");
                            context.Response.AddHeader("Pragma", "no-cache");
                            context.Response.AddHeader("Expires", "-1");
                            context.Response.ContentType     = @"application/json";
                            context.Response.ContentLength64 = jsonResponse.Length;
                            context.Response.OutputStream.Write(jsonResponse, 0, jsonResponse.Length);
                            context.Response.OutputStream.Flush();
                            context.Response.StatusCode = (int)HttpStatusCode.OK;

                            context.Response.Close();
                        }
                    }
                    else if (stringarr.Length == 5 && stringarr[4].Equals(@"contents"))
                    {
                        //Console.WriteLine("5555...");
                        // get and put file's content, only for xlsx and pptx
                        if (context.Request.HttpMethod.Equals(@"POST"))
                        {
                            var ms = new MemoryStream();
                            context.Request.InputStream.CopyTo(ms);
                            editSession.Save(ms.ToArray());
                            context.Response.ContentLength64 = 0;
                            context.Response.ContentType     = @"text/html";
                        }
                        else
                        {
                            var content = editSession.GetFileContent();
                            context.Response.ContentType     = @"application/octet-stream";
                            context.Response.ContentLength64 = content.Length;
                            context.Response.OutputStream.Write(content, 0, content.Length);
                        }
                        context.Response.StatusCode = (int)HttpStatusCode.OK;
                        context.Response.Close();
                    }
                    else if (context.Request.HttpMethod.Equals(@"POST") &&
                             context.Request.Headers["X-WOPI-Override"].Equals("COBALT"))
                    {
                        //Console.WriteLine("6666...");
                        //cobalt, for docx and pptx
                        var ms = new MemoryStream();
                        context.Request.InputStream.CopyTo(ms);
                        AtomFromByteArray atomRequest  = new AtomFromByteArray(ms.ToArray());
                        RequestBatch      requestBatch = new RequestBatch();

                        Object          ctx;
                        ProtocolVersion protocolVersion;

                        requestBatch.DeserializeInputFromProtocol(atomRequest, out ctx, out protocolVersion);
                        editSession.ExecuteRequestBatch(requestBatch);

                        foreach (Request request in requestBatch.Requests)
                        {
                            if (request.GetType() == typeof(PutChangesRequest) &&
                                request.PartitionId == FilePartitionId.Content)
                            {
                                editSession.Save();
                            }
                        }
                        var response = requestBatch.SerializeOutputToProtocol(protocolVersion);

                        context.Response.Headers.Add("X-WOPI-CorellationID", context.Request.Headers["X-WOPI-CorrelationID"]);
                        context.Response.Headers.Add("request-id", context.Request.Headers["X-WOPI-CorrelationID"]);
                        context.Response.ContentType     = @"application/octet-stream";
                        context.Response.ContentLength64 = response.Length;
                        context.Response.StatusCode      = (int)HttpStatusCode.OK;
                        response.CopyTo(context.Response.OutputStream);
                        context.Response.Close();
                    }
                    else if (context.Request.HttpMethod.Equals(@"POST") &&
                             (context.Request.Headers["X-WOPI-Override"].Equals("LOCK") ||
                              context.Request.Headers["X-WOPI-Override"].Equals("UNLOCK") ||
                              context.Request.Headers["X-WOPI-Override"].Equals("REFRESH_LOCK"))
                             )
                    {
                        //Console.WriteLine("7777...");
                        //lock, for xlsx and pptx
                        context.Response.ContentLength64 = 0;
                        context.Response.ContentType     = @"text/html";
                        context.Response.StatusCode      = (int)HttpStatusCode.OK;
                        context.Response.Close();
                    }
                    else
                    {
                        Console.WriteLine(@"Invalid request parameters");
                        ErrorResponse(context, @"Invalid request cobalt parameter");
                    }

                    Console.WriteLine("ok...");
                }
                catch (Exception ex)
                {
                    Console.WriteLine(@"process request exception:" + ex.Message);
                }
                m_listener.BeginGetContext(ProcessRequest, m_listener);
            }
            catch (Exception ex)
            {
                Console.WriteLine(@"get request context:" + ex.Message);
                return;
            }
        }
        //---------------------------------------------------------------------
        internal void ProcessRequests()
        {
            // There is not any request.
            RequestBatch batch = LastRequestBatch();

            if (batch == null)
            {
                return;
            }

            // Waiting for animation finished.
            if (batch.type == RequestType.ShowAnimation ||
                batch.type == RequestType.HideAnimation)
            {
                return;
            }

            // Waiting for asset loaded.
            if (batch.type == RequestType.Load)
            {
                // Pop last group
                PopRequestGroup();
                OnLoaded();
                return;
            }

            // Pop last group
            RequestGroup group = PopRequestGroup();

            if (group == null)
            {
                return;
            }

            // Apply new request data
            m_RequestData   = group.datas;
            m_CustomExecute = true;
            switch (batch.type)
            {
            case RequestType.Initialize:
                ExecuteInitialize();
                break;

            case RequestType.Refresh:
                ExecuteRefresh();
                break;

            case RequestType.Command:
                ExecuteCommand();
                break;

            case RequestType.ShowBegin:
                ExecuteShowBegin();
                break;

            case RequestType.ShowEnd:
                ExecuteShowEnd();
                break;

            case RequestType.HideBegin:
                ExecuteHideBegin();
                break;

            case RequestType.HideEnd:
                ExecuteHideEnd();
                break;

            case RequestType.Search:
                ExecuteSearch();
                break;

            default:
                m_RequestData = null;
                break;
            }
            m_CustomExecute = false;
        }
Example #34
0
 virtual public void ExecuteRequestBatch(RequestBatch requestBatch)
 {
 }
Example #35
0
 public void ExecuteRequestBatch(RequestBatch requestBatch)
 {
     CobaltFile.CobaltEndpoint.ExecuteRequestBatch(requestBatch);
     LastUpdated = DateTime.Now;
 }
Example #36
0
        private void ProcessRequest(IAsyncResult result)
        {
            try
            {
                HttpListener        listener = (HttpListener)result.AsyncState;
                HttpListenerContext context  = listener.EndGetContext(result);
                try
                {
                    Console.WriteLine(context.Request.HttpMethod + @" " + context.Request.Url.AbsolutePath);
                    var stringarr    = context.Request.Url.AbsolutePath.Split('/');
                    var access_token = context.Request.QueryString["access_token"];

                    if (stringarr.Length < 3 || access_token == null)
                    {
                        Console.WriteLine(@"Invalid request");
                        ErrorResponse(context, @"Invalid request parameter");
                        m_listener.BeginGetContext(ProcessRequest, m_listener);
                        return;
                    }

                    var filename = stringarr[3];
                    //use filename as session id just test, recommend use file id and lock id as session id
                    EditSession editSession = CobaltSessionManager.Instance.GetSession(filename);
                    if (editSession == null)
                    {
                        var fileExt = filename.Substring(filename.LastIndexOf('.') + 1);
                        if (fileExt.ToLower().Equals(@"xlsx"))
                        {
                            editSession = new FileSession(filename, m_docsPath + "/" + filename, @"yonggui.yu", @"yuyg", @"*****@*****.**", false);
                        }
                        else
                        {
                            editSession = new CobaltSession(filename, m_docsPath + "/" + filename, @"yonggui.yu", @"yuyg", @"*****@*****.**", false);
                        }
                        CobaltSessionManager.Instance.AddSession(editSession);
                    }

                    if (stringarr.Length == 4 && context.Request.HttpMethod.Equals(@"GET"))
                    {
                        //request of checkfileinfo, will be called first
                        var memoryStream = new MemoryStream();
                        var json         = new DataContractJsonSerializer(typeof(WopiCheckFileInfo));
                        json.WriteObject(memoryStream, editSession.GetCheckFileInfo());
                        memoryStream.Flush();
                        memoryStream.Position = 0;
                        StreamReader streamReader = new StreamReader(memoryStream);
                        var          jsonResponse = Encoding.UTF8.GetBytes(streamReader.ReadToEnd());

                        context.Response.ContentType     = @"application/json";
                        context.Response.ContentLength64 = jsonResponse.Length;
                        context.Response.OutputStream.Write(jsonResponse, 0, jsonResponse.Length);
                        context.Response.Close();
                    }
                    else if (stringarr.Length == 5 && stringarr[4].Equals(@"contents"))
                    {
                        // get and put file's content, only for xlsx and pptx
                        if (context.Request.HttpMethod.Equals(@"POST"))
                        {
                            var ms = new MemoryStream();
                            context.Request.InputStream.CopyTo(ms);
                            editSession.Save(ms.ToArray());
                            context.Response.ContentLength64 = 0;
                            context.Response.ContentType     = @"text/html";
                            context.Response.StatusCode      = (int)HttpStatusCode.OK;
                        }
                        else
                        {
                            var content = editSession.GetFileContent();
                            context.Response.ContentType     = @"application/octet-stream";
                            context.Response.ContentLength64 = content.Length;
                            context.Response.OutputStream.Write(content, 0, content.Length);
                        }
                        context.Response.Close();
                    }
                    else if (context.Request.HttpMethod.Equals(@"POST") && context.Request.Headers["X-WOPI-Override"].Equals("COBALT"))
                    {
                        //cobalt, for docx and pptx
                        var ms = new MemoryStream();
                        context.Request.InputStream.CopyTo(ms);
                        AtomFromByteArray atomRequest  = new AtomFromByteArray(ms.ToArray());
                        RequestBatch      requestBatch = new RequestBatch();

                        Object          ctx;
                        ProtocolVersion protocolVersion;

                        requestBatch.DeserializeInputFromProtocol(atomRequest, out ctx, out protocolVersion);
                        editSession.ExecuteRequestBatch(requestBatch);

                        foreach (Request request in requestBatch.Requests)
                        {
                            if (request.GetType() == typeof(PutChangesRequest) && request.PartitionId == FilePartitionId.Content)
                            {
                                //upload file to hdfs
                                editSession.Save();
                            }
                        }
                        var response = requestBatch.SerializeOutputToProtocol(protocolVersion);

                        context.Response.Headers.Add("X-WOPI-CorellationID", context.Request.Headers["X-WOPI-CorrelationID"]);
                        context.Response.Headers.Add("request-id", context.Request.Headers["X-WOPI-CorrelationID"]);
                        context.Response.ContentType     = @"application/octet-stream";
                        context.Response.ContentLength64 = response.Length;
                        response.CopyTo(context.Response.OutputStream);
                        context.Response.Close();
                    }
                    else if (context.Request.HttpMethod.Equals(@"POST") &&
                             (context.Request.Headers["X-WOPI-Override"].Equals("LOCK") ||
                              context.Request.Headers["X-WOPI-Override"].Equals("UNLOCK") ||
                              context.Request.Headers["X-WOPI-Override"].Equals("REFRESH_LOCK"))
                             )
                    {
                        //lock, for xlsx and pptx
                        context.Response.ContentLength64 = 0;
                        context.Response.ContentType     = @"text/html";
                        context.Response.StatusCode      = (int)HttpStatusCode.OK;
                        context.Response.Close();
                    }
                    else
                    {
                        Console.WriteLine(@"Invalid request parameters");
                        ErrorResponse(context, @"Invalid request cobalt parameter");
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine(@"process request exception:" + ex.Message);
                }
                m_listener.BeginGetContext(ProcessRequest, m_listener);
            }
            catch (Exception ex)
            {
                Console.WriteLine(@"get request context:" + ex.Message);
                return;
            }
        }
 //---------------------------------------------------------------------
 private bool ContainsRequestGroup(RequestBatch batch, string group)
 {
     return(GetRequestGroup(batch, group) != null);
 }
Example #38
0
        private void ProcessRequest(IAsyncResult result)
        {
            HttpListener listener = (HttpListener)result.AsyncState;
            HttpListenerContext context = listener.EndGetContext(result);

            var stringarr = context.Request.Url.AbsolutePath.Split('/');
            var access_token = context.Request.QueryString["access_token"];

            if (stringarr.Length < 3 || access_token == null)
            {
                Console.WriteLine(@"Invalid request");
                SendError(context);
                return;
            }

            var filename = stringarr[3];
            //filename = "test2.docx"; //overrride

            WopiSession cf = WopiSessionManager.Instance.GetSession(access_token);
            if (cf == null)
            {
                cf = new WopiSession(access_token, _docs + "/" + filename);
                WopiSessionManager.Instance.AddSession(cf);
            }

            if (stringarr.Length == 5 && context.Request.HttpMethod.Equals(@"GET"))
            {
                // get file's content
                var content = cf.GetFileContent();
                context.Response.ContentType = @"application/octet-stream";
                context.Response.ContentLength64 = content.Length;
                content.CopyTo(context.Response.OutputStream);
                context.Response.Close();
            }
            else if (context.Request.HttpMethod.Equals(@"POST") && context.Request.Headers["X-WOPI-Override"].Equals("COBALT"))
            {
                var ms = new MemoryStream();
                context.Request.InputStream.CopyTo(ms);
                AtomFromByteArray atomRequest = new AtomFromByteArray(ms.ToArray());
                RequestBatch requestBatch = new RequestBatch();

                Object ctx;
                ProtocolVersion protocolVersion;

                requestBatch.DeserializeInputFromProtocol(atomRequest, out ctx, out protocolVersion);
                cf.ExecuteRequestBatch(requestBatch);

                foreach (Request request in requestBatch.Requests)
                {
                    if (request.GetType() == typeof(PutChangesRequest) && request.PartitionId == FilePartitionId.Content)
                    {
                        cf.Save();
                    }
                }
                var response = requestBatch.SerializeOutputToProtocol(protocolVersion);
                
                context.Response.Headers.Add("X-WOPI-CorellationID", context.Request.Headers["X-WOPI-CorrelationID"]);
                context.Response.Headers.Add("request-id", context.Request.Headers["X-WOPI-CorrelationID"]);
                context.Response.ContentType = @"application/octet-stream";
                context.Response.ContentLength64 = response.Length;
                response.CopyTo(context.Response.OutputStream);
                context.Response.Close();
            }
            else if (stringarr.Length == 4 && context.Request.HttpMethod.Equals(@"GET"))
            {
                // encode json
                var memoryStream = new MemoryStream();
                var json = new DataContractJsonSerializer(typeof(WopiCheckFileInfo));
                json.WriteObject(memoryStream, cf.GetCheckFileInfo());
                memoryStream.Flush();
                memoryStream.Position = 0;
                StreamReader streamReader = new StreamReader(memoryStream);
                var jsonResponse = Encoding.UTF8.GetBytes(streamReader.ReadToEnd());

                context.Response.ContentType = @"application/json";
                context.Response.ContentLength64 = jsonResponse.Length;
                context.Response.OutputStream.Write(jsonResponse, 0, jsonResponse.Length);
                context.Response.Close();
            }
            else
            {
                Console.WriteLine(@"Invalid request parameters");
                SendError(context);
            }

            _listener.BeginGetContext(ProcessRequest, _listener);
        }
Example #39
0
        public static void GetPhotoModerationStatus(PluckConfigElement pluckConfig, List<string> photoKeys)
        {
            if (photoKeys.Count == 0)
                return;

            var pluckService = new PluckService(pluckConfig.apiUrl);
            var authToken = new UserAuthenticationToken(pluckConfig.userKey, pluckConfig.userNickname, pluckConfig.userEmail, pluckConfig.sharedSecret);
            RequestBatch requests = null;

            int numBatches = photoKeys.Count / PLUCK_BATCH_SIZE;
            if (photoKeys.Count % PLUCK_BATCH_SIZE > 0)
                numBatches++;

            int photoKeyIndex = 0;

            for (int batchNumber = 1; batchNumber <= numBatches; batchNumber++)
            {
                requests = new RequestBatch();
                #region build requests batch
                for (int i = 0; i < PLUCK_BATCH_SIZE; i++)
                {
                    photoKeyIndex = (batchNumber * PLUCK_BATCH_SIZE) - PLUCK_BATCH_SIZE + i;

                    if (photoKeyIndex == photoKeys.Count)
                        break;

                    var photorequest = new PhotoRequest()
                    {
                        PhotoKey = new PhotoKey { Key = photoKeys[photoKeyIndex] }
                    };

                    requests.AddRequest(photorequest);
                }
                #endregion

                ResponseBatch responseBatch = pluckService.SendRequest(requests, authToken);
                Dictionary<string, bool> photoStatus = new Dictionary<string, bool>();

                #region build responses batch
                if (responseBatch != null)
                {
                    foreach (var envelope in responseBatch.Envelopes)
                    {
                        var photo = (PhotoResponse)envelope.GetResponse();
                        var status = DetermineModerationStatus(photo);

                        if (status == PhotoModerationStatus.Pending || status == PhotoModerationStatus.Unknown)
                            continue;

                        try
                        {
                            //var photokey = photoKeys[photoKeyIndex];
                            //UserSubmitDB.SetModerationStatus(photo.Photo.PhotoKey.Key, (status == PhotoModerationStatus.Approved));
                            if (status == PhotoModerationStatus.Approved)
                            {
                                photoStatus.Add(photo.Photo.PhotoKey.Key, true);
                            }
                            else
                            {
                                string photokey = photo.ResponseStatus.Exceptions.Where(e => e.Name == "PhotoKey").Select(e => e.Value).FirstOrDefault();
                                photoStatus.Add(photokey, false);
                            }
                        }
                        catch
                        {
                            continue;
                        }
                    }
                }
                #endregion
            }
        }