Failed to connect to SAP Gateway from Eclipse - eclipse

I am trying to get the logged Sap Gateway user. The code below is in my controller:
onInit: function (evt) {
var oUserData;
var y = "/sap/bc/ui2/start_up";
var xmlHttp = new XMLHttpRequest();
xmlHttp.onreadystatechange = function() {
if (xmlHttp.readyState == 4 && xmlHttp.status == 200) {
oUserData = JSON.parse(xmlHttp.responseText);
alert(oUserData);
} else {
alert("fail");
}
};
xmlHttp.open("GET", y, false);
xmlHttp.send(null);
},
When I run my application in Eclipse, it also shows the alert "fail". Why is this happening? Am I doing it wrong?

Since you are using Eclipse I believe your application is running on localhost. This means that any relative URL's you use, will be relative to localhost. So /sap/bc/ui2/start_up will be converted to localhost:1234/sap/bc/ui2/start_up.
You will have to use the absolute path to your resource for this to work.
var y = "http://<your_gateway_system>:<port>/sap/bc/ui2/start_up";

Now it's working
Below is my new code
onInit : function (evt) {
var oUserData;
var y = "http://<your_gateway_system>:<port>/sap/bc/ui2/start_up";
var xmlHttp = null;
xmlHttp = new XMLHttpRequest();
xmlHttp.onreadystatechange = function() {
if (xmlHttp.readyState == 4 && xmlHttp.status == 200) {
oUserData = JSON.parse(xmlHttp.responseText);
alert(oUserData["fullName"]);
}
};
xmlHttp.open("GET", y, false);
xmlHttp.send(null);
},

Related

How can I make a REST XMLHttpRequest call from AFrame while using 8th Wall Web?

I am using 8th Wall SDK and trying to call an API. When I am attempting to do that from AFrame.registercomponent onclick method, the request is not getting sent.
I am new to AR. When I tried adding an alert messages for xhttp, it's empty.
What am I missing?
Is there an alternative to this?
By the way, I tried doing this with with an AR marker using Awe.js and it worked fine.
AFRAME.registerComponent('play-on-window-click', {
...
...
onClick: function(evt) {
var video = this.el.components.material.material.map.image;
// I'm sending a request from here - BEGIN
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.status == 200) {
this.responseText;
}
xhttp.open("GET", "https://myapi/rest/abc", true);
xhttp.send();
}
// END
video.play();
}
}
I expect the call is made successful to the API.
The xhttp.open and xhttp.send calls are inside the onreadystatechange handler so it will not get sent. Something like this should work:
AFRAME.registerComponent('play-on-window-click', {
...
...
onClick: function(evt) {
var video = this.el.components.material.material.map.image;
// I'm sending a request from here - BEGIN
var xhttp = new XMLHttpRequest();
http.onreadystatechange = function() {
if (this.status == 200) {
alert(this.responseText);
}
}
xhttp.open("GET", "https://myapi/rest/abc", true);
xhttp.send();
// END
video.play();
}
}

SAPUI5 and NW Portal

I have an SAPUI5 application deployed on my portal.
I am trying get the user login logged on portal in my SAPUI5.
But when I run my application it is not get any data.
Bellow is my code
sap.ui.define([
'jquery.sap.global',
'sap/ui/core/Fragment',
'sap/ui/core/mvc/Controller',
'sap/ui/model/Filter',
'sap/ui/model/json/JSONModel'
], function(jQuery, Fragment, Controller, Filter, JSONModel) {
"use strict";
var CController = Controller.extend("sap.m.ZHRUI001.C", {
inputId: '',
valueHelpRequest: function(oController) {
this.inputId = oController.oSource.sId;
var sServiceUrl = "http://<my server host>:<my server port>/sap/bc/ui2/start_up";
var oModel = new sap.ui.model.odata.ODataModel(sServiceUrl, true, "user", "password");
var oJsonModel = new sap.ui.model.json.JSONModel();
oModel.read("/?", null, null, true, function(oData, response) {
oJsonModel.setData(oData);
});
sap.ui.getCore().setModel(oJsonModel);
// Handling of both confirm and cancel; clear the filter
var that = this;
var handleClose = function(oEvent) {
var oSelectedItem = oEvent.getParameter("selectedItem");
if (oSelectedItem) {
that.byId(that.inputId).setValue(oSelectedItem.getTitle());
}
oEvent.getSource().getBinding("items").filter([]);
};
// Create a SelectDialog and display it; bind to the same
// model as for the suggested items
if (!this._valueHelpSelectDialog) {
this._valueHelpSelectDialog = new sap.m.SelectDialog("valueHelpSelectDialog", {
title: "{fullName}",
items: {
template: new sap.m.StandardListItem({
title: "{fullName}",
active: true
})
},
search: function(oEvent) {
var sValue = oEvent.getParameter("value");
var oFilter = new sap.ui.model.Filter(
"name",
sap.ui.model.FilterOperator.Contains, sValue
);
oEvent.getSource().getBinding("items").filter([oFilter]);
},
confirm: handleClose,
cancel: handleClose
});
this._valueHelpSelectDialog.setModel(oJsonModel);
} else {
this._valueHelpSelectDialog.setModel(oJsonModel);
}
this._valueHelpSelectDialog.open();
}
});
return CController;
});
From what I'm reading you are speaking of a SAP Portal, I expect you have a 7.3+ version.
I have found the SAP doc you used to find the user, be careful because this is not the code for a SAPUI5 application running on a portal but for one running on a R/3 system, the endpoint /sap/bc/ui2/start_up doesn't exist on a NetWeaver portal.
What you could do is develop a simple REST service (by developping a Servlet) that will send back the user and all the details that you need.
These details can be found in the PortalComponentRequest which holds a IUser object, you can find a sample portal servlet on my Git here :
https://gitlab.com/Almiriad/sap-portal-samples
You simply have to send a GET request to the url
http[s]://youserver:your port/irj/servlet/prt/portal/prtroot/UserServletSample.UserInfoSampleServlet
and you'll get a JSo
{
"user": {
"user-name":"<LASTNAME>, <FIRSTNAME>",
"user-id":"<USER_ID>",
"user-email":"<USER#EMAIL.COM>"
}
}
I hope this will help you.
`
var oUserData;
var y = "/sap/bc/ui2/start_up";
var xmlHttp = null;
xmlHttp = new XMLHttpRequest();
xmlHttp.onreadystatechange = function() {
if (xmlHttp.readyState == 4 && xmlHttp.status == 200) {
oUserData = JSON.parse(xmlHttp.responseText);
}
};
xmlHttp.open("GET", y, false);
xmlHttp.send(null);
`
console oUserData to get login details of that user who logged in.

Using QUnit and sinon.spy, how can I access my spy within an async callback?

I am new to QUnit and sinon.js and working to build tests for an ember-cli package. I am having problems getting sinon.spy(Ember.run, 'later') to work with the code below. inside the callback Ember.run.later is not being spied / has no .getCalls() etc...
How can I handle this type of test?
test('#authenticate rejects with invalid credentials', function() {
sinon.spy(Ember.run, 'later');
var jwt = JWT.create(),
expiresAt = (new Date()).getTime() + 60000;
var token = {};
token[jwt.identificationField] = 'test#test.com';
token[jwt.tokenExpireName] = expiresAt;
token = window.btoa(JSON.stringify(token));
var credentials = {
identification: 'username',
password: 'password'
};
App.server.respondWith('POST', jwt.serverTokenEndpoint, [
400,
{
'Content-Type': 'application/json'
},
'{"message":["Unable to login with provided credentials."]}'
]);
Ember.run(function(){
App.authenticator.authenticate(credentials).then(null, function(){
// Check that Ember.run.later was not called.
equal(Ember.run.later.getCall(0), null);
});
});
Ember.run.later.restore();
});
PS I currently am able to get this working by moving the sinon.spy and corresponding Ember.run.later.restore() to the module.setup() and module.teardown() methods respectively. Is there anything wrong with that that strategy other than it means they are spied for every test in my suite?
Thanks!
EDIT: Here is my authenticate method:
authenticate: function(credentials) {
var _this = this;
return new Ember.RSVP.Promise(function(resolve, reject) {
var data = _this.getAuthenticateData(credentials);
_this.makeRequest(_this.serverTokenEndpoint, data).then(function(response) {
Ember.run(function() {
var tokenData = _this.getTokenData(response),
expiresAt = tokenData[_this.tokenExpireName];
_this.scheduleAccessTokenRefresh(expiresAt, response.token);
response = Ember.merge(response, { expiresAt: expiresAt });
resolve(_this.getResponseData(response));
});
}, function(xhr) {
Ember.run(function() {
reject(xhr.responseJSON || xhr.responseText);
});
});
});
},

jQuery FileUpload: Ajax freezes the browser when uploading images (jpg, png)

I use jQuery Fileupload plugin for uploading files (.pdf,.zip,.dll and .png/.jpg) to server from local. All of file types above can be uploaded successfully on major browsers Chrome/Firefox/IE, except .png/.jpg.
When trying to upload the .png/.jpg on Chrome, the upload plugin will freeze this browser for 10-15 minutes until the ajax of sending data of XHR object is done, even the size of image is quite small (~90Kb). On contrast, the same process just takes 1-2 seconds to be done on FF/IE.
I am using v5.9 of this plugin with these overwrite options:
var maxFileSize = 500000000000000;
var resizeMaxWidth = 1920;
var resizeMaxHeight = 1200;
var maxChunkSize = 1073741824;
var maxNumberOfFiles = 1;
$('#fileupload').fileupload('option', {
forceIframeTransport: true,
maxFileSize: maxFileSize,
resizeMaxWidth: resizeMaxWidth,
resizeMaxHeight: resizeMaxHeight,
maxChunkSize: maxChunkSize,
xhrFields: {
withCredentials: true
},
acceptFileTypes: regularExpression,
autoUpload: autoUpload
});
I tried to set async: true; to force browser not to freeze the page, but failed.
and I got freezing page on Chrome when the scripts run to _onSend() event and can not return "success" callback.
_onSend: function (e, data) {
var that = this,
jqXHR,
slot,
pipe,
options = that._getAJAXSettings(data),
send = function (resolve, args) {
that._sending += 1;
jqXHR = jqXHR || (
(resolve !== false &&
that._trigger('send', e, options) !== false &&
(that._chunkedUpload(options) || $.ajax(options))) ||
that._getXHRPromise(false, options.context, args)
).success(function (result, textStatus, jqXHR) {
that._onDone(result, textStatus, jqXHR, options);
}).fail(function (jqXHR, textStatus, errorThrown) {
that._onFail(jqXHR, textStatus, errorThrown, options);
}).always(function (jqXHRorResult, textStatus, jqXHRorError) {
that._sending -= 1;
that._onAlways(
jqXHRorResult,
textStatus,
jqXHRorError,
options
);
if (options.limitConcurrentUploads &&
options.limitConcurrentUploads > that._sending) {
// Start the next queued upload,
// that has not been aborted:
var nextSlot = that._slots.shift();
while (nextSlot) {
if (!nextSlot.isRejected()) {
nextSlot.resolve();
break;
}
nextSlot = that._slots.shift();
}
}
});
return jqXHR;
};
this._beforeSend(e, options);
if (this.options.sequentialUploads ||
(this.options.limitConcurrentUploads &&
this.options.limitConcurrentUploads <= this._sending)) {
if (this.options.limitConcurrentUploads > 1) {
slot = $.Deferred();
this._slots.push(slot);
pipe = slot.pipe(send);
} else {
pipe = (this._sequence = this._sequence.pipe(send, send));
}
// Return the piped Promise object, enhanced with an abort method,
// which is delegated to the jqXHR object of the current upload,
// and jqXHR callbacks mapped to the equivalent Promise methods:
pipe.abort = function () {
var args = [undefined, 'abort', 'abort'];
if (!jqXHR) {
if (slot) {
slot.rejectWith(args);
}
return send(false, args);
}
return jqXHR.abort();
};
return this._enhancePromise(pipe);
}
return send();
},
Do you know how to force this plugin's Ajax to run on Chrome as it does on Firefox/IE ? or any hints to fix this issue ?
Thank you !
Cheers,

Drupal JSON POST from PhoneGap

I am trying to send a POST request to Drupal's Services module & JSON_Server module, however I am getting
{ "#error": true, "#data": "Invalid method " }
Since PhoneGap runs html files from locally on the phone, should i need to worry about JSONP. The issue I have with that is that I must POST data, and JSONP only allows for GET. Any ideas would be helpful. Thanks!
//SEND REQUEST AND CALLBACK FUNCTION
var req;
DrupalService.prototype.request = function(dataObject, callback){
req = false;
var url = DRUPAL_JSON_URL;
var params = "data="+dataObject;
try {
req = new XMLHttpRequest();
} catch(e) {
req = false;
}
if(req) {
req.onreadystatechange = function() {//Call a function when the state changes.
if(req.readyState == 4 && req.status == 200) {
console.log(">> "+req.responseText);
}
}
req.open("POST", url, false);
req.send(params);
}
}
So i figured it out, It had to do with conflicting content types
make sure you set it as
Content-Type = application/x-www-form-urlencoded;
var DRUPAL_JSON_URL = "http://myDrupalsSite.com/services/json";
var req;
DrupalService.prototype.request = function(dataObject, callback){
var url = DRUPAL_JSON_URL;
req = false;
var params = "method=system.connect";
try {
req = new XMLHttpRequest();
} catch(e) {
req = false;
}
if(req) {
req.onreadystatechange = function() {//Call a function when the state changes.
if(req.readyState == 4 && req.status == 200) {
alert("test " + req.responseText)
console.log("RESPONSE "+req.responseText);
}
}
req.open("POST", url, true);
req.setRequestHeader("Content-length", params.length);
req.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
req.send(params);
}
}