How to use FormData while testing API post request in opentest - opentest

Hi I am getting below error while using FormData in Post Method for opentest
my code:
var data = new FormData(); data.append("name", "test")
and I am getting below error:
at org.getopentest.base.TestActor.evalScript(TestActor.java:1441)
at org.getopentest.base.ScriptAction.run(ScriptAction.java:32)
at org.getopentest.base.TestActor.executeAction(TestActor.java:1527)
at org.getopentest.base.TestActor.executeActionByDef(TestActor.java:1695)
... 4 more
Caused by: javax.script.ScriptException: ReferenceError: "FormData" is not defined in <eval> at line number 1
at
jdk.nashorn.api.scripting.NashornScriptEngine.throwAsScriptException(NashornScriptEngine.java:470)
at jdk.nashorn.api.scripting.NashornScriptEngine.evalImpl(NashornScriptEngine.java:454)
at jdk.nashorn.api.scripting.NashornScriptEngine.evalImpl(NashornScriptEngine.java:406)
at jdk.nashorn.api.scripting.NashornScriptEngine.evalImpl(NashornScriptEngine.java:402)
at jdk.nashorn.api.scripting.NashornScriptEngine.eval(NashornScriptEngine.java:155)
at javax.script.AbstractScriptEngine.eval(AbstractScriptEngine.java:264)
at org.getopentest.base.TestActor.evalScript(TestActor.java:1427)

The FormData object is only available in web browsers and is not part of the OpenTest API. If you are trying to send a request using the HttpRequest keyword, you should be able to build this simply by concatenating the key/value pairs for the form fields and their values this way:
field1=value1&field2=value2&field3=value3
More details here.

Related

Response body is not returning from custom error responses in swagger Swashbuckle

I have integrated swagger to a dot.net core API application using Swashbuckle. When I execute an API via Swagger UI without providing credentials it is returning a "401- Unauthorized" response as expected.
But it is not showing the error response which I have configured to return as a custom error response as the body. It does returns the header as below image.
When I execute the same API via Postman it does return the custom error response as below.
What I need is, I need to see the custom error response body in the swagger UI as well.
In Postman,
In Swagger,
Same scenario with the 403 and 404 status codes.
After struggling a lot I have found the root cause to the issue.It is due to not having configure the Response Content type in the "app.UseStatusCodePages" middle ware.
// Custom status handling
app.UseStatusCodePages(async (StatusCodeContext context) =>
{
var settings = new JsonSerializerSettings();
settings.NullValueHandling = NullValueHandling.Ignore;
settings.Formatting = Formatting.Indented;
int statusCode = context.HttpContext.Response.StatusCode;
***context.HttpContext.Response.ContentType = "application/json";*** // Added this line to solve the issue
await context.HttpContext.Response.WriteAsync(JsonConvert.SerializeObject(
new ErrorResponse((HttpStatusCode)statusCode,
ReasonPhrases.GetReasonPhrase(statusCode)
), settings));
});
Had to add "context.HttpContext.Response.ContentType = "application/json";" to fix the issue.

GoogleDrive file multipart type upload in xamarin

My Xamarin forms application uploads a zip file to google drive using rest apis.But the name is always displaying as "untitled".So I tried using multipart content,but got the parse error with "code": 400,
var jsonstring = "{ \"name\": \"demo.zip\” }";
var multicontent = new MultipartContent();
var strcontent = new StringContent(jsonstring);
var backupContent = “byte array content of my file”;
multicontent.Add(strcontent);
multicontent.Add(backupContent);
HttpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer”, “my token value");
HttpClient.DefaultRequestHeaders.TryAddWithoutValidation("Content-Length", backupContent.ContentLength.ToString());
HttpClient.DefaultRequestHeaders.TryAddWithoutValidation("Content-Type", "multipart/related");
var res = await HttpClient.PostAsync( "https://www.googleapis.com/upload/drive/v2/files?uploadType=multipart", multicontent);
var stringContent = await res.Content.ReadAsStringAsync();
Based on the Google Drive documentation, The error 400: Bad Request that you got is a user error. This error is caused by:
required field or parameter has not been provided
the combination of provided fields is invalid
the value supplied in the parameter is invalid
Another caused of this error is when trying to add a duplicate parent to a Drive item. It can also be thrown when trying to add a parent that would create a cycle in the directory graph.
For more information, check this link to know the different upload options that you can do in Google Drive API. You can also check this ZIP Extractor if it can help you.

Receiving null parameters from request in JSP file when are being sent

I've a JSP app. It uploads a file, but to do so the user has to authenticate using a name and a password. So my JSP file starts with:
//0.2.- We get the password
String password = (String) request.getParameter("pass"); // -> This returns NULL
//0.3.- We get the "uvus"
String uvus = (String) request.getParameter("uvus"); //-> This also returns NULL
//More code
So I'm trying to know why am I getting null from those variables.
I went to the form I was uploading, and look for the data that was being sent. Using Firefox Debug Tools, I saw:
So in fact, it was being sent.
As additional info, I'm building the request like this:
var pUvus = document.getElementById("uvus").value;
var pPassword = document.getElementById("pass").value;
var file = document.getElementById("userFile");
var formData = new FormData();
formData.append("upload", file.files[0]);
formData.append("uvus", pUvus);
formData.append("pass", pPassword);
xmlhttp.open("POST","uploadFile.jsp",true);
xmlhttp.send(formData);
At last, I would like to say that I can get vars from application object in the same JSP with no errors, and have received in another pair of JSP files vars at request object without more problems, so I think my fault should be in the way I'm building the request in Ajax, but I've no more clue about that...
Anyone can guide me?
Thanks for your help
Update: #rickz asked for how do I get the file and parse the request (what is done after my problem, trying to get the objects from the request scope):
List items;
items = servlet_up.parseRequest(request);
for(int i=0;i<items.size();i++)
{
FileItem item = (FileItem) items.get(i);
if (! item.isFormField())
{
request.getParameter() won't work for a multipart/form-data request.
If you are using org.apache.commons.fileupload then you should be using something like
if(item.isFormField()){
name = item.getFieldName();
...
}

playframework ajax post - extracting post params to DynamicForm

I'm trying to extract post params sent ajaxly ($.ajax(...)) with DynamicForm:
new DynamicForm().bindFromRequest()
And I get this error:
Caused by: java.lang.RuntimeException: There is no HTTP Context available from here.
at play.mvc.Http$Context.current(Http.java:27) ~[play_2.9.1.jar:2.0.4]
at play.mvc.Controller.request(Controller.java:28) ~[play_2.9.1.jar:2.0.4]
at play.data.Form.requestData(Form.java:87) ~[play_2.9.1.jar:2.0.4]
at play.data.DynamicForm.bindFromRequest(DynamicForm.java:46) ~[play_2.9.1.jar:2.0.4]
at controllers.Login$$anonfun$login$1.apply(Login.scala:19) ~[classes/:2.0.4]
at controllers.Login$$anonfun$login$1.apply(Login.scala:18) ~[classes/:2.0.4]
If I try to bind the params with a mapped normal form it works:
val form = Form(
tuple(
"identity" -> nonEmptyText,
"password" -> nonEmptyText,
"loginType" -> nonEmptyText
)
)
form.bindFromRequest
this is good for my login ajax post. But for other ajax posts I have I still would like to use DynamicForm and work with Map[String,String]. any idea what's the problem?
My dev team and I had the same problem. In our case we used Java, the java.util collections package and the following line of code to bind request parameters to a Map.
final Map<String, String[]> myForm = request().body().asFormUrlEncoded();
I don't know Scala, but I think there's a way to use the Java collections in Scala.

Programatically fetch a list of all Salesforce Objects using apex in Salesforce

I want to fetch a list of all Salesforce objects.
I found this link
http://wiki.developerforce.com/index.php/Enterprise_Describe_Global
but there are some issues:
1) Missing session(Invalid session id)
To prevent this i appended the session key in the url also for the post request but it shows no request.
Error : Internal Server Error (500)
2) I found somewhere and added clientId along with the session header but again no response.
Error : Internal Server Error (500)
code sample of web request:
HttpRequest req = new HttpRequest();
Http http = new Http();
req.setMethod('POST');
req.setHeader('content-type','text/xml;charset=utf-8');
req.setHeader('Content-Length','1024');
req.setHeader('Host','na1.salesforce.com ');
req.setHeader('Connection','keep-alive');
req.setHeader('soapAction', 'getObjects');
String url = 'https://na1.salesforce.com/services/Soap/c/10.0/session_key';
String str = '<?xml version="1.0" encoding="utf-8"?> '+
'<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:urn=\"urn:enterprise.soap.sforce.com\">'+
'<soapenv:Header>'+
'<urn:SessionHeader>'+
'<urn:sessionId>'+'session_ID'+'</urn:sessionId>'+
'</urn:SessionHeader>'+
'<urn:CallOptions><urn:client>CLIENT_ID</urn:client></urn:CallOptions>'+
'</soapenv:Header>'+
'<soapenv:Body>'+
'<describeGlobal></describeGlobal>'+
'</soapenv:Body>'+
'</soapenv:Envelope>';
req.setEndpoint(url);
req.setBody(str);
HTTPResponse resp = http.send(req);
system.debug('response:::'+xml_resp);
Session_ID : I got this value from UserInfo.getSessionID();
client_ID : I tried following values : UserInfo.getUserID();/Secret token
but i couldnt make it a perfect call to get reaponse.
Hope somebody can help...
Why are you using an outbound web service call in Apex? Apex has native access to global describe information using Schema.getGlobalDescribe() - which is a much better way to access describe results.
http://www.salesforce.com/us/developer/docs/apexcode/Content/apex_methods_system_schema.htm has the full documentation for calling this from Apex.

Resources