Upload Attachment to ServiceNow using SOAP and Base64 via BluePrism - wsdl

I am trying to upload a file into ServiceNow using the WSDL <https://instanceName.Service-now.com/ecc_queue.do?WSDL>
I am converting the file to Base64 using Powershell. The upload via SOAPUI works fine, however the same file when downloaded is corrupted. If I upload an Excel file with data on downloading the file the Excel file is Empty
Source File Name is tp-certification-guide.pdf (Source PDF: - https://www.servicenow.com/content/dam/servicenow/other-documents/training/tp-certification-guide.pdf)
However, when I convert the file to Base64 using a portal (https://www.browserling.com/tools/file-to-base64/), I am able to upload and download the file without any issues. Again the file uploaded to ServiceNow does not get corrupted nor does it download an Empty File.
My SoapUI code: -
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:ecc="http://www.service-now.com/ecc_queue">
<soapenv:Header/>
<soapenv:Body>
<ecc:insert>
<agent>AttachmentUploader</agent>
<name>problem_data.pdf:application/pdf</name>
<payload>AAAAIGZ0eXBxdCrG[..truncated..]</payload>;
<source>incident:[sysid is here]</source>
<topic>AttachmentUploader</topic>
</ecc:insert>
</soapenv:Body>
</soapenv:Envelope>
Above Code taken from https://www.servicenowguru.com/integration/sending-attachment-servicenow/
My PowerShell code is as below
$InputFile = "D:\02_Downloads\ChromeDLs\tp-certification-guide.pdf"
# Read the file as text
$Text = [System.IO.File]::ReadAllText($InputFile)
# Convert the string to UTF-8 bytes
$UTF8Bytes = [System.Text.Encoding]::UTF8.GetBytes($Text)
# Encode the UTF-8 bytes as a Base64 string
$Base64String = [System.Convert]::ToBase64String($UTF8Bytes)
$Base64String | Out-File "D:\02_Downloads\ChromeDLs\tp-certification-guide.txt"
The file should uploaded to ServiceNow using the WSDL and the same file when downloaded should not be corrupted or empty.
I feel there is something wrong in the generation of Base64 using Powershell compared to the Online Edition which would need assistance.

I can't help you with the base64 problem, but if you're interested, then here's my dotnet code to upload attachment to SNOW using REST.
Dim request As WebRequest = WebRequest.Create(REST_Address)
request.UseDefaultCredentials = True
request.Credentials = new NetworkCredential(SNOW_Username, SNOW_Password)
request.Method = "POST"
request.ContentType = ContentType
Dim byteArray As Byte() = System.IO.File.ReadAllBytes(Filename)
request.ContentLength = byteArray.Length
Dim RequestStream As System.IO.Stream = request.GetRequestStream()
RequestStream.Write(byteArray, 0, byteArray.Length)
RequestStream.close()
Dim response As WebResponse = request.GetResponse
Dim responseStream As IO.Stream = response.GetResponseStream
Dim sr As New IO.StreamReader(responseStream)
resultData = sr.ReadToEnd
response.Close
REST address example: https://instance.service-now.com/api/now/attachment/file?table_name=SNOWTable&table_sys_id=32charsysid&file_name=test.pdf
content type: application/pdf

Related

Getting error "The attachment content must be base64 encoded" while sending pdf in zip as an attachment using SendGrid

We are using SendGrid latest available Java API to send emails. We are attaching a PDF enclosed in a zip file.
While sending mail we are getting a 404 response code and error message stating "The attachment content must be base64 encoded"
Complete Error Message:
{"errors":\[{"message":"The attachment content must be base64 encoded.","field":"attachments.0.content","help":"http://sendgrid.com/docs/API_Reference/Web_API_v3/Mail/errors.html#message.attachments.content"}\]}
What are we doing wrong? How can we solve this issue and send this attachment? Here is the code where we try to send the PDF in a Zip.
Code:
Path file = Paths.get(this.file.getAbsolutePath());
Attachments attachments = new Attachments();
attachments.setFilename(Base64.getMimeEncoder().encodeToString(file.getFileName().toString().getBytes(StandardCharsets.UTF_8)));
//attachments.setType``("application/pdf");
attachments.setDisposition("attachment");
byte[] attachmentContentBytes = Files.readAllBytes(file);
String attachmentContent = Base64.getMimeEncoder().encodeToString(attachmentContentBytes);
attachments.setContent(attachmentContent);
mail.addAttachments(attachments);
com.sendgrid.SendGrid sg = new com.sendgrid.SendGrid(this.apiKey);
Request request = new Request();
request.setMethod(Method.POST);
request.setEndpoint("mail/send");
request.setBody(mail.build());
Response response = sg.api(request);
Response:
{"errors":\[{"message":"The attachment content must be base64 encoded.","field":"attachments.0.content","help":"http://sendgrid.com/docs/API_Reference/Web_API_v3/Mail/errors.html#message.attachments.content"}\]}
Maven dependencies:
com.sendgrid.sendgrid-java 4.9.1
Try Base64.getEncoder() instead of Base64.getMimeEncoder(). Sometimes Sendgrid does not recognize the result from getMimeEncoder().

Rest Assured - Send POST Request (Content-Type : multipart/form-data) with Static JSON Payload and Files to be uploaded

I want to send a POST Request where -
Content Type is "multipart / form-data".
In "Body" section, I have 2 params -> body - {static JSON Payload}, files - {any file, say .log file}
In Rest Assured Code, I am able to get the Static JSON Payload in String format with below code -
String jsonFilePath = "<<Path to JSON File>>/Test_new.json";
String response = given().log().all().header("X-AUTH-TOKEN",res).body(new String(Files.readAllBytes(Paths.get(jsonFilePath)))).
when().post("<<POST RESOURCE URL>>").
then().log().body().assertThat().statusCode(200).extract().response().asString();
When running this code, only with Static JSON Payload, I am getting "415" error code.
Questions -
How can we successfully make this kind of call in Rest Assured?
When I want to upload files as well with this call, how to do that?
You need to use multiPart() methods for uploading files, not body() method. For example:
File json = new File("src/test/resources/test_new.json");
File file = new File("src/test/resources/debug.log");
given().log().all()
.multiPart("files", file)
.multiPart("body", json, "application/json")
.post("your_url");

How do I add a file into a HTTP PUT request calling the Microsoft Graph API?

I am trying to upload a file to a SharePoint Drive by using Microsoft Graph. I am new to REST APIs and Microsoft Graph.
This is what the documentation says:
PUT /me/drive/root:/FolderA/FileB.txt:/content
Content-Type: text/plain
The contents of the file goes here.
Before all of this, I do have my authorization/bearer token and I am able to call the HTTP get but I am not able to upload the file using HTTP PPU.
URL url = new URL(newUrl);
String readLine;
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestProperty("Authorization","Bearer "+ token);
connection.setRequestProperty("Accept","application/json");
This returns java.io.IOException: Server returned HTTP response code: 411 for URL.
I have tried passing it as a binary stream but the request is still failing.
The "type" of the file is determined by the Content-Type header. For some context, the Accept header states the format you expect the response body to use while the Content-Type states the format of your request.
To upload a standard text file, you'll want to use Content-Type: text/plain:
URL url = new URL(newUrl);
String readLine;
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestProperty("Authorization","Bearer "+ token);
connection.setRequestProperty("Accept","application/json");
connection.setRequestProperty("Content-Type","text/plain");

Grails Base64 to PDF - render a PDF inline

I have a Grails controller action that calls a service that will return XML that contains a base64 representation of a PDF. Here is an (abbreviated) example sample.
<response status="Success"><messages/><values><pages>8</pages></values><xml/><files><pdf name="FitnessApplication" content-type="application/pdf"><![CDATA[JVBERi0xLjQKJeL ... </files></response>
After we parse that out I want to display that PDF in the browser. So far I am able to decode the string and render it using the file attribute of the render method. This serves up the PDF correctly as a download but I want it to display in the browser (inline) and NOT as a file download.
Map responseMap = new XmlParserHelper().parse( formsResponse.payload )
byte[] decoded = responseMap.files.pdf.decodeBase64()
render( file: decoded, fileName: "${document}.pdf", contentType: "application/pdf", )
I tried setting the content disposition as both an option to render and in the header map but neither seem to do the trick. Does anyone know how I can serve this PDF to the user in the browser?
Just send it in the response. But you need to add the headers on your own. E.g. something like:
response.contentType = "application/pdf"
response.contentLength = FileUtils.copyFile(pdfFile, response.outputStream)
To build on what cfrick said here is the final solution I went with.
// response data
byte[] pdfData = responseMap.files.pdf.decodeBase64()
response.contentType = "application/pdf"
response.setHeader("Content-disposition", "inline; filename='dan.pdf'")
// write to output
OutputStream output = response.outputStream
output.write(pdfData);
output.close();

multipart http request to upload images

I m trying to use multipart post request to upload two string parameters( token and source) and an image captured from mobile device ( return jpeg encoded byte[] ). But it is generating error which I am sure is due to incorrect request.
I am still not sure about notation on creating a multipart post request. So any helpful links and resources would be good.
The code is for Blackberry java development
//------------------------------------------------------------------------------//
StringBuffer buffer = new StringBuffer();
String boundary = "--##$--";
byte[] image = byte[] from camera.getsnapshot;
buffer.append(boundary+"\r\nContent-Disposition: form- data;name=\"token\"\r\n"+token+"\r\n");
buffer.append(boundary+"\r\nContent-Disposition: form- data;name=\"source\"\r\n"+"Blackberry"+"\r\n");
buffer.append(boundary+"\r\nContent-Disposition: form- data;name=\"file.jpg\";filename=\""+ "file.jpg"+"\""+"\n" + "Content- Type:image/jpeg"+"\n"+ "Content-Transfer-Encoding: binary" + boundary +"\r\n" +new String(image));
buffer.append("\r\n" + boundary + "\r\n");
String string = new String(buffer);
byte[] post = string.getBytes();
HttpConnection connection = (HttpConnection)Connector.open(url);
connection.setRequestMethod("POST");
connection.setRequestProperty(HttpProtocolConstants.HEADER_CONTENT_TYPE,
HttpProtocolConstants.CONTENT_TYPE_MULTIPART_FORM_DATA+
";boundary="+boundary);
connection.setRequestProperty(HttpProtocolConstants.HEADER_CONTENT_LENGTH,String.valueOf(post.length));
connection.setRequestProperty("User-Agent", "Profile/MIDP_2.0 Configuration/CLDC-1.0");
OutputStream postStream =connection.openOutputStream();
postStream.write(post,0,post.length);
postStream.close();
\----------------------------------------------------------------------------------\
Perhaps this Nokia Community wiki page will help you: HTTP Post multipart file upload in Java ME

Resources