Пример #1
0
        /// <summary>
        /// Burns a markup JSON file into a document, producing a new PDF.
        /// </summary>
        /// <param name="sourceDocument">Existing <see cref="RemoteWorkFile" />
        /// to use as the source document.</param>
        /// <param name="markupJson">Existing <see cref="RemoteWorkFile" />
        /// containing the markup JSON you want burned into the source
        /// document.</param>
        /// <returns>RemoteWorkFile for the new PDF.</returns>
        public async Task <RemoteWorkFile> BurnMarkupAsync(RemoteWorkFile sourceDocument, RemoteWorkFile markupJson)
        {
            // Make sure we use the existing affinity token, if defined.
            AffinitySession affinitySession = this.restClient.CreateAffinitySession(sourceDocument.AffinityToken);

            // Make sure markupJson has the same affinity as the sourceDocument
            markupJson = await markupJson.GetInstanceWithAffinity(affinitySession, sourceDocument.AffinityToken);

            string json = this.BuildPostMarkupBurnersRequestJson(sourceDocument, markupJson);

            // Start the redaction creation process
            using (HttpResponseMessage response = await affinitySession.PostAsync("/PCCIS/V1/MarkupBurner", new StringContent(json, Encoding.UTF8, "application/json")))
            {
                await this.ThrowIfPostMarkupBurnersError(response);

                json = await response.Content.ReadAsStringAsync();
            }

            JObject process   = JObject.Parse(json);
            string  processId = (string)process["processId"];

            // Wait for the process to complete
            using (HttpResponseMessage response = await affinitySession.GetFinalProcessStatusAsync($"/PCCIS/V1/MarkupBurner/{processId}"))
            {
                await this.ThrowIfGetMarkupBurnersError(response);

                json = await response.Content.ReadAsStringAsync();
            }

            process = JObject.Parse(json);

            return(new RemoteWorkFile(affinitySession, (string)process["output"]["documentFileId"], affinitySession.AffinityToken, "pdf"));
        }
Пример #2
0
        /// <summary>
        /// Automatically create redaction definitions for a document and a given set of text-matching rules,
        /// producing a new markup JSON file that can be used in a subsequent operation to actually apply the
        /// redaction definitions to the document.
        /// </summary>
        /// <param name="sourceDocument">Source document the redactions should be created for.</param>
        /// <param name="rules">Rules defining what content in the document should have a redaction region created for it.</param>
        /// <returns><see cref="RemoteWorkFile"/> for the created markup JSON file.</returns>
        public async Task <RemoteWorkFile> CreateRedactionsAsync(RemoteWorkFile sourceDocument, IEnumerable <RedactionMatchRule> rules)
        {
            RedactionMatchRule[] rulesArray = rules.ToArray();

            // Make sure we use the existing affinity token, if defined.
            AffinitySession affinitySession = this.restClient.CreateAffinitySession(sourceDocument.AffinityToken);

            string json = this.BuildPostRedactionCreatorsRequestJson(sourceDocument, rules.ToArray());

            // Start the redaction creation process
            using (HttpResponseMessage response = await affinitySession.PostAsync("/v2/redactionCreators", new StringContent(json, Encoding.UTF8, "application/json")))
            {
                await this.ThrowIfPostRedactionCreatorsError(rulesArray, response);

                json = await response.Content.ReadAsStringAsync();
            }

            JObject process   = JObject.Parse(json);
            string  processId = (string)process["processId"];

            // Wait for the process to complete
            using (HttpResponseMessage response = await affinitySession.GetFinalProcessStatusAsync($"/v2/redactionCreators/{processId}"))
            {
                await this.ThrowIfGetRedactionCreatorsError(response);

                json = await response.Content.ReadAsStringAsync();
            }

            process = JObject.Parse(json);

            return(new RemoteWorkFile(affinitySession, (string)process["output"]["markupFileId"], affinitySession.AffinityToken, "json"));
        }
Пример #3
0
        public async Task GetFinalProcessStatusAsync_uses_an_initial_polling_delay_of_500ms_and_then_doubles_the_delay_between_each_poll_until_reaching_a_max_delay_of_8000ms()
        {
            int responsesSent = 0;

            mockServer
            .Given(Request.Create().WithPath("/wat/123").UsingGet())
            .RespondWith(Response.Create()
                         .WithCallback(req =>
            {
                var headers = new Dictionary <string, WireMockList <string> >();
                headers.Add("Content-Type", new WireMockList <string>("application/json"));

                string body = "{ \"processId\": \"123\", \"state\": \"" + (responsesSent < 7 ? "processing" : "complete") + "\" }";
                responsesSent++;

                return(new ResponseMessage
                {
                    StatusCode = 200,
                    Headers = headers,
                    BodyData = new BodyData
                    {
                        DetectedBodyType = BodyType.String,
                        BodyAsString = body
                    }
                });
            })
                         );

            AffinitySession session = client.CreateAffinitySession();

            using (HttpResponseMessage response = await session.GetFinalProcessStatusAsync("/wat/123"))
            {
                response.EnsureSuccessStatusCode();
            }

            List <RequestMessage> requests = mockServer.LogEntries.Select(x => x.RequestMessage).ToList();
            List <TimeSpan>       delaysBetweenRequests = new List <TimeSpan>();

            for (int i = 1; i < requests.Count; i++)
            {
                delaysBetweenRequests.Add(requests[i].DateTime - requests[i - 1].DateTime);
            }

            const double ALLOWED_DELTA = 500.0;

            Assert.AreEqual(500.0, delaysBetweenRequests[0].TotalMilliseconds, ALLOWED_DELTA);
            Assert.AreEqual(1000.0, delaysBetweenRequests[1].TotalMilliseconds, ALLOWED_DELTA);
            Assert.AreEqual(2000.0, delaysBetweenRequests[2].TotalMilliseconds, ALLOWED_DELTA);
            Assert.AreEqual(4000.0, delaysBetweenRequests[3].TotalMilliseconds, ALLOWED_DELTA);
            Assert.AreEqual(8000.0, delaysBetweenRequests[4].TotalMilliseconds, ALLOWED_DELTA);
            Assert.AreEqual(8000.0, delaysBetweenRequests[5].TotalMilliseconds, ALLOWED_DELTA);
            Assert.AreEqual(8000.0, delaysBetweenRequests[6].TotalMilliseconds, ALLOWED_DELTA);
        }
Пример #4
0
        /// <summary>
        /// Extracts text for each page, returning a string of plain text for each page in a RemoteWorkFile.
        /// </summary>
        public static async Task <string[]> ExtractPagesText(RemoteWorkFile remoteWorkFile)
        {
            AffinitySession session = Util.RestClient.CreateAffinitySession();

            HttpRequestMessage req = new HttpRequestMessage(HttpMethod.Post, "/v2/searchContexts");

            if (remoteWorkFile.AffinityToken != null)
            {
                req.Headers.Add("Accusoft-Affinity-Token", remoteWorkFile.AffinityToken);
            }

            req.Content = new StringContent(
                @"{
  ""input"": {
    ""documentIdentifier"": """ + remoteWorkFile.FileId + @""",
    ""source"": ""workFile"",
    ""fileId"": """ + remoteWorkFile.FileId + @"""
  }
}",
                Encoding.UTF8,
                "application/json");

            string json;

            using (HttpResponseMessage res = await session.SendAsync(req))
            {
                res.EnsureSuccessStatusCode();
                json = await res.Content.ReadAsStringAsync();
            }

            JObject process   = JObject.Parse(json);
            string  contextId = (string)process["contextId"];

            using (HttpResponseMessage res = await session.GetFinalProcessStatusAsync("/v2/searchContexts/" + contextId))
            {
                res.EnsureSuccessStatusCode();
            }

            using (HttpResponseMessage res = await session.GetAsync($"/v2/searchContexts/{contextId}/records?pages=0-"))
            {
                res.EnsureSuccessStatusCode();
                json = await res.Content.ReadAsStringAsync();
            }

            JObject data  = JObject.Parse(json);
            JArray  pages = (JArray)data["pages"];

            return(pages.Select(x => (string)x["text"]).ToArray());
        }
Пример #5
0
        public async Task GetFinalProcessStatusAsync_returns_when_the_state_becomes_anything_other_than_processing(string finalState)
        {
            int responsesSent = 0;

            mockServer
            .Given(Request.Create().WithPath("/wat/123").UsingGet())
            .RespondWith(Response.Create()
                         .WithCallback(req =>
            {
                var headers = new Dictionary <string, WireMockList <string> >();
                headers.Add("Content-Type", new WireMockList <string>("application/json"));

                string body = "{ \"processId\": \"123\", \"state\": \"" + (responsesSent < 1 ? "processing" : finalState) + "\" }";
                responsesSent++;

                return(new ResponseMessage
                {
                    StatusCode = 200,
                    Headers = headers,
                    BodyData = new BodyData
                    {
                        DetectedBodyType = BodyType.String,
                        BodyAsString = body
                    }
                });
            })
                         );

            AffinitySession session = client.CreateAffinitySession();


            using (HttpResponseMessage response = await session.GetFinalProcessStatusAsync("/wat/123"))
            {
                response.EnsureSuccessStatusCode();

                string json = await response.Content.ReadAsStringAsync();

                JObject obj = JObject.Parse(json);
                string  stateParsedFromTheReturnValueOfTheFunctionUnderTest = (string)obj["state"];

                Assert.AreEqual(finalState, stateParsedFromTheReturnValueOfTheFunctionUnderTest);
            }
        }
        public async Task Can_convert_a_DOCX_to_PDF_using_PrizmDoc_Cloud()
        {
            // Construct an instance of the PrizmDocRestClient.
            var    client = new PrizmDocRestClient(Environment.GetEnvironmentVariable("BASE_URL"));
            string apiKey = Environment.GetEnvironmentVariable("API_KEY");

            if (apiKey != null)
            {
                client.DefaultRequestHeaders.Add("Acs-Api-Key", apiKey);
            }

            // Create an affinity session for our processing work.
            //
            // You should use an affinity session anytime you have a group
            // of HTTP requests that go together as part of a processing
            // chain. The session ensures that all HTTP requests will
            // automatically use the same affinity (be routed to the same
            // PrizmDoc Server machine in the cluster).
            AffinitySession session = client.CreateAffinitySession();

            string json;

            // Create a new work file for the input document
            using (FileStream inputFileStream = File.OpenRead("input.docx"))
                using (HttpResponseMessage response = await session.PostAsync("/PCCIS/V1/WorkFile", new StreamContent(inputFileStream)))
                {
                    response.EnsureSuccessStatusCode();
                    json = await response.Content.ReadAsStringAsync();
                }


            JObject inputWorkFile = JObject.Parse(json);
            string  inputFileId   = (string)inputWorkFile["fileId"];

            // Start a conversion process using the input work file
            string postContentConvertersJson =
                @"{
    ""input"": {
        ""sources"": [
            {
                ""fileId"": """ + inputFileId + @"""
            }
        ],
        ""dest"": {
            ""format"": ""pdf""
        }
    }
}";

            using (HttpResponseMessage response = await session.PostAsync("/v2/contentConverters", new StringContent(postContentConvertersJson)))
            {
                response.EnsureSuccessStatusCode();
                json = await response.Content.ReadAsStringAsync();
            }

            JObject process   = JObject.Parse(json);
            string  processId = (string)process["processId"];

            // Wait for the process to finish
            using (HttpResponseMessage response = await session.GetFinalProcessStatusAsync($"/v2/contentConverters/{processId}"))
            {
                response.EnsureSuccessStatusCode();
                json = await response.Content.ReadAsStringAsync();
            }

            process = JObject.Parse(json);

            // Did the process error?
            if ((string)process["state"] != "complete")
            {
                throw new Exception("The process failed to complete:\n" + json);
            }

            // Download the output work file and save it to disk.
            string workFileId = (string)process["output"]["results"][0]["fileId"];

            using (HttpResponseMessage response = await session.GetAsync($"/PCCIS/V1/WorkFile/{workFileId}"))
            {
                response.EnsureSuccessStatusCode();

                using (Stream responseBodyStream = await response.Content.ReadAsStreamAsync())
                    using (FileStream outputFileStream = File.OpenWrite("output.pdf"))
                    {
                        await responseBodyStream.CopyToAsync(outputFileStream);
                    }
            }
        }