/// <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")); }
/// <summary> /// Returns a RemoteWorkFile instance with the specified affinity. /// If this instance already has the specified affinity, it will be /// returned. If it does not, it will be downloaded and re-uploaded /// to create a new instance with the proper affinity, and that new /// instance will be returned. /// </summary> /// <param name="affinitySession">Existing affinity session to use in case of re-upload.</param> /// <param name="affinityToken">Existing affinity token which the RemoteWorkFile needs to match.</param> /// <returns>This existing RemoteWorkFile if the AffinityToken matched the provided affinityToken, or a new RemoteWorkFile with the provided affinityToken.</returns> internal async Task <RemoteWorkFile> GetInstanceWithAffinity(AffinitySession affinitySession, string affinityToken = null) { // If no affinity token was specified, there is nothing to do. if (this.AffinityToken == null) { return(this); } // If this RemoteWorkFile already has the correct affinity, there is // nothing to do. if (this.AffinityToken == affinityToken) { return(this); } // If this RemoteWorkFile has the wrong affinity (it is on the wrong // machine), then download and re-upload it to the correct machine, // and assign the new RemoteWorkFile to this // ConversionSourceDocument. using (HttpResponseMessage res = await this.HttpGetAsync()) { await res.ThrowIfRestApiError(); Stream downloadStream = await res.Content.ReadAsStreamAsync(); return(await affinitySession.UploadAsync(downloadStream, this.FileExtension, affinityToken : affinityToken)); } }
internal RemoteWorkFile(AffinitySession session, string fileId, string affinityToken, string fileExtension) { this.session = session; this.FileId = fileId; this.AffinityToken = affinityToken; this.FileExtension = fileExtension; }
public async Task UploadAsync_throws_if_the_local_file_cannot_be_found() { AffinitySession affinitySession = Util.RestClient.CreateAffinitySession(); await UtilAssert.ThrowsExceptionWithMessageAsync <FileNotFoundException>( async() => { await affinitySession.UploadAsync("documents/does not exist.pdf"); }, "File not found: \"documents/does not exist.pdf\""); }
/// <summary> /// Upload a <see cref="Stream"/>, creating a new <see cref="RemoteWorkFile"/>. /// </summary> internal static async Task <RemoteWorkFile> UploadAsync(this AffinitySession affinitySession, Stream documentStream, string fileExtension = "txt", string affinityToken = null) { // Remove leading period on fileExtension if present. if (fileExtension != null && fileExtension.StartsWith(".")) { fileExtension = fileExtension.Substring(1); } var req = new HttpRequestMessage(HttpMethod.Post, $"/PCCIS/V1/WorkFile?FileExtension={fileExtension}") { Content = new StreamContent(documentStream), }; if (affinityToken != null) { req.Headers.Add("Accusoft-Affinity-Token", affinityToken); } string json; using (HttpResponseMessage response = await affinitySession.SendAsync(req)) { await response.ThrowIfRestApiError(); json = await response.Content.ReadAsStringAsync(); } var info = JsonConvert.DeserializeObject <PostWorkFileResponse>(json); var remoteWorkFile = new RemoteWorkFile(affinitySession, info.fileId, info.affinityToken, info.fileExtension); return(remoteWorkFile); }
/// <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")); }
public async Task GetInstanceWithAffinity_works() { // Arrange AffinitySession session1 = Util.RestClient.CreateAffinitySession(); AffinitySession session2 = Util.RestClient.CreateAffinitySession(); RemoteWorkFile file1 = await session1.UploadAsync("documents/confidential-contacts.pdf"); RemoteWorkFile file2 = await session2.UploadAsync("documents/confidential-contacts.pdf.markup.json"); Assert.AreNotEqual(file1.AffinityToken, file2.AffinityToken); // Act RemoteWorkFile file2Reuploaded = await file2.GetInstanceWithAffinity(session2, file1.AffinityToken); // Assert Assert.AreEqual(file2.FileExtension, file2Reuploaded.FileExtension, "The FileExtension was not set correctly after reupload!"); Assert.AreEqual(file1.AffinityToken, file2Reuploaded.AffinityToken, "The AffinityToken was not correct after reupload!"); using (var originalContent = new MemoryStream()) using (var reuploadedContent = new MemoryStream()) { await file2.CopyToAsync(originalContent); await file2Reuploaded.CopyToAsync(reuploadedContent); CollectionAssert.AreEqual(originalContent.ToArray(), reuploadedContent.ToArray()); } }
public async Task <RemoteWorkFile> UploadPlainTextAsync(AffinitySession affinitySession, string text) { using (var stream = new MemoryStream(Encoding.UTF8.GetBytes(text))) { return(await affinitySession.UploadAsync(stream)); } }
/// <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="localFilePathToMarkupJson">Path to a local markup.json /// file containing the markup you want burned in to the source /// document.</param> /// <returns>RemoteWorkFile for the new PDF.</returns> public async Task <RemoteWorkFile> BurnMarkupAsync(RemoteWorkFile sourceDocument, string localFilePathToMarkupJson) { AffinitySession affinitySession = this.restClient.CreateAffinitySession(); RemoteWorkFile markupJson = await affinitySession.UploadAsync(localFilePathToMarkupJson, sourceDocument.AffinityToken); return(await this.BurnMarkupAsync(sourceDocument, markupJson)); }
/// <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="localFilePath">Path to a local file to use as the source document for which redactions should be created.</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(string localFilePath, IEnumerable <RedactionMatchRule> rules) { AffinitySession affinitySession = this.restClient.CreateAffinitySession(); RemoteWorkFile sourceDocument = await affinitySession.UploadAsync(localFilePath); return(await this.CreateRedactionsAsync(sourceDocument, rules)); }
/// <summary> /// <para> /// Applies redactions in a markup JSON file to a document, producing a /// new redacted plain text file. /// </para> /// <para> /// Note that redaction options (like redaction reason, border /// color, fill color, etc.) are not used by PrizmDoc Server when /// redacting to plain text. Instead, PrizmDoc Server will simply /// indicate when a portion of a line was redacted with the string /// <c>"<Text Redacted>"</c>. /// </para> /// </summary> /// <param name="localFilePathToSourceDocument">Path to a local file 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> /// <param name="outputLineEndingFormat">Line ending to use in the /// output plain text file, such as <c>"\n"</c> or /// <c>"\r\n"</c>.</param> /// <returns>RemoteWorkFile for the new plain text file.</returns> public async Task <RemoteWorkFile> RedactToPlainTextAsync(string localFilePathToSourceDocument, RemoteWorkFile markupJson, string outputLineEndingFormat) { AffinitySession affinitySession = this.restClient.CreateAffinitySession(); RemoteWorkFile sourceDocument = await affinitySession.UploadAsync(localFilePathToSourceDocument, markupJson.AffinityToken); return(await this.RedactToPlainTextAsync(sourceDocument, markupJson, outputLineEndingFormat)); }
public async Task Will_POST_work_file_when_given_a_local_file_path() { AffinitySession affinitySession = Util.RestClient.CreateAffinitySession(); var input = new ConversionSourceDocument("documents/example.docx"); Assert.IsNull(input.RemoteWorkFile); await input.EnsureUsableRemoteWorkFileAsync(affinitySession); Assert.IsNotNull(input.RemoteWorkFile); }
public async Task Will_throw_an_exception_if_given_a_path_to_a_local_file_which_cannot_be_found() { AffinitySession affinitySession = Util.RestClient.CreateAffinitySession(); var input = new ConversionSourceDocument("documents/does not exist.pdf"); Assert.IsNull(input.RemoteWorkFile); await UtilAssert.ThrowsExceptionWithMessageAsync <FileNotFoundException>( async() => { await input.EnsureUsableRemoteWorkFileAsync(affinitySession); }, "File not found: \"documents/does not exist.pdf\""); }
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); }
public async Task PutAsync() { mockServer .Given(Request.Create().WithPath("/wat/123").UsingPut()) .RespondWith(Response.Create().WithStatusCode(200).WithBody(req => $"You PUT: {req.Body}")); AffinitySession session = client.CreateAffinitySession(); using (HttpResponseMessage response = await session.PutAsync("/wat/123", new StringContent("Hi there, friend."))) { response.EnsureSuccessStatusCode(); Assert.AreEqual("You PUT: Hi there, friend.", await response.Content.ReadAsStringAsync()); } }
public async Task PostAsync() { mockServer .Given(Request.Create().WithPath("/wat").UsingPost()) .RespondWith(Response.Create().WithStatusCode(200).WithBody(req => $"You POSTed: {req.Body}")); AffinitySession session = client.CreateAffinitySession(); using (HttpResponseMessage response = await session.PostAsync("/wat", new StringContent("Hello world!"))) { response.EnsureSuccessStatusCode(); Assert.AreEqual("You POSTed: Hello world!", await response.Content.ReadAsStringAsync()); } }
public async Task BaseAddress_with_trailing_slash_is_applied_correctly_to_each_request() { mockServer .Given(Request.Create().WithPath("/wat/123").UsingGet()) .RespondWith(Response.Create().WithStatusCode(200).WithBody("GET Response")); mockServer .Given(Request.Create().WithPath("/wat").UsingPost()) .RespondWith(Response.Create().WithStatusCode(200).WithBody("POST Response")); mockServer .Given(Request.Create().WithPath("/wat/123").UsingPut()) .RespondWith(Response.Create().WithStatusCode(200).WithBody("PUT Response")); mockServer .Given(Request.Create().WithPath("/wat/123").UsingDelete()) .RespondWith(Response.Create().WithStatusCode(200).WithBody("DELETE Response")); string baseAddressWithoutTrailingSlash = "http://localhost:" + mockServer.Ports.First(); string baseAddressWithTrailingSlash = baseAddressWithoutTrailingSlash + "/"; client = new PrizmDocRestClient(baseAddressWithTrailingSlash); AffinitySession session = client.CreateAffinitySession(); using (HttpResponseMessage response = await session.SendAsync(new HttpRequestMessage(HttpMethod.Get, "/wat/123"))) { Assert.AreEqual(baseAddressWithoutTrailingSlash + "/wat/123", response.RequestMessage.RequestUri.ToString()); } using (HttpResponseMessage response = await session.GetAsync("/wat/123")) { Assert.AreEqual(baseAddressWithoutTrailingSlash + "/wat/123", response.RequestMessage.RequestUri.ToString()); } using (HttpResponseMessage response = await session.PostAsync("/wat", new StringContent("body"))) { Assert.AreEqual(baseAddressWithoutTrailingSlash + "/wat", response.RequestMessage.RequestUri.ToString()); } using (HttpResponseMessage response = await session.PutAsync("/wat/123", new StringContent("body"))) { Assert.AreEqual(baseAddressWithoutTrailingSlash + "/wat/123", response.RequestMessage.RequestUri.ToString()); } using (HttpResponseMessage response = await session.DeleteAsync("/wat/123")) { Assert.AreEqual(baseAddressWithoutTrailingSlash + "/wat/123", response.RequestMessage.RequestUri.ToString()); } }
public async Task DeleteAsync() { mockServer .Given(Request.Create().WithPath("/wat/123").UsingDelete()) .RespondWith(Response.Create().WithStatusCode(200).WithBody(req => $"Resource deleted: {req.Path}")); AffinitySession session = client.CreateAffinitySession(); using (HttpResponseMessage response = await session.DeleteAsync("/wat/123")) { response.EnsureSuccessStatusCode(); Assert.AreEqual("Resource deleted: /wat/123", await response.Content.ReadAsStringAsync()); } }
public async Task Can_use_RemoteWorkFile_for_document_and_local_file_path_for_markup_JSON() { // Arrange PrizmDocServerClient prizmDocServer = Util.CreatePrizmDocServerClient(); AffinitySession affinitySession = Util.RestClient.CreateAffinitySession(); RemoteWorkFile document = await affinitySession.UploadAsync("documents/confidential-contacts.pdf"); // Act RemoteWorkFile result = await prizmDocServer.RedactToPlainTextAsync(document, "documents/confidential-contacts.pdf.markup.json", "\n"); // Assert await this.AssertPlainTextRedactionOccurredFor(result, "\n"); }
/// <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()); }
public async Task BurnMarkupAsync_fails_with_a_useful_error_message_when_the_source_document_cannot_be_found() { PrizmDocServerClient prizmDocServer = Util.CreatePrizmDocServerClient(); AffinitySession affinitySession = Util.RestClient.CreateAffinitySession(); RemoteWorkFile existingMarkupFile = await affinitySession.UploadAsync("documents/confidential-contacts.pdf.markup.json"); RemoteWorkFile nonExistentSourceDocument = new RemoteWorkFile(affinitySession, "non-existent-id", existingMarkupFile.AffinityToken, "pdf"); await UtilAssert.ThrowsExceptionWithMessageAsync <RestApiErrorException>( async() => { await prizmDocServer.BurnMarkupAsync(nonExistentSourceDocument, existingMarkupFile); }, "Could not use the given RemoteWorkFile as the source document: the work file resource could not be found on the remote server. It may have expired."); }
public async Task When_work_file_does_not_exist() { PrizmDocServerClient prizmDocServer = Util.CreatePrizmDocServerClient(); AffinitySession affinitySession = Util.RestClient.CreateAffinitySession(); RemoteWorkFile validWorkFile = await affinitySession.UploadAsync("documents/confidential-contacts.pdf"); RemoteWorkFile invalidWorkFile = new RemoteWorkFile(affinitySession, "non-existent-id", validWorkFile.AffinityToken, "pdf"); await UtilAssert.ThrowsExceptionWithMessageAsync <RestApiErrorException>( async() => { await prizmDocServer.CreateRedactionsAsync(invalidWorkFile, new[] { new RegexRedactionMatchRule("dummy rule") }); }, "Could not use the given RemoteWorkFile as the source document: the work file resource could not be found on the remote server. It may have expired."); }
public async Task GetAsync() { mockServer .Given(Request.Create().WithPath("/wat/123").UsingGet()) .RespondWith(Response.Create().WithStatusCode(200).WithBody("GET Response")); AffinitySession session = client.CreateAffinitySession(); HttpResponseMessage response; response = await session.GetAsync("/wat/123"); response.EnsureSuccessStatusCode(); Assert.AreEqual("GET Response", await response.Content.ReadAsStringAsync()); }
public async Task Will_reupload_an_existing_RemoteWorkFile_when_the_affinity_is_wrong() { AffinitySession session1 = Util.RestClient.CreateAffinitySession(); AffinitySession session2 = Util.RestClient.CreateAffinitySession(); RemoteWorkFile file1; using (var stream = new MemoryStream(Encoding.UTF8.GetBytes("File 1"))) { file1 = await session1.UploadAsync(stream); } RemoteWorkFile file2; using (var stream = new MemoryStream(Encoding.UTF8.GetBytes("File 2"))) { file2 = await session2.UploadAsync(stream); } Assert.AreNotEqual(file1.AffinityToken, file2.AffinityToken); var source2 = new ConversionSourceDocument(file2); RemoteWorkFile originalRemoteWorkFile = source2.RemoteWorkFile; Assert.AreEqual(file2, originalRemoteWorkFile); // Ensure file2 is re-uploaded to the same machine as file1... await source2.EnsureUsableRemoteWorkFileAsync(Util.RestClient.CreateAffinitySession(), affinityToken : file1.AffinityToken); // Verify source RemoteWorkFile assignment was changed to something new Assert.AreNotEqual(source2.RemoteWorkFile, originalRemoteWorkFile); // Verify the affinity token of file1 and source2.RemoteWorkFile now match Assert.AreEqual(file1.AffinityToken, source2.RemoteWorkFile.AffinityToken); // Verify the contents of the file are still correct using (var stream = new MemoryStream()) { await source2.RemoteWorkFile.CopyToAsync(stream); stream.Position = 0; using (var reader = new StreamReader(stream, Encoding.UTF8)) { string text = reader.ReadToEnd(); Assert.AreEqual("File 2", text); } } }
/// <summary> /// Ensures the RemoteWorkFile property is assigned a RemoteWorkFile instance with the given affinityToken. /// </summary> /// <param name="affinitySession">Affinity session to use for uploading files.</param> /// <param name="affinityToken">Existing affinity token to use for each upload.</param> /// <returns>A <see cref="Task"/> representing the asynchronous operation.</returns> internal async Task EnsureUsableRemoteWorkFileAsync(AffinitySession affinitySession, string affinityToken = null) { if (this.RemoteWorkFile == null) { if (!File.Exists(this.LocalFilePath)) { throw new FileNotFoundException($"File not found: \"{this.LocalFilePath}\""); } this.RemoteWorkFile = await affinitySession.UploadAsync(this.LocalFilePath, affinityToken : affinityToken); } else { this.RemoteWorkFile = await this.RemoteWorkFile.GetInstanceWithAffinity(affinitySession, affinityToken); } }
public async Task Can_use_local_file_path_for_document_and_RemoteWorkFile_for_markup_JSON() { // Arrange PrizmDocServerClient prizmDocServer = Util.CreatePrizmDocServerClient(); AffinitySession affinitySession = Util.RestClient.CreateAffinitySession(); RemoteWorkFile markupJson = await affinitySession.UploadAsync("documents/confidential-contacts.pdf.markup.json"); // Act RemoteWorkFile result = await prizmDocServer.BurnMarkupAsync("documents/confidential-contacts.pdf", markupJson); // Assert await result.SaveAsync("burned.pdf"); await this.AssertRedactionOccurredFor(result); }
public async Task Will_use_existing_RemoteWorkFile() { AffinitySession affinitySession = Util.RestClient.CreateAffinitySession(); RemoteWorkFile remoteWorkFile; using (var stream = new MemoryStream(Encoding.UTF8.GetBytes("Hello world!"))) { remoteWorkFile = await affinitySession.UploadAsync(stream); } var input = new ConversionSourceDocument(remoteWorkFile); Assert.AreEqual(remoteWorkFile, input.RemoteWorkFile); await input.EnsureUsableRemoteWorkFileAsync(affinitySession); Assert.AreEqual(remoteWorkFile, input.RemoteWorkFile); }
/// <summary> /// Upload a local file, creating a new <see cref="RemoteWorkFile"/>. /// </summary> internal static async Task <RemoteWorkFile> UploadAsync(this AffinitySession affinitySession, string localFilePath, string affinityToken = null) { if (affinitySession is null) { throw new ArgumentNullException(nameof(affinitySession)); } if (!File.Exists(localFilePath)) { throw new FileNotFoundException($"File not found: \"{localFilePath}\"", "localFilePathToDocument"); } string fileExtension = Path.GetExtension(localFilePath); using (FileStream localFileReadStream = File.OpenRead(localFilePath)) { return(await affinitySession.UploadAsync(localFileReadStream, fileExtension, affinityToken)); } }
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_use_RemoteWorkFile_instances_with_different_affinity() { // Arrange PrizmDocServerClient prizmDocServer = Util.CreatePrizmDocServerClient(); AffinitySession session1 = Util.RestClient.CreateAffinitySession(); AffinitySession session2 = Util.RestClient.CreateAffinitySession(); RemoteWorkFile document = await session1.UploadAsync("documents/confidential-contacts.pdf"); RemoteWorkFile markupJson = await session2.UploadAsync("documents/confidential-contacts.pdf.markup.json"); Assert.AreNotEqual(document.AffinityToken, markupJson.AffinityToken); // Act RemoteWorkFile result = await prizmDocServer.RedactToPlainTextAsync(document, markupJson, "\n"); // Assert await this.AssertPlainTextRedactionOccurredFor(result, "\n"); }