getting an error in unboxing in c# stating name does not exist in current context? - boxing

class Program
{
static void Main(string[] args)
{
Console.WriteLine("enter id");
int id = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("enter name");
string name = Console.ReadLine();
Console.WriteLine("price");
int price = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("enter quantity");
int quantity = Convert.ToInt32(Console.ReadLine());
product_demo p1 = new product_demo(id, name, price, quantity);
p1.diplay();
Console.Read();
}
}
public class product_demo
{
public int id;
public string name;
public int price;
public int quantity;
public product_demo(int id, string name, int price, int quantity)
{
this.id = id;
this.name = name;
this.price = price;
this.quantity = quantity;
object o1 = id;
object o2 = name;
object o3 = price;
object o4 = quantity;
}
public void diplay()
{
int j = (int)o1;
Console.WriteLine("id :");
}
}
getting an error while unboxing in display function. boxing is done in product_demo constructor. one more question ; can we define boxing outside any constructor or methods, directly in body of class.

You have created object o1 in the constructor of product_demo and therefore it exists only within that scope. You need to have your objects within the class (Similar to where you have placed your other variables such as int id, string name, etc.

Related

Asserion failed service testing spring

I have a simple shampoos-warehouse api and want to test it service logic, but something going wrong.
Here's my Service Test:
RunWith(SpringRunner.class)
#SpringBootTest
class ShampooServiceTest {
public static final String SHAMPOO_NAME = "name";
public static final int SHAMPOO_CAPACITY = 1000;
public static final int SHAMPOO_QUANTITY = 30;
public static final boolean SHAMPOO_IS_HEALTHY = true;
public static final LocalDate SHAMPOO_EXPIRATION_DATE = LocalDate.parse("2022-11-11");
public static final String SHAMPOO_PARAM = "equals";
#Autowired
ShampooService shampooService;
#MockBean
ShampooRepository shampooRepository;
#Test
void getAddAndGetTotalShampoosByParams(){
shampooService.addShampoos(UUID.randomUUID(), SHAMPOO_NAME, SHAMPOO_CAPACITY, SHAMPOO_QUANTITY, SHAMPOO_IS_HEALTHY, SHAMPOO_EXPIRATION_DATE);
assertEquals(String.valueOf(SHAMPOO_QUANTITY), shampooService.getTotalShampoosByParam(SHAMPOO_NAME, SHAMPOO_CAPACITY, SHAMPOO_PARAM));
}
I have an assertion error here:
org.opentest4j.AssertionFailedError:
Expected :30
Actual :0
Here's my DTO:
public class ShampooDto {
public interface IncomeValidation{}
public interface OutcomeValidation{}
#NotNull(groups={IncomeValidation.class, OutcomeValidation.class})
private String name;
#Min(100)
#Max(5000)
#NotNull(groups={IncomeValidation.class, OutcomeValidation.class})
private int capacity;
#NotNull(groups={IncomeValidation.class, OutcomeValidation.class})
private int quantity;
#NotNull(groups={IncomeValidation.class})
private boolean healthy;
#NotNull(groups={IncomeValidation.class})
private LocalDate expiration_date;
}
And here's my service:
public String getTotalShampoosByParam(String name, int capacity, String param){
Integer totalQuantity;
switch (param){
case "less":
totalQuantity = shampooRepository.getTotalQuantityWhereCapacityLess(name, capacity);
break;
case "equals":
totalQuantity = shampooRepository.getTotalQuantityWhereCapacityEquals(name, capacity);
break;
case "more":
totalQuantity = shampooRepository.getTotalQuantityWhereCapacityMore(name, capacity);
break;
default:
totalQuantity = 0;
}
if(totalQuantity!=null){
return String.valueOf(totalQuantity);
}
else{
return "0";
}
}
public Shampoo addShampoos(UUID id, String name, int capacity, int quantity, boolean healthy, LocalDate expiration_date) throws ValidationException {
Optional<Shampoo> answer = shampooRepository.findShampooByNameAndCapacity(name, capacity);
if(answer.isPresent()){
Shampoo shampoo = answer.get();
shampoo.setQuantity(shampoo.getQuantity() + quantity);
shampooRepository.save(shampoo);
return shampoo;
}
else{
Shampoo shampoo = new Shampoo(id, name, capacity, quantity, healthy, expiration_date, LocalDate.now());
shampooRepository.save(shampoo);
return shampoo;
}
}
The problem is that when I added Shampoos and search it by requests, all works, but my test give me "0" instead of "30"

IBM ODM Dependant XOM classes

HI I have two questions to ask :-
I have a XOM class like this -
package com.ibm.p2p;
import javax.xml.bind.annotation.XmlElement;
import ilog.rules.bom.annotations.BusinessName;
import ilog.rules.bom.annotations.CustomProperty;
public class PO {
#XmlElement
private int quantity;
#XmlElement
private double price;
#XmlElement
private double totalAmount;
public PO() {
}
#CustomProperty(name = "dataio.default", value = "true")
public PO(#BusinessName("price") double price, #BusinessName("quantity") int quantity, #BusinessName("totalAmount") int totalAmount) {
this();
this.price = price;
this.quantity = quantity;
this.totalAmount = totalAmount;
}
public int getPOQuantity() {
return quantity;
}
public void setPOQuantity(int quantity) {
this.quantity = quantity;
}
public double getPOPrice() {
return price;
}
public void setPOPrice(double price) {
this.price = price;
}
public double getPOTotalAmount() {
return totalAmount;
}
public void setPOTotalAmount(double totalAmount) {
this.totalAmount = totalAmount;
}
}
When I deploy this and run the TEST using the "OPENAPI-JSON" REST option , by default I get this input JSON (attached in this message) :-
I dont understant why does the extra "quantity", "price" and "totalAMount" comes ?? In my XOM I have defined "getPOQuanitity", "getPOTotalAMount","getPOPrice" right? So only "poquantity", "poprice", "pototalAmount" should come right? How is this OPENAPI-JSON getting formed? If anyone can help me clarifying this , it will be useful for our testing also.
) I have some Print statements in my Rule. When I run this RestAPI Test where can I find the COnsole Print statements? I dont see them in my Server logs.
maybe you can try removing this part of the class:
public PO(#BusinessName("price") double price, #BusinessName("quantity") int quantity, #BusinessName("totalAmount") int totalAmount) {
this();
this.price = price;
this.quantity = quantity;
this.totalAmount = totalAmount;
}

Android room. error: Cannot figure out how to read this field from a cursor

the SQLite database contains three tables 1) employee 2) skills 3) departments. The idea is this - the employee table stores data such as id, name, last_name, salary. Also, an employee has data such as skill and department, but there can be several data for one employee, so I created two separate skills and departments tables and linked them using the key to the employee table where the primary key for employee is id. Now with the help of id I need to display all the information about employee including his skills which can be several and departments. I implement the whole process using the ROOM library.
Here is the request I make
#Query("SELECT employ.id ,employ.name ,employ.last_name, employ.salary, " +
"skill.skill, department.department_name FROM employ INNER JOIN skill,department " +
"ON employ.id = :id AND skill.employ_id = :id AND department.employ_id = :id ")
AllAboutEmployee getAllAboutEmployee(String id);
Here is the AllAboutEmployee class whose object accepts the result of the request
public class AllAboutEmployee {
#ColumnInfo(name = "id")
private String id;
#ColumnInfo(name = "name")
private String name;
#ColumnInfo(name = "last_name")
private String lastName;
#ColumnInfo(name = "salary")
private String salary;
#ColumnInfo(name = "department_name")
private List<String> departmentsList; // THE ERROR IS ON THIS LINE
#ColumnInfo(name = "skill")
private List<String> skillList; // THE ERROR IS ON THIS LINE
public AllAboutEmployee(String id, String name, String lastName, String salary, List<String> departmentsList, List<String> skillList) {
this.id = id;
this.name = name;
this.lastName = lastName;
this.salary = salary;
this.departmentsList = departmentsList;
this.skillList = skillList;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getSalary() {
return salary;
}
public void setSalary(String salary) {
this.salary = salary;
}
public List<String> getDepartmentsList() {
return departmentsList;
}
public void setDepartmentsList(List<String> departmentsList) {
this.departmentsList = departmentsList;
}
public List<String> getSkillList() {
return skillList;
}
public void setSkillList(List<String> skillList) {
this.skillList = skillList;
}
}
So ther are two fields int the AllAboutEmployee class with the List type, in order to put several skills and several departments there. It is in these fields that an error occurs. Thank you in advance for your help
Wow.. that's so cool.. I was coding all day and got this error too!
You have to create a TypeCoverter to store your data into your Room's Database.
In this case you have two List, that are not types recognizable by Database, so you have to create an Converter for it to store as a String, and another method to do the inverse.
Something like:
class TypeCoverter{
#TypeConverter
fun arrayListToString(arrayList: ArrayList<String>?): String? {
if (arrayList.isNullOrEmpty()) return null
val string = StringBuilder()
for (item in arrayList) {
val isNotTheLastItemInTheArrayList = (item == arrayList.last()).not()
if (isNotTheLastItemInTheArrayList) {
string.append(item).append(COMMA)
} else {
string.append(item)
}
}
return string.toString()
}
}
#TypeConverter
fun stringToArrayList(string: String?): ArrayList<String>? {
when {
string.isNullOrEmpty() -> {
return null
}
string.contains(COMMA).not() -> {
val list = ArrayList<String>()
list.add(string)
return list
}
else -> {
return string.split(COMMA.toRegex()).dropLastWhile { it.isEmpty() } as ArrayList<String>
}
}
}
That's actually in Kotlin, but you can see how it works.

Sonar gives NullPointerException not right

I am having java code:
public class Test {
public static void main(String[] args) {
Student student = new Student(1,"test");
printId(student);
}
private static void printId(Student obj) {
if(Objects.isNull(obj))
return;
System.out.println("Id: " + obj.getId());
}
}
public class Student {
private int id;
private String name;
public Student(int id, String name) {
this.id = id;
this.name = name;
}
public int getId(){
return id;
}
}
At line System.out.println... sonar is showing that obj can be null but I had already checked for null value.
Is there any way to get rid of this issue?
You could use explicit null test.
if(null==obj)
return;
......
The rule itself does not recognize usage of Objects.isNull as null check. Objects.isNull(Object obj) returns result of null==obj expresion so it can be safely replaced.
However you could contact SonarSource and propose rule change.

Wrap collections in Value Objects

I have the following entities:
public class ComplexEntity {
public List<TenderLocation> tenderList;
public ComplexEntity(List<TenderLocation> tenderList) {
this.tenderList = tenderList;
}
}
public class TenderLocation {
public String location;
public List<TenderAirline> tenderAirlines;
public TenderLocation(String location, List<TenderAirline> tenderAirlines) {
this.tenderAirlines = tenderAirlines;
this.location = location;
}
}
public class TenderAirline {
public int ID;
public String name;
public TenderAirline(int ID, String name) {
this.ID = ID;
this.name = name;
}
}
And the following test for comparing two ComplexEntiey:
public class ComplexObjectGraphComparisonExample {
#Test
public void shouldCompareTwoComplexObjects() {
// given
Javers javers = JaversBuilder.javers().build();
// Construct test data
// ComplexEntity:
// - List<TLocation>
// TLoation:
// - location: String
// - List<TAir>
// TAir:
// - int ID
// - String Name
int locations = 3;
List<TenderLocation> tenderLocationsBase = new ArrayList<TenderLocation>(locations);
List<TenderLocation> tenderLocationsRef = new ArrayList<TenderLocation>(locations);
for (int j = 0; j < locations; ++j) {
int airlines = 10;
List<TenderAirline> tenderAirlinesBase = new ArrayList<TenderAirline>(airlines);
List<TenderAirline> tenderAirlinesRef = new ArrayList<TenderAirline>(airlines);
for (int i = 0; i < airlines; ++i) {
tenderAirlinesBase.add(new TenderAirline(i, "Airline" + i));
tenderAirlinesRef.add(new TenderAirline(i, "Airline" + i));
}
tenderLocationsBase.add(new TenderLocation("BV" + j, tenderAirlinesBase));
tenderLocationsRef.add(new TenderLocation("BV" + j, tenderAirlinesBase));
}
ComplexEntity baseEntity = new ComplexEntity(tenderLocationsBase);
ComplexEntity referenceEntity = new ComplexEntity(tenderLocationsRef);
// when
Diff diff = javers.compare(baseEntity, referenceEntity);
assertThat(diff.getChanges()).hasSize(0);
// Change a single small thing
referenceEntity.tenderList.get(1).location = "Difference_1";
// then there is a single change detected
diff = javers.compare(baseEntity, referenceEntity);
assertThat(diff.getChanges()).hasSize(1);
// there should be one change of type {#link ValueChange}
ValueChange change = diff.getChangesByType(ValueChange.class).get(0);
assertThat(change.getPropertyName()).isEqualTo("location");
assertThat(change.getLeft()).isEqualTo("BV1");
assertThat(change.getRight()).isEqualTo("Difference_1");
// do another change
referenceEntity.tenderList.get(1).tenderAirlines.get(1).name = "Difference_2";
// second difference is not detected, failing the commented test
diff = javers.compare(baseEntity, referenceEntity);
assertThat(diff.getChanges()).hasSize(2);
System.out.println(diff);
}
}
At comparison my second change is not identified because the compare method is not comparing in depth my lists.
I have read here
http://www.atetric.com/atetric/javadoc/org.javers/javers-core/1.3.4/org/javers/core/Javers.html
that if I "wrap collections in some Value Objects" the deep comparing of the collection is possible.
My question is, How exactly I can wrap my collection into Value Objects?
You can wrap the object something like below:
public class Wrapper
{
private final WrappedObject obj;
public Wrapper (WrappedObject obj)
{
this.obj = obj;
}
}
What is wrong in you code is mapping, you didn't do it at all. You should map your entities as Entities using #Id annotation:
public class TenderLocation {
#Id
public String location;
...
public class TenderAirline {
#Id
public int ID;
public String name;
...
Otherwise, JaVers maps your classes as Value Objects (objects without identity) which gives you limited diff experience.

Resources