Graphileon Proxy Feature For file uploads - ajax

We have a custom API which is running in a pod on Kubernetes server, with Graphileon also running in a pod on the same server.
The custom API takes spreadsheet as form-data, uploads it and processes it on to Neo4j database (also running in a pod on the same server).
All our 3 pods (custom API, Graphileon and Neo4j) are running in same namespace.
Our requirement is that we want to create a "HTMLView" on Graphileon which can open a small dialog box where we can upload the spreadsheet and hit our API on the backend.
Graphileon team advised us to use the proxy feature, but that seems to be not working in this case. Here is what we did:
LOCAL TESTING
We started neo4j, graphileon and custom API on local. We created the HTML view and used ajax call to call our API:
function createSchema(schemaType,formData)
{
var schemaUrl = "http://localhost:8080/create-schema/"+schemaType;
$.ajax({
url: schemaUrl,
type: "POST",
data: formData,
mimetype: "multipart/form-data",
cache: false,
processData: false,
success: function(data,status,xhr){
$("#result").html("");
$("#reset").show();
$("#schemaFileUpload").hide();
$("#result").append("<h4>Create "+ schemaType +" Schema Success <span style=\'color:green\' >"+xhr.responseText + " with Status code "+xhr.status+"<span></h4> </br>" );
$("#verticalSchemaFile").attr("disabled","disabled");
$("#customerSchemaFile").attr("disabled","disabled");
},
error: function(xhr,status,error){
$("#result").html("");
$("#reset").show();
$("#schemaFileUpload").hide();
$("#result").append( schemaType +" create Schema Failed. <span style=\'color:red\' >"+xhr.responseText + " with Status code "+xhr.status+"<span> </br>" );
$("#verticalSchemaFile").attr("disabled","disabled");
$("#customerSchemaFile").attr("disabled","disabled");
}
});
}
This works!
SERVER TESTING
When I put the same code over the server, its gives error - couldn't reach URL. So I did the proxy settings and tried the proxy way:
function createSchema(schemaType,formData)
{
var schemaUrl = "http://customapi:8080/create-schema/"+schemaType;
$.ajax({
url: "/proxy",
type: "POST",
data: "{\"url\": \"" + schemaUrl + "\", \"method\": \"POST\", \"data\": \"" + formData + "\"}",
mimetype: "multipart/form-data",
cache: false,
processData: false,
success: function(data,status,xhr){
$("#result").html("");
$("#reset").show();
$("#schemaFileUpload").hide();
$("#result").append("<h4>Create "+ schemaType +" Schema Success <span style=\'color:green\' >"+xhr.responseText + " with Status code "+xhr.status+"<span></h4> </br>" );
$("#verticalSchemaFile").attr("disabled","disabled");
$("#customerSchemaFile").attr("disabled","disabled");
},
error: function(xhr,status,error){
$("#result").html("");
$("#reset").show();
$("#schemaFileUpload").hide();
$("#result").append( schemaType +" create Schema Failed. <span style=\'color:red\' >"+xhr.responseText + " with Status code "+xhr.status+"<span> </br>" );
$("#verticalSchemaFile").attr("disabled","disabled");
$("#customerSchemaFile").attr("disabled","disabled");
}
});
}
This gives error saying "No JSON request parameters specified"
Appreciate any help here. Thanks

Disclamer: i am a lead developer at Graphileon.
The /proxy endpoint of Graphileon is more of a Remote Procedure Call. It calls request(...) with the parameters received as JSON in the request body (GET or POST data).
It is not designed to handle file uploads.
The only way to simulate a file upload in the target API is to send the file data in the formData parameter. The problem is that with JSON you can only send text files. So no binary data.
$.ajax({
url: "/proxy",
type: "POST",
data: JSON.stringify({
url: schemaUrl,
method: 'POST',
formData: {
file: {
value: '<file-contents>',
options: {
filename: 'my-file.txt',
contentType: 'text/plain'
}
}
}
})
})
You can read the selected file contents with the Javascript's FileReader API.

Related

How to invoke a web service published on a service bus using ajax?

I'm working with Oracle service bus, I've currently created services with SOA in jdeveloper which I have published on the service bus that offers oracle, now I need to access them from my mobile application made in phonegap. Does anyone know how to do it?. I have used a function in ajax but it does not work:
conectar = function () {
var url = "http://10.0.0.191:7001/OSBCapled/Proxy_Services/AutenticacionWS?WSDL"
var datos = '<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/">'
+ '<soap:Header xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">'
+ '</soap:Header>'
+ '<soapenv:Body>'
+ '<aut:requestRegistro xmlns:aut="http://www.integracion.org/autenticacion">'
+ '<aut:Email>'+$('#usuario').val()+'</aut:Email>'
+ '<aut:Clave>'+$('#clave').val()+'</aut:Clave>'
+ '</aut:requestRegistro>'
+ '</soapenv:Body>'
+ '</soapenv:Envelope>';
$.ajax({
url: url,
type: "POST",
crossDomain: true,
async: false,
data: datos,
cache:false,
dataType: 'text/xml',
success: function (data) {
alert("Funciono!! " + data.responseText);
},
error: function (data) {
alert("Error"):
},
});
}
Your URL has ?wsdl at the end. This implies that you want the specification of the service, rather than sending messages to the service.
Remove that, and you might have more luck.

Phonegap Android app web service

I am making Phone-gap app with android SDK using eclipse. In which i called web service for inserting data into database through AJAX call But i think url is not working properly. I am using localhost web service in running with emulator. My ajax call code is as per below.
$.ajax({
type: "POST",
contentType: "application/json",
dataType: "json",
async: false,
cache: false,
url:"http://xxx.xxx.x.xxx:8080/WebService2.asmx/HelloWorld",
data:"{'n':'" + document.getElementById('txtNum1').value + "', 'a':'" + document.getElementById('txtNum2').value + "','p':'" + document.getElementById('txtNum3').value + "'}",
success: function (response)
{
alert("Inserted data successfully");
document.getElementById('txtNum1').value="";
document.getElementById('txtNum2').value="";
document.getElementById('txtNum3').value="";
},
error: function(data) {
alert("Try Again");
}
});
}
If you want to access localhost from emulator then you need to use the IP address 10.0.2.2.
Try the url http://10.0.2.2:8080/WebService2.asmx/HelloWorld for your web-service when accessing it from emulator.
You can read more about Android emulator networking from the resource:-
http://developer.android.com/tools/devices/emulator.html#networkaddresses

Submitting files to django server from outside via Ajax

From client side A, I want to create a file on the fly by javascript and send it to a Django server B via Ajax for further processing.
The javascript code in A is like below. I use blob to create a file without a real uploaded one and send it via Ajax.
console.log("start sending binary data...");
var form = new FormData();
var blob = new Blob([bytesArray], {type: 'example/binary'});
form.append('file_name', blob, 'test.bin');
$.ajax({
url: THIRD_SERVER + 'test_binary',
type: 'POST',
data: form,
processData: false,
success: function(data){
console.log('test_binary ' + JSON.stringify(data));
}
});
However, on the Django server, what I got is like this (when i print request.POST), hence when i used Django FileUpload, it returned an exception.
<QueryDict: {u' name': [u'"file_name"'], u'------WebKitFormBoundarybCp3z7mAduz8BBDq\r\nContent-Disposition: form-data': [u''], u' filename': [u'"test.bin"\r\nContent-Type: example/binary\r\n\r\n\ufffd\ufffd\ufffd\x01\x05\x06\r\n------WebKitFormBoundarybCp3z7mAduz8BBDq--\r\n']}>
So I guess the above javascript doesn't do the right thing to send file to a Django server. Is there any proper way that I can use the FileUpload to handle?
Thanks,
You have to tell $.ajax not to set a content type otherwise it will be set incorrectly
$.ajax({
url: THIRD_SERVER + 'test_binary',
type: 'POST',
data: form,
processData: false,
contentType: false,
success: function(data){
console.log('test_binary ' + JSON.stringify(data));
}
});

My Ajax POST is coming up as an error even though I am returning 200

I am making an AJAX post to a Jersey Resource. I build an image and return it. The issue is, no matter what status I return, Ajax thinks it is an error. I can actually use the error message (via error.responseTest) and it works fine. But it is ugly. What do I return to make it a success? I have returned OK(200), Accepted(202) and Created(201). All of them give me an error message but in my Console Network tab, I get a success (green with the proper status).
I am returning it like this:
return Response.status(Response.Status.ACCEPTED).entity(image).header('Content-Type',"image/png").build();
My JS code:
$.ajax( Monocle.config.Sightline.jobUrl + "/sightline", {
type: "POST",
processData: false,
data: JSON.stringify({
Lat1: Monocle.Sightline.BBOX(feature,2),
Long1: Monocle.Sightline.BBOX(feature,1),
Lat2: Monocle.Sightline.BBOX(feature,4),
Long2: Monocle.Sightline.BBOX(feature,3),
OrgLat:observerCoords[0].lat,
OrgLong:observerCoords[0].lon,
ObHeight: feature.attributes.observerHeight,
TargHeight: feature.attributes.targetHeight,
OuterRadius: feature.attributes.outerRadius,
LVA: feature.attributes.lowerVertAngle,
UVA: feature.attributes.upperVertAngle,
sAzimuth: feature.attributes.startAzimuth,
eAzimuth: feature.attributes.endAzimuth,
outputType: "MAX"
}),
contentType: "application/json",
dataType: "json",
success: function( results ){
var graphic = new OpenLayers.Layer.Image(
Monocle.currentWidget.name + " Destination " + featurenum,
"data:image/png;base64," + results,
new OpenLayers.Bounds(Monocle.Sightline.BBOX(feature,1), Monocle.Sightline.BBOX(feature,2), Monocle.Sightline.BBOX(feature,3),Monocle.Sightline.BBOX(feature,4)),
new OpenLayers.Size(580, 288),
{ isBaseLayer: false,
opacity: 0.3,
displayOutsideMaxExtent: true
});
feature.legionObject = graphic;
graphic.relatedlayer = Monocle.currentWidget.name + " Destination " + featurenum;
Monocle.Map.map.addLayer(graphic);
},
error: function(errMsg) {
// TODO: really handle any errors
}
});
Setting dataType: "json", means that your response is to be json which it isn't that would cause the error so just remove it.
Also is your image data has to be base64 encoded to make a data uri.

wcf service json 400 Bad Request

I get a 400 Bad Request error when I try to call WCF service from client side using ajax. Following is my code,
[OperationContract]
[WebInvoke(Method = "POST",
BodyStyle = WebMessageBodyStyle.Wrapped,
ResponseFormat = WebMessageFormat.Json)]
string[] GetUser(string Id);
$.ajax({
type: "POST", //GET or POST or PUT or DELETE verb
url: "http://localhost:58055/Service1.svc/GetUser",
crossDomain: true,
data: '{"Id": "3"}',
contentType: "application/json; charset=utf-8",
dataType: "json", //Expected data format from server
processdata: true, //True or False
success: function (msg) {//On Successfull service call
alert(msg.GetUserResult[0]);
console.log("success " + msg);
},
error: function (msg) {//On Successfull service call
console.log(msg);
}
});
Any insights would be really helpfull...
The first thing you should try is hit the URL using fiddler(so that you could post your data too) and see if you get the same error.
Are you making a cross domain request. From the example it looks like you are not. Could you remove
crossDomain: true,
line and try the jquery again.
There are other options also which unnecessay like processdata. Suggest you to use the following code and see if it works or not.
$.ajax({
type: "POST",
// the url to the service -
url: "url",
// the format that the data should be in when
// it is returned
contentType: "json",
data: '{"Id": "3"}',
// the function that executes when the server
// responds to this ajax request successfully
success: function(data) {
// put the JSON response in the employees table
}
According to the ajax api documentation the default content type is 'application/x-www-form-urlencoded'. When sending JSON, the content type should be 'application/json; charset=utf-8' except that WCF does not like that. I got the same error messages and when I removed the content type I stopped getting this error. By the way, I noticed that you set crossDomain to true, this other question is relevant to that option.

Resources