InvalidRequestException of status code 400 when AWS Lambda Function was invoked - amazon-web-services

var config = {};
config.IOT_BROKER_ENDPOINT = "abcdefghijk.iot.us-east-1.amazonaws.com".toLowerCase();
config.IOT_BROKER_REGION = "us-east-1";
config.IOT_THING_2 = "Thing1";
var AWS = require('aws-sdk');
AWS.config.region = config.IOT_BROKER_REGION;
AWS.config.update({accessKeyId: 'xxxxxxxxxxxxxxxxxxxx', secretAccessKey: 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'});
var iotdata = new AWS.IotData({endpoint: config.IOT_BROKER_ENDPOINT});
// namespaces
const NAMESPACE_CONTROL = "Alexa.ConnectedHome.Control";
const NAMESPACE_DISCOVERY = "Alexa.ConnectedHome.Discovery";
// discovery
const REQUEST_DISCOVER = "DiscoverAppliancesRequest";
const RESPONSE_DISCOVER = "DiscoverAppliancesResponse";
// control
const REQUEST_TURN_ON = "TurnOnRequest";
const RESPONSE_TURN_ON = "TurnOnConfirmation";
const REQUEST_TURN_OFF = "TurnOffRequest";
const RESPONSE_TURN_OFF = "TurnOffConfirmation";
// errors
const ERROR_UNSUPPORTED_OPERATION = "UnsupportedOperationError";
const ERROR_UNEXPECTED_INFO = "UnexpectedInformationReceivedError";
// entry
exports.handler = function (event, context, callback) {
log("Received Directive", event);
var requestedNamespace = event.header.namespace;
var response = null;
try {
switch (requestedNamespace) {
case NAMESPACE_DISCOVERY:
response = handleDiscovery(event);
break;
case NAMESPACE_CONTROL:
response = handleControl(event);
break;
default:
log("Error", "Unsupported namespace: " + requestedNamespace);
response = handleUnexpectedInfo(requestedNamespace);
break;
}// switch
} catch (error) {
log("Error", error);
}// try-catch
callback(null, response);
}// exports.handler
var handleDiscovery = function (event) {
var header = createHeader(NAMESPACE_DISCOVERY, RESPONSE_DISCOVER);
var payload = {
"discoveredAppliances": [],
};
return createDirective(header, payload);
}// handleDiscovery
var handleControl = function (event) {
var response = null;
var requestedName = event.header.name;
switch (requestedName) {
case REQUEST_TURN_ON :
response = handleControlTurnOn(event);
break;
case REQUEST_TURN_OFF :
response = handleControlTurnOff(event);
break;
default:
log("Error", "Unsupported operation" + requestedName);
response = handleUnsupportedOperation();
break;
}// switch
return response;
}// handleControl
var handleControlTurnOn = function (event) {
var thingPicker = config.IOT_THING_2;
console.log("Turning On the LED now");
console.log("check 1");
var update = {
"desired": {
"led": 1,
},
};
console.log("check 2");
console.log(thingPicker);
iotdata.updateThingShadow({
payload: JSON.stringify(update),
thingName: thingPicker,
}, function (err, data) {
console.log("check 4");
if (err) {
console.log("check 5");
console.log(err);
} else {
console.log("check 6");
console.log(data);
}
});
var header = createHeader(NAMESPACE_CONTROL, RESPONSE_TURN_ON);
var payload = {};
return createDirective(header, payload);
}// handleControlTurnOn
var handleControlTurnOff = function (event) {
var thingPicker = config.IOT_THING_2;
console.log("Turning Off the LED now");
var update = {
"desired": {
"led": 0,
},
};
console.log(thingPicker);
iotdata.updateThingShadow({
payload: JSON.stringify(update),
thingName: thingPicker,
}, function (err, data) {
if (err) {
console.log(err);
} else {
console.log(data);
}
});
var header = createHeader(NAMESPACE_CONTROL, RESPONSE_TURN_OFF);
var payload = {};
return createDirective(header, payload);
}// handleControlTurnOff
var handleUnsupportedOperation = function () {
var header = createHeader(NAMESPACE_CONTROL, ERROR_UNSUPPORTED_OPERATION);
var payload = {};
return createDirective(header, payload);
}// handleUnsupportedOperation
var handleUnexpectedInfo = function (fault) {
var header = createHeader(NAMESPACE_CONTROL, ERROR_UNEXPECTED_INFO);
var payload = {
"faultingParameter": fault,
};
return createDirective(header, payload);
}// handleUnexpectedInfo
// support functions
var createMessageId = function () {
var d = new Date().getTime();
var uuid = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
var r = (d + Math.random() * 16) % 16 | 0;
d = Math.floor(d / 16);
return (c == 'x' ? r : (r & 0x3 | 0x8)).toString(16);
});
return uuid;
}// createMessageId
var createHeader = function (namespace, name) {
return {
"messageId": createMessageId(),
"namespace": namespace,
"name": name,
"payloadVersion": "2",
};
}// createHeader
var createDirective = function (header, payload) {
return {
"header": header,
"payload": payload,
};
}// createDirective
var log = function (title, msg) {
console.log('**** ' + title + ': ' + JSON.stringify(msg));
}// log
Piece of code related to AWS Lambda Function which is of smart home API, when it was run against a testing event to turn on light, its giving "InvalidRequestException" of status code :400
the test event that was run against the code was:
{
"header": {
"messageId" : "5d599a53-fe40-405f-b0ab-233611e2dc5c",
"name" : "TurnOnRequest",
"namespace" : "Alexa.ConnectedHome.Control",
"payloadVersion" : "2"
},
"payload" : {
"accessToken" : "acc355t0ken"
}
}
Can any one please help me solve that exception.
Thanks in advance

Related

HandshakeException: Handshake error in client (OS Error: I/flutter ( 9113): CERTIFICATE_VERIFY_FAILED: Hostname mismatch(handshake.cc:359))

Connection code
till yesterday everything working properly but now it giving the error to connect the json data.
...........................................................................................................................................................................................
class ProductDataStacture with ChangeNotifier {
List<Products> _products = [];
List<Banners> _banners = [];
List<Categories> _category = [];
List<Random> _random = [];
Future<bool> getProducts() async {
String url = 'https://shymee.com';
try {
// http.Response response = await http.get(Uri.parse(url + "/home"),
var response = await http.get(Uri.parse(url + "/home"), headers: {
'Authorization': 'token a867c3c092e8b1195f398ed5ca52dda4e5ff5ed8'
});
var data = json.decode(response.body);
print(data);
List<Products> prod = [];
List<Banners> bann = [];
List<Categories> cate = [];
List<Random> ran = [];
data['products'].forEach((element) {
Products product = Products.fromJson(element);
prod.add(product);
print("this is product ${product}");
});
data['banners'].forEach((element) {
Banners banner = Banners.fromJson(element);
bann.add(banner);
});
data['categories'].forEach((element) {
Categories category = Categories.fromJson(element);
cate.add(category);
});
data['random'].forEach((element) {
Random random = Random.fromJson(element);
ran.add(random);
});
_products = prod;
_banners = bann;
_category = cate;
_random = ran;
return true;
} catch (e) {
print("e getProducts");
print(e);
return false;
}
}
List<Products> get productsList {
return [..._products];
}
List<Banners> get bannersList {
return [..._banners];
}
List<Categories> get categoryList {
return [..._category];
}
List<Random> get randomList {
return [..._random];
}
}
Temporary you can solve this issue with below recommend
class MyHttpOverrides extends HttpOverrides{
#override
HttpClient createHttpClient(SecurityContext? context){
return super.createHttpClient(context)
..badCertificateCallback = (X509Certificate cert, String host, int
port)=> true;
}
}
enter link description here
But my suggestion is you use valid certificate in server side

Setting up NSubstitute Mock for functions that implement asp.net core IMemoryCache

I have a function that returns a status like this:
public async Task<Result> UpdateWeight(string id, int weight)
{
var data = await service.GetData(id);
if (data != null)
{
var user = await GetInfo(data.UserId);
var changedWeight = await UpdateWeight(newWeight, user);
if (!changedWeight)
{
return new ChangeWeightResult("Weight not updated");
}
return new ChangeWeightResult(newWeight);
}
return new ChangeWeightResult("Error changing weight");
}
And I'm trying to set up a unit test (xUnit - NSubstitute) for it.
public async Task UpdateUserAvatar_WhenCalled_ReturnChangedAvatarSuccess()
{
//Arrange
var id = "id";
var newWeight = 30;
var data = new DataEntity
{
Id = id
};
var user = new User
{
UserId = "id"
};
service.GetData(Arg.Any<string>()).Returns(data);
service.GetUser(Arg.Any<string>()).Returns(user);
//Act
var result = await service.UpdateWeight(data.Id, newWeight;
//Assert
result.IsSuccessful.Should().BeTrue();
result.Weight.Should().Be(newWeight);
}
However I keep stumble upon error such as null for the memory cache (CacheEntryFake) when I don't return the User or
"Cannot return value of type Task 1 for IMemoryCache.CreateEntry"
These are all the functions that I called within the function that I want to test
public async Task<DataEntity> GetData(string id)
{
var data = await memoryCache.GetOrCreateAsync(id, CacheFactory);
return data;
}
internal async Task<DataEntity> CacheFactory(ICacheEntry cache)
{
var data = await GetDataFromDb(cache.Key.ToString());
if (IsExpiredSession(data))
{
cache.Dispose();
}
else
{
cache.SetAbsoluteExpiration(relative);
}
return data;
}
private async Task<bool> GetInfo(string id)
{
if(setting.CacheTimeout > 0)
{
return await
memoryCache.GetOrCreateAsync(id, InfoCacheFactory):
}
return id;
}

How to choose different Lambda function while Start Streaming to Amazon Elasticsearch Service

Following this Streaming CloudWatch Logs Data to Amazon Elasticsearch Service, it's working fine to stream cloud watch log to ELK having one log group and one Lambda function.
But now I want to change target lambda function for my other logs group, but I am not able to do that as there is no option in AWS console.
Any Help will be appreciated.
Thanks
I was streaming to ELK using the AWS console option which is Start Streaming to Amazon Elasticsearch Service, But I failed to change or choose different lambda function as there is only lambda function can be selected for any log group using this option.
So, I create new lambda function and set stream target to AWS lambda function,
Here is the code that all you need, Node version for lambda function is 4.* as it was some issue with the new version but the pulse point is it does not require any extra NPM packages.
// v1.1.2
var https = require('https');
var zlib = require('zlib');
var crypto = require('crypto');
var endpoint = 'search-my-test.us-west-2.es.amazonaws.com';
exports.handler = function(input, context) {
// decode input from base64
var zippedInput = new Buffer(input.awslogs.data, 'base64');
// decompress the input
zlib.gunzip(zippedInput, function(error, buffer) {
if (error) { context.fail(error); return; }
// parse the input from JSON
var awslogsData = JSON.parse(buffer.toString('utf8'));
// transform the input to Elasticsearch documents
var elasticsearchBulkData = transform(awslogsData);
// skip control messages
if (!elasticsearchBulkData) {
console.log('Received a control message');
context.succeed('Control message handled successfully');
return;
}
// post documents to the Amazon Elasticsearch Service
post(elasticsearchBulkData, function(error, success, statusCode, failedItems) {
console.log('Response: ' + JSON.stringify({
"statusCode": statusCode
}));
if (error) {
console.log('Error: ' + JSON.stringify(error, null, 2));
if (failedItems && failedItems.length > 0) {
console.log("Failed Items: " +
JSON.stringify(failedItems, null, 2));
}
context.fail(JSON.stringify(error));
} else {
console.log('Success: ' + JSON.stringify(success));
context.succeed('Success');
}
});
});
};
function transform(payload) {
if (payload.messageType === 'CONTROL_MESSAGE') {
return null;
}
var bulkRequestBody = '';
payload.logEvents.forEach(function(logEvent) {
var timestamp = new Date(1 * logEvent.timestamp);
// index name format: cwl-YYYY.MM.DD
var indexName = [
'prod-background-wo-' + timestamp.getUTCFullYear(), // year
('0' + (timestamp.getUTCMonth() + 1)).slice(-2), // month
('0' + timestamp.getUTCDate()).slice(-2) // day
].join('.');
var source = buildSource(logEvent.message, logEvent.extractedFields);
source['response_time'] = source["end"] - source["start"];
source['#id'] = logEvent.id;
source['#timestamp'] = new Date(1 * logEvent.timestamp).toISOString();
source['#message'] = logEvent.message;
source['#owner'] = payload.owner;
source['#log_group'] = payload.logGroup;
source['#log_stream'] = payload.logStream;
var action = { "index": {} };
action.index._index = indexName;
action.index._type = payload.logGroup;
action.index._id = logEvent.id;
bulkRequestBody += [
JSON.stringify(action),
JSON.stringify(source),
].join('\n') + '\n';
});
return bulkRequestBody;
}
function buildSource(message, extractedFields) {
if (extractedFields) {
var source = {};
for (var key in extractedFields) {
if (extractedFields.hasOwnProperty(key) && extractedFields[key]) {
var value = extractedFields[key];
if (isNumeric(value)) {
source[key] = 1 * value;
continue;
}
jsonSubString = extractJson(value);
if (jsonSubString !== null) {
source['$' + key] = JSON.parse(jsonSubString);
}
source[key] = value;
}
}
return source;
}
jsonSubString = extractJson(message);
if (jsonSubString !== null) {
return JSON.parse(jsonSubString);
}
return {};
}
function extractJson(message) {
var jsonStart = message.indexOf('{');
if (jsonStart < 0) return null;
var jsonSubString = message.substring(jsonStart);
return isValidJson(jsonSubString) ? jsonSubString : null;
}
function isValidJson(message) {
try {
JSON.parse(message);
} catch (e) { return false; }
return true;
}
function isNumeric(n) {
return !isNaN(parseFloat(n)) && isFinite(n);
}
function post(body, callback) {
var requestParams = buildRequest(endpoint, body);
var request = https.request(requestParams, function(response) {
var responseBody = '';
response.on('data', function(chunk) {
responseBody += chunk;
});
response.on('end', function() {
var info = JSON.parse(responseBody);
var failedItems;
var success;
if (response.statusCode >= 200 && response.statusCode < 299) {
failedItems = info.items.filter(function(x) {
return x.index.status >= 300;
});
success = {
"attemptedItems": info.items.length,
"successfulItems": info.items.length - failedItems.length,
"failedItems": failedItems.length
};
}
var error = response.statusCode !== 200 || info.errors === true ? {
"statusCode": response.statusCode,
"responseBody": responseBody
} : null;
callback(error, success, response.statusCode, failedItems);
});
}).on('error', function(e) {
callback(e);
});
request.end(requestParams.body);
}
function buildRequest(endpoint, body) {
var endpointParts = endpoint.match(/^([^\.]+)\.?([^\.]*)\.?([^\.]*)\.amazonaws\.com$/);
var region = endpointParts[2];
var service = endpointParts[3];
var datetime = (new Date()).toISOString().replace(/[:\-]|\.\d{3}/g, '');
var date = datetime.substr(0, 8);
var kDate = hmac('AWS4' + process.env.AWS_SECRET_ACCESS_KEY, date);
var kRegion = hmac(kDate, region);
var kService = hmac(kRegion, service);
var kSigning = hmac(kService, 'aws4_request');
var request = {
host: endpoint,
method: 'POST',
path: '/_bulk',
body: body,
headers: {
'Content-Type': 'application/json',
'Host': endpoint,
'Content-Length': Buffer.byteLength(body),
'X-Amz-Security-Token': process.env.AWS_SESSION_TOKEN,
'X-Amz-Date': datetime
}
};
var canonicalHeaders = Object.keys(request.headers)
.sort(function(a, b) { return a.toLowerCase() < b.toLowerCase() ? -1 : 1; })
.map(function(k) { return k.toLowerCase() + ':' + request.headers[k]; })
.join('\n');
var signedHeaders = Object.keys(request.headers)
.map(function(k) { return k.toLowerCase(); })
.sort()
.join(';');
var canonicalString = [
request.method,
request.path, '',
canonicalHeaders, '',
signedHeaders,
hash(request.body, 'hex'),
].join('\n');
var credentialString = [ date, region, service, 'aws4_request' ].join('/');
var stringToSign = [
'AWS4-HMAC-SHA256',
datetime,
credentialString,
hash(canonicalString, 'hex')
] .join('\n');
request.headers.Authorization = [
'AWS4-HMAC-SHA256 Credential=' + process.env.AWS_ACCESS_KEY_ID + '/' + credentialString,
'SignedHeaders=' + signedHeaders,
'Signature=' + hmac(kSigning, stringToSign, 'hex')
].join(', ');
return request;
}
function hmac(key, str, encoding) {
return crypto.createHmac('sha256', key).update(str, 'utf8').digest(encoding);
}
function hash(str, encoding) {
return crypto.createHash('sha256').update(str, 'utf8').digest(encoding);
}

attributes are not defined with babel 6

I have an Ember app with ember-computed-decorators and I have this kind of model :
import DS from 'ember-data';
import {alias} from 'ember-computed-decorators';
export default DS.Model.extend({
#alias('customData.email') email
});
It worked with ember-cli-babel version 5 but I updated to the version 6 with tranform-decorator-legacy and I have this error :
email is not defined
I reproduced it with a simple js script like this :
function dec(target, name, descriptor) {
const method = descriptor.value;
descriptor.value = function(...args) {
return 'hello';
}
}
const Foo = {
#dec test
}
console.log(Foo.test);
And I have the same error.
This works :
function dec(target, name, descriptor) {
const method = descriptor.value;
descriptor.value = function(...args) {
return 'hello';
}
}
const Foo = {
#dec
test() {
return 'test';
}
}
console.log(Foo.test());
I think #dec test is strange but it worked with babel 5. What's the solution ?
Edit
Here is what's generated by ember :
define('tiny/models/subscription', ['exports', 'ember-data', 'ember-computed-decorators'], function (exports, _emberData, _emberComputedDecorators) {
function _createDecoratedObject(descriptors) { var target = {}; for (var i = 0; i < descriptors.length; i++) { var descriptor = descriptors[i]; var decorators = descriptor.decorators; var key = descriptor.key; delete descriptor.key; delete descriptor.decorators; descriptor.enumerable = true; descriptor.configurable = true; if ('value' in descriptor || descriptor.initializer) descriptor.writable = true; if (decorators) { for (var f = 0; f < decorators.length; f++) { var decorator = decorators[f]; if (typeof decorator === 'function') { descriptor = decorator(target, key, descriptor) || descriptor; } else { throw new TypeError('The decorator for method ' + descriptor.key + ' is of the invalid type ' + typeof decorator); } } } if (descriptor.initializer) { descriptor.value = descriptor.initializer.call(target); } Object.defineProperty(target, key, descriptor); } return target; }
exports['default'] = _emberData['default'].Model.extend(_createDecoratedObject([{
key: 'mail',
initializer: function initializer() {
return _emberData['default'].attr();
}
}, {
key: 'email',
decorators: [(0, _emberComputedDecorators.alias)('mail')],
initializer: function initializer() {
return email;
}
}]));
});
Here is what's generated by ember-cli-babel version 6 :
define('tiny/models/subscription', ['exports', 'ember-data', 'ember-computed-decorators'], function (exports, _emberData, _emberComputedDecorators) {
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
function _applyDecoratedDescriptor(target, property, decorators, descriptor, context) {
var desc = {};
Object['ke' + 'ys'](descriptor).forEach(function (key) {
desc[key] = descriptor[key];
});
desc.enumerable = !!desc.enumerable;
desc.configurable = !!desc.configurable;
if ('value' in desc || desc.initializer) {
desc.writable = true;
}
desc = decorators.slice().reverse().reduce(function (desc, decorator) {
return decorator(target, property, desc) || desc;
}, desc);
if (context && desc.initializer !== void 0) {
desc.value = desc.initializer ? desc.initializer.call(context) : void 0;
desc.initializer = undefined;
}
if (desc.initializer === void 0) {
Object['define' + 'Property'](target, property, desc);
desc = null;
}
return desc;
}
var _dec, _desc, _value, _obj, _init;
exports.default = _emberData.default.Model.extend((_dec = (0, _emberComputedDecorators.alias)('mail'), (_obj = { email: email
}, (_applyDecoratedDescriptor(_obj, 'email', [_dec], (_init = Object.getOwnPropertyDescriptor(_obj, 'email'), _init = _init ? _init.value : undefined, {
enumerable: true,
configurable: true,
writable: true,
initializer: function initializer() {
return _init;
}
}), _obj)), _obj)));
});
I have the same result with babel 5.

How to enableMajor?

How could I enable Major versioning on "Pages" list? My code is not working and I don't get any errors. Any suggestions?....
_spBodyOnLoadFunctionNames.push(onPageLoad());
function onPageLoad() {
ExecuteOrDelayUntilScriptLoaded(enableMajor, 'SP.js')
}
function enableMajor() {
var ctx = new SP.ClientContext.get_current();
var list = ctx.get_web().get_lists().getByTitle('Pages');
ctx.load(list);
ctx.executeQueryAsync(
function () {
list.enableMajor = true;
},
function (sender, args) {
console.log('Request failed. ' + args.get_message() + '\n' + args.get_stackTrace());
}
);
}
UPDATE 06-15
====---------------
Major version will not set? i dont why it is not setted? Any suggestions?
<script>
var list;
function getPublishingPages(success, error) {
var ctx = SP.ClientContext.get_current();
list = ctx.get_web().get_lists().getByTitle('Pages');
var items = list.getItems(SP.CamlQuery.createAllItemsQuery());
ctx.load(items, 'Include(File)');
list.set_e
ctx.executeQueryAsync(function () {
success(items);
},
error);
}
SP.SOD.executeFunc('SP.js', 'SP.ClientContext', function () {
getPublishingPages(printPagesInfo, logError);
});
function printPagesInfo(pages) {
pages.get_data().forEach(function (item) {
var file = item.get_file();
var pageStatus = file.get_level() === SP.FileLevel.published ? 'published' : 'not published';
alert(String.format('Page {0} is {1}', file.get_name(), pageStatus));
list.set_enableVersioning(true);
list.update();
alert('Major versioning enabled');
});
}
function logError(sender, args) {
alert('An error occured: ' + args.get_message());
}
</script>
In order to enable Create major versions the following steps should be performed:
set SP.List.enableVersioning property to true
call SP.List.update Method to update the list
Example
function enableListVersioning(listTitle,success,error) {
var ctx = SP.ClientContext.get_current();
var list = ctx.get_web().get_lists().getByTitle(listTitle);
list.set_enableVersioning(true);
list.update();
ctx.executeQueryAsync(
function () {
success();
},
error);
}
//usage
enableListVersioning('Pages',
function(){
console.log('Versioning is enabled');
},
function(sender,args){
console.log('An error occured: ' + args.get_message());
});