how to call a private function from another class if the instance of the object is already there in kotlin? - function

i want to call this function from another class - OneOffPaymentService
fun toPaymentRequestHistoryEvent(): PaymentRequestHistoryEvent {
return PaymentRequestHistoryEvent(
id = this.id,
userId = this.userId,
paymentDate = this.paymentDate,
type = this.type,
amount = this.amount
)
}
i tried to call this from another class OneOffPaymentService and WithdrawalService

i did this
checkPartialWithdrawalConditions(userId, accountId, amountToWithdraw)
val avaloqRequest = PartialWithdrawalAvaloqRequest(amountToWithdraw, refData.withdrawalDescription())
avaloqPaymentClient.makePartialWithdrawal(userId, accountId, avaloqRequest)
paymentRequestRecorder.recordPartialWithdrawal(userId, amount, LocalDate.now(clock))
.also { analyticsSqsPublisher.publishPaymentHistoryEvent(it.toPaymentRequestHistoryEvent()) }

Related

Derived classes' properties not getting value

Say one has an abstract Car class with a derived Cabrio class.
From a REST api he recieves a JSON with data
abstract class Car {
int id;
String name;
String description;
Car({
this.id,
this.name,
this.description,
});
factory Car.fromJson(Map<String, dynamic> json, String type) {
Car car;
if (type == 'cabrio') car = Cabrio.fromJson(json);
// other possible if-statements
car.id = int.parse(json['id']);
car.name = json['name'];
car.description = json['description'];
return car;
}
class Cabrio extends Car {
String roofMaterial;
String someOtherProp;
Cabrio({
id,
name,
this.roofMaterial,
this.someOtherProp
}) : super(
id: id,
name: name,
description: description);
factory Cabrio.fromJson(Map<String, dynamic> json) =>
Cabrio(
roofMaterial: json['roof_material'],
someOtherProp: json['some_other_prop']
);
}
dynamic dyn = jsonDecode(response.body);
Cabrio cabrio = Car.fromJson(dyn[0], 'cabrio');
cabrio.roofMaterial // null
cabrio.someOtherProp // null
return cabrio;
Why is cabrio.roofMaterial or cabrio.someOtherProp null ?
Why I am taking this approach
I didn't like seeing for example
id: json['id']
in all derived classes. This approach is to prevent such redundancy
What I know
according to the debugger, the properties of the derived class Cabrio are set correctly by the json values in it's fromJson
when inspecting the car object at car.name = json['name'] the derived class' properties (like cabrio.roofMaterial) are already null
What I consider to be a problem
at
if (type == 'cabrio') car = Cabrio.fromJson(json, type);
I am 'pushing' a cabrio object into a Car object (which has less properties than Cabrio). But that should not be wrong since it's just a parent class type
What you're needing in this example is an explicit type cast after you call Car.fromJson(...) to ensure that the type you're dealing with is Cabrio which has the extra fields rather than an instance of Car
final cabrio = Car.fromJson(json, 'cabrio') as Cabrio;
I spent some time to update your code to a newer version of Dart with the changes required to ensure that these fields were no longer null
https://gist.github.com/MarkOSullivan94/60ce6625538e16f373c5c1d6254952e9

post request of HttpClient of angular is not sending the proper data to server

In my below code, request is holding data {widgetName: "widgetName", widgetCriteria: "Activities", followUpDate: "1591727400000", uid: "someId"}
let request = JSON.parse(JSON.stringify(Object.assign(this.registrationForm.value, ...req)));
delete request.widgetFIlterOptions;
let uid = JSON.parse(window.localStorage.getItem("user")).uid;
request.uid = uid;
this.openWindow = false;
console.info("request-->", request);
this.contactService.addWidget(request).subscribe(res=> {
this.emService.updateWidgits();
})
Inside addWidget() function/method we are calling post request.
but after calling post request ResetController class should receive "followUpDate" with the other data. However in my case "followUpDate" is missing but I can see other data.
Can anyone help in this matter? What I am missing here? I am new to Angular.
addWidget(widget, data?) {
console.info("widget-->", widget); // here followUpDate is present
this.http.post(this.api.createWidget, widget).pipe(map(data => {
console.info("data-->", data); // this does not have the followUpDate.
let message = "Widget created successfully";
data['data'] = this.filterWidgets(data).length > 0 ? this.filterWidgets(data): alert("No data Available");
this.widgets.unshift(data);
this.toastr.success(message);
}),catchError(err => {
this.toastr.error(err.error);
return throwError(err);
}));
Below is my rest controller class
#RestController
public class DashboardController {
#Autowired
Service service;
#PostMapping(path = "createcriteria", produces = MediaType.APPLICATION_JSON_VALUE, consumes = MediaType.APPLICATION_JSON_VALUE)
#ApiOperation(value = "create the deal", response = Dashboard1.class)
public Dashboard1 saveCriteria(#RequestBody Dashboard1 dashboard1) {
System.out.println(dashboard1); // here "followUpDate" is missing
return service.saveCriteria(dashboard1);
}
}
Below is my Dashboard1 class
#Document(collection = "Dashboard1")
#JsonInclude(Include.NON_NULL)
public class Dashboard1 {
#Id
#ApiModelProperty(notes = "The database generated product ID")
private String id;
#Field(value = "widgetname")
private String WidgetName = null;
#Field(value = "widgetcriteria")
private String WidgetCriteria = null;
#Field(value = "uid")
private String uid = null;
#Field(value = "activitytype")
private String activityType = null;
#Field(value = "contactname")
private String contactName = null;
#Field(value = "updateby")
private String updateBy = null;
#Field(value = "followUpDate")
private String followUpDate = null;
// below all the getters, setters and toString() methods present
}
You dont need to JSON.stringfy the object. You just need to certify that the attribute names on json are the same of your class on spring, and just sed the pure object without the stringfy.
I found the issue in my code. Issue was in getters and setters. In my code field name and getter and setter name was different. Field name was followUpDate but the getter and setter name was getFallowUpDate() and setFallowUpDate(String)

Flutter JSON The class doesn't have a constructor named 'fromJson'

can anyone explain me why this code doenst work?
I have two classes
IngredientEntry.dart
import 'package:CoolKiosk/MasterData/ingredient.dart';
import 'package:decimal/decimal.dart';
class IngredientEntry {
Decimal addOnPrice;
Ingredient ingredient;
IngredientEntry(Decimal addOnPrice, Ingredient ingredient) {
this.addOnPrice = addOnPrice;
this.ingredient = ingredient;
}
factory IngredientEntry.fromJson(Map<String, dynamic> json) {
var _addOnPrice = Decimal.parse(json['price'].toString());
var _ingredient = Ingredient.fromJson(json['ingredient']);
return new IngredientEntry(_addOnPrice, _ingredient);
}
}
and class IngredientGroup.dart
import 'package:CoolKiosk/CustomWidget/IngredientEntry.dart';
import 'package:CoolKiosk/MasterData/base_object.dart';
class IngredientGroup extends BaseObject {
String networkId;
String satelliteId;
String name;
int minSelection;
int maxSelection;
int includedItems;
List<IngredientEntry> ingredientEntries = new List<IngredientEntry>();
IngredientGroup(String id, String networkId, String satelliteId, String name,
int minSel, int maxSel, int includedItems)
: super(id) {
this.networkId = networkId;
this.satelliteId = satelliteId;
this.name = name;
this.minSelection = minSel;
this.maxSelection = maxSel;
this.includedItems = includedItems;
}
factory IngredientGroup.fromJson(Map<String, dynamic> json) {
var _id = json['_id'];
var _networkId = json['networkId'];
var _satelliteId = json['satelliteId'];
var _name = json['name'];
var _minSelection = json['minSelection'];
var _maxSelection = json['maxSelection'];
var _includedItems = json['includedItems'];
IngredientGroup ingredientGroup = new IngredientGroup(_id, _networkId,
_satelliteId, _name, _minSelection, _maxSelection, _includedItems);
final _ingredientEntryList = json['ingredientEntries'];
for (var i = 0; i < _ingredientEntryList.length; i++) {
ingredientGroup.ingredientEntries
.add(new IngredientEntry.fromJson(_ingredientEntryList[i]));
}
return ingredientGroup;
}
}
class Ingredient.dart
import 'package:CoolKiosk/MasterData/base_object.dart';
import 'package:decimal/decimal.dart';
class Ingredient extends BaseObject {
String networkId;
String satelliteId;
String name;
Decimal addOnPrice;
Decimal downPrice;
Ingredient(String id, String networkId, String satelliteId, String name,
Decimal addOnPrice, Decimal downPrice)
: super(id) {
this.networkId = networkId;
this.satelliteId = satelliteId;
this.name = name;
this.addOnPrice = addOnPrice;
this.downPrice = downPrice;
}
factory Ingredient.fromJson(Map<String, dynamic> json) {
var _id = json['_id'];
var _networkId = json['networkId'];
var _satelliteId = json['satelliteId'];
var _name = json['name'];
var _addOnPrice = Decimal.parse(json['addOnPrice'].toString());
var _downPrice = Decimal.parse(json['downPrice'].toString());
return Ingredient(
_id, _networkId, _satelliteId, _name, _addOnPrice, _downPrice);
}
}
The part IngredientEntry.fromJson failes with the following error:
The class 'IngredientEntry' doesn't have a constructor named 'fromJson'.
Try invoking a different constructor, or define a constructor named 'fromJson'.dart(new_with_undefined_constructor)
I do not understand what im doing wrong.
Thanks for any help!
Maybe your Ingredient class does not have factory method. Can you edit that into the question as well?
If someone comes arround this question,
the coude aboce should run fine. My mistake was outside of this snipped, i had a class and a widget named IngredientEntry.

How to get a specific value from a JSON object, like a name?

I use Angular as the front end of my application. For the backend I use glassfish. I currently use a Http GET verb to get a JSON object with an id and name and address. I only want to get the name of the object, how do I do that in a typescript file? How do I get the name of the newest added object of the rest server?
I want to get restaurantName from the object:
{ restaurantId: 1, restaurantName: 'Mcdonalds', restaurantAdres: 'Kalverstraat 5' },
Code that retrieves the object from the rest server:
ngOnInit() {
this.http.get('http://localhost:8080/aquadine-jee/resources/restaurant')
.subscribe(
val => {
const restStr = JSON.stringify(val);
console.log(restStr);
);
Backend code:
#GET
#Produces("application/json")
public Response all(){
List<Restaurant> all = repositoryService.getAllRestaurants();
return Response
.status(200)
.header("Access-Control-Allow-Origin", "*")
.entity(all)
.build();
}
public List<Restaurant> getAllRestaurants() {
EntityManager em = entityManagerFactory.createEntityManager();
List<Restaurant> restaurants = em.createQuery("SELECT r FROM Restaurant r").getResultList();
em.close();
return restaurants;
}
#Entity
#Table(name = "restaurant")
#NamedQueries({
#NamedQuery(name = "Restaurant.findOne", query = "select m from Restaurant m where m.id = :id"),
#NamedQuery(name = "Restaurant.getAll", query = "select m from Restaurant m")
})
public class Restaurant implements Serializable {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
// #Column(name="naam")
// #NotBlank
// private String naam;
// #NotBlank
String restaurantName;
// #NotBlank
String restaurantAdres;
int restaurantId;
public Restaurant(){
}
public Restaurant(int restaurantId, String restaurantName, String restaurantAdres) {
this.restaurantId = restaurantId;
this.restaurantName = restaurantName;
this.restaurantAdres = restaurantAdres;
}
First, I'd create a class and maybe an interface to give you strongly typed objects in your TypeScript:
Then you can return the object from your get request as that object and use that however you want like result.restaurantName
A quick mock of what that looks like (using a stub method instead of http) is here:
In short though:
the class and interface for Angular:
export interface IRestaurant {
restaurantId: number;
restaurantName: string;
restaurantAddres: string;
}
export class Restaurant implements IRestaurant {
restaurantId:number;
restaurantName:string;
restaurantAddres:string;
}
And then the component that gets the data via a method, and uses essentially the JSON as an object:
export class AppComponent {
favoriteRestaurant: IRestaurant;
retrieve(){
this.favoriteRestaurant = this.getRestaurant();
alert(this.favoriteRestaurant.restaurantName);
}
getRestaurant():IRestaurant {
var result: Restaurant = {
restaurantId: 1,
restaurantName: 'Mcdonalds',
restaurantAddres: 'Kalverstraat 5'
};
return result;
}
}
Making it more useful for you though, change the http.get method to something like this:
ngOnInit() {
this.http.get('http://localhost:8080/aquadine-jee/resources/restaurant')
.subscribe(
val:IRestaurant => {
this.favoriteRestaurant = val;
console.log(restStr.restaurantName);
);
You don't want to use JSON.stringify above, because that gives you a string!
Additionally, your restaurantAddress is mispelled, these would need to match exactly. So I would correct the backend.

Room returns incorrect initialized object from generated query

I have three tables, one containing Cards, one containing CardDecks and third one implementing a many-to-many relation between the former two and additionally containg a symbol for every relation entry.
My task is to get three columns from the card-table and the symbol from the relation-table and save it in a data Object specifically designed for handling those inputs, the codition being, that all entries match the given deckId. Or in (hopefully correct) sql-language:
#Query("SELECT R.symbol, C.title, C.type, C.source " +
"FROM card_table C JOIN cards_to_card_deck R ON C.id = R.card_id"+
"WHERE R.card_deck_id = :cardDeckId")
LiveData<List<CardWithSymbol>> getCardsWithSymbolInCardDeckById(long cardDeckId);
But the room implementation class generates:
#Override
public LiveData<List<CardWithSymbol>> getCardsWithSymbolInCardDeckById(long
cardDeckId) {
final String _sql = "SELECT R.symbol, C.title, C.typ, C.source FROM
cards_to_card_deck R INNER JOIN card_table C ON R.card_id = C.id WHERE
R.card_deck_id = ?";
final RoomSQLiteQuery _statement = RoomSQLiteQuery.acquire(_sql, 1);
int _argIndex = 1;
_statement.bindLong(_argIndex, cardDeckId);
return new ComputableLiveData<List<CardWithSymbol>>() {
private Observer _observer;
#Override
protected List<CardWithSymbol> compute() {
if (_observer == null) {
_observer = new Observer("cards_to_card_deck","card_table") {
#Override
public void onInvalidated(#NonNull Set<String> tables) {
invalidate();
}
};
__db.getInvalidationTracker().addWeakObserver(_observer);
}
final Cursor _cursor = __db.query(_statement);
try {
final int _cursorIndexOfSymbol = _cursor.getColumnIndexOrThrow("symbol");
final List<CardWithSymbol> _result = new ArrayList<CardWithSymbol>(_cursor.getCount());
while(_cursor.moveToNext()) {
final CardWithSymbol _item;
final int _tmpSymbol;
_tmpSymbol = _cursor.getInt(_cursorIndexOfSymbol);
_item = new CardWithSymbol(_tmpSymbol,null,null,null);
_result.add(_item);
}
return _result;
} finally {
_cursor.close();
}
}
#Override
protected void finalize() {
_statement.release();
}
}.getLiveData();
}
Where
_item = new CardWithSymbol(_tmpSymbol,null,null,null);
should return my fully initialized object.
The CardWithSymbol class is declared as follows:
public class CardWithSymbol {
public int symbol;
public String cardName;
public String cardType;
public String cardSource;
public CardWithSymbol(int symbol, String cardName, String cardType, String cardSource){
this.symbol = symbol;
this.cardName = cardName;
this.cardType = cardType;
this.cardSource = cardSource;
}
And the types of the columns returned by the query are:
int symbol, String title, String type, String source
I already went through some debugging and the rest of the application works just fine. I can even read the symbol from the objects return by the query, but as mentioned above for some reason room ignores the other three parameters and just defaults them to null in the query-implementation.
So after some trial and error and reading through the dao-documentation once again i found my error:
When creating a class for handling subsets of columns in room, it is important to tell room which variable coresponds to which columns via #ColumnInfo(name = "name of the column goes here")-annotation.
So changing my CardWithSymbol class as follows solved the issue for me:
import android.arch.persistence.room.ColumnInfo;
public class CardWithSymbol {
#ColumnInfo(name = "symbol")
public int symbol;
#ColumnInfo(name = "title")
public String cardName;
#ColumnInfo(name = "type")
public String cardType;
#ColumnInfo(name = "source")
public String cardSource;
public CardWithSymbol(int symbol, String cardName, String cardType, String cardSource){
this.symbol = symbol;
this.cardName = cardName;
this.cardType = cardType;
this.cardSource = cardSource;
}
}