Calling Worklight adapter from external app - ibm-mobilefirst

I have deployed the adapter on Worklight server and there is some requirement where I am calling worklight adapter from outside as a rest serverice , it is working fine and returning data as required but instead of giving json output it is giving HTML
<!DOCTYPE html><html><head><meta charset="UTF-8" /><title>Invoke Procedure Result</title><script src="/secure/console/js/jquery-1.6.min.js"></script><style> textarea { width: 100%; } .textwrapper { margin: 5px 0; padding: 3px; }</style></head><body onload="attachEvent();"><div><span id="invRes">Invocation Result of procedure: 'Authentication' from the Worklight Server</span>: </div><div id="target"><textarea rows="20">{
"RESPONSE": {
"USER_ID": "292265"
},
"errors": [
],
"info": [
],
"isSuccessful": true,
"responseHeaders": {
"Content-Length": "1195",
"Content-Type": "text\/xml;charset=ISO-8859-1",
"Date": "Thu, 21 Nov 2013 10:10:13 GMT",
"Server": "Oracle GlassFish Server 3.1.2.2",
"X-Powered-By": "Servlet\/3.0 JSP\/2.2 (Oracle GlassFish Server 3.1.2.2 Java\/Oracle Corporation\/1.7)"
},
"responseTime": 4234,
"statusCode": 200,
"statusReason": "OK",
"totalTime": 4235,
"warnings": [
]
}</textarea></div><script>function attachEvent() {$('#target').ajaxError(function(e, xhr, ajaxOptions, thrownError){$(this).text("Error: Please ensure that the XML input and XSL transformation are valid and try again.");});}function run_xslt() {var xml = $('#originalXML').val();var xsl = $('#originalXSL').val();$.post('/secure/dev/xslt',{'xml':xml,'xsl':xsl},function(data, textStatus, XMLHttpRequest){$('#target').empty();json = $("<textarea></textarea>");json.attr("rows",25);json.text(data);$('#target').append(json);$('#invRes').text('Result of Local XSL Transformation');},'text');}</script></body></html>
in code I am again parsing it from HTML and storing json into string. Then only i can use it. This is the url given below for calling adapter externally as per worklight docs.
http://WorklightServer.com/secure/dev/invoke?adapter=Reports&procedure=Authentication&parameters=%5B%5D

remove /dev/ component from the URL, it is for development ease purposes only. without it you'll get your JSON.

I had the same issue and after reading Anton's answers I set the "dataType" of the Ajax call to "text" and then edit the response to remove the /*-secure- and */ and then parsed the string to get the JSON "JSON.parse(theString)"
$.ajax({
type: 'POST',
url: ajaxURL,
async: true,
cache: true,
timeout: 5,
dataType: "text",
success: function(data){
data = data.replace("/*-secure-","");
data = data.replace("*/","");
var dataJSON = JSON.parse(data);
//Do success
},
error: function(data, statusCode){
//Do error
}
});

Related

Trying to run Automation Anywhere import API through Power Automate Cloud Flow

Have anyone tried to run Automation Anywhere A360 import API with HTTP Post action with Power Automate Flow?
The flow runs smoothly and I'm receiving the requestId in response. However, the whole action fails at the Automation Anywhere Control Room side with no imported bot at the end. I'm receiving the following error: net.lingala.zip4j.exception.ZipException: Zip headers not found. Probably not a zip file?
Power Automate HTTP Post - Body
I added below code to the Http Post Body:
{
"$content-type": "multipart/form-data",
"$multipart": [
{
"headers": {
"Content-Type": "application/x-zip-compressed",
"Content-Disposition": "form-data; name=\"upload\"; filename=\"#{variables('fullPath')}\""
},
"body": "#{variables('contentString')}"
},
{
"headers": {
"Content-Disposition": "form-data; name=\"actionIfExisting\""
},
"body": "OVERWRITE"
},
{
"headers": {
"Content-Disposition": "form-data; name=\"publicWorkspace\""
},
"body": "true"
},
{
"headers": {
"Content-Disposition": "form-data; name=\"upload\""
},
"body": "#{variables('fullPath')}"
}
]
}
The contentString variable is: #{body('Get_file_content_using_path')?['$content']}
What am I doing wrong?

React native sending image to server using formdata

I have a problem sending a picture to a server, that's like the default approach, but it does not seem to work.
var source = '/Users/alexx/Library/Developer/CoreSimulator/Devices/44F0FA92-4898-4CFB-862E-4E5EC4C8AB28/data/Containers/Bundle/Application/34BCE695-4B4F-472F-AB5C-F2336AC45273/DoorLock.app/123.jpg';
const form = new FormData();
form.append('image', {
uri: source,
type: 'image/jpg',
name: '123.jpg',
});
const data = () => {
fetch(api ,{
method: 'POST',
body: form,
})
that's the response i get from the server:
{
"_bodyBlob": {
"_data": {
"__collector": [
Object
],
"blobId": "78B18938-15BF-4F18-B3C8-1EB30A24D9F8",
"name": "test.html",
"offset": 0,
"size": 192,
"type": "text/html"
}
},
"_bodyInit": {
"_data": {
"__collector": [
Object
],
"blobId": "78B18938-15BF-4F18-B3C8-1EB30A24D9F8",
"name": "test.html",
"offset": 0,
"size": 192,
"type": "text/html"
}
},
"bodyUsed": false,
"headers": {
"map": {
"connection": "keep-alive",
"content-length": "192",
"content-type": "text/html",
"date": "Mon, 02 Nov 2020 22:57:21 GMT",
"server": "PythonAnywhere"
}
},
"ok": false,
"status": 400,
"statusText": undefined,
"type": "default",
"url": api
}
Although this python code works perfectly and gets a correct response
img = {'file':('123.png', open('the path to the pic/123.png', 'rb'), 'image/png)}
post(api, files = img)
is there any way to get this working or its the server side problem that can't receive the correct arguments?
Adding "file://" to the beginning of the source string fixed the problem.
so the src looks like
var source = 'file:///Users/alexx/Library/Developer/CoreSimulator/Devices/44F0FA92-4898-4CFB-862E-4E5EC4C8AB28/data/Containers/Bundle/Application/34BCE695-4B4F-472F-AB5C-F2336AC45273/DoorLock.app/123.jpg';
then it fetches perfectly, hope it helps anybody who tries to send a local image using formdata, the summary looks like this now
const form = new FormData();
form.append('file', {
uri: source,
name: '123.jpg',
fileName: 'file', //optional
});
fetch(uri,{
method: 'post',
body: form,
})
.then(response => {
console.log("image uploaded")
console.log(response)
})
.catch(console.log);
In Formdata when you pass files, you need to pass 3 parameters where
key expected from the backend (in your case image).
It will be an object which has three properties named name, type, and uri where type is the mime type (ex: image/jpeg).
name of the file
Eg:
data.append("FilePath",{
name:"image.png",
type:"image/png",
uri:"content://com.camera/image.png"
},image.png)

How to create a webhook on a repository on the GitHub web api using AJAX?

I am experimenting with Webhooks in the GitHub api. I got one working by doing it manually as in going into my repository and clicking into the setting and enabling a web hook. But now I want to do this in AJAX and I am getting problems. Anytime I try to send a POST to the web api it fails with a 400 (Bad Request). I am not sure where I am going wrong with my code.
function createWebHooksOnRepos(token){
const webhookURL = "https://api.github.com/repos/DanoBuck/AlgorithmsAndDataStructures/hooks";
const json = {
"name": "WebHook",
"active": true,
"events": [
"issue_comment",
"issues"
],
"config": {
"url": "http://39a40427.ngrok.io/api/webhooks/incoming/github",
"content_type": "json"
}
};
$.ajax({
headers: {
"Authorization": "Token " + token
},
url: webhookURL,
data: json,
type: "POST",
dataType: "json",
success: function(data){
console.log(data);
}
});
}
Thank you
From github Webhook API doc :
name - string - Required. Use "web" for a webhook or use the name of a valid
service. (See /hooks for the list of valid service names.)
So in your case, just rename Webhook to web :
const json = {
"name": "web",
"active": true,
"events": [
"issue_comment",
"issues"
],
"config": {
"url": "http://39a40427.ngrok.io/api/webhooks/incoming/github",
"content_type": "json"
}
};
Also JSON.stringify your data before sending :
$.ajax({
headers: {
"Authorization": "Token " + token
},
url: webhookURL,
data: JSON.stringify(json),
type: "POST",
dataType: "json",
success: function(data) {
console.log(data);
}
});

How to use dojox/data/JsonRestStore with dojox/grid/LazyTreeGrid?

I have now this code:
define([
"dojo/_base/declare",
"dojox/data/JsonRestStore",
"dojox/grid/LazyTreeGrid",
"dojox/grid/LazyTreeGridStoreModel"
], function(
declare,
JsonRestStore,
LazyTreeGrid,
LazyTreeGridStoreModel
) {
var layout = { ... },
store = new JsonRestStore({
target: "/api/items" // for example
limitParam: "limit",
offsetParam: "offset"
}),
model = new LazyTreeGridStoreModel({
serverStore: true,
store: store,
childrenAttrs: [ "children" ]
});
return declare("CustomTreeGrid", [ LazyTreeGrid ], {
treeModel: model,
structure: layout
});
});
My widget send thousand requests to target URL after startup and freeze my browser. How to fix wrong behavior and save compatibility with RESTful API?
Solution with QueryReadStore work, but not in my situation - Django REST Framework return page with API declaration on GET requests.
Server return data in JSON format:
{
"items": [ ] //Array of items
"identifier": "id",
"numRows": 12 // Total count of items
}
Also I change the server response for returning array. Response headers also contain key "Content-Range: 0-2/3" (for example) and it's not work for me.
Server response headers:
HTTP 200 OK
Allow: GET, POST, HEAD, OPTIONS
Content-Range: items 0-1/2
Content-Type: application/json
Vary: accept
Server response body:
[
{
"id": 1,
"children": false,
"name": "name1"
},
{
"id": 2,
"children": false,
"name": "name2"
}
]
It is pretty hard to make a jsfiddle out of it because you need the server part as well.
I found this implementation: https://github.com/jeremyg484/dojo-json-rest-store
It uses a combination of : dojo.store.Cache, dojo.store.JsonRest, dojo.store.Memory and dojo.data.ObjectStore
Maybe you can do something with it...
See how it is used :
myStore = dojo.store.Cache(dojo.store.JsonRest({target:"usstates/"}), dojo.store.Memory());
grid = new dojox.grid.DataGrid({store: dataStore = dojo.data.ObjectStore({objectStore: myStore})

Invoking http adapter procedure failure

I'm trying to send some values to a web server and it is going to respond with true or false using http adapter in ibm mobilefirst. When i invoke the procedure from the environment, i got this error:
{
"errors": [
"Runtime: Http request failed: java.net.UnknownHostException: mfpreader.comze.com\/"
],
"info": [
],
"isSuccessful": false,
"warnings": [
]
}
Here is the link i'm using:
http://mfpreader.comze.com/login.php?username=kevin&password=pass
The server is working.
LoginAdapter.xml
<connectivity>
<connectionPolicy xsi:type="http:HTTPConnectionPolicyType">
<protocol>https</protocol>
<domain>mfpreader.comze.com/</domain>
<port>443</port>
<procedure name="getVerify"/>
LoginAdapter-impl.js
function getVerify(pName) {
var input = {
method : 'get',
returnedContentType : 'json',
path : '/login.php',
parameters : {
'username' : pName,
'password' : 'pass' // hard-coded
}
};
return WL.Server.invokeHttp(input);
}
Can i have some help please. Thanks.
I think your issue is that you have a surplus / in your domain name:
<domain>mfpreader.comze.com/</domain>
This is a domain name, not a URL. You need to specify only the hostname of the server you are trying to reach:
<domain>mfpreader.comze.com</domain>
connect website using http port 80 .on the other hand return returnedContentType : 'plain' .
LoginAdapter.xml
<connectivity>
<connectionPolicy xsi:type="http:HTTPConnectionPolicyType">
<protocol>http</protocol>
<domain>mfpreader.comze.com</domain>
<port>80</port>
<procedure name="getVerify"/>
LoginAdapter-impl.js
function getVerify(pName) {
var input = {
method : 'get',
returnedContentType : 'plain',
path : '/login.php',
parameters : {
'username' : pName,
'password' : 'pass' // hard-coded
}
};
return WL.Server.invokeHttp(input);
}
invocation result:
{
"errors": [
],
"info": [
],
"isSuccessful": true,
"responseHeaders": {
"Connection": "close",
"Content-Length": "748",
"Content-Type": "text\/html",
"Date": "Fri, 19 Feb 2016 11:56:31 GMT",
"Server": "Apache",
"X-Powered-By": "PHP\/5.2.17"
},
"responseTime": 563,
"statusCode": 200,
"statusReason": "OK",
"text": "<br><table border='1' cellpadding='2' bgcolor='#FFFFDF' bordercolor='#E8B900' align='center'><tr><td><font face='Arial' size='1' color='#000000'><b>PHP Error Message<\/b><\/font><\/td><\/tr><\/table><br \/>\n<b>Warning<\/b>: json_encode() expects exactly 1 parameter, 2 given in <b>\/home\/a1974455\/public_html\/login.php<\/b> on line <b>72<\/b><br \/>\n<br><table border='1' cellpadding='2' bgcolor='#FFFFDF' bordercolor='#E8B900' align='center'><tr><td><div align='center'><a href='http:\/\/www.000webhost.com\/'><font face='Arial' size='1' color='#000000'>Free Web Hosting<\/font><\/a><\/div><\/td><\/tr><\/table> \n<!-- Hosting24 Analytics Code -->\n<script type=\"text\/javascript\" src=\"http:\/\/stats.hosting24.com\/count.php\"><\/script>\n<!-- End Of Analytics Code -->",
"totalTime": 578,
"warnings": [
]
}
The website does not work.
When you pointed to it, you're using http, but in the XML you're using https. And when trying to access the website with the https protocol, it is not loading.