Does ColdFusion 11 support body content for HTTP DELETE verb - rest

The below script block on ColdFUsion 11 has GetHttpRequestData().content as hello
If I change the verb to DELETE it is empty.
So ...
Does ColdFusion not support this when making requests via cfhttp?
Is this the wrong way?
Is there a workaround?
Code:
cfhttp(method="POST", charset="utf-8", url="http://x/showrequest.cfm", result="result" ) {
cfhttpparam(name="body", type="body", value="hello");
}
writeOutput(result.filecontent);abort;

Work around was to use java (shiver). Im sure there are helper libs to do this more succinctly but here it is.
<cfscript>
var u = createObject("java", "java.net.URL").init("https://api.cloudflare.com/client/v4/zones/#site.zoneId#/purge_cache");
var req = u.openConnection();
req.setRequestMethod("DELETE");
req.setDoOutput(true);
req.setRequestProperty("Content-Type", "application/json" );
req.setRequestProperty("X-Auth-Email", "xxxxx" );
req.setRequestProperty("X-Auth-Key", "xxxx" );
var os = req.getOutputStream();
os.write(javaCast("string",'{"files":#serializeJSON(urls)#}').getBytes("UTF-8"));
os.close();
ret = req.getResponseMessage();
var i = req.getInputStream();
var br = createObject("java", "java.io.BufferedReader").init(createObject("java", "java.io.InputStreamReader").init(i));
var sb = createObject("java", "java.lang.StringBuilder").init();
var line = br.readLine();
while(!isNull(line)){
sb.append(line);
line = br.readLine();
}
req.disconnect();
</cfscript>
<cfdump var="req.getResponseCode() = #req.getResponseCode()#">
<cfdump var="#ret#">
<cfdump var="#sb.toString()#">

Related

Getting Invalid Response from API . - Groovy Scripting

I am trying a POST method in groovy which basically creates a Issue in Jira . I am getting invalid response from the API . However in postman I could able to get the response . I have searched few questions in stackoverflow where they are recommending to set the Accept-Encoding to "" . I tried out different methods but it didnt work .
Code :
import javax.net.ssl.*;
import java.security.cert.*;
import groovy.json.JsonBuilder;
import groovy.json.JsonOutput;
import groovy.json.JsonSlurperClassic;
import groovy.json.StreamingJsonBuilder;
def jiraurl = "xxxxx";
def netProxyAddr = "xxxx";
def netProxyPort = 80;
try {
// NOTE: Adjust the following as needed
def uri = jiraurl + "/issue";
def jiraTicketMap = [:];
jiraTicketMap["fields"] = [:];
jiraTicketMap["fields"]["project"]= [:];
jiraTicketMap["fields"]["project"]["id"] = "12412"
jiraTicketMap["fields"]["summary"] = "Test ticket for API";
jiraTicketMap["fields"]["assignee"] = [:];
jiraTicketMap["fields"]["assignee"]["name"] = "*********";
jiraTicketMap["fields"]["customfield_10700"] = [:];
jiraTicketMap["fields"]["customfield_10700"]["value"] = "Normal";
jiraTicketMap["fields"]["customfield_16901"] = "nothing impacted";
jiraTicketMap["fields"]["customfield_16900"] = "testing ";
jiraTicketMap["fields"]["customfield_10710"] = "removing the URL" ;
jiraTicketMap["fields"]["customfield_10711"] = "********";
jiraTicketMap["fields"]["customfield_16902"] = "descriptiong";
jiraTicketMap["fields"]["customfield_10702"] = [:];
jiraTicketMap["fields"]["customfield_10702"]["value"] ="Low";
jiraTicketMap["fields"]["customfield_10900"] = [:];
jiraTicketMap["fields"]["customfield_10900"]["value"] = "Yes";
jiraTicketMap["fields"]["customfield_10703"] = [:];
jiraTicketMap["fields"]["customfield_10703"]["value"] = "Low";
jiraTicketMap["fields"]["customfield_10705"] = "2022-03-19T10:29:29.908+1100";
jiraTicketMap["fields"]["customfield_10706"] = "2022-03-20T10:29:29.908+1100";
jiraTicketMap["fields"]["customfield_10707"] = "testing done";
jiraTicketMap["fields"]["customfield_10708"] = "Implemtation test done for zscaler";
jiraTicketMap["fields"]["customfield_10709"] = "post implention done";
jiraTicketMap["fields"]["issuetype"] = [:];
jiraTicketMap["fields"]["issuetype"]["id"]= "10200";
jiraTicketMap["fields"]["labels"] = ["test"];
jiraTicketMap["fields"]["customfield_21400"] = "Test Environment is required.";
jiraTicketMap["fields"]["customfield_21500"] = "Back-Out Test Details is required";
DEBUG.println("DEBUG: jiraTicketMap is: ${jiraTicketMap}");
def payloadData = StringUtils.mapToJson(jiraTicketMap);
DEBUG.println("DEBUG: Payload is: ${payloadData}");
DEBUG.println("DEBUG: PayloadData is: ${payloadData}");
DEBUG.println("DEBUG: PayloadData type is:"+payloadData.getClass());
netProxyPort = netProxyPort.toInteger();
Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(netProxyAddr, netProxyPort));
def authString = "*********".getBytes().encodeBase64().toString()
def url = new URL(uri);
// NOTE: The following removes all checks against SSL certificates
disableSSL();
def conn = url.openConnection(proxy);
conn.doOutput = true;
// Build the Credentials and HTTP headers
conn.setRequestProperty("Authorization", "Basic ***********");
conn.setRequestProperty("Content-type", "application/JSON;charset=UTF-8");
conn.setRequestProperty("Accept","*/*");
conn.setRequestMethod("POST");
conn.setDoOutput(true);
//BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(conn.getOutputStream(), "UTF8"));
OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream(),"UTF-8")
writer?.write(payloadData);
writer?.flush();
writer?.close();
if(conn.getResponseCode() == 201 || conn.getResponseCode() == 200 ) {
InputStream responseStream = conn.getInputStream();
result = responseStream.getText("UTF-8");
DEBUG.println("DEBUG:>>>>>>>>>>>>> SUccessfully Posted Data to Jira");
// NOTE: If you need to get the response header, use below
//INPUTS.HEADERS = conn.getHeaderFields();
responseStream.close();
}
else {
INPUTS.RSEXCEPTION = "Response code was " + conn.getResponseCode();
// Attempt to parse error stream.
InputStream responseStream = conn.getErrorStream();
result = responseStream?.getText("UTF-8");
responseStream?.close();
}
}
catch (Exception e) {
//INPUTS.RSEXCEPTION = e.getMessage();
result = e.getMessage();
result += "\n" + e.getClass() + ": " + e.getMessage();
for (trace in e.getStackTrace())
{
result += "\n\t" + trace;
}
}
return result;
Response :
Response from Postman and local code editor
{
"id": "12212",
"key": "WCM-2211",
"self": "https://********/rest/api/2/issue/2496228"
}
Response from Vendor Tool:
�4̱#0��w��^BV��\z(M��J"��u1���?`4tPȶ.���S���7��0�%���q7A M�X����xv…qD�h�O��~��NCe
Response Headers
[X-AREQUESTID:[533x1208409x1], null:[HTTP/1.1 201 Created], Server:[Web Server], X-Content-Type-Options:[nosniff], Connection:[close], X-ANODEID:[node1], Date:[Thu, 12 May 2022 07:53:25 GMT], X-Frame-Options:[SAMEORIGIN], Referrer-Policy:[no-referrer-when-downgrade], Strict-Transport-Security:[max-age=15768000], Cache-Control:[no-cache, no-store, no-transform], Content-Security-Policy:[frame-ancestors 'self'], X-AUSERNAME:[SVC], Content-Encoding:[gzip], X-ASESSIONID:[1l2vszx], Set-Cookie:[akaalb_jira_dev_alb=~op=jira_dev_lb:jira-dev-ld6|~rv=95~m=jia-dev-ld6:0|~os=287df636055edb4e278283~id=de0d2567c76bf80374af7c583f; path=/; HttpOnly; Secure; SameSite=None, JESSIONID=2920944044.37151.0000; path=/; Httponly; Secure, atlassian.xsrf.token=BZXB-Z179-LJQD-6WAV_9b298f0387a7c68a8652e963b69e4_lin; Path=/; Secure, JSESSIONID=27C93900AA8B780AA44C2861F73; Path=/; Secure; HttpOnly], Feature-Policy:[midi 'none'], Vary:[Accept-Encoding, User-Agent], X-XSS-Protection:[1; mode=block], X-Seraph-LoginReason:[OK], X-Powered-By:[Web Server], Content-Type:[application/json;charset=UTF-8]]
Solution from #dagget :
// use the below code when reading it from input stream
accept-encoding : identity
responseStream = new java.util.zip.GZIPInputStream(responseStream)

Alfresco REST API:Data Size Limit?

I am developing REST based webservices in alfresco for data transfer & want to know what is the maximum amount of data i can send/get thru REST protocol?
Any reference would be very helpful.
Regards.
The max amount of data is as large as 2147000000. That's why if your data is large enough it is advisable to stream it to post to your REST service. Here's an example.
Sender/ Uploader Application or Client
var sb = new StringBuilder();
sb.Append("Just test data. You can send large one also");
var postData = sb.ToString();
var url = "REST Post method example http://localhost:2520/DataServices/TestPost";
var memoryStream = new MemoryStream();
var dataContractSerializer = new DataContractSerializer(typeof(string));
dataContractSerializer.WriteObject(memoryStream, postData);
var xmlData = Encoding.UTF8.GetString(memoryStream.ToArray(), 0, (int)memoryStream.Length);
var client = new WebClient();
client.UploadStringAsync(new Uri(url), "POST", "");
client.Headers["Content-Type"] = "text/xml";
client.UploadStringCompleted += (s, ea) =>
{
if (ea.Error != null) Console.WriteLine("An error has occured while processing your request");
var doc = XDocument.Parse(ea.Result);
if (doc.Root != null) Console.WriteLine(doc.Root.Value);
if (doc.Root != null && doc.Root.Value.Contains("1"))
{
string test = "test";
}
};
REST Service method
[WebInvoke(UriTemplate = "TestPost", Method = "POST", BodyStyle = WebMessageBodyStyle.WrappedRequest, RequestFormat = WebMessageFormat.Xml)]
public string Publish(string market,string sportId, Stream streamdata)
{
var reader = new StreamReader(streamdata);
var res = reader.ReadToEnd();
reader.Close();
reader.Dispose();
}
Don't forget to put the following configuration settings on your REST Service config file if you don't have this it will throw you an error
<system.web>
<compilation debug="true" targetFramework="4.0" />
<httpRuntime maxRequestLength="2147000000" maxQueryStringLength="2097151" maxUrlLength="2097151"/>
</system.web>
<system.webServer>
........
</system.webServer>
<system.serviceModel>
<serviceHostingEnvironment aspNetCompatibilityEnabled="true" />
<standardEndpoints>
<webHttpEndpoint>
<standardEndpoint name="" helpEnabled="true" automaticFormatSelectionEnabled="true" maxReceivedMessageSize="2147000000" maxBufferPoolSize="2147000000" maxBufferSize="2147000000"/>
</webHttpEndpoint>
</standardEndpoints>
</system.serviceModel>

force.com callout exception Unable to tunnel through proxy

We make a callout from one Salesforce org to another Salesforce org using the REST API. That worked until end of november. We didn't make any changes at the affected classes or configuration.
Now, while sending a request to the rest api a callout exception will be thrown with the message : "Unable to tunnel through proxy. Proxy returns "HTTP/1.0 503 Service Unavailable".
The authorisation to the rest api is done by session id.
Does anyone have any idea what the problem is?
Here the code snipped:
final String WS_ENDPOINT = 'https://login.salesforce.com/services/Soap/c/24.0';
final String REST_ENDPOINT = 'https://eu2.salesforce.com/services/apexrest/UsageReporterService';
final String USERNAME = '*****';
final String PASSWORD = '*****';
HTTP h = new HTTP();
HTTPRequest req = new HTTPRequest();
req.setMethod('POST');
req.setEndpoint(REST_ENDPOINT);
req.setHeader('Content-Type', 'application/json');
req.setTimeout(60000);
HTTP hLogin = new HTTP();
HTTPRequest reqLogin = new HTTPRequest();
reqLogin.setMethod('POST');
reqLogin.setEndpoint(WS_ENDPOINT);
reqLogin.setHeader('Content-Type', 'text/xml');
reqLogin.setHeader('SOAPAction', 'login');
reqLogin.setTimeout(60000);
reqLogin.setCompressed(false);
// get a valid session id
String sessionId;
String loginSoap = '<?xml version="1.0" encoding="UTF-8"?>';
loginSoap += '<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:urn="urn:enterprise.soap.sforce.com">';
loginSoap += '<soapenv:Body>';
loginSoap += '<urn:login>';
loginSoap += '<urn:username>' + USERNAME + '</urn:username>';
loginSoap += '<urn:password>' + PASSWORD + '</urn:password>';
loginSoap += '</urn:login>';
loginSoap += '</soapenv:Body>';
loginSoap += '</soapenv:Envelope>';
reqLogin.setBody(loginSoap);
HTTPResponse respLogin;
try {
respLogin = hLogin.send(reqLogin);
} catch(CalloutException c){
return null;
}
System.debug('++++++'+respLogin.getStatus() + ': ' + respLogin.getBody());
Dom.Document doc = new Dom.Document();
doc.load(respLogin.getBody());
Dom.XMLNode root = doc.getRootElement();
String ns = root.getNamespace();
Dom.XMLNode bodyEl = root.getChildElements()[0];
if(bodyEl.getChildElements()[0].getName().equals('loginResponse')){
sessionId = bodyEl.getChildElements()[0].getChildElement('result', ns).getChildElement('sessionId', ns).getText();
}
// finished getting session Id
if(sessionId != null){ // login was successfull
req.setHeader('Authorization', 'Bearer ' + sessionId);
// serialize data into json string
UsageReporterModel usageReporterData = new UsageReporterModel();
String inputStr = usageReporterData.serialize();
req.setBody('{ "usageReportData" : ' + inputStr + '}');
// fire!
HTTPResponse resp;
try {
resp = h.send(req);
} catch(CalloutException c){
return null;
}
}
I suspect this will relate to a change of IP addresses for one of the org's which haven't been whitelisted correctly (or added to the "network access" object). With it being Salesforce to Salesforce I would hope that Salesforce.com support can assist?

Crystal Reports asks password in Client systems

This is the Login Info Method
private void SetLogonInfo()
{
try
{
LogInfo.ConnectionInfo.ServerName = "ServerName";
LogInfo.ConnectionInfo.UserID = "UserID";
LogInfo.ConnectionInfo.Password = "Password";
LogInfo.ConnectionInfo.DatabaseName = "DataBase";
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
To create report I used this code
crystalReportViewer1.ReportSource = null;
rptdoc = new ReportDocument();
rptdoc.Load("REPORTS\\TC.rpt");
crystalReportViewer1.SelectionFormula =selectionFormula;
crystalReportViewer1.ReportSource = rptdoc;
rptdoc.Database.Tables[0].ApplyLogOnInfo(LogInfo);
It works well in server system, but if I use this in client systems, it asks for username and password. I'm using Crystal Reports 10. Moreover sometimes it asks for Username password in server system also. How to resolve this?
You're doing things in the wrong order. You need to do the login programmatically BEFORE you load the report on the viewer.
Additionally, I cannot stress enough that you need to test your program on the server machine and a test client machine before you release it to users.
The reason for this error is wrong username, password.
Check username, password and use the code below:
ReportDocument cryRpt = new ReportDocument();
TableLogOnInfos crtableLogoninfos = new TableLogOnInfos();
TableLogOnInfo crtableLogoninfo = new TableLogOnInfo();
ConnectionInfo crConnectionInfo = new ConnectionInfo();
Tables CrTables;
//This is for Access Database
crConnectionInfo.ServerName = "" + "" +Application.StartupPath + "\\Database.mdb"; //access Db Path
crConnectionInfo.DatabaseName = "" + "" + Application.StartupPath + "\\Database.mdb";//access Db Path
crConnectionInfo.UserID = "ADMIN";
crConnectionInfo.Password = Program.DBPassword; //access password
//This is for Sql Server
crConnectionInfo.UserID = Program.Severuser; //username
crConnectionInfo.Password = Program.Password;//password
crConnectionInfo.ServerName = Program.server;//servername
crConnectionInfo.DatabaseName = Program.database;//database
string path = "" + Application.StartupPath + "\\supportingfiles\\Invoice.rpt";
cryRpt.Load(path);
CrTables = cryRpt.Database.Tables;
foreach (CrystalDecisions.CrystalReports.Engine.Table CrTable in CrTables)
{
crtableLogoninfo = CrTable.LogOnInfo;
crtableLogoninfo.ConnectionInfo = crConnectionInfo;
CrTable.ApplyLogOnInfo(crtableLogoninfo);
}
cryRpt.SetParameterValue("invoiceno", Program.billno);
crystalReportViewer1.ReportSource = cryRpt;
crystalReportViewer1.Refresh();

coldfusion struct in function argument

I'm trying to do server side facebook connect, but the sdk (get it here) provided gives the following error:
Invalid CFML construct found on line 523 at column 78.
ColdFusion was looking at the following text:
{
And it doesn't explain why it's throwing this error. I'm not good at cfscript, so I don't know whether the sdk uses the correct syntax, but it throws the error on this function, at the braces of the struct in the function arguments:
private String function getUrl(String path = "", Struct parameters = {})
{
var key = "";
var resultUrl = "https://www.facebook.com/" & arguments.path;
if (structCount(arguments.parameters)) {
resultUrl = resultUrl & "?" & serializeQueryString(arguments.parameters);
}
return resultUrl;
}
I had thought that using an sdk would be a no brainer, but apparently I'm missing something.
What am I doing wrong?
Part 2:
The code now comes to a halt at:
for (var propertyName in arguments.properties) {
httpService.addParam(type="formField", name=propertyName, value=arguments.properties[propertyName]);
}
Are you not allowed to use a for loop in cfscript?
Try structNew() or "#structNew()#" instead of {}
This should work for connecting to Facebook and getting an access token:
<cfset appID = ""/>
<cfset secret_key = ""/>
<cfset app_url = ""/>
<cfparam name="URL.Code" default="0">
<cfparam name="URL.state" default="0">
<cfparam name="SESSION.Redirect" default="0">
<cfset code_ = URL.Code>
<cfif code_ EQ "" OR code_ EQ 0>
<cfset SESSION.State = Hash(CreateUUID(),"MD5")>
<cfset dialog_url = "http://www.facebook.com/dialog/oauth?client_id=" & appID & "&redirect_uri=" & app_url & "&scope=email,user_photos,publish_stream" & "&state=" & SESSION.State>
<cflocation url="#dialog_url#" addtoken="no">
</cfif>
<cfif SESSION.State EQ URL.State>
<cfset token_url = "https://graph.facebook.com/oauth/access_token?client_id=" & appID & "&redirect_uri=" & app_url & "&client_secret=" & secret_key & "&code=" & code_>
<cfhttp url="#token_url#" result="AccessToken" method="GET">
<cfelse>
<p>The state does not match. You may be a victim of CSRF.</p>
</cfif>