How can I output the return value of a Method like totalAmount in an Spring Rest Entity - spring

is it possible to output a return Value totalAmount of an Entity ShoppingCart that is not a Value in the Class but a Method? So for example I have a Class Shoppingcart with a List of Items. and a Method totalAmount. Now when I make a request to the API with the URL http://localhost:8082/carts/1 I want to get a response like the following:
{
"creationDate": "2016-12-07T09:45:38.000+0000",
"items": [
{
"itemName": "Nintendo 2DS",
"description": "Konsole from Nintendo",
"price": 300.5,
"quantity": 3
},
{
"itemName": "Nintendo Classic",
"description": "Classic nintendo Console from the 80th...",
"price": 75,
"quantity": 2
}
],
"totalAmount": "1051,50",
"_links": {
"self": {
"href": "http://localhost:8082/carts/2"
},
"cart": {
"href": "http://localhost:8082/carts/2"
},
"checkout": {
"href": "http://localhost:8083/order"
}
}
}
Currently the response of an API request looks like the following:
{
"creationDate": "2016-12-07T09:45:38.000+0000",
"items": [
{
"itemName": "Nintendo 2DS",
"description": "Konsole from Nintendo",
"price": 300.5,
"quantity": 3
},
{
"itemName": "Nintendo Classic",
"description": "Classic nintendo Console from the 80th...",
"price": 75,
"quantity": 2
}
],
"_links": {
"self": {
"href": "http://localhost:8082/carts/2"
},
"cart": {
"href": "http://localhost:8082/carts/2"
},
"checkout": {
"href": "http://localhost:8083/order"
}
}
}
Is there an Annotation that do this job or something other. I tried to add it in the CartResourceProcessor (org.springframework.hateoas.ResourceProcessor) but there is only the possibility to add additional links. Or do I need to add a Class value totalAmount?

Yes you can achieve that by annotating your method with Jackson #JsonProperty annotation
Code sample
#JsonProperty("totalAmount")
public double computeTotalAmount()
{
// compute totalAmout and return it
}

And to answer the possible next question you get after reading this. How the totalAmount is calculated. Here the snippet
public Class Cart{
// some Class values
#JsonProperty("totalAmount")
public BigDecimal total(){
return items.stream()
.map(Item::total)
.reduce(BigDecimal.ZERO, BigDecimal::add);
}
}
public class Item{
// some Item values
#JsonProperty("totalAmount")
public BigDecimal total(){
return price.multiply(new BigDecimal(this.quantity));
}
}
Outputs something similar to this:
{
"creationDate": "2016-12-07T09:45:38.000+0000",
"items": [
{
"itemName": "Nintendo 2DS",
"description": "Konsole from Nintendo",
"price": 300.5,
"quantity": 3,
"totalAmount": 901.5
},
{
"itemName": "Nintendo Classic",
"description": "Classic nintendo Console from the 80th...",
"price": 75,
"quantity": 2,
"totalAmount": 150
}
],
"totalAmount": 1051.5,
"_links": {
"self": {
"href": "http://localhost:8082/carts/2"
},
"cart": {
"href": "http://localhost:8082/carts/2"
},
"checkout": {
"href": "http://localhost:8083/order"
}
}
}
Hope it helps you :)

Related

Dynamics 365 Search Resource Availability With Constraints

I've been trying to add filters to my Search Resource Availability api call following this page: Search resource availability API
No matter what I do I can't seem to filter by Organizational Unit.
Here's my http call body:
{
"Version": "3",
"IsWebApi": true,
"Requirement": {
"msdyn_fromdate": "2021-11-01T00:00:00Z",
"msdyn_todate": "2021-11-30T23:59:00Z",
"msdyn_remainingduration": 60,
"msdyn_duration": 60,
"#odata.type": "Microsoft.Dynamics.CRM.msdyn_resourcerequirement"
},
"Settings": {
"ConsiderSlotsWithProposedBookings": false,
"MovePastStartDateToCurrentDate": true,
"#odata.type": "Microsoft.Dynamics.CRM.expando"
},
"ResourceSpecification":{
"#odata.type": "Microsoft.Dynamics.CRM.expando",
"ResourceTypes#odata.type": "Collection(Microsoft.Dynamics.CRM.expando)",
"ResourceTypes": [
{
"#odata.type": "Microsoft.Dynamics.CRM.expando",
"value": "3"
}
],
"Constraints": {
"#odata.type": "Microsoft.Dynamics.CRM.expando",
"OrganizationalUnits#odata.type": "Collection(Microsoft.Dynamics.CRM.expando)",
"OrganizationalUnits":[
{
"#odata.type": "Microsoft.Dynamics.CRM.expando",
"value": "b2054232-a114-ec11-b6e7-000d3a842ab8"
}
]
}
}
}
And here's the response I get:
{
"#odata.context": "https://orga215da53.api.crm3.dynamics.com/api/data/v9.2/$metadata#Microsoft.Dynamics.CRM.msdyn_SearchResourceAvailabilityResponse",
"TimeSlots": [],
"Resources": [],
"Related": {
"#odata.type": "#Microsoft.Dynamics.CRM.expando",
"TimeSlots#odata.type": "#Collection(Microsoft.Dynamics.CRM.crmbaseentity)",
"TimeSlots": [],
"Resources#odata.type": "#Collection(Microsoft.Dynamics.CRM.crmbaseentity)",
"Resources": []
},
"Exceptions": {
"#odata.type": "#Microsoft.Dynamics.CRM.expando"
}
}
But i KNOW that that organization unit exists in CRM.
I tried changing the odata.type to the actual Organization Unit CRM type (msdyn_organizationalunit) but that just gives me an error (An error occurred while validating input parameters: System.ArgumentNullException: Value cannot be null)
What is it that I'm doing wrong?
Thanks!
Good day,
I'm not sure but maybe "Constraints" should be outside "ResourceSpecification" like:
{
"Version": "3",
"IsWebApi": true,
"Requirement": {
"msdyn_fromdate": "2021-11-01T00:00:00Z",
"msdyn_todate": "2021-11-30T23:59:00Z",
"msdyn_remainingduration": 60,
"msdyn_duration": 60,
"#odata.type": "Microsoft.Dynamics.CRM.msdyn_resourcerequirement"
},
"Settings": {
"ConsiderSlotsWithProposedBookings": false,
"MovePastStartDateToCurrentDate": true,
"#odata.type": "Microsoft.Dynamics.CRM.expando"
},
"ResourceSpecification":{
"#odata.type": "Microsoft.Dynamics.CRM.expando",
"ResourceTypes#odata.type": "Collection(Microsoft.Dynamics.CRM.expando)",
"ResourceTypes": [
{
"#odata.type": "Microsoft.Dynamics.CRM.expando",
"value": "3"
}
]
},
"Constraints": {
"#odata.type": "Microsoft.Dynamics.CRM.expando",
"OrganizationalUnits#odata.type": "Collection(Microsoft.Dynamics.CRM.expando)",
"OrganizationalUnits":[
{
"#odata.type": "Microsoft.Dynamics.CRM.expando",
"value": "b2054232-a114-ec11-b6e7-000d3a842ab8"
}
]
}
}

How to extend CollectionModel/PagedModel in Spring Hateoas?

A hypermedia response that needs to be consumed by one of my services looks like this:
{
"_embedded": {
"content": [
{
"createdBy": "...",
"createdDate": "2020-03-07T14:21:27.507Z",
"id": "...",
"name": "item1",
"_links": {
"self": {
"href": ".."
}
}
}
]
},
"_links": {
"self": {
"href": "..."
},
},
"pageNumber": 1,
"totalItems": 20,
"pageSize": 10
}
See how the paging related info is not what's expected by Spring Hateoas PagedModel which should have a single "page" property instead of individual ones for pageNumber, totalItems and pageSize:
"page": {
"size": 2,
"totalElements": 1000,
"totalPages": 500,
"number": 5
}
What I did in the end was to extend CollectionModel by adding those individual properties. This does work correctly deserialising a response shown above. But, all the CollectionModel constructors are now deprecated and the alternative is to use "CollectionModel.of", which however returns just CollectionModel.
What's the right way of customising paging information in using Spring Hateoas?
Many thanks!

change hasManyThrough() relation attribute name through accessor

I have 3 Models
Campaign PK(id)
CampaignMedium FK(campaign_id)
AccountReceivable FK(campaign_medium_id) (has an amount column)
Controller function:
public function all()
{
return Campaign::with(['customer', 'receivedPayments'])->get();
}
In Campaign Model relationships are defined as follows:
public function customer()
{
return $this->belongsTo(Customer::class);
}
public function accountReceivable()
{
return $this->hasManyThrough(AccountReceivable::class, CampaignMedium::class);
}
public function receivedPayments()
{
return $this->accountReceivable()
->selectRaw('sum(account_receivables.amount) as total')
->groupBy('campaign_id');
}
public function getReceivedPaymentsAttribute()
{
if (!array_key_exists('receivedPayments', $this->relations)) {
$this->load('receivedPayments');
}
$relation = $this->getRelation('receivedPayments')->first();
return ($relation) ? $relation->total : 0;
}
Final Output:
{
"data": [
{
"id": 8,
"name": "example",
"image": "campaign/90375849f6c3cc6b0e542a0e3e6295b890375849f6c3cc6b0e542a0e3e6295b8.jpeg",
"amount": 10,
"description": "saddsa",
"start_at": "2019-02-12 00:00:00",
"end_at": "2019-02-12 00:00:00",
"due_at": "2019-02-12 00:00:00",
"status": "active",
"customer": {
"id": 1,
"name": "test",
"email": "info#test.com",
"image": "customer/ec812116705ff3ae85298234fe6c4e97ec812116705ff3ae85298234fe6c4e97.jpeg",
"address": "sample address"
},
"received_payments": [
{
"total": "700",
"laravel_through_key": 8
}
]
},
{
"id": 9,
"name": "example",
"image": "campaign/fff9fadc92a809513dc28134379851aafff9fadc92a809513dc28134379851aa.jpeg",
"amount": 10,
"description": "saddsa",
"start_at": "2019-02-12 00:00:00",
"end_at": "2019-02-12 00:00:00",
"due_at": "2019-02-12 00:00:00",
"status": "active",
"customer": {
"id": 1,
"name": "test",
"email": "info#test.com",
"image": "customer/ec812116705ff3ae85298234fe6c4e97ec812116705ff3ae85298234fe6c4e97.jpeg",
"address": "sample address"
},
"received_payments": []
}
]
}
summary: trying to get the sum of AccountReceivable amount attribute, which is working fine but the getReceivedPaymentsAttribute() isn't working which needs to return the total value only. also can anyone please help me to explain why laravel_through_key is added with received_payments?
I've never tried to use an attribute modifier to modify a relation this way. You are overriding the expected result of receivedPayments(). You might be better off to define a separate attribute like so:
public function getSumReceivedPaymentsAttribute()
{
// ...your code...
}
Now you can access the attribute using $model->sum_received_payments or always preload it using:
// model.php
protected $appends = ['sum_received_payments'];

NLog: LayoutRenderer cannot be found: 'aspnet-user-identity

I try to implement NLog into my .NET Core Api web service.
I want to log to an Oracle database. All works well through an nlog.config XML file.
But the goal is to implement NLog config into appsettings.json and here problem occurs.
I get the error set in title:
LayoutRenderer cannot be found: 'aspnet-user-identity
My config file is like this :
"NLog": {
"autoReload": true,
"throwConfigExceptions": true,
"internalLogLevel": "info",
"internalLogFile": "c:/app/log/dev/internal-appsetting-nlog.txt",
"extensions": {
"NLog.Extensions.Logging": {
"assembly": [
"NLog.Extensions.Logging",
"NLog.Web.AspNetCore"
]
}
},
"variables": {
"var_logdir": "c:/app/log/dev"
},
"default-wrapper": {
"type": "AsyncWrapper",
"overflowAction": "Block"
},
"targets": {
"all-file": {
"type": "File",
"fileName": "${var_logdir}/nlog-all-${shortdate}.log",
"layout": {
"type": "JsonLayout",
"Attributes": [
{
"name": "timestamp",
"layout": "${date:format=o}"
},
{
"name": "level",
"layout": "${level}"
},
{
"name": "logger",
"layout": "${logger}"
},
{
"name": "message",
"layout": "${message:raw=true}"
},
{
"name": "properties",
"encode": false,
"layout": {
"type": "JsonLayout",
"includeallproperties": "true"
}
}
]
}
},
"db": {
"type": "Database",
"commandText": "INSERT INTO logtable (LOGLEVEL,LOGGER,MESSAGE,MACHINENAME,USERNAME,CALLSITE, THREADID,EXCEPTIONMESSAGE,STACKTRACE,SESSIONID) VALUES (:pLEVEL,:pLOGGER,:pMESSAGE,:pMACHINENAME, :pCALLSITE,:pTHREADID,:pEXCEPTIONMESSAGE,:pSTACKTRACE)",
"parameters": [
{
"name": "#pLEVEL",
"layout": "${level}"
},
{
"name": "#pLOGGER",
"layout": "${logger}"
},
{
"name": "#pMESSAGE",
"layout": "${message}"
},
{
"name": "#pMACHINENAME",
"layout": "${machinename}"
},
{
"name": "#pUSERNAME",
"layout": "${aspnet-user-identity}"
},
{
"name": "#pCALLSITE",
"layout": "${callsite:filename=true}"
},
{
"name": "#pTHREADID",
"layout": "${threadid}"
},
{
"name": "#pEXCEPTIONMESSAGE",
"layout": "${exception}"
},
{
"name": "#pSTACKTRACE",
"layout": "${stacktrace}"
},
{
"name": "#pSESSIONID",
"layout": "${aspnet-sessionid}"
}
],
"dbProvider": "Oracle.ManagedDataAccess.Client.OracleConnection, Oracle.ManagedDataAccess",
"connectionString": "xxxxxxxxxxxx"
}
},
"rules": [
{
"logger": "*",
"minLevel": "Trace",
"writeTo": "all-file"
},
{
"logger": "*",
"minLevel": "Trace",
"writeTo": "db"
},
{
"logger": "Microsoft.*",
"maxLevel": "Info",
"final": true
}
]
},
The internal debugger reports:
2019-10-09 16:48:48.6665 Info Adding target AsyncTargetWrapper(Name=all-file)
2019-10-09 16:48:48.7859 Warn Error when setting property 'Layout' on 'NLog.Targets.DatabaseParameterInfo' Exception: System.ArgumentException: LayoutRenderer cannot be found: 'aspnet-user-identity'. Is NLog.Web not included?
at NLog.Config.Factory`2.CreateInstance(String itemName)
at NLog.Layouts.LayoutParser.GetLayoutRenderer(ConfigurationItemFactory configurationItemFactory, String name)
at NLog.Layouts.LayoutParser.ParseLayoutRenderer(ConfigurationItemFactory configurationItemFactory, SimpleStringReader stringReader)
at NLog.Layouts.LayoutParser.CompileLayout(ConfigurationItemFactory configurationItemFactory, SimpleStringReader sr, Boolean isNested, String& text)
at NLog.Layouts.SimpleLayout.set_Text(String value)
at NLog.Internal.PropertyHelper.TryNLogSpecificConversion(Type propertyType, String value, Object& newValue, ConfigurationItemFactory configurationItemFactory)
at NLog.Internal.PropertyHelper.SetPropertyFromString(Object obj, String propertyName, String value, ConfigurationItemFactory configurationItemFactory)
Error occurs on ${aspnet-sessionid}. If I comment out both layout, everything works well.
I found different things on GitHub issue report but all I tried was a fail.
Could someone help?
The unknown aspnet-user-identity is probably an issue with your extensions:
"extensions": [
{ "assembly": "NLog.Extensions.Logging" },
{ "assembly": "NLog.Web.AspNetCore" }
],
Could you try the above suggestion?
P.S. Updated the wiki to include example of multiple "extensions"

Data format issue for related models (Laravel / jenssegers/laravel-mongodb)

Here is an open bug on Github for the laravel-mongodb package, but there is no response. Maybe someone knows a solution..?
When selecting as single doc, dates displays as a date
{
"_id": "5ca71ce0d542352064004034",
"title": "General review",
"status": "active",
"start_date": "2019-04-05 09:16:16.000000",
"end_date": "2038-01-19 03:14:07.000000",
"start_review_date": "2019-04-05 09:16:16.000000",
"submission_fee": 100,
"reward": 0,
"is_general_review_round": true,
"created_at": "2019-04-05 09:16:16.000000",
"updated_at": "2019-04-05 09:16:16.000000",
"proposals": [],
"demography": null
}
But on select as related object (nested array) I have this date conversion issue...
{
"title": "Omnis perspiciatis aut voluptatem dolores vel repudiandae.",
"start_date": {
"$date": {
"$numberLong": "1554542206000"
}
},
"end_date": {
"$date": {
"$numberLong": "1556183806000"
}
},
"start_review_date": {
"$date": {
"$numberLong": "1555406206000"
}
},
"updated_at": {
"$date": {
"$numberLong": "1554455806312"
}
},
"created_at": {
"$date": {
"$numberLong": "1554455806312"
}
}
}
Dates can be formatted from parent model:
If your parent model is User and you are embedding UserDetails you could cast dates this way:
public function userDetails()
{
return $this->embedsOne('UserDetails');
}
protected $dates = ['userDetails.created_at', 'userDetails.updated_at'];

Resources