OGNL setValue target is null - java

public class Customer {
private User user;
private String name;
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
public class User {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
public static void main(String[] args) {
try {
Customer customer = new Customer();
Object tree = Ognl.parseExpression("user.name");
Ognl.setValue(tree, customer, "hello");
} catch (OgnlException e) {
e.printStackTrace();
}
}
ognl.OgnlException: target is null for setProperty(null, "name", hello)
how to let ognl to create user auto.

Try this
public static void main(String[] args) {
try {
Customer customer = new Customer();
User user = new User();
customer.setUser(user);
Object tree = Ognl.parseExpression("user.name");
Ognl.setValue(tree, customer, "hello");
} catch (OgnlException e) {
e.printStackTrace();
}
}
The problem with your sample code is that your instance "customer" has a null user. So OGNL is essentially calling customer.getUser().setName("hello"), where "customer.getUser()" returns null.

Related

The constructor Client(String, String, String, String, String) is undefined

I have an assignment where I am supposed to simulate a management and billing application for a phone company. I created some classes, and one object for each class, but I get this error: "The constructor Client(String, String, String, String, String) is undefined"
Here are the relevant classes:
public class CreateUsers {
public static void main(String[] args) {
Client client = new Client("user1", "user", "user", "Client", "12345678");
Admin admin = new Admin("user2", "user", "user", "Admin");
Seller seller = new Seller("user3", "user", "user", "Seller");
}
}
public class Client extends Users {
String AFM;
public Client(String u, String n, String s, String p, String i){
this.AFM = i;
this.username = u;
this.name = n;
this.surname = s;
this.property= p;
UsersCount++;
}
public void ViewBill()
{
System.out.println("The bill");
}
public void ViewHistory()
{
System.out.println("The history");
}
public void PayBill()
{
System.out.println("Bill payment");
}
public String getAFM() {
return AFM;
}
}
public class Admin extends Users
{
public Admin() {
UsersCount++;
}
public void CreateSeller()
{
System.out.println("Seller was created!");
}
public void DeleteSeller()
{
System.out.println("Seller was deleted!");
}
public void CreateUser()
{
System.out.println("User was created!");
}
public void DeleteUser()
{
System.out.println("User was deleted!");
}
public void CreateNewProgram()
{
System.out.println("A new program was created!");
}
}
public class Seller extends Users
{
int salary;
String shift;
String pt_or_ft;
public void NewCustomer()
{
System.out.println("Customer was created!");
}
public void IssueBill()
{
System.out.println("Bill was issued!");
}
public void ChangeProgram()
{
System.out.println("Program was changed!");
}
public int getSalary() {
return salary;
}
public void setSalary(int salary) {
this.salary = salary;
}
public String getShift() {
return shift;
}
public void setShift(String shift) {
this.shift = shift;
}
public String getPt_or_ft() {
return pt_or_ft;
}
public void setPt_or_ft(String pt_or_ft) {
this.pt_or_ft = pt_or_ft;
}
public Seller() {
UsersCount++;
}
}
public class Users
{
String username;
String name;
String surname;
String property;
static int UsersCount = 0;
static void register()
{
System.out.println("User registerd!");
}
static void login()
{
System.out.println("Login succesful!");
}
static void logout()
{
System.out.println("Logout succesful!");
}
public String getUserame()
{
return username;
}
public void setUsername(String newUsername)
{
this.username = newUsername;
}
public String getName()
{
return name;
}
public void setName(String newName)
{
this.name = newName;
}
public String getSurname()
{
return surname;
}
public void setSurname(String newSurname)
{
this.surname = newSurname;
}
public String getProperty()
{
return property;
}
public void setProperty(String newProperty)
{
this.property = newProperty;
}
public Users() {}
}
I am getting these errors in the CreateUsers class, in the lines where I declared the objects "admin" and "seller".
What am I doing wrong? How can I fix this?
instead of having the public static void main(String[] args) {}
you can have like a public fuction with a method that will include all your variables as parameters for example this is how I would have done it.
public class CreateUsers {
public ClientData(String Client, String Admin, String) {
Client client = new Client("user1", "user", "user", "Client", "12345678");
Admin admin = new Admin("user2", "user", "user", "Admin");
Seller seller = new Seller("user3", "user", "user", "Seller");
}
}

JsonMappingException: N/A when trying to deserialize JSON file

I have a User class and a Json file containing an array of Users. When trying to deserialize those users and get a List I'm getting a JsonMappingException, I don't understand what's wrong.
This is my User class:
public class User {
private StringProperty username;
private StringProperty password;
private StringProperty name;
private StringProperty surname;
private StringProperty email;
private StringProperty company;
private StringProperty phone;
private BooleanProperty canMonitorize;
private BooleanProperty canCreateProject;
private BooleanProperty canOpenProject;
private BooleanProperty admin;
public User() {}
public User(String user, String pass, String name, String surname, String email, String company, String phone,
boolean monitorize, boolean createP, boolean openP, boolean admin) {
this.username = new SimpleStringProperty(user);
this.password = new SimpleStringProperty(pass);
this.name = new SimpleStringProperty(name);
this.surname = new SimpleStringProperty(surname);
this.email = new SimpleStringProperty(email);
this.company = new SimpleStringProperty(company);
this.phone = new SimpleStringProperty(phone);
this.canMonitorize = new SimpleBooleanProperty(monitorize);
this.canCreateProject = new SimpleBooleanProperty(createP);
this.canOpenProject = new SimpleBooleanProperty(openP);
this.admin = new SimpleBooleanProperty(admin);
}
public String getUsername() {
return username.get();
}
public void setUsername(String username) {
this.username.set(username);
}
public String getPassword() {
return password.get();
}
public void setPassword(String password) {
this.password.set(password);
}
public String getName() {
return name.get();
}
public void setName(String name) {
this.name.set(name);
}
public String getSurname() {
return surname.get();
}
public void setSurname(String surname) {
this.surname.set(surname);
}
public String getEmail() {
return email.get();
}
public void setEmail(String email) {
this.email.set(email);
}
public String getCompany() {
return company.get();
}
public void setCompany(String company) {
this.company.set(company);
}
public String getPhone() {
return phone.get();
}
public void setPhone(String phone) {
this.phone.set(phone);
}
public boolean canMonitorize() {
return canMonitorize.get();
}
public void setCanMonitorize(boolean canMonitorize) {
this.canMonitorize.set(canMonitorize);
}
public boolean canCreateProject() {
return canCreateProject.get();
}
public void setCanCreateProject(boolean canCreateProject) {
this.canCreateProject.set(canCreateProject);
}
public boolean canOpenProject() {
return canOpenProject.get();
}
public void setCanOpenProject(boolean canOpenProject) {
this.canOpenProject.set(canOpenProject);
}
public boolean isAdmin() {
return admin.get();
}
public void setAdmin(boolean isAdmin) {
this.admin.set(isAdmin);
}
}
And this is an example of the Json file:
[{"username":"admin","password":"blablabla","name":"admin","surname":"admin","email":"admin#admin.com","company":"admin","phone":"admin","admin":true}]
This is the method that should obtain the list of users:
public static List<User> getUsers(String jsonArrayStr) {
ObjectMapper mapper = new ObjectMapper();
List<User> ret;
try {
User[] userArray = mapper.readValue(jsonArrayStr, User[].class);
ret = new ArrayList<>(Arrays.asList(userArray));
} catch (IOException e) {
return new ArrayList<User>();
}
return ret;
}
The error I get when executing the code:
com.fasterxml.jackson.databind.JsonMappingException: N/A (through reference chain: object.User["username"])
When you have a public 0-args constructor it is used by default to create new POJO instance. But in your case you should not allow to create instance with default constructor because all internal fields are null and when Jackson tries to set first property, username, NullPointerException is thrown. Try to declare your constructor as below and remove default one:
#JsonCreator
public User(#JsonProperty("username") String user,
#JsonProperty("password") String pass,
#JsonProperty("name") String name,
#JsonProperty("surname") String surname,
#JsonProperty("email") String email,
#JsonProperty("company") String company,
#JsonProperty("phone") String phone,
#JsonProperty("monitorize") boolean monitorize,
#JsonProperty("createP") boolean createP,
#JsonProperty("openP") boolean openP,
#JsonProperty("admin") boolean admin) {
//your code;
}
Also, your getUsers method could look like this:
public static List<User> getUsers(String json) {
final ObjectMapper mapper = new ObjectMapper();
try {
final JavaType collectionType = mapper.getTypeFactory().constructCollectionType(List.class, User.class);
return mapper.readValue(json, collectionType);
} catch (IOException e) {
//You should not hide exceptions. Try to log it at least.
//But probably application should not start when app configuration is missing or wrong.
e.printStackTrace();
return Collections.emptyList();
}
}

Data integrity when using parallel stream

I have the implemented the below and I have not tested it yet with large amount of data.
public class Main {
public static void main(String[] args) {
CombinedData combinedData = new CombinedData();
List<String> nameList = Arrays.asList("x1", "x3", "x2");
nameList.parallelStream().forEach(name -> {
populateDetails(name, combinedData);
});
}
static void log(String str) {
System.out.println(str);
}
static void populateDetails(String name, CombinedData combinedData) {
if (combinedData.getOrg() == null) {
combinedData.setOrg(MyUtil.getOrg(name));
}
if (combinedData.getRawData() != null) {
combinedData.setRawData(combinedData.getRawData() + name);
}
combinedData.addToDetails(new Details(name, MyUtil.getAdd(name)));
}
}
class CombinedData {
private String org;
private List<Details> details;
private String rawData;
public String getOrg() {
return org;
}
public void setOrg(String org) {
this.org = org;
}
public void addToDetails(Details details) {
this.details.add(details);
}
public List<Details> getDetails() {
return details;
}
public void setDetails(List<Details> details) {
this.details = details;
}
public String getRawData() {
return rawData;
}
public void setRawData(String rawData) {
this.rawData = rawData;
}
}
class Details {
private String name;
private String address;
public Details(
String name,
String address) {
this.name = name;
this.address = address;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
}
If you check the line 13 and 16 I need to add the org to combined response only once and I have added the check there and also I need to append the name to the rawData. My question is that since I'm using parallel stream how would that behave.
Im sure there might be a scenario that when threads are in parallel thing might break.
How can I go ahead and handle that scenario?

apache commons beanutils, how to set property value?

In the java, commons beanutils, try to set property 'address' and 'creditCardList' to object, but it gave me error :
java.lang.NoSuchMethodException: Property 'address' has no setter method in class 'class com.dao.Student'
but I have this method there. The code is here:
public class Main {
public static void main(String[] args) {
Object student = new Student("John");
Object address = new Address("NJ");
try {
PropertyUtils.setProperty(student, "address", address);
//----------
List list = new ArrayList();
Object creditCard = new CreditCard();
list.add(creditCard);
PropertyUtils.setProperty(student, "creditCardList", list);
} catch (Exception e) {
e.printStackTrace();
}
}
}
class Student {
private String name;
private Address address;
private List<CreditCard> creditCardList;
public Student(String name) {
super();
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Address getAddress() {
return address;
}
public void setAddress(Address address) {
this.address = address;
}
public List<CreditCard> getCreditCardList() {
return creditCardList;
}
public void setCreditCardList(List<CreditCard> creditCardList) {
this.creditCardList = creditCardList;
}
}
class Address {
private String name;
public Address(String name) {
super();
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
class CreditCard{
private String cardName;
public String getCardName() {
return cardName;
}
public void setCardName(String cardName) {
this.cardName = cardName;
}
}
Your class Student should be a public class , try making it public and rerun your code.
I moved Student to a own file and made it public, that worked fine :)

checking login algorithm

i am currently stucked on how to create a login algorithm which will login a user based on 2 HashMap objects namely Students and StaffMembers from a class DataStorage, i do not know after getting the texts input from LoginHandler() what do i do with them to compare it with my DataStorage .
/* Class DataStorage*/
public class DataStorage
{
HashMap<String, Student> students = new HashMap<String, Student>();
HashMap<String, Staff> staffMembers = new HashMap<String, Staff>();
//Default constructor
public DataStorage(){
}
public void addStaffMember(Staff aAcc)
{
staffMembers.put(aAcc.getAccID(),aAcc);
}
public void addStudentMember(Student aAcc)
{
students.put(aAcc.getAccID(),aAcc);
}
public Staff getStaffMember(Staff aAcc)
{
return staffMembers.get(aAcc.getAccID());
}
public Student getStudent(Student aAcc)
{
return students.get(aAcc.getAccID());
}
public Account authUser(String user, String pass)
{
}
}
/* Class Account*/
public class Account {
private String name;
private String department;
private String username;
private String password;
private String accountID;
public Account()
{
}
public Account(String nm,String dep,String user,String pass, String accID)
{
name = nm;
department = dep;
username = user;
password = pass;
accountID = accID;
}
public void setName(String nm)
{
name = nm;
}
public String getName()
{
return name;
}
public void setDep(String d)
{
department = d;
}
public String getDep()
{
return department;
}
public void setUser(String u)
{
username = u;
}
public String getUser()
{
return username;
}
public void setPass(String p)
{
password = p;
}
public String getPass()
{
return password;
}
public void setAccID(String a)
{
accountID = a;
}
public String getAccID()
{
return accountID;
}
}
/* Class Staff extends account*/
public class Staff extends Account {
public Staff(String n, String id, String dep, String user, String pass)
{
super(n, dep, user, pass, id);
}
}
/** Class Student extends Account**/
public class Student extends Account {
private String studentNRIC;
public Student(String n, String nr, String id, String dep, String user, String pass)
{
super(n, dep, user, pass, id);
studentNRIC = nr;
}
public void setStudentNRIC(String nr)
{
studentNRIC = nr;
}
public String getStudentNRIC()
{
return studentNRIC;
}
}
/* class loginHandler which will handle a login button/
class LoginHandler implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
String tempUser;
String tempPass;
tempUser = txfUser.getText();
tempPass = txfPass.getText();
}
}
First of all you should change the getters in DataStorage to have String parameters, so that you can look up a student (or staff member) based on her account ID:
public Student getStudent(String aAcc)
{
return students.get(aAcc);
}
You can then lookup the username in actionPerformed, like
Student student = dataStorage.getStudent(tempUser);
if (student != null && student.getPass().equals(tempPass))
{
// login successful
...
} else {
// Login failed - display error message
}
Similarly for staff members.

Categories

Resources