Need help to use node-soap module - web-services

I have to make a server to update some device.
They asked me to use node.js and the device send a soap request.
I need to check the parameters to verify the version. So I decided to use the node-soap module. (The WSDL file I use is a local file)
But I can't find how to recover the value of those parameters.
I read the node-soap spec, but I couldn't find how to do that. :/
Here is my code (I didn't do much yet because I'm stuck because of this) :
var myService = {
ActiaProxyAPI: { //MyService
ActiaProxyAPI: { //MyPort
GetData: function(args) { //MyFunction
if (args.i-uiType == "11") {
var ID = args.i-pcIdentifiant;
var reg=new RegExp("[ $]+", "g"); //parse the string (actually works)
var tableau=ID.split(reg);
console.log(tableau[4] );
}
return {
name: args.o-poData
};
}
}
}
};
var xml = require('fs').readFileSync('./wsdl/ActiaProxyAPI.wsdl', 'utf8'),
server = http.createServer(function(request,response) {
response.end("404: Not Found: "+request.url);
});
server.listen(8080);
soap.listen(server, '/wsdl', myService, xml);

I've found how to retrieve the arguments' value : instead of args.i-uiType I used args["i-uiType"] , and instead of name: args.o-poData :
'tns:GetDataResponse': {'o-poData': result}
Well I hope this can help other people, because it works for me !

Related

.net core 6 jwt token mocking

I am looking for a tutorial on how to mock authentication tokens for .net core 6 web services. Some years ago, at a previous job, I looked up how to do this with .net 3 and got it to work. But 6 removed the startup.cs file and seems to have shifted things around quite a bit. There are very few examples of doing this for 6.
I am in the process of creating a series of unit tests for the endpoints in a new web application. I am starting over from bare bones. Here is the code example. I know that it is possible to recreate the Startup.cs file, but for the time being I would prefer to do it without that. Are there any examples of this for a .net 6 specific architecture?
internal class DssiApiTest : WebApplicationFactory<Program>
{
private readonly string _environment;
public DssiApiTest(string environment = "Development")
{
_environment = environment;
}
protected override IHost CreateHost(IHostBuilder builder)
{
builder.UseEnvironment(_environment);
var settings = new ApiSettings();
// Add mock/test services to the builder here
builder.ConfigureServices(services =>
{
services.AddScoped(sp =>
{
var options = new DbContextOptionsBuilder<ApplicationDbContext>()
.UseInMemoryDatabase("Tests")
.UseApplicationServiceProvider(sp)
.Options;
using (var context = new ApplicationDbContext(options,
MakeMockTenantService(),
(Microsoft.Extensions.Options.IOptions<ApiSettings>)settings))
{
context.PartCustomers.Add(CreatePartCustomer(1, 1));
context.PartCustomers.Add(CreatePartCustomer(2, 1));
context.SaveChanges();
}
// Replace SQLite with in-memory database for tests
return options;
});
});
return base.CreateHost(builder);
}
}
I think I found the answer to what I needed to do. I have not been able to fully test it yet, however, because I am running into another issue that is throwing an error. Will have to ask another question for that one. Here is what I have so far. If anyone can elaborate or correct this please feel free to do so. Like I said, I have not fully tested it and don't want to lead others astray. Will update once I have it worked out.
I added a new TestAuthHandler to the virtual client that returns a mock auth result like so :
using var application = new TestWebApplicationFactory();
var client = application.WithWebHostBuilder(builder =>
{
builder.ConfigureTestServices(services =>
{
services.AddAuthentication("Test")
.AddScheme<AuthenticationSchemeOptions, TestAuthHandler>(
"Test", options => { });
});
})
.CreateClient(new WebApplicationFactoryClientOptions
{
AllowAutoRedirect = false,
});
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Test");
Here is the code for the TestAuthHandler
public class TestAuthHandler : AuthenticationHandler<AuthenticationSchemeOptions>
{
public TestAuthHandler(IOptionsMonitor<AuthenticationSchemeOptions> options,
ILoggerFactory logger, UrlEncoder encoder, ISystemClock clock)
: base(options, logger, encoder, clock)
{
}
protected override Task<AuthenticateResult> HandleAuthenticateAsync()
{
var claims = new[] { new Claim(ClaimTypes.Name, "Test user") };
var identity = new ClaimsIdentity(claims, "Test");
var principal = new ClaimsPrincipal(identity);
var ticket = new AuthenticationTicket(principal, "Test");
var result = AuthenticateResult.Success(ticket);
return Task.FromResult(result);
}
}

unitary testing in doGet(request) - Google Apps Script

I'm developing a simple google Script and publishing it as a web app.
The starting of my method is as follows:
function doGet(request) {
var start = request.parameters.start;
var end = request.parameters.end;
if (isNaN(Number(start)))
return generateError (3, start);
if (isNaN(Number(end)))
return generateError (4, end);
/*
* ...
* lot of irrelevant stuff for current question
* ...
*/
}
I want to add some basic unitary testing. I have it ready for secondary functions, but I'm not sure how to do it with the doGet (request) function.
At the present moment I'm using the following method:
function testDoGet(){
var queryString = "?start=1&end=5";
var url = ScriptApp.getService().getUrl() + queryString;
var options =
{
"method" : "GET",
"followRedirects" : true,
"muteHttpExceptions": true
};
Logger.log(url);
var result = UrlFetchApp.fetch(url, options);
Logger.log(result);
But this does not allow me to debug, and also it requires that the code has been published (but is not executing the latest code), I would be interested in validate parameters received (for example)
Is there any way so we can simulate this?
I guess you can just call it directly and provide the parameters as an actual HTTP call would do, e.g.
function testDoGet() {
var requestMock = {
parameters: {
start: 1,
end: 5
}
};
Logger.log(requestMock);
var result = doGet(requestMock);
Logger.log(result);
}

How to update warning in webstorm?

I've been developing node js app which use mongodb to manipulate static data. I'm using webstorm to my main editor program.
I wrote a function which use mongodb to find a data. Actually, this is sample code in the mongodb's getting started document.
var findRestaurants = function(db, callback) {
var cursor =db.collection('restaurants').find( );
cursor.each(function(err, doc) {
assert.equal(err, null);
if (doc != null) {
console.dir(doc);
} else {
callback();
}
});
};
In the 3rd line, each is the method of the cursor object which defined in mongodb driver api. This method operate the callback function to the returned records which the cursor pointing to, and there's no problem to run this code.
But, in the webstorm editor window, the program gives warning to each method, saying that this symbol is deprecated. It says that javascript has deprecated this each method. It may seems that webstorm doesn't know about the api information of node js or mongodb. Of course, I could ignore this message, but it makes me a little irritated.
Is there a way to update warning information of webstorm program? I think that there's a way to register node js or mongodb api list to webstorm program, but I can't find it by searching.
Thanks.
I was experiencing this same problem, and I have found it to be a reference to the javascript .each() method which is in fact deprecated. The simplest (read quick fix) way to resolve this, is to place "//noinspection JSDeprecatedSymbols" above the line giving the error. You can alternatively click on the lightbulb icon on the left, goto "inspection Deprecated Javascript symbol options", then Suppress for statement (or any other option you may wish to use to disable this warning)
var findRestaurants = function(db, callback) {
var cursor =db.collection('restaurants').find( );
//noinspection JSDeprecatedSymbols
cursor.each(function(err, doc) {
assert.equal(err, null);
if (doc != null) {
console.dir(doc);
} else {
callback();
}
});
};
I took a look at the list of functions present in MongoDB engine for Node.JS. There two function that can replace "each" function: "next" and "hasNext".
So for your example, I would write this code:
var findRestaurants = function(db, callback) {
var cursor = db.collection('restaurants').find( );
var parseRestaurant = function() {
cursor.next(function(err, restaurant){
if (err)
return console.error(err);
console.dir(doc);
hasNextRestaurant();
});
};
var hasNextRestaurant = function() {
cursor.hasNext(function(err, result){
if (err)
return console.error(err);
if (result)
parseRestaurant();
else {
//Here is the last point of iterations
//We can use this for statistics output
return console.log('That\'s all');
}
});
};
hasNextRestaurant();
}
Or something like this:
var findRestaurants = function(db, callback) {
var cursor = db.collection('restaurants').find( );
var parseRestaurant = function(err, doc) {
if (err)
return console.error(err);
console.dir(doc);
cursor.hasNext(checkNext);
};
var checkNext = function(err) {
if (err)
return console.error(err);
if (result)
parseRestaurant();
else {
//Here is the last point of iterations
//We can use this for statistics output
return console.log('That\'s all');
}
cursor.next(parseRestaurant);
};
cursor.hasNext(checkNext);
}

Loopback strange behaviour

I am talking about loopback push component. I am trying to intercept the "create" method of "Installation" model. My code looks like this -
server/boot/installationex.js
module.exports = function (app) {
var Installation = app.models.Installation;
var create = Installation.create;
Installation.create = function (data, cb) {
//reinitializing old implementation
this.create = create;
console.log("Received data: "+JSON.stringify(data));
if (!data || !data.imei) {
console.log("No data or imei was provided, creating new");
this.create(data, cb);
return;
}
//saving 'this' reference
var that = this;
//search by imei filter
var filter = {where: {imei: data.imei}};
this.findOne(filter, function (err, result) {
if (err) {
console.log("Error occurred while looking for installation by IMEI");
cb(err);
return;
}
if (!result) {
console.log("No installation found by IMEI, will create a new installation");
that.create(data, cb);
return;
}
console.log("Found existing installation with id: " + JSON.stringify(result));
result.deviceToken = result.gpsLocation = result.osVersion = result.vendor = result.phoneNumbers = null;
if (data.deviceToken) {
result.deviceToken = data.deviceToken;
}
if (data.gpsLocation) {
result.gpsLocation = data.gpsLocation;
}
if (data.osVersion) {
result.osVersion = data.osVersion;
}
if (data.vendor) {
//result.vendor=data.vendor;
result.vendor = 'jahid';
}
if (data.phoneNumbers) {
result.phoneNumbers = data.phoneNumbers;
}
that.upsert(result, cb);
});
}
}
Unfortunately this code is invoked only once, I mean the first time. After that this code is never invoked. I became sure by looking at the log. It only prints the log first time. After that it does not print any log.
Any idea why this glue code is only invoked once? My intention is to intercept all create method invocation for Installation model. And check if there is already an entry for supplied "IMEI", if so then reuse that. Otherwise create new.
Thanks in advance.
Best regards,
Jahid
What I would start here with is:
instead of implementing your own intercepting mechanism use Model Hooks
check out findOrCreate() method
boot scripts are only run once during application startup. if you want a function that triggers every time a function is called, use a remote hook or model hook. probably something along the lines of:
...
Installation.beforeRemote('create', ...
...
see http://docs.strongloop.com/display/LB/Adding+logic+to+models for more info

AWS S3 Bucket Upload using CollectionFS and cfs-s3 meteor package

I am using Meteor.js with Amazon S3 Bucket for uploading and storing photos. I am using the meteorite packges collectionFS and aws-s3. I have setup my aws-s3 connection correctly and the images collection is working fine.
Client side event handler:
'click .submit': function(evt, templ) {
var user = Meteor.user();
var photoFile = $('#photoInput').get(0).files[0];
if(photoFile){
var readPhoto = new FileReader();
readPhoto.onload = function(event) {
photodata = event.target.result;
console.log("calling method");
Meteor.call('uploadPhoto', photodata, user);
};
}
And my server side method:
'uploadPhoto': function uploadPhoto(photodata, user) {
var tag = Random.id([10] + "jpg");
var photoObj = new FS.File({name: tag});
photoObj.attachData(photodata);
console.log("s3 method called");
Images.insert(photoObj, function (err, fileObj) {
if(err){
console.log(err, err.stack)
}else{
console.log(fileObj._id);
}
});
The file that is selected is a .jpg image file but upon upload I get this error on the server method:
Exception while invoking method 'uploadPhoto' Error: DataMan constructor received data that it doesn't support
And no matter whether I directly pass the image file, or attach it as data or use the fileReader to read as text/binary/string. I still get that error. Please advise.
Ok, maybe some thoughts. I have done things with collectionFS some months ago, so take care to the docs, because my examples maybe not 100% correct.
Credentials should be set via environment variables. So your key and secret is available on server only. Check this link for further reading.
Ok first, here is some example code which is working for me. Check yours for differences.
Template helper:
'dropped #dropzone': function(event, template) {
addImage(event);
}
Function addImage:
function addImagePreview(event) {
//Go throw each file,
FS.Utility.eachFile(event, function(file) {
//Some Validationchecks
var reader = new FileReader();
reader.onload = (function(theFile) {
return function(e) {
var fsFile = new FS.File(image.src);
//setMetadata, that is validated in collection
//just own user can update/remove fsFile
fsFile.metadata = {owner: Meteor.userId()};
PostImages.insert(fsFile, function (err, fileObj) {
if(err) {
console.log(err);
}
});
};
})(file);
// Read in the image file as a data URL.
reader.readAsDataURL(file);
});
}
Ok, your next point is the validation. The validation can be done with allow/deny rules and with a filter on the FS.Collection. This way you can do all your validation AND insert via client.
Example:
PostImages = new FS.Collection('profileImages', {
stores: [profileImagesStore],
filter: {
maxSize: 3145728,
allow: {
contentTypes: ['image/*'],
extensions: ['png', 'PNG', 'jpg', 'JPG', 'jpeg', 'JPEG']
}
},
onInvalid: function(message) {
console.log(message);
}
});
PostImages.allow({
insert: function(userId, doc) {
return (userId && doc.metadata.owner === userId);
},
update: function(userId, doc, fieldNames, modifier) {
return (userId === doc.metadata.owner);
},
remove: function(userId, doc) {
return false;
},
download: function(userId) {
return true;
},
fetch: []
});
Here you will find another example click
Another point of error is maybe your aws configuration. Have you done everything like it is written here?
Based on this post click it seems that this error occures when FS.File() is not constructed correctly. So maybe this should be you first way to start.
A lot for reading so i hope this helps you :)