cannot convert from 'void' to 'object' API - azure

I'm not sure where the void is coming from... or how to fix it.
the value of "body" is:
{
"sourceInstance": "string",
"sourceEnvironment": "string",
"webLinkMODetails": [{
"objectName": "string",
"genericTextKey": "string",
"webLinkName": "string",
"webLinkURL": "string"
}]
}
<set-body>
#{
JObject apimBody = JObject.Parse((string)context.Variables["body"]);
string env = apimBody["sourceEnvironment"].ToString();
string inst = apimBody["sourceInstance"].ToString();
if(inst == "CNL" || inst == "TCO") {
if(env == "PD") {
apimBody.Add(new JProperty("environment", "J" + inst + "PRD"));
}
else {
apimBody.Add(new JProperty("environment", "J" + inst + env));
}
}
else {
apimBody.Add(new JProperty("environment", "J" + env + inst));
}
apimBody.Add(new JProperty("webLinkMODetails", new JArray(
apimBody.Add(new JProperty("objectName", apimBody["objectName"])),
apimBody.Add(new JProperty("genericTextKey", apimBody["genericTextKey"])),
apimBody.Add(new JProperty("webLinkName", apimBody["webLinkName"])),
apimBody.Add(new JProperty("webLinkURL", apimBody["webLinkUrl"]))
)));
apimBody.Property("sourceEnvironment").Remove();
apimBody.Property("sourceInstance").Remove();
return apimBody.ToString();
}
</set-body>
This is part of a POST policy. where the response should be:
I have tried other formats of passing values, but its either this error or a user/pass error which indicates that my evn/inst are not read properly.
{
"addURLWOMediaObject_Repeating": [
{
"objectName": "string",
"genericTextKey": "string",
"webLinkName": "string",
"webLinkURL": "string",
}
]
}

Related

Issue while rendering OpenAPI spec json in terraform rest api gateway resource

I wanted to pass some variables while rendering the json file of OpenAPI spec through the template file but it shows the below changes.
Code:
resource.tf
resource "aws_api_gateway_rest_api" "default" {
body = jsonencode(var.routes)
name = "dev-api-gateway-fargate"
endpoint_configuration {
types = ["REGIONAL"]
}
}
main.tf
module "api_gateway_new" {
source = "../../../modules/api-gateway/new/"
routes = templatefile("${path.module}/routes.tpl",{
url = "https://ip-ranges.amazonaws.com/ip-ranges.json"
}
)
}
Terraform Plan
~ resource "aws_api_gateway_rest_api" "default" {
~ body = jsonencode(
~ {
- info = {
- title = "example"
- version = "1.0"
}
- openapi = "3.0.1"
- paths = {
- "/path1" = {
- get = {
- x-amazon-apigateway-integration = {
- httpMethod = "GET"
- payloadFormatVersion = "1.0"
- type = "HTTP_PROXY"
- uri = "https://ip-ranges.amazonaws.com/ip-ranges.json"
}
}
}
}
} -> <<-EOT
{
openapi = "3.0.1"
info = {
title = var.rest_api_name
version = "1.0"
}
paths = {
"/v1/alerts" = {
get = {
x-amazon-apigateway-integration = {
httpMethod = "GET"
payloadFormatVersion = "1.0"
type = "HTTP_PROXY"
uri = "https://ip-ranges.amazonaws.com/ip-ranges.json"
}
}
}
}
}
EOT
)
id = "mxktrgeypg"
name = "dev-api-gateway-fargate"
tags = {}
# (10 unchanged attributes hidden)
# (1 unchanged block hidden)
}
routes.tpl
{
openapi = "3.0.1"
info = {
title = var.rest_api_name
version = "1.0"
}
paths = {
"/v1/alerts" = {
get = {
x-amazon-apigateway-integration = {
httpMethod = "GET"
payloadFormatVersion = "1.0"
type = "HTTP_PROXY"
uri = "${url}"
}
}
}
}
}
There is an error in the template file as it seems you were trying to add a name for the API but you provided var.rest_api_name which is treated as a literal. In order to fix this, there are two changes that need to take place, one in the module call and one in the template file itself.
module "api_gateway_new" {
source = "../../../modules/api-gateway/new/"
routes = templatefile("${path.module}/routes.tpl",{
url = "https://ip-ranges.amazonaws.com/ip-ranges.json",
name = var.rest_api_name
}
)
}
Then, in the template file:
{
openapi = "3.0.1"
info = {
title = "${name}" # this has changed
version = "1.0"
}
paths = {
"/v1/alerts" = {
get = {
x-amazon-apigateway-integration = {
httpMethod = "GET"
payloadFormatVersion = "1.0"
type = "HTTP_PROXY"
uri = "${url}"
}
}
}
}
}
Since the template file is almost JSON formatted already, I would suggest changing the file to look like this:
{
"openapi": "3.0.1",
"info": {
"title": "${name}",
"version": "1.0"
},
"paths": {
"/v1/alerts": {
"get": {
"x-amazon-apigateway-integration": {
"httpMethod": "GET",
"payloadFormatVersion": "1.0",
"type": "HTTP_PROXY",
"uri": "${url}"
}
}
}
}
}
And then you can drop the jsonencode form the module code:
resource "aws_api_gateway_rest_api" "default" {
body = var.routes
name = "dev-api-gateway-fargate"
endpoint_configuration {
types = ["REGIONAL"]
}
}
Also, this should work for creating an OpenAPI spec, but the validation of this code says it is missing a responses section. So for the sake of testing if it works, you could add the responses:
{
"openapi": "3.0.1",
"info": {
"title": "${name}",
"version": "1.0"
},
"paths": {
"/v1/alerts": {
"get": {
"responses": {
"200": {
"description": "200 response",
"content": {
"application/json": {
"schema": {
"$ref" : "#/components/schemas/Empty"
}
}
}
}
},
"x-amazon-apigateway-integration": {
"httpMethod": "GET",
"payloadFormatVersion": "1.0",
"type": "HTTP_PROXY",
"uri": "${url}"
}
}
}
},
"components": {
"schemas": {
"Empty": {
"title": "Empty Schema",
"type": "object"
}
}
}
}
I have used [1] to validate the OpenAPI spec, so if it is still complaining, the tool should give you a pretty good idea of what is missing/wrong.
[1] https://apitools.dev/swagger-parser/online/

Find and convert values in nested dict and update db collection

I have converted many xml files to json using xmltodict and inserted those in arangodb.
Now I well loop over the collection and change some values in the database. LIke day, mount and year from string to int. The documents can be very nested and the values that I well change can be in different places.
This is what I have of the code.
# Get the API wrapper for "FORM16" collection.
FORM16 = db.collection('FORM16')
def recursive_items(dictionary):
for key, value in dictionary.items():
if type(value) is dict:
yield from recursive_items(value)
else:
yield (key, value)
search_key = 'LOW_VALUE'
for item in FORM16:
for key, value in recursive_items(item):
if search_key in list(key):
item[search_key] = int(item[search_key])
else:
pass
FORM16.update(item)
{'_id': 'FORM16/2098312',
'_key': '2098312',
'_rev': '_blGxlRi---',
'_old_rev': '_blGvpVO---'}
The code runs but It won’t update the database and the document that I receive that has changed is only the last document in the collection.
What do I have to change in the code to convert values in keys like day, mount and year to int?
EDIT:
This is one of the nested json's doc. that I well update
{
"DOFFIN_ESENDERS": {
"DOFFIN_APPENDIX": {
"AUTHORITY_ORGANISATION_NR": "986 105 174",
"DOFFIN_FORM_TYPE": {
"NATIONAL": {
"EXPRESSION_OF_INTEREST_URL": "https://kgv.doffin.no/ctm/Supplier/Notice/260549",
"EXTERNAL_DOCUMENT_URL": "https://kgv.doffin.no/ctm/Supplier/Documents/Folder/124452",
"LOCATION": {
"NATIONWIDE": null
},
"PUBLISH_TO_TED": null
}
}
},
"FORM_SECTION": {
"PRIOR_INFORMATION_DEFENCE": {
"CATEGORY": "ORIGINAL",
"FD_PRIOR_INFORMATION_DEFENCE": {
"AUTHORITY_PRIOR_INFORMATION_DEFENCE": {
"NAME_ADDRESSES_CONTACT_PRIOR_INFORMATION": {
"CA_CE_CONCESSIONAIRE_PROFILE": {
"ADDRESS": "Postboks 800, Postmottak",
"ATTENTION": "Ole Jan Skoglund",
"CONTACT_POINT": "Forsvarets logistikkorganisasjon",
"COUNTRY": {
"VALUE": "NO"
},
"E_MAILS": {
"E_MAIL": "olskoglund#mil.no"
},
"FAX": "+47 67863799",
"ORGANISATION": {
"NATIONALID": "986105174",
"OFFICIALNAME": "Forsvarets logistikkorganisasjon"
},
"PHONE": "+47 67863787",
"POSTAL_CODE": "LILLEHAMMER",
"TOWN": "N-2617"
},
"FURTHER_INFORMATION": {
"IDEM": null
},
"INTERNET_ADDRESSES_PRIOR_INFORMATION": {
"URL_BUYER": "https://kgv.doffin.no/ctm/Supplier/CompanyInformation/Index/1127",
"URL_GENERAL": "http://www.forsvaret.no"
}
},
"TYPE_AND_ACTIVITIES_OR_CONTRACTING_ENTITY_AND_PURCHASING_ON_BEHALF": {
"PURCHASING_ON_BEHALF": {
"PURCHASING_ON_BEHALF_NO": null
},
"TYPE_AND_ACTIVITIES": {
"TYPE_OF_ACTIVITY": {
"VALUE": "DEFENCE"
},
"TYPE_OF_CONTRACTING_AUTHORITY": {
"VALUE": "MINISTRY"
}
}
}
},
"CTYPE": "SUPPLIES",
"LEFTI_PRIOR_INFORMATION": null,
"OBJECT_WORKS_SUPPLIES_SERVICES_PRIOR_INFORMATION": {
"ADDITIONAL_INFORMATION": {
"P": "Konkurransen vil bli utført som en forhandlet prosedyre etter en planlagt kunngjøring ultimo 2015 i henhold til “Forskrift 4. oktober 2013 nr. 1185 om forsvars og sikkerhetsanskaffelser“ basert på Eu direktiv 2009/81/EC fra Europa Parlamentet."
},
"CPV": {
"CPV_ADDITIONAL": [
{
"CPV_CODE": {
"CODE": "18900000"
}
},
{
"CPV_CODE": {
"CODE": "18930000"
}
},
{
"CPV_CODE": {
"CODE": "18937000"
}
},
{
"CPV_CODE": {
"CODE": "33000000"
}
},
{
"CPV_CODE": {
"CODE": "33120000"
}
},
{
"CPV_CODE": {
"CODE": "33124000"
}
},
{
"CPV_CODE": {
"CODE": "33140000"
}
},
{
"CPV_CODE": {
"CODE": "33141000"
}
},
{
"CPV_CODE": {
"CODE": "33141100"
}
},
{
"CPV_CODE": {
"CODE": "33141200"
}
},
{
"CPV_CODE": {
"CODE": "33141300"
}
},
{
"CPV_CODE": {
"CODE": "50400000"
}
}
],
"CPV_MAIN": {
"CPV_CODE": {
"CODE": "33100000"
}
}
},
"FRAMEWORK_AGREEMENT": {
"VALUE": "YES"
},
"QUANTITY_SCOPE_WORKS_DEFENCE": {
"COSTS_RANGE_AND_CURRENCY": {
"CURRENCY": "NOK",
"RANGE_VALUE_COST": {
"HIGH_VALUE": "200000000",
"LOW_VALUE": "150000000"
}
},
"F16_DIVISION_INTO_LOTS": {
"DIV_INTO_LOT_NO": null
},
"TOTAL_QUANTITY_OR_SCOPE": {
"P": "Forsvarets logistikkorganisasjon planlegger å skifte ut Forsvarets prehospitale sanitetssystem. Vi ser derfor etter en systemleverandør som kan levere test moduler, store initielle systemleveranser og ta ansvar for effektiv etterforsyning til Forsvaret på rammeavtaler med inntil syv års varighet."
}
},
"SCHEDULED_DATE_PERIOD": {
"PERIOD_WORK_DATE_STARTING": {
"MONTHS": "84"
}
},
"TITLE_CONTRACT": {
"P": "RFI P9346 -Nytt Prehospital Sanitetssystem til Forsvaret"
},
"TYPE_CONTRACT_PLACE_DELIVERY_DEFENCE": {
"SITE_OR_LOCATION": {
"LABEL": "N-2055 Nordkisa",
"NUTS": {
"CODE": "NO"
}
},
"TYPE_CONTRACT_PI_DEFENCE": {
"TYPE_CONTRACT": {
"VALUE": "SUPPLIES"
}
}
}
},
"OTH_INFO_PRIOR_INFORMATION": {
"ADDITIONAL_INFORMATION": {
"P": "Vi ønsker svar både fra Systemleverandører og Underleverandører på denne RFI."
},
"INFORMATION_REGULATORY_FRAMEWORK": {
"TAX_LEGISLATION": {
"TAX_LEGISLATION_VALUE": "www.lovdata.no"
}
},
"NOTICE_DISPATCH_DATE": {
"DAY": "28",
"MONTH": '11',
"YEAR": "2014"
},
"RELATES_TO_EU_PROJECT_NO": null
}
},
"FORM": "16",
"LG": "NB",
"VERSION": "R2.0.8.S02"
}
},
"VERSION": "V2.0.0",
"http://www.w3.org/2001/XMLSchema-instance:noNamespaceSchemaLocation": "DOFFIN_ESENDERS.xd",
"xmlns": {
"xsi": "http://www.w3.org/2001/XMLSchema-instance"
}
}
}
It looks like your code is correct, assuming the JSON blob at the bottom is a representation of item. Just make sure the data you're passing to .update() includes a valid _key and/or _id attribute.
However, it looks like your update statement is not indented properly and/or out of order. I would put the update inline, when you make the change:
FORM16 = db.collection('FORM16')
for item in FORM16:
for key, value in recursive_items(item):
if search_key in list(key):
item[search_key] = int(item[search_key])
FORM16.update(item)
else:
pass
or in the top-level for loop:
FORM16 = db.collection('FORM16')
for item in FORM16:
for key, value in recursive_items(item):
if search_key in list(key):
item[search_key] = int(item[search_key])
else:
pass
FORM16.update(item)
I did find a functin for convert sting to int and float in JSON files.
def _decode(o):
# Note the "unicode" part is only for python2
if isinstance(o, str):
try:
return int(o)
except ValueError:
try:
return float(o)
except ValueError:
return o
elif isinstance(o, dict):
return {k: _decode(v) for k, v in o.items()}
elif isinstance(o, list):
return [_decode(v) for v in o]
else:
return o
path = 'C:/doffin/test/'
for filename in os.listdir(path):
if not filename.endswith('.json'):
continue
#26  
#fullname = os.path.join(path, filename)
fullname = os.path.join(path, filename)
with open(fullname, 'rb') as f:
jsonstr = f.read()
json_sting = json.loads(jsonstr, object_hook=_decode)
json_str2 = json.dumps(json_sting)
with open(fullname[:-4] + ".json", 'w') as f:
f.write(json_str2)
and afther that I use arango import form the shell. It works better then the API.

Groovy: Convert Json to Text

Would like to convert the below json record into a text using Groovy
import groovy.json.*
def js = """{
"title": {
"titleid": "222",
"titlename": "ABCD",
"titledesc": null
},
"customer": {
"customerDetail": {
"customerid": 878378743,
"customerstatus": "ACTIVE",
"customersystems": {
"customersystem1": "SYS01",
"customersystem2": null
},
"sysid": null
},
"store": {
"storeid": "LOS002",
"storename": "LAStore",
"areacode": "JDHJ8K988"
},
"persons": {
"person1": {
"personid": "123",
"personname": "IIISKDJKJSD"
},
"person2": {
"personid": "456",
"personname": "IUDFIDIKJK"
}
},
"order": {
"orderdetail": {
"orderid": "4291026",
"ordername": "ORD93999"
}
},
"product": {
"orderdate": "20190101",
"currency": "USD",
"amount": 1000.23
}
}
}
"""
def data = new JsonSlurper().parseText(js)
Expected output should as below with proper header names:
customerId,customerstatus,customersystem1,sysid,storeid,storename,person1.personid,person1.personname,orderid,orderdate,currency,amount,titlename
878378743,ACTIVE,SYS01,null,LOS002,LAStore,123,IIISKDJKJSD,4291026,20190101,USD,1000.23
This is just a single json record so how would I convert all my json records using Groovy?
The following code:
import groovy.json.*
def js = """
[
{
"title": {
"titleid": "222",
"titlename": "ABCD",
"titledesc": null
},
"customer": {
"customerDetail": {
"customerid": 878378743,
"customerstatus": "ACTIVE",
"customersystems": {
"customersystem1": "SYS01",
"customersystem2": null
},
"sysid": null
},
"store": {
"storeid": "LOS002",
"storename": "LAStore",
"areacode": "JDHJ8K988"
},
"persons": {
"person1": {
"personid": "123",
"personname": "IIISKDJKJSD"
},
"person2": {
"personid": "456",
"personname": "IUDFIDIKJK"
}
},
"order": {
"orderdetail": {
"orderid": "4291026",
"ordername": "ORD93999"
}
},
"product": {
"orderdate": "20190101",
"currency": "USD",
"amount": 1000.23
}
}
}
]
"""
/*
customerId,customerstatus,customersystem1,sysid,storeid,storename,person1.personid,person1.personname,orderid,orderdate,currency,amount,titlename
878378743,ACTIVE,SYS01,null,LOS002,LAStore,123,IIISKDJKJSD,4291026,20190101,USD,1000.23
*/
def data = new JsonSlurper().parseText(js)
def mappings = [
customerId: { n -> n.customer.customerDetail.customerid },
customerstatus: { n -> n.customer.customerDetail.customerstatus },
customersystem1: { n -> n.customer.customerDetail.customersystems.customersystem1 },
sysid: { n -> n.customer.customerDetail.sysid },
storeid: { n -> n.customer.store.storeid },
storename: { n -> n.customer.store.storename },
'person1.personid': { n -> n.customer.persons.person1.personid },
'person1.personname': { n -> n.customer.persons.person1.personname },
orderid: { n -> n.customer.order.orderdetail.orderid },
orderdate: { n -> n.customer.product.orderdate },
currency: { n -> n.customer.product.currency },
amount: { n -> n.customer.product.amount },
titlename: { n -> n.title.titlename }
]
def headers = mappings.keySet().join(',') //edited thanks to comment
println headers
data.each { item ->
def row = mappings.collect { k, v -> v(item) }.join(',')
println row
}
does what you ask for. Note that I made the json be a list of items instead of the single item since it seemed from your text that that is what you were after.
Running the above code produces:
~> groovy solution.groovy
customerId,customerstatus,customersystem1,sysid,storeid,storename,person1.personid,person1.personname,orderid,orderdate,currency,amount,titlename
878378743,ACTIVE,SYS01,null,LOS002,LAStore,123,IIISKDJKJSD,4291026,20190101,USD,1000.23,ABCD
~>
note that if this is going into some critical system and is not just a one-off ad-hoc piece of code, you should probably do things like check the return value of v(item) and log some error of otherwise handle when there is no value for a certain path in the json etc.
Should also be noted that the above code relies on the fact that a map literal in groovy (i.e. def mappings = [:]) creates an instance of java's LinkedHashMap which has predictable iteration order for things like keySet() and collect { }.
<< edit >>
For a single item json blob, you would change the code as follows:
def js = """
{
...
}
"""
def item = new JsonSlurper().parseText(js)
def mappings = ...
def headers = mappings.keySet().join(',') //edited thanks to comment
println headers
def row = mappings.collect { k, v -> v(item) }.join(',')
println row
where ... denotes that the block is unchanged from the example above.

Validate the schema

How can we validate the written schema valid or not .
const schema = {
"properties": {
"foo": { "add": "string" , "minLenfeffgth": 3, "maxLefngth": 255 }
}
};
above mention schema are valid schema according to ajv.validateSchema() .
like we validating the data , there is any function who validate the schema .
complete code :
var Ajv = require('ajv');
var ajv = new Ajv({ allErrors: true});
const schema = {
"properties": {
"foo": { "add": "string" , "minLenfeffgth": 3, "maxLefngth": 255 }
}
};
// console.log(ajv.validateSchema(schema));
var validate = ajv.compile(schema);
test({"foo": ""});
function test(data) {
var valid = validate(data);
if (valid) console.log('Valid!');
else console.log(validate.errors);
}
result is : valid
You can configure Ajv to throw errors and use compile:
var ajv = new Ajv({
allErrors: true
});
var schema = {
type: 'object',
properties: {
date: {
type: 'unexisting-type'
}
}
};
try {
var validate = ajv.compile(schema);
} catch (e) {
console.log(e.message);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/ajv/6.6.2/ajv.min.js"></script>
above mention schema are valid schema according to ajv.validateSchema().
It's valid but it validated nothing, if you want to test a simple object with a foo mandatory property, you can do something like that :
var ajv = new Ajv({
allErrors: true
});
var schema = {
"$schema": "http://json-schema.org/draft-07/schema#",
"type": "object",
"properties": {
"foo": {
"type": "string",
"minLength": 3,
"maxLength": 255
}
},
"required": [
"foo"
]
};
try {
var validate = ajv.compile(schema);
test({"foo": "" });
} catch (e) {
console.log("Validate error :" + e.message);
}
function test(data) {
var valid = validate(data);
if (valid) {
console.log('Valid!');
} else {
console.log(validate.errors);
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/ajv/6.6.2/ajv.min.js"></script>
Run with data = {"foo": "" } return the error message below :
[
{
"keyword": "minLength",
"dataPath": ".foo",
"schemaPath": "#/properties/foo/minLength",
"params": {
"limit": 3
},
"message": "should NOT be shorter than 3 characters"
}
]
Run with data = {"foo": "abcdef" } return the message below :
Valid!

how to generate and store UUDI for a device in loopback an

I want to make a web service to generate UUID and store it with Loopback in a table something like
http://localhost:3000/api/getuudi
The functions for token and uuid are working fine but I dont know where should I had to place for example uuid to get token and store in table
function generateUUID() {
var d = new Date().getTime();
if(window.performance && typeof window.performance.now === "function"){
d += performance.now();; //use high-precision timer if available
}
var uuid = 'xxxxxxxxxxxx7xxxyxxxxxxxxxxxxxxx'.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;
};
Token
function generateToken() {
var d = new Date().getTime();
if(window.performance && typeof window.performance.now === "function"){
d += performance.now();; //use high-precision timer if available
}
var uuid = 'xxxxxxxxxxxx9xxxyxxxxxxxxxxxxxxx'.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;
};
UUDI.json
"name": "UUDI",
"plural": "getuudi",
"base": "PersistedModel",
"idInjection": true,
"options": {
"validateUpsert": true
},
"properties": {
"uuid": {
"type": "string",
"required": true
},
"date": {
"type": "string",
"required": true
},
"time": {
"type": "string",
"required": true
}
},
"validations": [],
"relations": {},
"acls": [],
"methods": {}
}
You can generate uuid using loopback functional properties.
Check - https://loopback.io/doc/en/lb3/Model-definition-JSON-file.html#properties

Resources