Mule - Salesforce connector - Retrieve job failed results bulk v2 - not returning failed data - salesforce

I am querying Salesforce Bulk api failed results in Mule. But it doesn't fetch the data. It jus shows the record id and error message. But if i check in workbench, it shows the id, error, datacolumns(a,b,c)
How to get those details..Is there any other way to get the bulk api v2 failed results in Mule
doing simple Transformation before logging
%dw 2.0
output application/json
---
payload
Debug Log :
On workbench, I get the actual data.
please share your thoughts why i don't see those data

#RestResource(urlMapping='/bulkapi/failures')
global without sharing class RestGetBulkAPIResults
{
#HttpGet
global static void getFailedRecords()
{
RestRequest req = RestContext.request;
RestResponse res = RestContext.response;
res.addHeader('Content-Type', 'application/json');
Http http = new Http();
HttpRequest httpReq = new HttpRequest();
HttpResponse httpRes = new HttpResponse();
httpReq.setMethod('GET');
httpReq.setHeader('Authorization', 'Bearer ' + UserInfo.getSessionId());
string path = '/services/data/v48.0/jobs/ingest/7502i000001fJG9AAM/failedResults/';
httpReq.setEndpoint(URL.getSalesforceBaseUrl().toExternalForm()+ path);
httpRes = http.send(httpReq);
string op = httpRes.getBody();
string[] rowList = op.split('\n');
string[] headers = rowList[0].split(',');
integer columnsCount = headers.size();
integer dataRowsCount = rowList.size();
string fullFormattedData = '[';
for(integer rowIndex =1; rowIndex < dataRowsCount; rowIndex++)
{
string[] rowData = rowList[rowIndex].split(',');
string rowJsonData ='{';
for(integer columnIndex=0; columnIndex < columnsCount; columnIndex++)
{
rowJsonData += headers[columnIndex] + ':' + rowData[columnIndex] + ',';
}
rowJsonData = rowJsonData.removeEnd(',');
rowJsonData += '}';
fullFormattedData += rowJsonData;
}
fullFormattedData += ']';
system.debug('resp' + httpRes.getBody());
res.responseBody = Blob.valueOf(fullFormattedData);
res.statusCode = 200;
}
}

Related

Cannot upload a file in blob in sharefile

I am trying to upload a file in Citrix ShareFile via REST API. There are four requests
Get the access_token
Get the folder URI's to decide n which I am going to upload the file.
Get chunk Uri
Upload the file in that chunk Uri
The first three steps work perfectly. When I am trying to POST a request for the no 4. part,
it is creating a file in sharefile but with size of 0.
I have tried that with POSTMAN, and with form-data and the selection of a file, it is working fine. The file is uploaded in sharefile.
The problem arises when I am trying to upload blob data.
I am calling this methods from Salesforce Platform and in Salesforce, I cannot get the physical file in a physical location. I have blob file data stored in salesforce database.
The below part works well.
String fileName_m = 'a12.pdf';
// Get Authentication Token
HttpRequest req = new HttpRequest();
req.setEndpoint('https://{server}.sf-api.com/oauth/token?grant_type=password&client_id={client_id}&client_secret={secret}&username={user_name}&password={password}!');
req.setMethod('GET');
Http http = new Http();
HttpResponse response = http.send(req);
System.Debug(response.getBody());
Map<String, Object> results = (Map<String, Object>)JSON.deserializeUntyped(response.getBody());
String token = '';
String refreshtoken = '';
if(response.getStatusCode() == 200){
token = (String)results.get('access_token');
refreshtoken = (String)results.get('refresh_token');
}
system.debug('token=' + token);
// Get Folder ID
HttpRequest req1 = new HttpRequest();
req1.setEndpoint('https://{server}.sf-api.com/sf/v3/Items?$expand=Children');
req1.setMethod('GET');
req1.setHeader('Authorization','Bearer ' + token);
Http http1 = new Http();
HttpResponse response1 = http1.send(req1);
System.Debug(response1.getBody());
Map<String, Object> results1 = (Map<String, Object>)JSON.deserializeUntyped(response1.getBody());
String url = '';
if(response1.getStatusCode() == 200){
url = (String)results1.get('url');
}
System.Debug('Folder Url ' + url);
// Get Chunk URI
HttpRequest req2 = new HttpRequest();
String endPoint = url + '/Upload2';
req2.setEndpoint(endPoint);
req2.setMethod('POST');
req2.setHeader('Authorization','Bearer ' + token);
req2.setHeader('Content-Type', 'application/x-www-form-urlencoded');
String payload1 = 'FileName='+fileName_m;
req2.setBody(payload1);
Http http2 = new Http();
HttpResponse response2 = http2.send(req2);
Map<String, Object> results2 = (Map<String, Object>)JSON.deserializeUntyped(response2.getBody());
String ChunkUri = '';
if(response2.getStatusCode() == 200){
ChunkUri = (String)results2.get('ChunkUri');
}
System.Debug('ChunkUri' + ChunkUri);
But, when I am trying to upload blob file data in sharefile, the API responds with a 200 status code. In sharefile, the file is created, but the size of the file is 0.
// Problem is here, it is not working
// Upload File
Attachment att = [SELECT Id, Body, Name, ContentType FROM Attachment WHERE Id='00P3p00001XNLOHEA5'];
String body = EncodingUtil.base64Encode(att.body);
List<Attachment> cvList = [SELECT Id, Body, Name, ContentType FROM Attachment WHERE Id='00P3p00001XNLOHEA5'];
String attachmentBody = EncodingUtil.base64Encode(cvList[0].Body);
Blob pdfBlob = EncodingUtil.base64Decode(attachmentBody);
system.debug('pdfBlob' + pdfBlob);
HttpRequest req3 = new HttpRequest();
req3.setEndpoint(ChunkUri);
req3.setMethod('POST');
req3.setHeader('Authorization','Bearer ' + token);
req3.setHeader('Content-Length', String.valueOf(attachmentBody.length()));
req3.setHeader('Content-Encoding', 'UTF-8');
req3.setHeader('Content-type', 'application/pdf');
req3.setHeader('Connection', 'keep-alive');
req3.setBodyAsBlob(pdfBlob);
Http http3 = new Http();
HttpResponse response3 = http3.send(req3);
System.Debug(response3.getBody());
How to solve the issue?

How do i filter using a partial VM name (string) in vmware vSphere client REST API?

Good day!
i am trying to automate some actions to be done to VM's in my organisation.
The action to be done depends on the a substring in the VM name.
for eg, i would need to delete all VM's whose name starts with 'delete', etc.
I can use the below API to fetch the list of VM's:
GET https://{{vc}}/rest/vcenter/vm
However, this API can only fetch a maximum of 1000 VM's.
Is there any way i can filter and get only the list of VM's with the expected substring from this API?
from what i understand, appending filter.names.1 to the above API works but for that i need to input the exact and entire VM name.
is there a way where i can search for a list of VM's with partial text?
Apologies, i am a newbie to this.
thank you for your time!
Since vSphere API does not provide such capability to search by partial VM name there is a tricky way to do this.
I am using the search functionality in vSphere Client 6.7.0.
Prerequisite is to get the following cookies first:
VSPHERE-USERNAME
VSPHERE-CLIENT-SESSION-INDEX
VSPHERE-UI-JSESSIONID
You have to do three calls in order to get them:
1. GET "https://[URL]/ui/login" you will be forwarded to a new URL from where you can take "SAMLRequest token"
2. POST "https://[URL]/websso/SAML2/SSO/vsphere.local?SAMLRequest=[SAMLRequest token]", set as header "CastleAuthorization=Basic%20[credentials]" where credentials is the Base64 encoding of "User:Password". Get the value of "SAMLResponse" hidden field from the response.
3. POST "https://[URL]/ui/saml/websso/sso", set "SAMLResponse=[SAMLResponse value]", where "SAMLResponse value" you have it from the previous response. From this response you will get the cookies.
Once you have those three cookies, make a new call as you set the cookies
4. GET "https://[URL]/ui/search/quicksearch/?opId=0&query=[partial VM name]"
For example for this call "https://[URL]/ui/search/quicksearch/?opId=0&query=test"
you will get response like this:
[{
"icon": "vsphere-icon-vm",
"labelPlural": "Virtual Machines",
"label": "Virtual Machine",
"results": [{
"id": "urn:vmomi:VirtualMachine:vm-2153:103ac083-e314-47ea-942a-c685d9a4e6c9",
"type": "VirtualMachine",
"name": "TestVM1"
}, {
"id": "urn:vmomi:VirtualMachine:vm-3391:103ac083-e314-47ea-942a-c685d9a4e6c9",
"type": "VirtualMachine",
"name": "TestVM2"
}, {
"id": "urn:vmomi:VirtualMachine:vm-3438:103ac083-e314-47ea-942a-c685d9a4e6c9",
"type": "VirtualMachine",
"name": "TestVM3"
}
]
}
]
Below is my own vSphere Search Proxy Client written in C#:
using System;
using System.IO;
using System.Net;
using System.Text;
using System.Text.RegularExpressions;
using System.Web;
namespace VsphereSearchProxy
{
static class Program
{
const string VSPHERE_URL = "VSPHERE_URL";
static string VSPHERE_CRED_BASE64
{
get
{
var plainTextCred = Encoding.UTF8.GetBytes("USER:PASS");
return Convert.ToBase64String(plainTextCred);
}
}
static void Main(string[] args)
{
if (args.Length == 0)
{
Console.WriteLine("Expected one argument: Virtual Machine name");
return;
}
var vmName = args[0];
var vsphereUri = VSPHERE_URL.TrimEnd('/');
ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
ServicePointManager.Expect100Continue = true;
//=================================================================
Console.WriteLine("\nStep 1\n");
var url1 = vsphereUri + "/ui/login";
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url1);
request.Method = "GET";
request.KeepAlive = true;
request.AllowAutoRedirect = true;
var response = (HttpWebResponse)request.GetResponse();
var url2 = response.ResponseUri.AbsoluteUri;
Console.WriteLine("url2: " + url2);
WebHeaderCollection headerCollection = response.Headers;
Console.WriteLine("\nResponse headers\n");
for (int i = 0; i < headerCollection.Count; i++)
{
Console.WriteLine("\t" + headerCollection.GetKey(i) + " = " + headerCollection.Get(i));
}
//=================================================================
Console.WriteLine("\nStep 2\n");
request = (HttpWebRequest)WebRequest.Create(url2);
request.Method = "POST";
request.Headers.Add("Authorization: Basic " + VSPHERE_CRED_BASE64);
request.ContentType = "application/x-www-form-urlencoded";
request.KeepAlive = true;
request.AllowAutoRedirect = false;
using (var streamWriter = new StreamWriter(request.GetRequestStream()))
{
streamWriter.Write("CastleAuthorization=Basic%20" + VSPHERE_CRED_BASE64);
streamWriter.Flush();
streamWriter.Close();
}
response = (HttpWebResponse)request.GetResponse();
if (response.StatusCode != HttpStatusCode.OK)
{
throw new Exception("Expected 200 OK, but got " + response.StatusCode);
}
headerCollection = response.Headers;
Console.WriteLine("\nResponse headers\n");
for (int i = 0; i < headerCollection.Count; i++)
{
Console.WriteLine("\t" + headerCollection.GetKey(i) + " = " + headerCollection.Get(i));
}
var responseString = "";
using (Stream stream = response.GetResponseStream())
{
StreamReader reader = new StreamReader(stream, Encoding.UTF8);
responseString = reader.ReadToEnd();
}
var SAMLResponse = "";
Match match = Regex.Match(responseString, "<input[^>]*type=\"hidden\"\\s+name=\"SAMLResponse\"[^>]*value=\"([^\"]*)\"");
if (match.Success)
{
SAMLResponse = match.Groups[1].Value;
SAMLResponse = SAMLResponse.Replace("\n", "");
//Console.WriteLine("SAMLResponse: " + SAMLResponse);
}
if (string.IsNullOrWhiteSpace(SAMLResponse))
{
throw new Exception("SAMLResponse is missing or blank");
}
//=================================================================
Console.WriteLine("\nStep 3\n");
var url3 = vsphereUri + "/ui/saml/websso/sso";
request = (HttpWebRequest)WebRequest.Create(url3);
request.Method = "POST";
request.Headers.Add("Authorization: Basic " + VSPHERE_CRED_BASE64);
request.ContentType = "application/x-www-form-urlencoded";
request.KeepAlive = true;
request.AllowAutoRedirect = false;
using (var streamWriter = new StreamWriter(request.GetRequestStream()))
{
streamWriter.Write("SAMLResponse=" + HttpUtility.UrlEncode(SAMLResponse));
streamWriter.Flush();
streamWriter.Close();
}
response = (HttpWebResponse)request.GetResponse();
var cookies = response.Headers["Set-Cookie"];
Console.WriteLine("cookies: " + cookies);
headerCollection = response.Headers;
Console.WriteLine("\nResponse headers\n");
for (int i = 0; i < headerCollection.Count; i++)
{
Console.WriteLine("\t" + headerCollection.GetKey(i) + " = " + headerCollection.Get(i));
}
//=================================================================
Console.WriteLine("\nStep 4\n");
var url4 = vsphereUri + "/ui/search/quicksearch/?opId=:1&query=" + vmName;
request = (HttpWebRequest)WebRequest.Create(url4);
request.Method = "GET";
request.Headers.Add("Cookie: " + cookies);
request.KeepAlive = true;
request.AllowAutoRedirect = false;
response = (HttpWebResponse)request.GetResponse();
if (response.StatusCode != HttpStatusCode.OK)
{
throw new Exception("Expected 200 OK, but got " + response.StatusCode);
}
var jsonResp = "";
using (Stream stream = response.GetResponseStream())
{
StreamReader reader = new StreamReader(stream, Encoding.UTF8);
jsonResp = reader.ReadToEnd();
}
Console.WriteLine(jsonResp);
}
}
}
Unfortunately the vSphere Automation API isn't setup to filter on partial names or even when using a wildcard. Some of the available filters may help you limit the output to be under the 1000 object limit (example: filter on specific clusters and/or folders).
Hopefully this is something that's added in a future release.

Unable to send attachment - Salesforce Docusign API

I am trying to send attachment (record has one attachment) in opportunity record via Apex and Docusign "CreateAndSendEnvelope" API.
But I am getting this error "The DocuSign EnvelopeId:Exception - System.CalloutException: Web service callout failed: WebService returned a SOAP Fault: An Error Occurred during anchor tag processing. Invalid document faultcode=soap:Client faultactor=https://demo.docusign.net/api/3.0/dsapi.asmx"
Below is the piece of code used.
// Render the contract
System.debug('Rendering the contract');
PageReference pageRef = new PageReference('/apex/RenderContract');
pageRef.getParameters().put('id',contract.Id);
//Blob pdfBlob = pageRef.getContent();
Attachment att = [SELECT Id, Name, Body, ContentType FROM Attachment WHERE Parentid = :contract.Id LIMIT 1];
Blob pdfBlob = att.Body;
// Document
DocuSignAPI.Document document = new DocuSignAPI.Document();
document.ID = 1;
document.pdfBytes = EncodingUtil.base64Encode(pdfBlob);
document.Name = 'Contract';
document.FileExtension = 'pdf';
envelope.Documents = new DocuSignAPI.ArrayOfDocument();
envelope.Documents.Document = new DocuSignAPI.Document[1];
envelope.Documents.Document[0] = document;
// Recipient
System.debug('getting the contact');
Contact contact = [SELECT email, FirstName, LastName
from Contact where id = :contract.CustomerSignedId];
DocuSignAPI.Recipient recipient = new DocuSignAPI.Recipient();
recipient.ID = 1;
recipient.Type_x = 'Signer';
recipient.RoutingOrder = 1;
recipient.Email = contact.Email;
recipient.UserName = contact.FirstName + ' ' + contact.LastName;
// This setting seems required or you see the error:
// "The string '' is not a valid Boolean value.
// at System.Xml.XmlConvert.ToBoolean(String s)"
recipient.RequireIDLookup = false;
envelope.Recipients = new DocuSignAPI.ArrayOfRecipient();
envelope.Recipients.Recipient = new DocuSignAPI.Recipient[1];
envelope.Recipients.Recipient[0] = recipient;
// Tab
DocuSignAPI.Tab tab1 = new DocuSignAPI.Tab();
tab1.Type_x = 'SignHere';
tab1.RecipientID = 1;
tab1.DocumentID = 1;
tab1.AnchorTabItem = new DocuSignAPI.AnchorTab();
tab1.AnchorTabItem.AnchorTabString = 'By:';
DocuSignAPI.Tab tab2 = new DocuSignAPI.Tab();
tab2.Type_x = 'DateSigned';
tab2.RecipientID = 1;
tab2.DocumentID = 1;
tab2.AnchorTabItem = new DocuSignAPI.AnchorTab();
tab2.AnchorTabItem.AnchorTabString = 'Date Signed:';
envelope.Tabs = new DocuSignAPI.ArrayOfTab();
envelope.Tabs.Tab = new DocuSignAPI.Tab[2];
envelope.Tabs.Tab[0] = tab1;
envelope.Tabs.Tab[1] = tab2;
System.debug('Calling the API');
try {
DocuSignAPI.EnvelopeStatus es
= dsApiSend.CreateAndSendEnvelope(envelope);
envelopeId = es.EnvelopeID;
} catch ( CalloutException e) {
System.debug('Exception - ' + e );
envelopeId = 'Exception - ' + e;
}
Any ideas how to overcome this error?
Thanks.
The Original Poster's (OP's) comment is
it worked fine on rendering the whole record to pdf...but now i tried sending attachments only instead of whole record.. i started to get this error.
So my guess is that the envelope request has a document problem.
Best way to debug: see what is being sent to the DocuSign platform.
Try the beta API logger or the regular logger. Then add the log to your question by editing your question.
This problem came across me with same error .
" An Error Occurred during anchor tag processing. Invalid document faultcode=soap:Client faultactor=https://demo.docusign.net/api/3.0/dsapi.asmx "
you need to replace anchor tab string with desired string given in your attached document where signature is required.
Replace :
tab1.AnchorTabItem.AnchorTabString = 'By:';
tab2.AnchorTabItem.AnchorTabString = 'Date Signed:';
To :
tab1.AnchorTabItem.AnchorTabString = 'Signature label in your document';
tab2.AnchorTabItem.AnchorTabString = 'Signature label in your document';

Cannot send a content-body with this verb-type. error while getting response when trying to Upload file in Box Storage

When i am trying to upload files in Box Storage using api provided by Box but at response time i am getting this error
public static void UploadFileRequest(string FolderID, string accesstoken)
{
string boundary = string.Format("----------------------------{0}", DateTime.Now.Ticks.ToString("x"));
string filename="C:\\Users\\Administrator\\Desktop\\Text.txt";
HttpWebRequest httpWReq = (HttpWebRequest)WebRequest.Create("https://upload.box.com/api/2.0/files/content");
ASCIIEncoding encoding = new ASCIIEncoding();
string hh = "\"filename=#\"" + filename + "\" "+";"+"";
hh += "parent_id=\"" + FolderID + "\"";
string kj = string.Format(("filename=#" + filename));
byte[] data = encoding.GetBytes(hh);
httpWReq.Headers.Add("Authorization", "Bearer " + accesstoken);
httpWReq.ContentType = "application/json";
httpWReq.ContentLength = data.Length;
using (Stream stream = httpWReq.GetRequestStream())
{
stream.Write(data, 0, data.Length);
}
HttpWebResponse response = (HttpWebResponse)httpWReq.GetResponse();
string responseString = new StreamReader(response.GetResponseStream()).ReadToEnd();
}
Without knowing the Box API, I will assume that the upload should be a POST operation, so you will need to specify the correct HTTP method on your request, before sending it:
httpWReq.Method = "POST";
The Method property defaults to "GET", and GET operations does not normally have a body..
Here is the solution , as C# accepts bytes format and then any Upload is done , i was missing that .. hope it helps
private void UploadBoxFile(string Filename)
{
HttpWebRequest req = HttpWebRequest.Create("https://upload.box.com/api/2.0/files/content") as HttpWebRequest;
req.Method = "POST";
req.Headers.Add("Authorization", "Bearer < Access Token >");
req.ContentType = "multipart/form-data; boundary=\"d174f29b-6def-47db-8519-3da38b21b398\"";
string Content = GetFormatedData(Filename);
req.ContentLength = Content.Length;
using (Stream Writer = req.GetRequestStream())
{
Writer.Write(Encoding.UTF8.GetBytes(Content), 0, Content.Length);
}
req.GetResponse();
}
private string GetFormatedData(string Filename)
{
StringBuilder build = new StringBuilder();
string Id = "d174f29b-6def-47db-8519-3da38b21b398";
build.AppendLine("--" + Id);
build.AppendLine("Content-Disposition: form-data; filename=\"hello1.txt\"; name=\"filename\"");
build.AppendLine("Content-Type: application/octet-stream");
build.AppendLine();
string FileContent = "This is a sample text";
build.AppendLine(FileContent);
build.AppendLine("--" + Id);
build.AppendLine("Content-Disposition: form-data; name=\"folder_id\"");
build.AppendLine();
build.AppendLine("0");
build.AppendLine("--" + Id + "--");
return build.ToString();
}
Thanks..

Post data to web API

I've been trying to send data to a web API VIA post. But it doesn't seem to be sending it.
Here's how I do it.
var baseAddress = "http://192.168.0.103/vchatapi/api/Images?gsmNumber=" + profileNumberLbl.Content + "&content=" + base64 + "&contentType=image/" + contentType;
var http = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(new System.Uri(baseAddress));
http.Accept = "application/json";
http.ContentType = "application/json";
http.Method = "POST";
This code works with get:
var baseAddress = "http://192.168.0.103/vchatapi/api/SendSMSVerificationCode?gsmNumber=" + areCode + mobile + "&udid=123456";
var http = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(new System.Uri(baseAddress));
http.Accept = "application/json";
http.ContentType = "application/json";
http.Method = "GET";
try
{
var response = http.GetResponse();
var stream = response.GetResponseStream();
var sr = new StreamReader(stream);
var content = sr.ReadToEnd();
verificationCode = verificationCode.FromJson(content);
if (!verificationCode.Equals(""))
{
MessageBox.Show(this, "Verification Code: " + verificationCode);
verificationTextBox.IsEnabled = true;
areaCodeCB.IsEnabled = false;
mobileNumberTB.IsEnabled = false;
}
else
{
MessageBox.Show(this, "Invalid Number");
}
}
catch (Exception ex)
{
MessageBox.Show(this, ex.Message);
}
Any ideas? Thanks!
Since you are doing a POST, you would be sending the content in the body of the request. You would need to get hold of the request's stream and write data to it. The following answer post has a very concise example:
https://stackoverflow.com/a/2551006/1184056

Resources