How to call Azure function from Kotlin - kotlin

I currently have deployed an Azure function used to get an AD token.
Function:
https://getadtokennet.azurewebsites.net/api/getadtokennet
Request header:
x-functions-key = {key}
How can I call this function from my Kotlin app?
This is the way I call it from Javascript
function getTokenAzure(onsuccess, onerror) {
var tokenUrl = 'https://getadtokennet.azurewebsites.net/api/getadtokennet';
$.ajax(tokenUrl, {
method: 'GET',
beforeSend: function (request) {
request.setRequestHeader("x-functions-key", "function key");
},
success: function (data) {
onsuccess(data);
console.log('token: ' + data.token);
},
error: function (xhr, status, error) {
var failureMessage = "GetToken error: " + status + " - " + error;
onerror(failureMessage);
console.log(failureMessage);
}
});
}

In IntelliJ IDEA, select Create New Project.
In the New Project window, select Maven from the left pane.
Select the Create from archetype check box, and then select Add Archetype for the azure-functions-kotlin-archetype.
In the Add Archetype window, complete the fields as follows:
GroupId: com.microsoft.azure
ArtifactId: azure-functions-kotlin-archetype
Version: Use the latest version from the central repository
Select OK, and then select Next.
Enter your details for current project, and select Finish.
For complete information refer to the below links which has same information.
Kotlin Function and Running Kotlin in Azure Functions

I found the way, here it is.
fun getToken(): String {
val tokenUrl = URL("https://getadtokennet.azurewebsites.net/api/getadtokennet")
val connection = tokenUrl.openConnection() as HttpURLConnection
connection.requestMethod = "POST"
connection.setRequestProperty("x-functions-key", "function key")
connection.doOutput = true
val responseCode = connection.responseCode
if (responseCode == HTTP_OK) {
val readerIn = BufferedReader(InputStreamReader(connection.inputStream))
var inputLine = readerIn.readLine()
val response = StringBuffer()
do {
response.append(inputLine)
} while (inputLine.length < 0)
readerIn.close()
// Return token
return response.toString()
} else {
val responseError = Error(code = "BadRequest", message = "There was an error getting the token.")
throw IOException(responseError.toString())
}
}

Related

MobileFirst - Invoking Java SQL Adapter adapter procedure

I am following the Java SQL Adapter tutorial for MobileFirst Platform 7.
I'm trying to Get User with userId = "bjones", but I don't know how to set the params {userId} into the procedure /adapters/UserAdapter/{userId}.
function loadUsers(){
busyIndicator.show();
var resourceRequest = new WLResourceRequest("/adapters/UserAdapter/", WLResourceRequest.GET);
resourceRequest.setQueryParameter("userId", "bjones");
resourceRequest.send().then(
loadUsersSuccess,
loadUsersFailure
);}
function loadUsersSuccess(result){
WL.Logger.debug("Feed retrieve success");
busyIndicator.hide();
WL.Logger.debug(JSON.stringify(result));
if (result.responseJSON.length>0)
displayFeeds(result.responseJSON);
else
loadUsersFailure();}
function loadUsersFailure(result){
WL.Logger.error("Feed retrieve failure");
busyIndicator.hide();
WL.SimpleDialog.show("Banking Application", "Service not available. Try again later.",
[{
text : 'Reload',
handler : WL.Client.reloadApp
},
{
text: 'Close',
handler : function() {}
}]
);}
My request is
localhost:10080/JavaAdapters/adapters/UserAdapter/?userId=bjones
but the JSON response contains all user stored in my database
Image for response
In addition, how about the REST call type #PUT, with Path param "userId" and body params: "firstName", "lastName", "password", in order to update an user
From the tutorial the adapter endpoint is /{userId} which means the userId is not a query param but it is part of the url. You need to update your loadUsers function so that it appends the userId at the end of the url, so in your example the fullpath will be /adapters/UserAdapter/bjones
function loadUsers(){
busyIndicator.show();
var usedId = "bjones";
var resourceRequest = new WLResourceRequest("/adapters/UserAdapter/"+userId, WLResourceRequest.GET);
resourceRequest.send().then(loadUsersSuccess,loadUsersFailure);
}
UPDATE:
function loadUsersSuccess(result) {
WL.Logger.debug("Feed retrieve success");
busyIndicator.hide();
WL.Logger.debug(JSON.stringify(result));
// if responseJSON is not null user data was returned
if (result.responseJSON != null) {
displayFeeds(result.responseJSON);
} else{
loadUsersFailure();
}
}
there are basically two type of URL with Parameters:
1. Path parameter:
/adapters/UserAdapter/users/{userId}
2. Query Parameter:
/adapters/UserAdapter/users?userId={userId}
java adapter with query parameter:
#GET
#Produces("application/json")
#OAuthSecurity(enabled = false)
#Path("/users")
public String getuserById(#QueryParam("userID") String userId)
{
System.out.println(userId);
}
java adapter with path parameter:
#GET
#Produces("application/json")
#OAuthSecurity(enabled = false)
#Path("/users/{userId}")
public String getuserById(#PathParam("userId") String userId)
{
System.out.println(userId);
}
I hope, second example answers your question in java adapter.

Google Analytics API fails to login with bad request and invalidKey

I´m trying to get some data from analytics, but can´t get authorized. It returns the following error:
I renewed my credentials at google console several times.
The code I´m using:
var clientId = '*****************0m1fnmuae00abaaq.apps.googleusercontent.com';
var apiKey = '********fB9eVMVfQ0oR6';
var scopes = 'https://www.googleapis.com/auth/analytics.readonly';
function handleClientLoad() {
gapi.client.setApiKey(apiKey);
window.setTimeout(checkAuth, 1);
}
function checkAuth() {
gapi.auth.authorize({
client_id: clientId, scope: scopes, immediate: true}, handleAuthResult);
}
function handleAuthResult(authResult) {
if (authResult) {
gapi.client.load('analytics', 'v3', handleAuthorized);
} else {
handleUnauthorized();
}
}
function handleAuthorized() {
var authorizeButton = document.getElementById('authorize-button');
var runDemoButton = document.getElementById('run-demo-button');
authorizeButton.style.visibility = 'hidden';
runDemoButton.style.visibility = '';
runDemoButton.onclick = makeApiCall;
outputToPage('Click the Run Demo button to begin.');
}
function handleUnauthorized() {
var authorizeButton = document.getElementById('authorize-button');
var runDemoButton = document.getElementById('run-demo-button');
runDemoButton.style.visibility = 'hidden';
authorizeButton.style.visibility = '';
authorizeButton.onclick = handleAuthClick;
outputToPage('Please authorize this script to access Google Analytics.');
}
function handleAuthClick(event) {
gapi.auth.authorize({
client_id: clientId, scope: scopes, immediate: false}, handleAuthResult);
return false;
}
When I run the code, it returns the following error:
error: {errors:[{domain:usageLimits, reason:keyInvalid, message:Bad Request}], code:400, message:Bad Request}
code: 400
errors: [{domain:usageLimits, reason:keyInvalid, message:Bad Request}]
0: {domain:usageLimits, reason:keyInvalid, message:Bad Request}
domain: "usageLimits"
message: "Bad Request"
reason: "keyInvalid"
message: "Bad Request"
Someone can help with this issue?
Find the error.
In Google Console, you have to create the OAuth ID and the Public API Access ID.
Take the cliendId from the first and the APIKey from the second.
I think it´s very confuse, and it could be more explicit in documentation.

IBM Worklight 6.0 - Getting "Uncaught type error cannot call method 'initCollection' of undefined"

I'm working with Worklight to build an application which uses a local storage. I declared a function createCollection() in common/js/myApp.js.
However when I run it on the browser simulator, the console JavaScript shows:
Uncaught TypeError: Cannot call method 'initCollection' of undefined.
Any suggestions?
My JavaScript:
function wlCommonInit(){
// Common initialization code goes here
}
// inizializzazione json
window.onload = createCollection;
var isOpen = true;
var menuboxw = $("#menubox").css("width");
$("#contentbox").css("left",menuboxw);
var headerh = $("#header").height();
$("#contentbox").css("top", headerh);
$("#menu_btn").click(function(){menu()});
// apertura/chiusura menu principale
function menu() {
if(isOpen){
$('#contentbox').animate({ left: -5 }, 1);
$("#menubox").css("visibility", "hidden");
isOpen = false;
}
else{
$('#contentbox').animate({ left: menuboxw }, 1);
$("#menubox").css("visibility", "visible");
isOpen = true;
}
}
// creazione collection 'canti' e 'categorie'
function createCollection(){
WL.Logger.debug("Called createCollection");
WL.SimpleDialog.show("Message", "createCollection called", [{text: "Ok"}]);
var collectionCanti = "canti";
var searchFieldsCanti = {titolo: "string", autore: "string", id_categoria: "string", testo: "string"};
var collectionCategorie = "categorie";
var searchFieldsCategorie = {titolo: "string", attiva: "number"};
var success = function(data){
logMessage("Collection created successfully " + data);
};
var failure = function(data){
logMessage("Collection doesn't created " + data);
};
var options = {onSuccess: success, onFailure: failure};
canti = WL.JSONStore.initCollection(collectionCanti, searchFieldsCanti, options);
categorie = WL.JSONStore.initCollection(collectionCategorie, searchFieldsCategorie, options);
}
Do the following:
Remove window.onload = createCollection;
Add createCollection(); inside wlCommonInit()
BTW, that logMessage produces errors. Should probably be changed to WL.Logger.debug (which you are already utilizing in the code...).
Please go over the IBM Worklight Getting Started training material. No skipping.

Win 8 Apps : saving and retrieving data in roamingfolder

I'm trying to store few user data into a roamingFolder method/property of Windows Storage in an app using JavaScript. I'm following a sample code from the Dev Center, but no success. My code snippet is as follows : (OR SkyDrive link for the full project : https://skydrive.live.com/redir?resid=F4CAEFCD620982EB!105&authkey=!AE-ziM-BLJuYj7A )
filesReadCounter: function() {
roamingFolder.getFileAsync(filename)
.then(function (filename) {
return Windows.Storage.FileIO.readTextAsync(filename);
}).done(function (data) {
var dataToRead = JSON.parse(data);
var dataNumber = dataToRead.count;
var message = "Your Saved Conversions";
//for (var i = 0; i < dataNumber; i++) {
message += dataToRead.result;
document.getElementById("savedOutput1").innerText = message;
//}
//counter = parseInt(text);
//document.getElementById("savedOutput2").innerText = dataToRead.counter;
}, function () {
// getFileAsync or readTextAsync failed.
//document.getElementById("savedOutput2").innerText = "Counter: <not found>";
});
},
filesDisplayOutput: function () {
this.filesReadCounter();
}
I'm calling filesDisplayOutput function inside ready method of navigator template's item.js file, to retrieve last session's data. But it always shows blank. I want to save upto 5 data a user may need to save.
I had some trouble running your code as is, but that's tangential to the question. Bottom line, you're not actually reading the file. Note this code, there's no then or done to execute when the promise is fulfilled.
return Windows.Storage.FileIO.readTextAsync(filename);
I hacked this in your example solution and it's working... typical caveats of this is not production code :)
filesReadCounter: function () {
roamingFolder.getFileAsync(filename).then(
function (filename) {
Windows.Storage.FileIO.readTextAsync(filename).done(
function (data) {
var dataToRead = JSON.parse(data);
var dataNumber = dataToRead.count;
var message = "Your Saved Conversions";
//for (var i = 0; i < dataNumber; i++) {
message += dataToRead.result;
document.getElementById("savedOutput1").innerText = message;
//}
//counter = parseInt(text);
//document.getElementById("savedOutput2").innerText = dataToRead.counter;
}, function () {
// readTextAsync failed.
//document.getElementById("savedOutput2").innerText = "Counter: <not found>";
});
},
function () {
// getFileAsync failed
})
},

Angular http testing

I have a fairly simple controller that gets a simple json list of objects ...
function ProductGroupsCtrl($scope, $http, $routeParams, sharedService, popupService) {
$scope.list = null;
$scope.selectedItem = null;
$scope.selectedItemJsonString = '';
$scope.selectItem = function (item) {
$scope.selectedItem = item;
$scope.selectedItemJsonString = JSON.stringify(item);
//alert(JSON.stringify(item));
};
$scope.closePopup = function () {
$scope.selectedItem = null;
$scope.selectedItemJsonString = '';
};
// sharedService.prepForBroadcast($routeParams.anotherVar);
$http({
method: 'GET',
url: '/ProductGroup'
}).success(function (data) {
$scope.list = data;
}).
error(function (data) {
$scope.message = 'There was an error with the data request.';
});
}
I then try to mock the request in the test class:
var scope, ctrl, $httpBackend, sharedServiceMock = {}, popupServiceMock = {};
beforeEach(inject(function (_$httpBackend_, $rootScope, $controller) {
$httpBackend = _$httpBackend_;
$httsypBackend.expectGET('/ProductGroup').
respond([{
ProductGroupID: 5,
MenuTitle: "Promotional Products",
AlternativeText: "Coming soon - a collection of environmentally friendly Promotional Products",
OrdinalPosition: 5,
Active: false
}]);
scope = $rootScope.$new();
ctrl = $controller(ProductGroupsCtrl, {
$scope: scope,
$http: $httpBackend,
sharedService: sharedServiceMock,
popupService: popupServiceMock
});}));
However I receive an error in the testacular window object undefined. What have I done wrong here?
Found the answer. If I remove the error callback function from the $http.get method then it works, i.e. remove the following ...
error(function (data) {
$scope.message = 'There was an error with the data request.';
}
I have to say Angular sure is a steep learning curve for someone who is not a day to day JavaScript programmer (although I seem to be doing more and more). Thanks for the help anyway KatieK :-)