I have a main class called User implemented as follows
package edu.uoc.dpoo;
import java.util.ArrayList;
import java.util.List;
public class User {
private String username;
private String password;
private String fullName;
private Platform platform;
private List<Message> inBox;
private List<Message> outBox;
public User(String username, String password, String fullName) {
this.username = username;
this.password = password;
this.fullName = fullName;
inBox = new ArrayList<Message>();
outBox = new ArrayList<Message>();
}
public User() {
username="";
password="";
fullName="";
}
public String getUserName() {
return username;
}
public String getPassword() {
return password;
}
public String getFullName() {
return fullName;
}
public void setUserName(String username) {
this.username = username;
}
public void setPassword(String password) {
this.password = password;
}
public void setFullName(String fullname) {
this.fullName = fullname;
}
public boolean checkPassword(String password){
if (password.equals(this.password)){
return true;
}else
{
return false;
}
}
public List<Message> getMessages() {
return null;
}
public Organizer asOrganizer(){
Organizer ObjetoO = new Organizer(username,password,fullName);
return ObjetoO;
}
public Participant asParticipant(){
Participant ObjetoP = new Participant(username,password,fullName);
return ObjetoP;
}
public Message sendMessage(String to,String Subject,String message){
return null;
}
public String toString () {
return null;
}
#Override
public boolean equals (Object o) {
boolean prueba = false;
if ((o != null) && (o instanceof User)) {
User p = (User) o;
if (this.username == null && this.password == null && this.fullName == null) {
prueba = (p.username == null);
prueba = (p.password == null);
prueba = (p.fullName == null);
}
else {
prueba = this.username.equals(p.username);
prueba = this.password.equals(p.password);
prueba = this.fullName.equals(p.fullName);
}
}
return prueba;
}
public List<Competition> myCompetitions(){
return null;
}
User(User u1) {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
}
And two classes that inherit from User that are Organizer and Participant implemented as follows
Organizer
package edu.uoc.dpoo;
import java.util.ArrayList;
import java.util.List;
public class Organizer extends User {
private List<Competition> competitions;
public Organizer(String username, String password, String fullName) {
super(username, password, fullName);
competitions = new ArrayList<Competition>();
}
public boolean removeSubmission(Submission submission){
return true;
}
public boolean sendMessage(Competition competition, String subject, String message){
return true;
}
public Competition newCompetition(String tittle,float target){
return null;
}
public void closeCompetition(Competition competition){
}
}
Participant
package edu.uoc.dpoo;
import java.util.ArrayList;
import java.util.List;
public class Participant extends User {
private List<Competition> competitions;
private List<Submission> submission;
public Participant(String username, String password, String fullName) {
super(username, password, fullName);
competitions = new ArrayList<Competition>();
submission = new ArrayList<Submission>();
}
public Submission submitPrediction(Competition competition, float prediction){
return null;
}
public List<Submission> getSubmissions(){
return null;
}
void asParticipant(Submission aThis) {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
}
I'm asked to implement the asOrganizer and asParticipant methods of the User class.
These methods must create an object of the specific class, and initialize the parent class with the data of the User object. To perform this task, you are prompted to implement the copy constructor of the User class.
I create the objects in the two methods that ask me but I should not do something well in the constructor because junit fails me
I add the junit that fails me
#Test
public void userCopyConstructor() {
Platform platform = new Platform();
User u1=platform.registerUser(username1, password1, fullName1);
// User is not NULL
assertNotNull(u1);
// Get a participant object from user object
User u2 = new User(u1);
assertNotNull(u2);
assertEquals(u1, u2);
}
My problem comes at this point
// Get a participant object from user object
User u2 = new User(u1);
assertNotNull(u2);
assertEquals(u1, u2);
public User(User Prueba){
this(Prueba.getUserName(),Prueba.getPassword(),Prueba.getFullName());
}
Thanks to the answers they gave me.
Without you it would be more difficult
Related
I am new to java!
I am trying to read objects of type Admin, containing 3 strings, from a JSON file and store them in a List. I am getting "com.fasterxml.jackson.databind.JsonMappingException: Cannot find a deserializer for non-concrete Map type" but it seems I cannot find a solution.
What is a solution for my code so that I can load the list from the file?
Code snippet :
private static List<Admin> admins=new ArrayList<Admin>();
public static void loadAdminsFromFile() { /*LOAD THE LIST WITH JSON(ADMIN) OBJECTS*/
try {
ObjectMapper mapper = new ObjectMapper();
InputStream inputStream = new FileInputStream(new File("*path to file*"));
TypeReference<List<Admin>> typeReference = new TypeReference<List<Admin>>() {};
admins = mapper.readValue(inputStream, typeReference);
inputStream.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (JsonParseException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
Admin class :
package model;
import javafx.scene.control.TextField;
public class Admin {
private String username;
private String ID;
private String password;
public Admin() {}
public Admin(String username, String ID, String password) {
this.username=username;
this.ID=ID;
this.password=password;
}
public String getUsername() {
return this.username;
}
public void setUsername(TextField username) {
this.username = username.getText();
}
public String getID() {
return this.ID;
}
public void setID(TextField ID) {
this.ID = ID.getText();
}
public String getPassword() {
return this.password;
}
public void setPassword(TextField password) {
this.password = password.getText();
}
#Override
public boolean equals(Object o) {
if(this==o) return true;
if(o==null || getClass()!=o.getClass()) return false;
Admin admin=(Admin) o;
if(!username.equals(admin.username)) return false;
if(!ID.equals(admin.ID)) return false;
if(!password.equals(admin.password)) return false;
return true;
}
#Override
public int hashCode (){
int result=username.hashCode();
result=31*result+ID.hashCode();
result=31*result+password.hashCode();
return result;
}
#Override
public String toString() {
return "Admin -> " + username + ID + password;
}
}
Try to override the setters method to accept String values:
....
public void setUsername(String username) {
this.username = username;
}
....
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();
}
}
I want a help in order to capture or store the user id from the session after the user login to the system.
I have method called 'Login' in the loginBean class, I want after the validation the userId stored in order to use it for example to add records to the DB.
loginBean class:
private String userName;
private String password;
public LoginBean() {}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String Login() {
if (userName == null || userName.trim().length() == 0 || password == null || password.trim().length() == 0) {
addErrorMessage("please enter your username and password");
return null;
}
UserDto userDto = isRegisteredUser(userName);
if (userInfoDto == null) {
addErrorMessage("not validated");
return null;
}
try {
connect(userName, password);
} catch (NamingException e) {
addErrorMessage("wrong userName and password");
return null;
}
return "goMainList";
}
userDto class:
public class UserDto {
private int userSequence;
private String userName;
private String userLogin;
public int getSequence() {
return sequence;
}
public void setSequence(int sequence) {
this.sequence = sequence;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getUserLogin() {
return userLogin;
}
public void setUserLogin(String userLogin) {
this.userLogin = userLogin;
}
}
I want int the (loginBean) class to save the user id, can anyone help me!
Thank you in advance,
I am new to Java. I am now using HashMap for the purpose to store data from MySQL database and I will use the JSon POST request to get the input from user and search for the related data in the HashMap and retrieve from the HashMap. I need three inputs from the user but in the HashMap only able to input 1 key. So, I tried the way to input the key as an object but it is not working. Below is my code for storing data from MySQL database.
public class AppDataService {
HashMap<AppDataRequest, AppData> appdatas = new HashMap<AppDataRequest, AppData>();
static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
static final String DB_URL = "jdbc:mysql://****:3306/****_demo";
static final String USER = "****";
static final String PASS = "****";
public AppDataService(){
Connection conn = null;
Statement stat = null;
try{
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection(DB_URL, USER, PASS);
stat = conn.createStatement();
String sql = "SELECT * FROM testdata";
ResultSet resu = stat.executeQuery(sql);
while(resu.next()){
int id = resu.getInt("app_id");
String email = resu.getString("email");
String password = resu.getString("password");
String status = resu.getString("status");
String message = resu.getString("message");
String token = resu.getString("token");
appdatas.put(new AppDataRequest(id, email, password), new AppData(status, message, token));
}
resu.close();
stat.close();
conn.close();
}
catch(SQLException se){
se.printStackTrace();
}
catch(Exception e){
e.printStackTrace();
}
finally{
try{
if(stat!=null){
stat.close();
}
}
catch (SQLException se2){
}
try{
if(conn!=null){
conn.close();
}
}
catch(SQLException se3){
se3.printStackTrace();
}
}
}
public List<AppData> getAllAppData(){
return new ArrayList<AppData>(appdatas.values());
}
public AppData getAppData(int id){
return appdatas.get(id);
}
public AppData getSAppData(int id, String email, String password){
return appdatas.get(new AppDataRequest (id, email, password));
}
}
My JSon POST code
#Path("/appdata")
#Consumes(MediaType.APPLICATION_JSON)
#Produces(MediaType.APPLICATION_JSON)
AppDataService ads = new AppDataService();
#POST
#Path("/appdatas")
public AppData getSAppData(AppDataRequest adr){
return ads.getSAppData(adr.getId(), adr.getEmail(),adr.getPassword());
}
AppData Class
public class AppData {
public String status;
public String message;
public String token;
public AppData(){
}
public AppData(String status, String message, String token) {
this.status = status;
this.message = message;
this.token = token;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public String getToken() {
return token;
}
public void setToken(String token) {
this.token = token;
}
}
AppDataRequest Class
public class AppDataRequest {
public int id;
public String email;
public String password;
public AppDataRequest(){
}
public AppDataRequest(int id, String email, String password) {
this.id = id;
this.email = email;
this.password = password;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
You can overide hashCode and equals in your class :
#Override
public int hashCode() {
int hash = 3;
hash = 83 * hash + this.id;
hash = 83 * hash + Objects.hashCode(this.email);
hash = 83 * hash + Objects.hashCode(this.password);
return hash;
}
#Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final AppDataRequest other = (AppDataRequest) obj;
if (this.id != other.id) {
return false;
}
if (!Objects.equals(this.email, other.email)) {
return false;
}
if (!Objects.equals(this.password, other.password)) {
return false;
}
return true;
}
Why you don't make the id like a key if it is unique in your table, and your other information as value of map :
Map<Integer, AppData> appdatas;
appdatas.put(id, new AppData(status, message, token, email, password));
HashMap internally makes use of HashCode and Equals method to insert and retrieve the Object from the collection.
You need to override the equals() and Hashcode() method in Java to use a Custom Object as Key within a HashMap. Also it is preferred to have an Immutable Class as a Key which again you have to consider.
Have a look at below
What issues should be considered when overriding equals and hashCode in Java?
If not you can always use the Standard String/Wrapper Classes as Key as they by default provide the methods and design necessary to use.
As Further Reading look for how HashMap Works and you will understand why.
Hope this helps.
Given the following class:
package com.example.model;
import java.util.Collection;
import java.util.Set;
import org.neo4j.graphdb.Direction;
import org.neo4j.helpers.collection.IteratorUtil;
import org.springframework.data.neo4j.annotation.Indexed;
import org.springframework.data.neo4j.annotation.NodeEntity;
import org.springframework.data.neo4j.annotation.RelatedTo;
import org.springframework.data.neo4j.annotation.RelatedToVia;
import org.springframework.security.core.GrantedAuthority;
#NodeEntity
public class User {
private static final String SALT = "cewuiqwzie";
public static final String FRIEND = "FRIEND";
public static final String RATED = "RATED";
#Indexed
String login;
String name;
String password;
String info;
private Roles[] roles;
public User() {
}
public User(String login, String name, String password, Roles... roles) {
this.login = login;
this.name = name;
this.password = encode(password);
this.roles = roles;
}
private String encode(String password) {
return "";
// return new Md5PasswordEncoder().encodePassword(password, SALT);
}
#RelatedToVia(elementClass = Rating.class, type = RATED)
Iterable<Rating> ratings;
#RelatedTo(elementClass = Movie.class, type = RATED)
Set<Movie> favorites;
#RelatedTo(elementClass = User.class, type = FRIEND, direction = Direction.BOTH)
Set<User> friends;
public void addFriend(User friend) {
this.friends.add(friend);
}
public Rating rate(Movie movie, int stars, String comment) {
return relateTo(movie, Rating.class, RATED).rate(stars, comment);
}
public Collection<Rating> getRatings() {
return IteratorUtil.asCollection(ratings);
}
#Override
public String toString() {
return String.format("%s (%s)", name, login);
}
public String getName() {
return name;
}
public Set<User> getFriends() {
return friends;
}
public Roles[] getRole() {
return roles;
}
public String getLogin() {
return login;
}
public String getPassword() {
return password;
}
public String getInfo() {
return info;
}
public void setInfo(String info) {
this.info = info;
}
public void updatePassword(String old, String newPass1, String newPass2) {
if (!password.equals(encode(old)))
throw new IllegalArgumentException("Existing Password invalid");
if (!newPass1.equals(newPass2))
throw new IllegalArgumentException("New Passwords don't match");
this.password = encode(newPass1);
}
public void setName(String name) {
this.name = name;
}
public boolean isFriend(User other) {
return other != null && getFriends().contains(other);
}
public enum Roles implements GrantedAuthority {
ROLE_USER, ROLE_ADMIN;
#Override
public String getAuthority() {
return name();
}
}
}
I get a compilation exception here:
public Rating rate(Movie movie, int stars, String comment) {
return relateTo(movie, Rating.class, RATED).rate(stars, comment);
}
Following the tutorial here. Any insight as to where this function resides is appreciated.
You're trying to use the advanced mapping mode. See the reference manual for more information. You'll need to set up AspectJ support in your IDE. Methods are woven into your entity classes at compile time.